Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Create structured MDX entries from collection folders (#6317)
Oleg Isonene69a3d2f8efe
diff --git a/apps/builder/app/auth/login.tsx b/apps/builder/app/auth/login.tsxindex e56752ed62..c8a66c0ec5 100644--- a/apps/builder/app/auth/login.tsx+++ b/apps/builder/app/auth/login.tsx@@ -2,7 +2,6 @@ import { TooltipProvider } from "@radix-ui/react-tooltip";import {Button,Flex,- rawTheme,Text,theme,cssVar,@@ -47,16 +46,7 @@ export const Login = ({minWidth: theme.spacing[20],padding: theme.spacing[17],borderRadius: theme.spacing[5],- backgroundColor: `light-dark(- transparent,- ${cssVar("--background-primary")}- )`,- [`@media (min-width: ${rawTheme.spacing[35]})`]: {- backgroundColor: `light-dark(- oklch(from ${cssVar("--background-primary")} l c h / 50%),- ${cssVar("--background-primary")}- )`,- },+ backgroundColor: `oklch(from ${cssVar("--background-primary")} l c h / 50%)`,}}><WebstudioIcon size={48} />diff --git a/apps/builder/app/builder/features/assets/assets.tsx b/apps/builder/app/builder/features/assets/assets.tsxindex cd3aeaf22d..5a92b9e642 100644--- a/apps/builder/app/builder/features/assets/assets.tsx+++ b/apps/builder/app/builder/features/assets/assets.tsx@@ -1,44 +1,221 @@import {+ PanelContent,+ PanelBanner,+ Button,DropdownMenu,DropdownMenuContent,DropdownMenuItem,DropdownMenuTrigger,+ Flex,IconButton,PanelTitle,Separator,Tooltip,+ Text,+ toast,} from "@webstudio-is/design-system";-import { BrushCleaningIcon, PlusIcon } from "@webstudio-is/icons";-import { useRef, useState } from "react";+import {+ AlertCircleIcon,+ BrushCleaningIcon,+ PlusIcon,+ SettingsIcon,+} from "@webstudio-is/icons";+import { useEffect, useRef, useState } from "react";import { useStore } from "@nanostores/react";-import { getAssetUrl, isTextFileAsset } from "@webstudio-is/sdk";+import {+ formatAssetName,+ getAssetUrl,+ isTextFileAsset,+} from "@webstudio-is/sdk";import { AssetManager } from "~/builder/shared/asset-manager";import { AssetUpload, type AssetUploadHandle } from "~/builder/shared/assets";+import { uploadSingleAsset } from "~/builder/shared/assets/upload-assets";+import {+ canConfigureContentCollections,+ getCollectionReservedAssetIds,+ useContentCollections,+ type ContentCollection,+} from "~/builder/shared/assets";import { openDeleteUnusedAssetsDialog } from "~/builder/shared/asset-manager/delete-unused-assets";-import { CreateAssetFolderDialog } from "~/builder/shared/asset-manager/asset-folder-dialogs";-import { $authPermit } from "~/shared/nano-states";-import { $assets } from "~/shared/sync/data-stores";+import {+ CreateAssetFolderDialog,+ type createContentCollectionFolder,+} from "~/builder/shared/asset-manager/asset-folder-dialogs";+import { $authPermit, $isContentMode } from "~/shared/nano-states";+import { $assets, $project } from "~/shared/sync/data-stores";+import {+ $settings,+ getSetting,+ setSetting,+} from "~/builder/shared/client-settings";import type { Publish } from "~/shared/pubsub";import { useImageAssetCanvasDrag } from "./use-image-asset-canvas-drag";import { TextFileEditor } from "~/builder/features/text-file-editor/text-file-editor";import { CreateTextFileDialog } from "~/builder/features/text-file-editor/create-text-file-dialog";+import { CreateCollectionEntryDialog } from "~/builder/shared/asset-manager/create-collection-entry-dialog";+import {+ CollectionSettingsDialog,+ ConvertCollectionDialog,+} from "~/builder/shared/asset-manager/collection-settings-dialog";+import {+ CollectionRetryButton,+ CollectionUnavailableNotice,+} from "./collection-unavailable-notice";+import { useCollectionEntryValidation } from "~/builder/shared/assets/use-collection-entry-validation";+import { CollectionEntrySettingsDialog } from "~/builder/shared/asset-manager/collection-entry-settings-dialog";+import type { Asset } from "@webstudio-is/sdk";export const AssetsPanel = ({publish,+ createCollection,}: {publish: Publish;onClose: () => void;+ createCollection?: typeof createContentCollectionFolder;}) => {- const [folderId, setFolderId] = useState<string>();+ const projectId = useStore($project)?.id;+ const settings = useStore($settings);+ const folderId =+ projectId === undefined+ ? undefined+ : settings.lastAssetFolderIds[projectId];+ const setFolderId = (folderId: string | undefined) => {+ if (projectId === undefined) {+ return;+ }+ const current = getSetting("lastAssetFolderIds");+ if (current[projectId] === folderId) {+ return;+ }+ const next = { ...current };+ if (folderId === undefined) {+ delete next[projectId];+ } else {+ next[projectId] = folderId;+ }+ setSetting("lastAssetFolderIds", next);+ };const [createFolderOpen, setCreateFolderOpen] = useState(false);const [createTextFileOpen, setCreateTextFileOpen] = useState(false);+ const [collectionRefreshKey, setCollectionRefreshKey] = useState(0);+ const [collectionToConfigure, setCollectionToConfigure] = useState<string>();+ const configureCollection = (folderId: string) => {+ setFolderId(folderId);+ setCollectionToConfigure(folderId);+ setCollectionRefreshKey((key) => key + 1);+ };+ const [collectionToConvert, setCollectionToConvert] =+ useState<ContentCollection>();+ const [repairingCollection, setRepairingCollection] = useState(false);+ const [entryCollection, setEntryCollection] =+ useState<Extract<ContentCollection, { status: "ready" }>>();+ const [settingsCollection, setSettingsCollection] =+ useState<Extract<ContentCollection, { status: "ready" }>>();const [openedTextAssetId, setOpenedTextAssetId] = useState<string>();+ const [entrySettings, setEntrySettings] = useState<{+ asset: Asset;+ collection: Extract<ContentCollection, { status: "ready" }>;+ }>();const uploadRef = useRef<AssetUploadHandle>(null);const authPermit = useStore($authPermit);+ const isContentMode = useStore($isContentMode);+ const canManageFolders = authPermit !== "view";+ const canConfigureCollections = canConfigureContentCollections(authPermit);+ const collections = useContentCollections(folderId, collectionRefreshKey);+ const collectionReservedAssetIds = getCollectionReservedAssetIds(+ collections,+ { includeInvalid: true }+ );+ const currentCollection =+ folderId === undefined ? undefined : collections.get(folderId);+ const entryValidation = useCollectionEntryValidation(currentCollection);+ useEffect(() => {+ if (collectionToConfigure === undefined) {+ return;+ }+ const collection = collections.get(collectionToConfigure);+ if (collection?.status === "invalid") {+ setCollectionToConfigure(undefined);+ return;+ }+ if (collection?.status !== "ready") {+ return;+ }+ setCollectionToConfigure(undefined);+ setSettingsCollection(collection);+ }, [collectionToConfigure, collections]);+ const builderRepair =+ currentCollection?.status === "invalid" &&+ isContentMode === false &&+ canConfigureCollections+ ? currentCollection+ : undefined;+ const repairAction = builderRepair?.repairAction;+ const repairAssetToOpen =+ repairAction === "edit" && builderRepair !== undefined+ ? builderRepair.repairAsset+ : repairAction === undefined &&+ builderRepair !== undefined &&+ builderRepair.missingTemplateFilename === undefined &&+ builderRepair.forbiddenAsset === undefined &&+ isTextFileAsset(builderRepair.repairAsset)+ ? builderRepair.repairAsset+ : undefined;+ const invalidCollectionMessage =+ currentCollection?.status !== "invalid"+ ? undefined+ : builderRepair?.repairAction !== undefined+ ? currentCollection.message+ : isContentMode+ ? "New entries are unavailable until a builder repairs this collection."+ : canConfigureCollections+ ? currentCollection.message+ : `${currentCollection.message} A builder must repair this collection.`;const addActions = {upload: () => uploadRef.current?.open(),createFile: () => setCreateTextFileOpen(true),createFolder: () => setCreateFolderOpen(true),+ createEntry: () => {+ if (currentCollection?.status === "ready") {+ setEntryCollection(currentCollection);+ }+ },+ };+ const createMissingTemplate = async () => {+ if (+ currentCollection?.status !== "invalid" ||+ currentCollection.missingTemplateFilename === undefined ||+ repairingCollection+ ) {+ return;+ }+ setRepairingCollection(true);+ try {+ const template = await uploadSingleAsset(+ "file",+ new File(+ ["---\n---\n\nStart writing.\n"],+ currentCollection.missingTemplateFilename,+ { type: "text/mdx" }+ ),+ { folderId: currentCollection.folderId, deduplicate: true }+ );+ if (template === undefined) {+ throw new Error(+ "The missing collection template could not be created."+ );+ }+ setCollectionRefreshKey((key) => key + 1);+ toast.success("Collection template created.");+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : "The missing collection template could not be created."+ );+ } finally {+ setRepairingCollection(false);+ }};const openAsset = (assetId: string) => {const asset = $assets.get().get(assetId);@@ -67,6 +244,42 @@ export const AssetsPanel = ({<PanelTitlesuffix={<>+ {currentCollection?.status === "ready" &&+ isContentMode === false &&+ canConfigureCollections && (+ <Tooltip content="Collection settings">+ <IconButton+ aria-label="Collection settings"+ onClick={() => {+ setSettingsCollection(currentCollection);+ }}+ >+ <SettingsIcon />+ </IconButton>+ </Tooltip>+ )}+ {currentCollection?.status === "invalid" &&+ (builderRepair?.missingTemplateFilename !== undefined ||+ repairAssetToOpen !== undefined) && (+ <Tooltip content={currentCollection.message}>+ <IconButton+ aria-label="Repair invalid collection"+ onClick={() => {+ if (+ builderRepair?.missingTemplateFilename !== undefined+ ) {+ void createMissingTemplate();+ return;+ }+ if (repairAssetToOpen !== undefined) {+ setOpenedTextAssetId(repairAssetToOpen.id);+ }+ }}+ >+ <AlertCircleIcon />+ </IconButton>+ </Tooltip>+ )}<Tooltip content="Delete unused assets"><IconButtonaria-label="Delete unused assets"@@ -87,41 +300,168 @@ export const AssetsPanel = ({</DropdownMenuTrigger></Tooltip><DropdownMenuContent align="end">- <DropdownMenuItem onSelect={addActions.upload}>- Upload- </DropdownMenuItem>- <DropdownMenuItem onSelect={addActions.createFile}>- Create text file- </DropdownMenuItem>- <DropdownMenuItem onSelect={addActions.createFolder}>- Create folder- </DropdownMenuItem>+ {(currentCollection === undefined ||+ currentCollection.status === "ready") && (+ <>+ <DropdownMenuItem onSelect={addActions.upload}>+ Upload+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={addActions.createFile}>+ Create text file+ </DropdownMenuItem>+ </>+ )}+ {currentCollection?.status === "ready" && (+ <DropdownMenuItem onSelect={addActions.createEntry}>+ New entry+ </DropdownMenuItem>+ )}+ {canManageFolders && (+ <DropdownMenuItem onSelect={addActions.createFolder}>+ Create folder+ </DropdownMenuItem>+ )}</DropdownMenuContent></DropdownMenu></>}>- Assets+ {currentCollection === undefined ? "Assets" : "Assets collection"}</PanelTitle><Separator /><AssetManager+ entryIssues={entryValidation.issues}+ folderNotice={+ <>+ {currentCollection?.status === "ready" &&+ entryValidation.issues !== undefined &&+ entryValidation.issues.size > 0 && (+ <PanelBanner variant="warning" role="status">+ <Flex direction="column" gap={2}>+ <Text>+ {entryValidation.issues.size}{" "}+ {entryValidation.issues.size === 1+ ? "entry needs"+ : "entries need"}{" "}+ attention. Open a marked entry to inspect it.+ </Text>+ <Button onClick={entryValidation.retry}>Check again</Button>+ </Flex>+ </PanelBanner>+ )}+ {currentCollection?.status === "loading" && (+ <PanelContent as={Flex} role="status" align="center">+ <Text variant="tiny">Loading collection settings…</Text>+ </PanelContent>+ )}+ {currentCollection?.status === "invalid" && (+ <PanelContent as={Flex} role="alert" direction="column" gap={2}>+ <Text color="destructive" variant="tiny">+ {invalidCollectionMessage}+ </Text>+ {builderRepair !== undefined && (+ <Flex gap={2} wrap="wrap">+ {builderRepair?.missingTemplateFilename !== undefined && (+ <Button+ disabled={repairingCollection}+ onClick={() => void createMissingTemplate()}+ >+ {repairingCollection+ ? "Creating…"+ : "Create missing template"}+ </Button>+ )}+ {repairAssetToOpen !== undefined && (+ <Button+ onClick={() =>+ setOpenedTextAssetId(repairAssetToOpen.id)+ }+ >+ Open {formatAssetName(repairAssetToOpen)}+ </Button>+ )}+ <CollectionRetryButton+ collection={currentCollection}+ onCheckAgain={() =>+ setCollectionRefreshKey((key) => key + 1)+ }+ />+ </Flex>+ )}+ </PanelContent>+ )}+ {currentCollection?.status === "unavailable" && (+ <CollectionUnavailableNotice+ collection={currentCollection}+ onCheckAgain={() => setCollectionRefreshKey((key) => key + 1)}+ />+ )}+ </>+ }folderId={folderId}onFolderChange={setFolderId}+ onConfigureCollection={configureCollection}+ createCollection={createCollection}onOpen={openAsset}- canManageFolders={authPermit !== "view"}+ onEntrySettings={(assetId) => {+ const asset = $assets.get().get(assetId);+ const collection = collections.get(asset?.folderId ?? "");+ if (asset !== undefined && collection?.status === "ready") {+ setEntrySettings({ asset, collection });+ }+ }}+ canManageFolders={canManageFolders}panelActions={{- ...(authPermit === "view" ? {} : addActions),+ ...(authPermit === "view"+ ? {}+ : {+ ...(currentCollection === undefined ||+ currentCollection.status === "ready"+ ? {+ upload: addActions.upload,+ createFile: addActions.createFile,+ }+ : {}),+ ...(currentCollection?.status === "ready"+ ? { createEntry: addActions.createEntry }+ : {}),+ ...(canManageFolders+ ? { createFolder: addActions.createFolder }+ : {}),+ }),deleteUnusedAssets: openDeleteUnusedAssetsDialog,+ ...(currentCollection !== undefined &&+ canConfigureCollections &&+ !isContentMode+ ? {+ convertCollection: () =>+ setCollectionToConvert(currentCollection),+ }+ : {}),}}+ collections={collections}+ emptyMessage={+ currentCollection === undefined+ ? undefined+ : currentCollection.status === "ready"+ ? "No entries yet. Use New entry to create one."+ : "No collection entries are available."+ }/><CreateAssetFolderDialogopen={createFolderOpen}onOpenChange={setCreateFolderOpen}+ onConfigureCollection={configureCollection}+ createCollection={createCollection}currentFolderId={folderId}+ canCreateContentCollection={+ isContentMode === false && canConfigureCollections+ }/><CreateTextFileDialogopen={createTextFileOpen}folderId={folderId}+ canCreateCollectionConfig={canConfigureCollections}onOpenChange={setCreateTextFileOpen}onCreated={setOpenedTextAssetId}/>@@ -129,6 +469,10 @@ export const AssetsPanel = ({<TextFileEditorkey={openedTextAssetId}assetId={openedTextAssetId}+ readOnly={+ canConfigureCollections === false &&+ collectionReservedAssetIds.has(openedTextAssetId)+ }onOpenChange={(open) => {if (open === false) {setOpenedTextAssetId(undefined);@@ -136,6 +480,46 @@ export const AssetsPanel = ({}}/>)}+ {entryCollection !== undefined && (+ <CreateCollectionEntryDialog+ collection={entryCollection}+ open+ onOpenChange={(nextOpen) => {+ if (nextOpen === false) {+ setEntryCollection(undefined);+ }+ }}+ />+ )}+ {entrySettings !== undefined && (+ <CollectionEntrySettingsDialog+ key={entrySettings.asset.id}+ {...entrySettings}+ onClose={() => setEntrySettings(undefined)}+ onOpenFile={() => openAsset(entrySettings.asset.id)}+ />+ )}+ {settingsCollection !== undefined &&+ isContentMode === false &&+ canConfigureCollections && (+ <CollectionSettingsDialog+ collection={settingsCollection}+ open+ onOpenChange={(nextOpen) => {+ if (nextOpen === false) {+ setSettingsCollection(undefined);+ }+ }}+ />+ )}+ {collectionToConvert !== undefined &&+ canConfigureCollections &&+ !isContentMode && (+ <ConvertCollectionDialog+ configAsset={collectionToConvert.configAsset}+ onClose={() => setCollectionToConvert(undefined)}+ />+ )}</>);};diff --git a/apps/builder/app/builder/features/assets/collection-unavailable-notice.test.tsx b/apps/builder/app/builder/features/assets/collection-unavailable-notice.test.tsxnew file mode 100644index 0000000000..6a4beeef62--- /dev/null+++ b/apps/builder/app/builder/features/assets/collection-unavailable-notice.test.tsx@@ -0,0 +1,126 @@+import { useState } from "react";+import { act } from "react-dom/test-utils";+import { afterEach, expect, test, vi } from "vitest";+import type { Asset } from "@webstudio-is/sdk";+import type { ContentCollection } from "~/builder/shared/assets";+import { createAssetManagerTestRenderer } from "~/builder/shared/asset-manager/test-utils";+import {+ CollectionRetryButton,+ CollectionUnavailableNotice,+} from "./collection-unavailable-notice";++const renderer = createAssetManagerTestRenderer();++const configAsset: Asset = {+ id: "config",+ projectId: "project",+ name: "collection.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: 1,+ createdAt: "2026-09-06T00:00:00.000Z",+ meta: {},+};++const createUnavailableCollection = (): Extract<+ ContentCollection,+ { status: "unavailable" }+> => ({+ status: "unavailable",+ folderId: "posts",+ configAsset,+ reservedAssets: [configAsset],+ siblingAssets: [configAsset],+ message: "Collection files could not be loaded: Request timed out",+});++afterEach(() => {+ renderer.cleanup();+});++test("shows retry progress until collection discovery finishes", () => {+ const onCheckAgain = vi.fn();+ let finishCheck: () => void = () => undefined;+ const Notice = () => {+ const [collection, setCollection] = useState(createUnavailableCollection);+ finishCheck = () => setCollection(createUnavailableCollection());+ return (+ <CollectionUnavailableNotice+ collection={collection}+ onCheckAgain={onCheckAgain}+ />+ );+ };+ renderer.render(<Notice />);++ const alert = document.querySelector<HTMLElement>("[role=alert]");+ expect(alert).not.toBeNull();+ // Transport diagnostics are not user-facing copy.+ expect(alert?.textContent).not.toContain("Request timed out");+ const retry = Array.from(+ document.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Retry");+ if (retry === undefined) {+ throw new Error("Expected collection retry button");+ }++ act(() => retry.click());++ expect(onCheckAgain).toHaveBeenCalledOnce();+ expect(retry).toBeDisabled();+ expect(retry.textContent).toBe("Retrying…");++ act(finishCheck);++ expect(retry).toBeEnabled();+ expect(retry.textContent).toBe("Retry");+});++test("shows the same retry progress for an invalid collection", () => {+ const onCheckAgain = vi.fn();+ let finishCheck: () => void = () => void 0;+ const InvalidRetry = () => {+ const [collection, setCollection] = useState<+ Extract<ContentCollection, { status: "invalid" }>+ >({+ status: "invalid",+ folderId: "posts",+ configAsset,+ reservedAssets: [configAsset],+ siblingAssets: [configAsset],+ repairAsset: configAsset,+ message: "Collection configuration is invalid",+ });+ finishCheck = () =>+ setCollection((current) => ({+ ...current,+ reservedAssets: [...current.reservedAssets],+ }));+ return (+ <CollectionRetryButton+ collection={collection}+ onCheckAgain={onCheckAgain}+ />+ );+ };+ renderer.render(<InvalidRetry />);+ const retry = Array.from(+ document.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Retry");+ if (retry === undefined) {+ throw new Error("Expected collection retry button");+ }++ act(() => retry.click());++ expect(onCheckAgain).toHaveBeenCalledOnce();+ expect(retry).toBeDisabled();+ expect(retry.textContent).toBe("Retrying…");++ act(finishCheck);++ expect(retry).toBeEnabled();+ expect(retry.textContent).toBe("Retry");+});diff --git a/apps/builder/app/builder/features/assets/collection-unavailable-notice.tsx b/apps/builder/app/builder/features/assets/collection-unavailable-notice.tsxnew file mode 100644index 0000000000..f953e4ec2b--- /dev/null+++ b/apps/builder/app/builder/features/assets/collection-unavailable-notice.tsx@@ -0,0 +1,61 @@+import { useState } from "react";+import { PanelBanner, Button, Flex, Text } from "@webstudio-is/design-system";+import type { ContentCollection } from "~/builder/shared/assets";++type UnavailableCollection = Extract<+ ContentCollection,+ { status: "unavailable" }+>;+type RetryableCollection = Extract<+ ContentCollection,+ { status: "invalid" | "unavailable" }+>;++export const CollectionRetryButton = ({+ collection,+ onCheckAgain,+}: {+ collection: RetryableCollection;+ onCheckAgain: () => void;+}) => {+ const [checkingCollection, setCheckingCollection] = useState<+ RetryableCollection | undefined+ >();+ const checking = checkingCollection === collection;++ return (+ <Button+ disabled={checking}+ onClick={() => {+ setCheckingCollection(collection);+ onCheckAgain();+ }}+ >+ {checking ? "Retrying…" : "Retry"}+ </Button>+ );+};++export const CollectionUnavailableNotice = ({+ collection,+ onCheckAgain,+}: {+ collection: UnavailableCollection;+ onCheckAgain: () => void;+}) => {+ return (+ <PanelBanner role="alert" variant="error" css={{ flexShrink: 0 }}>+ <Flex align="center" justify="between" gap={2}>+ <Text>+ Couldn’t load collection settings. Retry to use collection actions.+ </Text>+ <Flex>+ <CollectionRetryButton+ collection={collection}+ onCheckAgain={onCheckAgain}+ />+ </Flex>+ </Flex>+ </PanelBanner>+ );+};diff --git a/apps/builder/app/builder/features/blocking-alerts/blocking-alerts.tsx b/apps/builder/app/builder/features/blocking-alerts/blocking-alerts.tsxindex 3db5767475..18f831090b 100644--- a/apps/builder/app/builder/features/blocking-alerts/blocking-alerts.tsx+++ b/apps/builder/app/builder/features/blocking-alerts/blocking-alerts.tsx@@ -3,6 +3,7 @@ import { Alert } from "./alert";import { useWindowResizeDebounced } from "~/shared/dom-hooks";import { isFeatureEnabled } from "@webstudio-is/feature-flags";import {+ PanelContent,Button,Dialog,DialogActions,@@ -11,7 +12,6 @@ import {DialogTitle,Link,Text,- theme,} from "@webstudio-is/design-system";import { $isPreviewMode } from "~/shared/nano-states";import { useStore } from "@nanostores/react";@@ -63,7 +63,7 @@ export const UnsupportedBrowserDialog = ({<DialogContent width={480}><DialogTitle>Unsupported browser</DialogTitle><DialogDescription asChild>- <Text css={{ padding: theme.panel.padding }}>+ <PanelContent as={Text}>The Webstudio Builder UI currently supports any{" "}<Linkhref="https://en.wikipedia.org/wiki/Chromium_(web_browser)"@@ -115,7 +115,7 @@ export const UnsupportedBrowserDialog = ({<br />The website you're building should function correctly across allbrowsers!- </Text>+ </PanelContent></DialogDescription><DialogActions><Button autoFocus onClick={onDismiss}>diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsxindex 2cd570e27e..d7754f7927 100644--- a/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsx+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsx@@ -1,6 +1,7 @@import { Fragment, useState, useMemo } from "react";import { createId, type Breakpoint } from "@webstudio-is/sdk";import {+ PanelContent,theme,Flex,PanelTitle,@@ -318,14 +319,14 @@ export const BreakpointsEditor = ({{allBreakpoints.map((breakpoint, index, all) => {return (<Fragment key={breakpoint.id}>- <Box css={{ p: theme.panel.padding }}>+ <PanelContent as={Box}><BreakpointEditorItembreakpoint={breakpoint}onChangeComplete={handleChangeComplete}onDelete={onDelete}autoFocus={index === 0}/>- </Box>+ </PanelContent>{index < all.length - 1 && <PopoverSeparator />}</Fragment>);diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsxindex 07c1e8cffc..7146bc4d07 100644--- a/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsx+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsx@@ -1,5 +1,6 @@import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";import {+ PanelContent,Flex,Button,Text,@@ -106,11 +107,7 @@ export const BreakpointsMenu = ({<DropdownMenuSeparator />)}- <Flex- align="center"- justify="center"- css={{ padding: theme.panel.padding }}- >+ <PanelContent as={Flex} align="center" justify="center"><ButtononClick={() => {onEditClick();@@ -119,7 +116,7 @@ export const BreakpointsMenu = ({>Edit breakpoints</Button>- </Flex>+ </PanelContent></DropdownMenuContent></DropdownMenu>);diff --git a/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsx b/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsxindex 7071d1fa4b..4de6f8fbfc 100644--- a/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsx+++ b/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsx@@ -1,5 +1,6 @@import { useStore } from "@nanostores/react";import {+ PanelContent,theme,Flex,Label,@@ -50,7 +51,7 @@ export const CanvasSettingsPopover = () => {align="start"css={{ width: theme.spacing[30] }}>- <Flex css={{ padding: theme.panel.padding }} gap="3">+ <PanelContent as={Flex} gap="3"><WidthInput min={minCanvasWidth} /><Flex align="center" gap="2"><Label>Scale</Label>@@ -60,7 +61,7 @@ export const CanvasSettingsPopover = () => {readOnly/></Flex>- </Flex>+ </PanelContent></PopoverContent></Popover>);diff --git a/apps/builder/app/builder/features/components/components.tsx b/apps/builder/app/builder/features/components/components.tsxindex fb5da134e0..8d205ee0f3 100644--- a/apps/builder/app/builder/features/components/components.tsx+++ b/apps/builder/app/builder/features/components/components.tsx@@ -10,6 +10,7 @@ import {listComponentCatalogAvailableComponents,} from "@webstudio-is/project-build/runtime";import {+ PanelContent,theme,Flex,ComponentCard,@@ -172,13 +173,13 @@ export const ComponentsPanel = ({<PanelTitle>Components</PanelTitle><Separator />- <Box css={{ padding: theme.panel.padding }}>+ <PanelContent as={Box}><SearchField{...searchFieldProps}autoFocusplaceholder="Find components"/>- </Box>+ </PanelContent><Separator /><ScrollArea ref={draggableContainerRef}>diff --git a/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.tsx b/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.tsxindex 028040b699..913050ca60 100644--- a/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.tsx+++ b/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.tsx@@ -1,5 +1,6 @@import { useStore } from "@nanostores/react";import {+ PanelContent,Dialog,DialogTitle,DialogContent,@@ -324,10 +325,10 @@ export const KeyboardShortcutsDialog = () => {><DialogTitle>Keyboard shortcuts</DialogTitle><ScrollArea>- <Grid columns={2} gap={3} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} columns={2} gap={3}><Grid gap={5}>{leftCategories.map(renderCategory)}</Grid><Grid gap={5}>{rightCategories.map(renderCategory)}</Grid>- </Grid>+ </PanelContent></ScrollArea></DialogContent></Dialog>diff --git a/apps/builder/app/builder/features/marketplace/card.tsx b/apps/builder/app/builder/features/marketplace/card.tsxindex c47589898e..35f26100fe 100644--- a/apps/builder/app/builder/features/marketplace/card.tsx+++ b/apps/builder/app/builder/features/marketplace/card.tsx@@ -1,5 +1,6 @@import { forwardRef } from "react";import {+ PanelContent,Flex,Text,theme,@@ -106,13 +107,13 @@ export const Card = forwardRef<HTMLDivElement, CardProps>(ref) => {return (- <Flex+ <PanelContent+ as={Flex}{...props}ref={ref}direction="column"data-state={state}css={{- padding: theme.panel.padding,position: "relative",overflow: "hidden",outline: "none",@@ -131,7 +132,7 @@ export const Card = forwardRef<HTMLDivElement, CardProps>(</Text>{suffix}</Flex>- </Flex>+ </PanelContent>);});diff --git a/apps/builder/app/builder/features/marketplace/templates.tsx b/apps/builder/app/builder/features/marketplace/templates.tsxindex 48cf4af32f..b7a1ff4a06 100644--- a/apps/builder/app/builder/features/marketplace/templates.tsx+++ b/apps/builder/app/builder/features/marketplace/templates.tsx@@ -7,13 +7,13 @@ import {import { executeRuntimeMutation } from "~/shared/instance-utils/data";import { useMemo } from "react";import {+ PanelContent,Button,Flex,List,ListItem,ScrollArea,Separator,- theme,Link,Tooltip,} from "@webstudio-is/design-system";@@ -190,11 +190,11 @@ export const Templates = ({return (<Flex direction="column" css={{ height: "100%" }}>- <Flex+ <PanelContent+ as={Flex}align="center"shrink="false"justify="between"- css={{ padding: theme.panel.padding }}gap="3"><Button@@ -230,7 +230,7 @@ export const Templates = ({<ExternalLinkIcon /></Link></Tooltip>- </Flex>+ </PanelContent><Separator /><ScrollArea>{Array.from(templatesDataByCategory.keys())diff --git a/apps/builder/app/builder/features/navigator/css-preview.tsx b/apps/builder/app/builder/features/navigator/css-preview.tsxindex 2313a00f7e..779a7c55e0 100644--- a/apps/builder/app/builder/features/navigator/css-preview.tsx+++ b/apps/builder/app/builder/features/navigator/css-preview.tsx@@ -1,6 +1,7 @@import { computed } from "nanostores";import { useStore } from "@nanostores/react";import {+ PanelContent,ScrollArea,css,textVariants,@@ -92,14 +93,14 @@ export const CssPreview = () => {}return (<CollapsibleSection label="CSS preview" fullWidth showSeparator={false}>- <ScrollArea css={{ padding: theme.panel.padding }}>+ <PanelContent as={ScrollArea}><pre tabIndex={0} className={preStyle()}><divstyle={{ whiteSpace: "break-spaces" }}dangerouslySetInnerHTML={{ __html: code }}></div></pre>- </ScrollArea>+ </PanelContent></CollapsibleSection>);};diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.test.ts b/apps/builder/app/builder/features/navigator/navigator-tree.test.tsindex 27baf72001..bc8c7883cc 100644--- a/apps/builder/app/builder/features/navigator/navigator-tree.test.ts+++ b/apps/builder/app/builder/features/navigator/navigator-tree.test.ts@@ -3,6 +3,7 @@ import {blockBodyComponent,blockComponent,elementComponent,+ contentBlockSourceProp,} from "@webstudio-is/sdk";import { $flatTree, __testing__ } from "./navigator-tree";import {@@ -11,10 +12,11 @@ import {$selectedPageId,selectInstances,} from "~/shared/nano-states";-import { $instances, $pages } from "~/shared/sync/data-stores";+import { $instances, $pages, $props } from "~/shared/sync/data-stores";import { $externalContentRoots } from "~/shared/external-content-mutations";const {+ getMdxContentSource,commitNavigatorDrop,getFocusSelectionSkipCountAfterPointerDown,getBuilderDropTarget,@@ -26,6 +28,102 @@ const {shouldSelectOnPointerDown,} = __testing__;+test("identifies only the connected MDX Body, including an empty Body", () => {+ const previousRoots = $externalContentRoots.get();+ $instances.set(+ new Map([+ [+ "block",+ {+ id: "block",+ type: "instance",+ component: blockComponent,+ children: [+ { type: "id", value: "body" },+ { type: "id", value: "shell" },+ ],+ },+ ],+ [+ "body",+ {+ id: "body",+ type: "instance",+ component: blockBodyComponent,+ children: [],+ },+ ],+ [+ "shell",+ {+ id: "shell",+ type: "instance",+ component: elementComponent,+ tag: "div",+ children: [],+ },+ ],+ ])+ );+ $props.set(new Map());+ expect(getMdxContentSource(["body", "block"])).toBeUndefined();+ $props.set(+ new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset",+ value: "article",+ },+ ],+ ])+ );+ try {+ expect(getMdxContentSource(["body", "block"])).toEqual({+ assetId: "article",+ });+ expect(getMdxContentSource(["shell", "block"])).toBeUndefined();+ expect(getMdxContentSource(["block"])).toBeUndefined();+ $props.set(+ new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "expression",+ value: "collection.data._id",+ },+ ],+ ])+ );+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ blockInstanceId: "block",+ contentInstanceId: "body",+ assetId: "article",+ instanceIds: new Set(),+ mutationRevision: 0,+ },+ ],+ ])+ );+ expect(getMdxContentSource(["body", "block"])).toEqual({+ assetId: "article",+ });+ } finally {+ $props.set(new Map());+ $externalContentRoots.set(previousRoots);+ }+});+const createTreeItem = ({parentComponent = "Box",}: { parentComponent?: string } = {}): Parameters<diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.tsx b/apps/builder/app/builder/features/navigator/navigator-tree.tsxindex d34bd1829f..2915f10785 100644--- a/apps/builder/app/builder/features/navigator/navigator-tree.tsx+++ b/apps/builder/app/builder/features/navigator/navigator-tree.tsx@@ -8,6 +8,10 @@ import { mergeRefs } from "@react-aria/utils";import { useStore } from "@nanostores/react";import {Box,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,cssVar,keyframes,ScrollArea,@@ -28,6 +32,8 @@ import {ROOT_INSTANCE_ID,collectionComponent,blockBodyComponent,+ contentBlockSourceProp,+ getContentBlockSource,blockComponent,rootComponent,blockTemplateComponent,@@ -40,6 +46,8 @@ import {EyeClosedIcon,EyeOpenIcon,InfoCircleIcon,+ MarkdownEmbedIcon,+ SettingsIcon,} from "@webstudio-is/icons";import {$allSelectedInstanceSelectors,@@ -85,12 +93,87 @@ import {externalContentInstanceNameMessage,isExternalContentInstance,resolveExternalContentOccurrence,+ findExternalContentRoot,} from "~/shared/external-content-mutations";import {getInstanceLabel,InstanceIcon,} from "~/builder/shared/instance-label";import { InstanceContextMenu } from "~/builder/shared/instance-context-menu";+import { TextFileEditor } from "../text-file-editor/text-file-editor";++const getMdxContentSource = (selector: InstanceSelector) => {+ const instances = $instances.get();+ if (instances.get(selector[0])?.component !== blockBodyComponent) {+ return;+ }+ const blockIndex = selector.findIndex(+ (id) => instances.get(id)?.component === blockComponent+ );+ if (blockIndex === -1) {+ return;+ }+ const blockSelector = selector.slice(blockIndex);+ const root =+ Array.from($externalContentRoots.get().values()).find(+ (root) =>+ root.contentInstanceId === selector[0] &&+ root.blockInstanceId === blockSelector[0]+ ) ??+ findExternalContentRoot(+ $externalContentRoots.get(),+ blockSelector[0],+ JSON.stringify(blockSelector)+ );+ const source = getContentBlockSource({+ blockInstanceId: root?.sourceBlockInstanceId ?? blockSelector[0],+ props: $props.get().values(),+ });+ if (source === undefined) {+ return;+ }+ const value = $propValuesByInstanceSelector+ .get()+ .get(getInstanceKey(blockSelector))+ ?.get(contentBlockSourceProp);+ return {+ assetId:+ source.type === "asset"+ ? source.assetId+ : (root?.assetId ??+ (typeof value === "string" && value !== "" ? value : undefined)),+ };+};++const MdxContentMenu = ({ assetId }: { assetId?: string }) => {+ const [open, setOpen] = useState(false);+ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <SmallIconButton+ aria-label="MDX content settings"+ icon={<SettingsIcon />}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ onCloseAutoFocus={(event) => {+ if (open) {+ event.preventDefault();+ }+ }}+ >+ <DropdownMenuItem disabled={!assetId} onSelect={() => setOpen(true)}>+ Open MDX file+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ {open && assetId && (+ <TextFileEditor assetId={assetId} onOpenChange={setOpen} />+ )}+ </>+ );+};type TreeItemAncestor =| undefined@@ -540,11 +623,13 @@ const EditableTreeNodeLabel = styled("div", {const TreeNodeContent = ({instance,+ mdx = false,isEditing,isNameEditable,onIsEditingChange,}: {instance: Instance;+ mdx?: boolean;isEditing: boolean;isNameEditable: boolean;onIsEditingChange: (isEditing: boolean) => void;@@ -552,7 +637,7 @@ const TreeNodeContent = ({const editableRef = useRef<HTMLDivElement | null>(null);const [error, setError] = useState<string>();- const label = getInstanceLabel(instance);+ const label = mdx ? "MDX content" : getInstanceLabel(instance);const { ref, handlers } = useContentEditable({value: label,isEditable: isNameEditable,@@ -581,9 +666,19 @@ const TreeNodeContent = ({});return (- <TreeNodeLabel prefix={<InstanceIcon instance={instance} />}>+ <TreeNodeLabel+ prefix={+ mdx ? <MarkdownEmbedIcon /> : <InstanceIcon instance={instance} />+ }+ ><Tooltip- content={isNameEditable ? error : externalContentInstanceNameMessage}+ content={+ mdx+ ? "Content inside this region is saved to the connected MDX file. Other instances in this Content Block are saved in the project."+ : isNameEditable+ ? error+ : externalContentInstanceNameMessage+ }delayDuration={0}><EditableTreeNodeLabel@@ -1038,7 +1133,7 @@ export const NavigatorTree = () => {</Text>}>- <InfoCircleIcon />+ <InfoCircleIcon color={cssVar("--foreground-secondary")} /></Tooltip>}>@@ -1081,6 +1176,7 @@ export const NavigatorTree = () => {const isAnimating = isAnimationSelected || isAnimationPinned;const meta = metas.get(item.instance.component);+ const mdxSource = getMdxContentSource(item.selector);if (meta === undefined) {return;@@ -1124,7 +1220,7 @@ export const NavigatorTree = () => {isSelectedDescendant={isSelectedDescendantItem}isHighlighted={hoveredKey === key || dropTargetKey === key}isExpanded={item.isExpanded}- isActionVisible={isAnimating}+ isActionVisible={isAnimating || mdxSource !== undefined}onExpand={(isExpanded, all) =>handleExpand(item, isExpanded, all)}@@ -1160,16 +1256,22 @@ export const NavigatorTree = () => {onKeyUp: handleKeyUp,}}action={- <ShowToggle- instance={item.instance}- value={show}- isAnimating={isAnimating}- />+ mdxSource ? (+ <MdxContentMenu assetId={mdxSource.assetId} />+ ) : (+ <ShowToggle+ instance={item.instance}+ value={show}+ isAnimating={isAnimating}+ />+ )}><TreeNodeContentinstance={item.instance}+ mdx={mdxSource !== undefined}isNameEditable={+ mdxSource === undefined &&isExternalContentInstance(externalContentRoots,item.instance.id@@ -1199,6 +1301,8 @@ export const NavigatorTree = () => {};export const __testing__ = {+ MdxContentMenu,+ getMdxContentSource,commitNavigatorDrop,getFocusSelectionSkipCountAfterPointerDown,getBuilderDropTarget,diff --git a/apps/builder/app/builder/features/pages/confirmation-dialogs.tsx b/apps/builder/app/builder/features/pages/confirmation-dialogs.tsxindex 2d9c829abc..8f3f5f6bd6 100644--- a/apps/builder/app/builder/features/pages/confirmation-dialogs.tsx+++ b/apps/builder/app/builder/features/pages/confirmation-dialogs.tsx@@ -1,4 +1,5 @@import {+ PanelContent,Dialog,DialogActions,DialogContent,@@ -7,7 +8,6 @@ import {Flex,Text,Button,- theme,} from "@webstudio-is/design-system";import type { Page, Folder, PageTemplate } from "@webstudio-is/sdk";import { getPageDisplayName } from "./page-utils";@@ -34,13 +34,13 @@ export const DeletePageConfirmationDialog = ({><DialogContent><DialogTitle>Delete page</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column"><Text>{`Are you sure you want to delete "${getPageDisplayName(page)}"?`}</Text><Text>You can undo it even if you delete the page as long as you don'treload.</Text>- </Flex>+ </PanelContent><DialogActions><ButtonautoFocus@@ -82,9 +82,9 @@ export const DeleteFolderConfirmationDialog = ({><DialogContent><DialogTitle>Delete confirmation</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column"><Text>{`Delete folder "${folder.name}" including all of its pages?`}</Text>- </Flex>+ </PanelContent><DialogActions><ButtonautoFocus@@ -126,13 +126,13 @@ export const DeleteTemplateConfirmationDialog = ({><DialogContent><DialogTitle>Delete template</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column"><Text>{`Are you sure you want to delete the template "${template.name}"?`}</Text><Text>You can undo it even if you delete the template as long as you don'treload.</Text>- </Flex>+ </PanelContent><DialogActions><ButtonautoFocusdiff --git a/apps/builder/app/builder/features/pages/folder-settings.tsx b/apps/builder/app/builder/features/pages/folder-settings.tsxindex bc868b0d33..eff0ba6e5b 100644--- a/apps/builder/app/builder/features/pages/folder-settings.tsx+++ b/apps/builder/app/builder/features/pages/folder-settings.tsx@@ -1,5 +1,6 @@import { useStore } from "@nanostores/react";import {+ PanelContent,Button,cssVar,DialogClose,@@ -80,7 +81,7 @@ const FormFields = ({return (<Grid css={{ height: "100%" }}><ScrollArea>- <Grid gap={3} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} gap={3}><Grid gap={1}><Label htmlFor={fieldIds.name}>Folder name</Label><InputErrorsTooltip errors={errors.name}>@@ -132,7 +133,7 @@ const FormFields = ({/></InputErrorsTooltip></Grid>- </Grid>+ </PanelContent></ScrollArea></Grid>);diff --git a/apps/builder/app/builder/features/pages/image-info.tsx b/apps/builder/app/builder/features/pages/image-info.tsxindex 330103137d..1240243367 100644--- a/apps/builder/app/builder/features/pages/image-info.tsx+++ b/apps/builder/app/builder/features/pages/image-info.tsx@@ -1,4 +1,5 @@import {+ PanelContent,cssVar,IconButton,Text,@@ -43,9 +44,10 @@ export const ImageInfo = ({pr: theme.spacing[5],}}>- <Grid+ <PanelContent+ as={Grid}columns={1}- css={{ padding: theme.panel.padding, width: theme.spacing[34] }}+ css={{ width: theme.spacing[34] }}gap={2}align={"center"}>@@ -73,7 +75,7 @@ export const ImageInfo = ({</Text></Flex></Grid>- </Grid>+ </PanelContent></Grid><IconButton onClick={onDelete} disabled={disabled}><TrashIcon />diff --git a/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx b/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsxindex 388a57f156..df9e09d447 100644--- a/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx+++ b/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx@@ -1,6 +1,7 @@import { useId } from "react";import { useStore } from "@nanostores/react";import {+ PanelContent,Box,Button,cssVar,@@ -39,7 +40,7 @@ export const MarketplaceSection = ({const thumbnailAsset = assets.get(values.marketplace.thumbnailAssetId);const thumnailFallbackAsset = assets.get(values.socialImageAssetId);return (- <Grid gap={2} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} gap={2}><Gridflow="column"gap={1}@@ -117,6 +118,6 @@ export const MarketplaceSection = ({</Grid></Box></Grid>- </Grid>+ </PanelContent>);};diff --git a/apps/builder/app/builder/features/publish/collapsible-domain-section.stories.tsx b/apps/builder/app/builder/features/publish/collapsible-domain-section.stories.tsxindex d30cec39cc..6fd3b785f1 100644--- a/apps/builder/app/builder/features/publish/collapsible-domain-section.stories.tsx+++ b/apps/builder/app/builder/features/publish/collapsible-domain-section.stories.tsx@@ -1,4 +1,5 @@import {+ PanelContent,Flex,Grid,Text,@@ -484,9 +485,9 @@ export const PublishDialogLayout = () => (<Separator /></Flex>- <Flex direction="column" gap="2" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} direction="column" gap="2"><Button color="primary">Publish</Button>- </Flex>+ </PanelContent></Flex></StorySection>);@@ -504,7 +505,7 @@ export const ExportDialogLayout = () => (}}><PopoverTitle>Export</PopoverTitle>- <Grid columns={1} gap={3} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} columns={1} gap={3}><Grid columns={2} gap={2} align="center"><Text color="main" variant="labels">Destination@@ -580,7 +581,7 @@ export const ExportDialogLayout = () => (</Button></Flex></Grid>- </Grid>+ </PanelContent></Flex></Popover></StorySection>@@ -599,7 +600,7 @@ export const ExportStaticLayout = () => (}}><PopoverTitle>Export</PopoverTitle>- <Grid columns={1} gap={3} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} columns={1} gap={3}><Grid columns={2} gap={2} align="center"><Text color="main" variant="labels">Destination@@ -620,7 +621,7 @@ export const ExportStaticLayout = () => (here</Link></Text>- </Grid>+ </PanelContent></Flex></Popover></StorySection>diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsxindex 7e0fa95796..92244c4cf7 100644--- a/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx@@ -14,13 +14,44 @@ export const showContentDatabasePublishWarning = async ({await nativeClient.build.contentDatabasePublishDiagnostics.query({projectId,});- if (- diagnostics === undefined ||- diagnostics.stats.truncated === false ||- diagnostics.stats.omissionReason === undefined- ) {+ const databaseWarning =+ diagnostics.stats?.truncated &&+ diagnostics.stats.omissionReason !== undefined;+ if (!databaseWarning && diagnostics.mdxOmissions.length === 0) {return;}- const message = <ContentDatabasePublishWarning diagnostics={diagnostics} />;+ const message = (+ <>+ {diagnostics.mdxOmissions.length > 0 && (+ <div>+ Some MDX content cannot render because its custom template is missing+ or ambiguous. Add or repair the template in the Content Block:+ <ul>+ {diagnostics.mdxOmissions.slice(0, 10).map((issue) => (+ <li key={JSON.stringify(issue)}>+ {issue.filename}: {issue.templateName}+ </li>+ ))}+ </ul>+ {diagnostics.mdxOmissions.length > 10 && (+ <div>+ And {diagnostics.mdxOmissions.length - 10} more template+ references.+ </div>+ )}+ </div>+ )}+ {databaseWarning &&+ diagnostics.stats !== undefined &&+ diagnostics.affectedResources !== undefined && (+ <ContentDatabasePublishWarning+ diagnostics={{+ stats: diagnostics.stats,+ affectedResources: diagnostics.affectedResources,+ }}+ />+ )}+ </>+ );showPublishWarning({ message, setWarning });};diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsxindex e939b8023c..95975b8dfc 100644--- a/apps/builder/app/builder/features/publish/publish.tsx+++ b/apps/builder/app/builder/features/publish/publish.tsx@@ -11,6 +11,7 @@ import {} from "react";import { useStore } from "@nanostores/react";import {+ PanelContent,Button,cssVar,Tooltip,@@ -1108,7 +1109,7 @@ const Content = (props: {<Flex direction="column" justify="end" css={{ height: 0 }}><Separator /></Flex>- <Flex direction="column" gap="2" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} direction="column" gap="2"><AddDomainprojectId={props.projectId}refresh={refreshProject}@@ -1139,7 +1140,7 @@ const Content = (props: {disabled={false}restrictedFeatures={restrictedFeatures}/>- </Flex>+ </PanelContent></form>);};@@ -1187,7 +1188,7 @@ const ExportContent = (props: { projectId: Project["id"] }) => {const [deployTarget, setDeployTarget] = useState<DeployTargets>("docker");return (- <Grid columns={1} gap={3} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} columns={1} gap={3}><Grid columns={1} gap={2}><div /><Grid columns={2} gap={2} align={"center"}>@@ -1353,7 +1354,7 @@ const ExportContent = (props: { projectId: Project["id"] }) => {</Grid></Grid>)}- </Grid>+ </PanelContent>);};diff --git a/apps/builder/app/builder/features/safe-mode.tsx b/apps/builder/app/builder/features/safe-mode.tsxindex e22d3d0a51..dd3885cdf7 100644--- a/apps/builder/app/builder/features/safe-mode.tsx+++ b/apps/builder/app/builder/features/safe-mode.tsx@@ -1,6 +1,7 @@import { useState } from "react";import { ShieldIcon } from "@webstudio-is/icons";import {+ PanelContent,Popover,cssVar,PopoverTrigger,@@ -34,11 +35,11 @@ export const SafeModeButton = () => {</IconButton></PopoverTrigger><PopoverContent>- <Flex+ <PanelContent+ as={Flex}direction="column"gap="2"css={{- padding: theme.panel.padding,width: theme.spacing[30],}}>@@ -51,7 +52,7 @@ export const SafeModeButton = () => {<Button color="destructive" onClick={handleExitSafeMode}>Exit safe mode</Button>- </Flex>+ </PanelContent></PopoverContent></Popover>);diff --git a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx b/apps/builder/app/builder/features/settings-panel/controls/combined.tsxindex dd65e1e98a..ff38337dab 100644--- a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/combined.tsx@@ -1,4 +1,5 @@import { TextControl } from "./text";+import { DateControl } from "./date";import { CodeControl } from "./code";import { NumberControl } from "./number";import { CheckControl } from "./check";@@ -59,6 +60,10 @@ export const renderControl = ({return <TextControl key={key} meta={meta} prop={prop} {...rest} />;}+ if (meta.control === "date") {+ return <DateControl key={key} meta={meta} prop={prop} {...rest} />;+ }+if (meta.control === "resource") {return <ResourceControl key={key} meta={meta} prop={prop} {...rest} />;}diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.test.tsxindex 0734598eef..5a894be23a 100644--- a/apps/builder/app/builder/features/settings-panel/controls/content-block-source.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.test.tsx@@ -6,6 +6,9 @@ import { TooltipProvider } from "@webstudio-is/design-system";import type { Asset } from "@webstudio-is/sdk";import { $assets } from "~/shared/sync/data-stores";import { ContentBlockSourceControl } from "./content-block-source";+import { $builderMode } from "~/shared/nano-states";+import { EditorView } from "@codemirror/view";+import { userEvent } from "@vitest/browser/context";(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }@@ -256,6 +259,95 @@ test("shows only a full-width bindable connect button without a source", () => {expect(document.body.textContent).not.toContain("Create MDX file");});+test("validates source bindings only after a source is configured", () => {+ const previousMode = $builderMode.get();+ $builderMode.set("design");+ try {+ for (const source of [+ undefined,+ { type: "expression" as const, value: '\"\"' },+ undefined,+ ]) {+ act(() => {+ root.render(+ <TooltipProvider>+ <ContentBlockSourceControl+ source={source}+ readOnly={false}+ onRequestSource={async () => ({ status: "applied" })}+ onOpen={() => {}}+ />+ </TooltipProvider>+ );+ });+ const binding = container.querySelector(+ "button[data-variant] [data-variant]"+ );+ expect(binding).not.toBeNull();+ expect(binding?.getAttribute("data-variant")).toBe(+ source === undefined ? "default" : "error"+ );+ }+ } finally {+ $builderMode.set(previousMode);+ }+});++test("marks rejected bindings on the expression input with an error tooltip", async () => {+ const previousMode = $builderMode.get();+ $builderMode.set("design");+ const onRequestSource = vi.fn(async () => ({+ status: "blocked" as const,+ message: "Content source does not resolve to an MDX Asset",+ }));+ try {+ act(() =>+ root.render(+ <TooltipProvider>+ <ContentBlockSourceControl+ readOnly={false}+ onRequestSource={onRequestSource}+ onOpen={() => {}}+ />+ </TooltipProvider>+ )+ );+ await act(async () =>+ userEvent.click(container.querySelector("button[data-variant]")!)+ );+ await vi.waitFor(() =>+ expect(document.querySelector(".cm-content")).not.toBeNull()+ );+ const editor = document.querySelector<HTMLElement>(".cm-content")!;+ const view = EditorView.findFromDOM(editor)!;+ await act(async () => {+ view.dispatch({+ changes: {+ from: 0,+ to: view.state.doc.length,+ insert: '"not-an-asset"',+ },+ });+ });+ await act(async () => {+ editor.blur();+ await Promise.resolve();+ });+ expect(onRequestSource).toHaveBeenCalledOnce();+ expect(editor.closest('[data-invalid="true"]')).not.toBeNull();+ expect(document.querySelector('[role="dialog"] [role="alert"]')).toBeNull();+ expect(container.querySelector('fieldset [role="alert"]')).toBeNull();+ await act(async () => userEvent.hover(editor));+ await vi.waitFor(() =>+ expect(document.querySelector('[role="tooltip"]')?.textContent).toBe(+ "Content source does not resolve to an MDX Asset"+ )+ );+ } finally {+ $builderMode.set(previousMode);+ }+});+test("asks for confirmation before connecting over existing content", async () => {const onRequestSource = vi.fn()@@ -294,9 +386,7 @@ test("asks for confirmation before connecting over existing content", async () =expect(document.body.textContent).toContain("The MDX file will not be changed.");- expect(document.body.textContent).toContain(- "Unexpected closing tag. Line 3, column 2."- );+ expect(document.querySelector('[role="dialog"] [role="status"]')).toBeNull();const dialogButtons = Array.from(document.body.querySelectorAll<HTMLButtonElement>("button"))diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source.tsx b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.tsxindex 56584ced28..f6c989f900 100644--- a/apps/builder/app/builder/features/settings-panel/controls/content-block-source.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.tsx@@ -1,5 +1,6 @@import { useRef, useState } from "react";import {+ PanelContent,Button,Box,Dialog,@@ -42,24 +43,17 @@ type ContentBlockSourceActionResult =diagnostics?: readonly ContentBlockDiagnostic[];}>;-type PendingSource = Readonly<{- source: ContentBlockSource;- diagnostics: readonly ContentBlockDiagnostic[];-}>;-const getErrorMessage = (error: unknown, fallback: string) =>error instanceof Error ? error.message : fallback;const ConnectSourceDialog = ({disabled,error,- diagnostics,onClose,onConfirm,}: {disabled: boolean;error?: string;- diagnostics: readonly ContentBlockDiagnostic[];onClose: () => void;onConfirm: () => void;}) => (@@ -67,10 +61,10 @@ const ConnectSourceDialog = ({<DialogContent><DialogTitle>Connect content source</DialogTitle><DialogDescription asChild>- <Text css={{ padding: theme.panel.padding }}>+ <PanelContent as={Text}>Connecting this file will replace the existing Content Block content.The MDX file will not be changed.- </Text>+ </PanelContent></DialogDescription>{error !== undefined && (<Text@@ -85,17 +79,6 @@ const ConnectSourceDialog = ({{error}</Text>)}- {diagnostics.map((diagnostic) => (- <Text- key={JSON.stringify(diagnostic)}- role="status"- color="subtle"- variant="tiny"- css={{ paddingInline: theme.panel.paddingInline }}- >- {formatContentBlockDiagnostic(diagnostic)}- </Text>- ))}<DialogActions><Button disabled={disabled} onClick={onConfirm}>Connect@@ -145,10 +128,11 @@ export const ContentBlockSourceControl = ({}) => Promise<ContentBlockSourceActionResult>;onOpen: (assetId: string) => void;}) => {- const [pendingSource, setPendingSource] = useState<PendingSource>();+ const [pendingSource, setPendingSource] = useState<ContentBlockSource>();const [busy, setBusy] = useState(false);const busyRef = useRef(false);const [localError, setLocalError] = useState<string>();+ const [bindingError, setBindingError] = useState<string>();const isDisabled = disabled || loading || busy;const isSourceMutationDisabled = readOnly || isDisabled;const connected = source !== undefined;@@ -174,6 +158,7 @@ export const ContentBlockSourceControl = ({busyRef.current = true;setBusy(true);setLocalError(undefined);+ setBindingError(undefined);return true;};@@ -189,25 +174,24 @@ export const ContentBlockSourceControl = ({if (readOnly || beginOperation() === false) {return;}+ const setRequestError =+ requestedSource.type === "expression" ? setBindingError : setLocalError;try {const result = await onRequestSource({source: requestedSource,confirmed,});if (result.status === "requires-confirmation") {- setPendingSource({- source: requestedSource,- diagnostics: result.diagnostics ?? [],- });+ setPendingSource(requestedSource);return;}if (result.status === "blocked" || result.status === "partial") {- setLocalError(result.message);+ setRequestError(result.message);return;}setPendingSource(undefined);} catch (error) {- setLocalError(getErrorMessage(error, "Unable to change source"));+ setRequestError(getErrorMessage(error, "Unable to change source"));} finally {finishOperation();}@@ -221,9 +205,10 @@ export const ContentBlockSourceControl = ({showBinding={readOnly === false}value={resolvedAsset?.id}validate={(value) =>- typeof value === "string" && value !== ""+ bindingError ??+ (!connected || (typeof value === "string" && value !== "")? undefined- : "Content source must resolve to an Asset ID"+ : "Content source must resolve to an Asset ID")}onChangeValue={(value) => {if (typeof value === "string" && value !== "") {@@ -242,7 +227,7 @@ export const ContentBlockSourceControl = ({connected ? (<Grid columns={2} gap="2" aria-label="Content source actions"><Flex align="center" gap="1">- <Box css={{ flex: 1, minWidth: 0 }}>+ <Box css={{ flex: 1 }}><SelectAssetassetId={resolvedAsset?.id}title="Switch MDX file"@@ -364,9 +349,8 @@ export const ContentBlockSourceControl = ({<ConnectSourceDialogdisabled={isSourceMutationDisabled}error={localError ?? error}- diagnostics={pendingSource.diagnostics}onClose={() => setPendingSource(undefined)}- onConfirm={() => void requestSource(pendingSource.source, true)}+ onConfirm={() => void requestSource(pendingSource, true)}/>)}</Grid>diff --git a/apps/builder/app/builder/features/settings-panel/controls/date.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/date.test.tsxnew file mode 100644index 0000000000..113201c6b0--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/date.test.tsx@@ -0,0 +1,87 @@+import { act } from "react-dom/test-utils";+import { useState } from "react";+import { createRoot } from "react-dom/client";+import { expect, test, vi } from "vitest";+import { userEvent } from "@vitest/browser/context";+import { TooltipProvider } from "@webstudio-is/design-system";+import { Time } from "@webstudio-is/sdk-components-react/metas";+import { renderControl } from "./combined";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++test.each([+ ["2025-07-07", "date", "2025-07-07", "2025-08-09", "2025-08-09"],+ [+ "2025-07-07T12:30:00+02:00",+ "datetime-local",+ "2025-07-07T10:30",+ "2025-08-09T11:45",+ "2025-08-09T11:45:00.000Z",+ ],+ [+ "2025-07-07T12:30",+ "datetime-local",+ "2025-07-07T12:30",+ "2025-08-09T11:45",+ "2025-08-09T11:45",+ ],+ ["", "date", "", "2025-08-09", "2025-08-09"],+ ["not a date", "text", "not a date", "2025-08-09", "2025-08-09"],+])(+ "edits Date Time value %s without changing it on focus",+ async (source, type, displayed, edited, saved) => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const onChange = vi.fn();+ const Harness = () => {+ const [value, setValue] = useState(source);+ return (+ <TooltipProvider>+ {renderControl({+ instanceId: "date",+ propName: "datetime",+ meta: Time.props!.datetime,+ prop: {+ id: "datetime",+ instanceId: "date",+ name: "datetime",+ type: "string",+ value,+ },+ computedValue: value,+ onChange: (next) => {+ onChange(next);+ if (next.type === "string") {+ setValue(next.value);+ }+ },+ })}+ </TooltipProvider>+ );+ };+ try {+ await act(async () => root.render(<Harness />));+ const input = container.querySelector<HTMLInputElement>("input")!;+ expect(input?.type).toBe(type);+ expect(input.value).toBe(displayed);+ await act(async () => userEvent.click(input));+ await act(async () => input.blur());+ expect(onChange).not.toHaveBeenCalled();+ await act(async () => userEvent.fill(input, edited));+ await act(async () => input.blur());+ expect(onChange).toHaveBeenLastCalledWith({+ type: "string",+ value: saved,+ });+ await act(async () => userEvent.fill(input, ""));+ await act(async () => input.blur());+ expect(onChange).toHaveBeenLastCalledWith({ type: "string", value: "" });+ } finally {+ await act(async () => root.unmount());+ container.remove();+ }+ }+);diff --git a/apps/builder/app/builder/features/settings-panel/controls/date.tsx b/apps/builder/app/builder/features/settings-panel/controls/date.tsxnew file mode 100644index 0000000000..5389bf6361--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/date.tsx@@ -0,0 +1,117 @@+import { useId, useMemo } from "react";+import { InputField, Tooltip } from "@webstudio-is/design-system";+import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";+import { useDraftValue } from "~/builder/shared/use-draft-value";+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";+import {+ type ControlProps,+ ResponsiveLayout,+ humanizeAttribute,+} from "../shared";+import { PropertyLabel } from "../property-label";+import { useBindableControl } from "./use-bindable-control";++const getDateInput = (source: string) => {+ // Let the platform recognize native date and local date-time values. Keep+ // legacy/invalid values editable instead of silently clearing them.+ const input = document.createElement("input");+ for (const type of ["date", "datetime-local"] as const) {+ input.type = type;+ input.value = source;+ if (input.value !== "" || source === "") {+ return { type, value: input.value, utc: false };+ }+ }+ const date = new Date(source);+ if (Number.isNaN(date.getTime()) === false) {+ input.type = "datetime-local";+ input.value = date.toISOString().slice(0, -1);+ if (input.value !== "") {+ return { type: "datetime-local" as const, value: input.value, utc: true };+ }+ }+ return { type: "text" as const, value: source, utc: false };+};++export const DateControl = ({+ meta,+ prop,+ propName,+ computedValue,+ onChange,+}: ControlProps<"date">) => {+ const id = useId();+ const source = String(computedValue ?? "");+ const input = useMemo(() => getDateInput(source), [source]);+ const binding = useBindableControl({+ boundExpression: prop?.type === "expression" ? prop : undefined,+ fallbackExpression: JSON.stringify(computedValue),+ });+ const localValue = useDraftValue(input.value, (value) => {+ if (binding.bindingState.overwritable === false) {+ return;+ }+ onChange({+ type: "string",+ value:+ value !== "" && input.utc ? new Date(`${value}Z`).toISOString() : value,+ });+ });+ const label = humanizeAttribute(meta.label || propName);+ return (+ <ResponsiveLayout+ label={+ <PropertyLabel+ name={propName}+ readOnly={binding.bindingState.overwritable === false}+ />+ }+ >+ <BindableExpressionControl+ {...binding}+ value={source}+ validate={(value) => validatePrimitiveValue(value, label)}+ onChangeValue={(value) => onChange({ type: "string", value })}+ onChangeExpression={(value) => onChange({ type: "expression", value })}+ onRemove={(value) => onChange({ type: "string", value: String(value) })}+ renderControl={({ readOnly }) => (+ <Tooltip+ content={+ binding.fieldError ??+ (input.utc+ ? "Date and time in UTC. Display formatting and time zone are configured separately."+ : "")+ }+ open={+ binding.fieldError === undefined && input.utc === false+ ? false+ : undefined+ }+ >+ <InputField+ id={id}+ aria-label={input.utc ? `${label} (UTC)` : label}+ type={input.type}+ step="any"+ value={localValue.value}+ disabled={readOnly}+ color={binding.fieldError === undefined ? undefined : "error"}+ aria-invalid={binding.fieldError !== undefined || undefined}+ onChange={(event) => {+ if (event.currentTarget.validity.badInput === false) {+ localValue.set(event.currentTarget.value);+ }+ }}+ onBlur={localValue.save}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ localValue.save();+ }+ }}+ />+ </Tooltip>+ )}+ />+ </ResponsiveLayout>+ );+};diff --git a/apps/builder/app/builder/features/settings-panel/controls/number.tsx b/apps/builder/app/builder/features/settings-panel/controls/number.tsxindex 501b74fd57..95eec7c1ae 100644--- a/apps/builder/app/builder/features/settings-panel/controls/number.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/number.tsx@@ -1,5 +1,5 @@import { useId, useState } from "react";-import { InputField } from "@webstudio-is/design-system";+import { InputField, Tooltip } from "@webstudio-is/design-system";import { useDraftValue } from "~/builder/shared/use-draft-value";import { BindableExpressionControl } from "~/builder/shared/bindable-expression";import {@@ -72,25 +72,37 @@ export const NumberControl = ({});}}renderControl={({ readOnly }) => (- <InputField- id={id}- disabled={readOnly}- type="number"- value={localValue.value}- color={isInvalid ? "error" : undefined}- onChange={({ target: { valueAsNumber, value } }) => {- localValue.set(- Number.isNaN(valueAsNumber) ? value : valueAsNumber- );- setIsInvalid(false);- }}- onBlur={localValue.save}- onKeyDown={(event) => {- if (event.key === "Enter") {- localValue.save();+ <Tooltip+ content={binding.fieldError ?? ""}+ open={binding.fieldError === undefined ? false : undefined}+ >+ <InputField+ id={id}+ disabled={readOnly}+ type="number"+ value={localValue.value}+ color={+ isInvalid || binding.fieldError !== undefined+ ? "error"+ : undefined}- }}- />+ aria-invalid={+ isInvalid || binding.fieldError !== undefined || undefined+ }+ onChange={({ target: { valueAsNumber, value } }) => {+ localValue.set(+ Number.isNaN(valueAsNumber) ? value : valueAsNumber+ );+ setIsInvalid(false);+ }}+ onBlur={localValue.save}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ localValue.save();+ }+ }}+ />+ </Tooltip>)}/></ResponsiveLayout>diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsxindex c8ed0e4c95..ddf80d43df 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.test.tsx@@ -2,12 +2,17 @@ import { act } from "react-dom/test-utils";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, test, vi } from "vitest";import { EditorView } from "@codemirror/view";-import { TooltipProvider } from "@webstudio-is/design-system";+import { TooltipProvider, toast } from "@webstudio-is/design-system";import { textContentAttribute } from "@webstudio-is/react-sdk";-import type { Instance } from "@webstudio-is/sdk";+import { encodeDataSourceVariable, type Instance } from "@webstudio-is/sdk";import { createDefaultPages } from "@webstudio-is/project-build";-import { $builderMode } from "~/shared/nano-states";-import { $instances, $pages } from "~/shared/sync/data-stores";+import { $builderMode, selectInstance } from "~/shared/nano-states";+import { $instances, $pages, $props } from "~/shared/sync/data-stores";+import { $externalContentRoots } from "~/shared/external-content-mutations";+import {+ createAssetContentBridge,+ __testing__,+} from "~/shared/asset-content-bridge.client";import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";import { TextContent } from "./text-content";@@ -23,6 +28,7 @@ const rangeGetClientRects = Object.getOwnPropertyDescriptor(Range.prototype,"getClientRects");+const { initBridge, clearBridge } = __testing__;const setReadingTimeChildren = (children: Instance["children"]) => {$instances.set(@@ -72,6 +78,11 @@ afterEach(() => {act(() => root.unmount());container.remove();$instances.set(new Map());+ $props.set(new Map());+ $externalContentRoots.set(new Map());+ selectInstance(undefined);+ clearBridge();+ vi.restoreAllMocks();vi.unstubAllGlobals();if (rangeGetClientRects === undefined) {delete (Range.prototype as { getClientRects?: unknown }).getClientRects;@@ -84,6 +95,109 @@ afterEach(() => {}});+test("shows the actual canvas-frame error when a frontmatter text edit fails", async () => {+ const frame = document.createElement("iframe");+ document.body.appendChild(frame);+ try {+ const foreignError = new (+ frame.contentWindow as Window & typeof globalThis+ ).Error("The authoring reference changed. Reload before editing.");+ expect(foreignError).not.toBeInstanceOf(Error);+ const showError = vi+ .spyOn(toast, "error")+ .mockImplementation(() => "test-toast");+ const bridge = createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: () => {},+ });+ bridge.registerFrontmatterWriter({+ rootKey: "root",+ projectId: "project",+ assetId: "article",+ update: async () => {+ throw foreignError;+ },+ });+ initBridge(bridge);+ setReadingTimeChildren([+ {+ type: "expression",+ value: `${encodeDataSourceVariable("document")}.frontmatter.name`,+ mode: "readwrite",+ },+ ]);+ $instances.set(+ new Map($instances.get()).set("block", {+ id: "block",+ type: "instance",+ component: "ws:block",+ children: [{ type: "id", value: "reading-time" }],+ })+ );+ $props.set(+ new Map([+ [+ "document",+ {+ id: "document",+ instanceId: "block",+ name: "document",+ type: "parameter",+ value: "document",+ },+ ],+ ])+ );+ $props.set(+ new Map($props.get()).set("source", {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "article",+ })+ );+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ assetId: "article",+ blockInstanceId: "block",+ instanceIds: new Set(["reading-time"]),+ mutationRevision: 0,+ document: {+ children: [],+ frontmatter: { properties: { name: "Before" } },+ },+ },+ ],+ ])+ );+ $builderMode.set("content");+ selectInstance(["reading-time", "block"]);+ renderTextContent("Before");+ const element = container.querySelector<HTMLElement>('[role="textbox"]')!;+ const view = EditorView.findFromDOM(element)!;+ act(() => {+ view.dispatch({+ changes: { from: 0, to: view.state.doc.length, insert: "After" },+ });+ });+ await act(async () => {+ view.focus();+ view.contentDOM.blur();+ });+ await vi.waitFor(() =>+ expect(showError).toHaveBeenCalledWith(foreignError.message)+ );+ } finally {+ frame.remove();+ }+});+const renderTextContent = (computedValue = " · 2") => {act(() => {root.render(diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsxindex d72f37cd9f..3df3b30494 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx@@ -9,6 +9,7 @@ import {DialogTitleActions,Flex,Text,+ Tooltip,toast,} from "@webstudio-is/design-system";import type { ExpressionBindingMode, Instance } from "@webstudio-is/sdk";@@ -28,6 +29,7 @@ import { useBindableControl } from "./use-bindable-control";import { evaluateExpressionWithinScope } from "~/builder/shared/binding-popover";import { getTextContentUpdateOperation } from "./text-content-utils";import { useCodeTextLanguageSupport } from "./code";+import { parseError } from "~/shared/error/error-parse";const useInstance = (instanceId: Instance["id"]) => {const $store = useMemo(() => {@@ -118,11 +120,7 @@ export const TextContent = ({const localValue = useDraftValue(String(displayedValue ?? ""), (value) => {if (child.type === "expression") {void binding.writeBoundValue?.(value).catch((error) => {- toast.error(- error instanceof Error- ? error.message- : "Unable to update MDX frontmatter"- );+ toast.error(parseError(error).message);});return;}@@ -181,27 +179,34 @@ export const TextContent = ({}onRemove={resetBindings}renderControl={({ readOnly }) => (- <CodeEditor- title={- <DialogTitle- maximizable- suffix={- <DialogTitleActions>- <DialogMaximize />- <DialogClose />- </DialogTitleActions>- }- >- <Text variant="labels">Text content</Text>- </DialogTitle>- }- size="small"- languageSupport={languageSupport}- readOnly={readOnly}- value={localValue.value}- onChange={localValue.set}- onChangeComplete={localValue.save}- />+ <Tooltip+ content={binding.fieldError ?? ""}+ open={binding.fieldError === undefined ? false : undefined}+ >+ <CodeEditor+ aria-invalid={binding.fieldError !== undefined || undefined}+ color={binding.fieldError === undefined ? undefined : "error"}+ title={+ <DialogTitle+ maximizable+ suffix={+ <DialogTitleActions>+ <DialogMaximize />+ <DialogClose />+ </DialogTitleActions>+ }+ >+ <Text variant="labels">Text content</Text>+ </DialogTitle>+ }+ size="small"+ languageSupport={languageSupport}+ readOnly={readOnly}+ value={localValue.value}+ onChange={localValue.set}+ onChangeComplete={localValue.save}+ />+ </Tooltip>)}/></VerticalLayout>diff --git a/apps/builder/app/builder/features/settings-panel/controls/text.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/text.test.tsxindex c8e765f614..0371416cb5 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text.test.tsx@@ -10,7 +10,22 @@ import {type Prop,} from "@webstudio-is/sdk";import { $builderMode, selectInstance } from "~/shared/nano-states";-import { $instances, $props } from "~/shared/sync/data-stores";+import {+ $assets,+ $project,+ $instances,+ $props,+} from "~/shared/sync/data-stores";+import { createDefaultCollectionConfig } from "@webstudio-is/content-engine";+import {+ createAssetContentBridge,+ __testing__,+} from "~/shared/asset-content-bridge.client";+import {+ assetContentDescriptorHeader,+ serializeAssetContentDescriptor,+} from "@webstudio-is/protocol/asset-resource-api";+import type { Asset } from "@webstudio-is/sdk";import { $externalContentRoots } from "~/shared/external-content-mutations";import { TextControl } from "./text";@@ -20,6 +35,7 @@ import { TextControl } from "./text";let container: HTMLDivElement;let root: Root;+const { initBridge, clearBridge } = __testing__;beforeEach(() => {container = document.createElement("div");@@ -100,6 +116,96 @@ afterEach(() => {$props.set(new Map());$externalContentRoots.set(new Map());$builderMode.set("design");+ $assets.set(new Map());+ $project.set(undefined);+ clearBridge();+});++test("shows a collection field error on an editable Content-mode input", async () => {+ const files: Asset[] = ["article.mdx", "collection.json", "template.mdx"].map(+ (name) => ({+ id: name === "article.mdx" ? "article" : name,+ projectId: "project",+ name,+ folderId: "posts",+ type: "file",+ format: name.endsWith("json") ? "json" : "mdx",+ size: 1,+ meta: {},+ createdAt: "2026-09-08T00:00:00Z",+ })+ );+ $assets.set(new Map(files.map((asset) => [asset.id, asset])));+ $project.set({ id: "project" } as never);+ const roots = new Map($externalContentRoots.get());+ roots.set("root", {+ ...roots.get("root")!,+ assetId: "article",+ document: {+ children: [],+ frontmatter: { properties: { title: "", slug: "article" } },+ },+ });+ $externalContentRoots.set(roots);+ initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ authorize: () => true,+ requireReload: () => undefined,+ request: async (url) => {+ const isConfig = String(url).includes("collection.json");+ const source = isConfig+ ? createDefaultCollectionConfig()+ : "---\ndraft: true\n---\n";+ const asset = {+ ...files[isConfig ? 1 : 2],+ size: new TextEncoder().encode(source).length,+ };+ return new Response(source, {+ headers: {+ [assetContentDescriptorHeader]:+ serializeAssetContentDescriptor(asset),+ },+ });+ },+ })+ );+ act(() =>+ root.render(+ <TooltipProvider>+ <TextControl+ instanceId="heading"+ meta={{ type: "string", control: "text", required: false }}+ prop={$props.get().get("title")}+ propName="title"+ computedValue=""+ onChange={vi.fn()}+ />+ </TooltipProvider>+ )+ );+ await vi.waitFor(() =>+ expect(+ container.querySelector("textarea")?.getAttribute("aria-invalid")+ ).toBe("true")+ );+ expect(container.querySelector("textarea")).not.toBeDisabled();+ act(() => {+ const assets = new Map($assets.get());+ assets.set("article", {+ ...assets.get("article")!,+ type: "file",+ meta: {},+ filename: "support",+ format: "txt",+ });+ $assets.set(assets);+ });+ await vi.waitFor(() =>+ expect(+ container.querySelector("textarea")?.getAttribute("aria-invalid")+ ).toBeNull()+ );});test("saves an edited direct frontmatter binding without exposing the binding", () => {diff --git a/apps/builder/app/builder/features/settings-panel/controls/text.tsx b/apps/builder/app/builder/features/settings-panel/controls/text.tsxindex 0ec8da6678..024c4ca2e9 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text.tsx@@ -1,5 +1,5 @@import { useId } from "react";-import { TextArea } from "@webstudio-is/design-system";+import { TextArea, Tooltip } from "@webstudio-is/design-system";import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";import { useDraftValue } from "~/builder/shared/use-draft-value";import { BindableExpressionControl } from "~/builder/shared/bindable-expression";@@ -39,18 +39,25 @@ export const TextControl = ({onChangeExpression={(value) => onChange({ type: "expression", value })}onRemove={(value) => onChange({ type: "string", value: String(value) })}renderControl={({ readOnly }) => (- <TextArea- id={id}- disabled={readOnly}- autoGrow- value={localValue.value}- rows={meta.rows ?? 1}- // Set maxRows to 3 when meta.rows is undefined or equal to 1, otherwise set it to rows * 2- maxRows={Math.max(2 * (meta.rows ?? 1), 3)}- onChange={localValue.set}- onBlur={localValue.save}- onSubmit={localValue.save}- />+ <Tooltip+ content={binding.fieldError ?? ""}+ open={binding.fieldError === undefined ? false : undefined}+ >+ <TextArea+ color={binding.fieldError === undefined ? undefined : "error"}+ aria-invalid={binding.fieldError !== undefined || undefined}+ id={id}+ disabled={readOnly}+ autoGrow+ value={localValue.value}+ rows={meta.rows ?? 1}+ // Set maxRows to 3 when meta.rows is undefined or equal to 1, otherwise set it to rows * 2+ maxRows={Math.max(2 * (meta.rows ?? 1), 3)}+ onChange={localValue.set}+ onBlur={localValue.save}+ onSubmit={localValue.save}+ />+ </Tooltip>)}/>);diff --git a/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.ts b/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.tsindex c78f51b172..03e6c39ce1 100644--- a/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.ts+++ b/apps/builder/app/builder/features/settings-panel/controls/use-bindable-control.ts@@ -7,7 +7,10 @@ import {$isContentMode,$selectedInstanceSelector,} from "~/shared/nano-states";-import { $instances, $props } from "~/shared/sync/data-stores";+import { $assets, $instances, $props } from "~/shared/sync/data-stores";+import { useContentCollections } from "~/builder/shared/assets/content-collections";+import { getCollectionEntryValidationIssues } from "@webstudio-is/content-engine";+import { formatAssetName, getAssetDisplayNameParts } from "@webstudio-is/sdk";import {$externalContentRoots,findExternalContentRootEntryBySelector,@@ -16,7 +19,7 @@ import { updateExternalContentFrontmatter } from "~/shared/external-content-rootimport {getSelectedContentBlockDocumentBindingPath,getSelectedContentBlockExpressionMode,- isObjectPathWritable,+ getFrontmatterWriteTarget,} from "~/shared/content-block-document";import { $selectedInstanceScope } from "../shared";import type {@@ -52,6 +55,7 @@ export const useBindableControl = ({const selectedInstanceSelector = useStore($selectedInstanceSelector);const externalContentRoots = useStore($externalContentRoots);const isContentMode = useStore($isContentMode);+ const assets = useStore($assets);const bindingState = useBindingState(boundExpression?.value);const externalEntry =selectedInstanceSelector === undefined@@ -77,13 +81,37 @@ export const useBindableControl = ({renderedBlockInstanceId: externalRoot?.blockInstanceId,}): undefined;- const isEditableFrontmatterBinding =- frontmatterPath !== undefined &&- externalRoot?.document !== undefined &&- isObjectPathWritable({- value: externalRoot.document.frontmatter.properties,- path: frontmatterPath,- });+ const writeTarget =+ frontmatterPath !== undefined && externalRoot?.document !== undefined+ ? getFrontmatterWriteTarget({+ assetId: externalRoot.assetId ?? "",+ sources: externalRoot.frontmatterSources,+ value: externalRoot.document.frontmatter.properties,+ path: frontmatterPath,+ })+ : undefined;+ const isEditableFrontmatterBinding = writeTarget !== undefined;+ const targetAsset =+ writeTarget === undefined ? undefined : assets.get(writeTarget.assetId);+ const collections = useContentCollections(targetAsset?.folderId);+ const collection = collections.get(targetAsset?.folderId ?? "");+ const targetProperties =+ writeTarget?.assetId === externalRoot?.assetId+ ? externalRoot?.document?.frontmatter.properties+ : externalRoot?.frontmatterSources?.find(+ (source) => source.assetId === writeTarget?.assetId+ )?.properties;+ const fieldError =+ collection?.status === "ready" &&+ targetAsset !== undefined &&+ targetProperties !== undefined &&+ collection.config.matchesEntry(formatAssetName(targetAsset))+ ? getCollectionEntryValidationIssues({+ config: collection.config,+ properties: targetProperties,+ basename: getAssetDisplayNameParts(targetAsset).basename,+ }).find((issue) => issue.fieldKey === writeTarget?.path[0])?.message+ : undefined;const bound = boundExpression !== undefined;const expression = boundExpression?.value ?? fallbackExpression;const writeBoundValue =@@ -111,6 +139,7 @@ export const useBindableControl = ({});};return {+ fieldError: fieldError ?? externalRoot?.persistenceError,expression,bound,scope,diff --git a/apps/builder/app/builder/features/settings-panel/property-label.tsx b/apps/builder/app/builder/features/settings-panel/property-label.tsxindex adbad1497b..49e2a47bc4 100644--- a/apps/builder/app/builder/features/settings-panel/property-label.tsx+++ b/apps/builder/app/builder/features/settings-panel/property-label.tsx@@ -1,16 +1,12 @@import { micromark } from "micromark";-import { useMemo, useState, type ReactNode } from "react";+import { useMemo, type ReactNode } from "react";import { computed } from "nanostores";import { useStore } from "@nanostores/react";import {- Button,cssVar,Flex,- Kbd,- Label,+ ResettableLabel,Text,- Tooltip,- theme,} from "@webstudio-is/design-system";import { AlertIcon } from "@webstudio-is/icons";import type { Prop } from "@webstudio-is/sdk";@@ -104,7 +100,6 @@ export const PropertyLabel = ({deletable?: boolean;onDelete?: () => void;}) => {- const [isOpen, setIsOpen] = useState(false);const propMeta = usePropMeta(name);const prop = useProp(name);const label = propMeta?.label ?? humanizeAttribute(name);@@ -124,70 +119,30 @@ export const PropertyLabel = ({onDelete();};return (- <Flex align="center" css={{ gap: theme.spacing[3] }}>- {/* prevent label growing */}- <div>- <Tooltip- open={isOpen}- onOpenChange={setIsOpen}- triggerProps={{- onClick: (event) => {- if (event.altKey) {- event.preventDefault();- if (canDelete) {- handleDelete();- }- return;- }- setIsOpen(true);- },- }}- content={- <Flex- direction="column"- gap="2"- css={{ maxWidth: theme.spacing[28] }}- >- <Text variant="titles" css={{ textTransform: "none" }}>- {label}+ <ResettableLabel+ color={prop ? "local" : "default"}+ onReset={canDelete ? handleDelete : undefined}+ resetLabel={isResettable ? "Reset value" : "Delete property"}+ content={+ <>+ <Text variant="titles">{label}</Text>+ {propMeta?.description && <Text>{propMeta.description}</Text>}+ {readOnly && (+ <Flex gap="1">+ <AlertIcon+ color={cssVar("--foreground-warning")}+ style={{ flexShrink: 0 }}+ />+ <Text>+ The value is controlled by an expression and cannot be changed.</Text>- {propMeta?.description && <Text>{propMeta.description}</Text>}- {readOnly && (- <Flex gap="1">- <AlertIcon- color={cssVar("--foreground-warning")}- style={{ flexShrink: 0 }}- />- <Text>- The value is controlled by an expression and cannot be- changed.- </Text>- </Flex>- )}- {canDelete && (- <Button- color="neutral-destructive"- // to align button text in the middle- prefix={<div></div>}- suffix={<Kbd value={["alt", "click"]} color="moreSubtle" />}- css={{ gridTemplateColumns: "1fr max-content 1fr" }}- onClick={() => {- handleDelete();- setIsOpen(false);- }}- >- {isResettable ? "Reset value" : "Delete property"}- </Button>- )}</Flex>- }- >- <Label truncate color={prop ? "local" : "default"}>- {label}- </Label>- </Tooltip>- </div>- </Flex>+ )}+ </>+ }+ >+ {label}+ </ResettableLabel>);};@@ -198,84 +153,27 @@ export const FieldLabel = ({onReset,children,}: {- /**- * Markdown text to show in tooltip or react element- */description?: string | ReactNode;- /**- * when true means field has value and colored true- */resettable?: boolean;resetDisabled?: boolean;onReset?: () => void;children: string;-}) => {- const [isOpen, setIsOpen] = useState(false);- const canReset = resettable && !resetDisabled;- if (typeof description === "string") {- description = (- <Text- css={{- "> *": { marginTop: 0 },- }}- dangerouslySetInnerHTML={{ __html: micromark(description) }}- ></Text>- );- } else if (description) {- description = <Text>{description}</Text>;- }- return (- <Flex align="center" css={{ gap: theme.spacing[3] }}>- {/* prevent label growing */}- <div>- <Tooltip- open={isOpen}- onOpenChange={setIsOpen}- triggerProps={{- onClick: (event) => {- if (event.altKey) {- event.preventDefault();- if (canReset) {- onReset?.();- }- return;- }- setIsOpen(true);- },- }}- content={- <Flex- direction="column"- gap="2"- css={{ maxWidth: theme.spacing[28] }}- >- <Text variant="titles" css={{ textTransform: "none" }}>- {children}- </Text>- {description}- {canReset && (- <Button- color="neutral-destructive"- // to align button text in the middle- prefix={<div></div>}- suffix={<Kbd value={["alt", "click"]} color="moreSubtle" />}- css={{ gridTemplateColumns: "1fr max-content 1fr" }}- onClick={() => {- onReset?.();- setIsOpen(false);- }}- >- Reset value- </Button>- )}- </Flex>- }- >- <Label truncate color={resettable ? "local" : "default"}>- {children}- </Label>- </Tooltip>- </div>- </Flex>- );-};+}) => (+ <ResettableLabel+ color={resettable ? "local" : "default"}+ onReset={resettable ? onReset : undefined}+ resetDisabled={resetDisabled}+ description={+ typeof description === "string" ? (+ <Text+ css={{ "> *": { marginTop: 0 } }}+ dangerouslySetInnerHTML={{ __html: micromark(description) }}+ />+ ) : (+ description+ )+ }+ >+ {children}+ </ResettableLabel>+);diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsxindex 26d6c529ad..87b7efc8a0 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsx@@ -1,6 +1,7 @@import isEqual from "fast-deep-equal";import { forwardRef, useState, type ComponentProps } from "react";import {+ PanelContent,Grid,theme,Select,@@ -213,7 +214,7 @@ const AnimationConfig = ({((value: undefined, isEphemeral: true) => void);}) => {return (- <Grid gap={2} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} gap={2}><Grid gap={1} align="center" columns={2}><FieldLabel description="Type of the timeline defines how the animation is triggered.">Type@@ -326,7 +327,7 @@ const AnimationConfig = ({/></Grid>)}- </Grid>+ </PanelContent>);};diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-transforms.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-transforms.tsxindex 7e09756987..f8b3c06c32 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-transforms.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-transforms.tsx@@ -1,9 +1,9 @@import { useState } from "react";import {+ PanelContent,EnhancedTooltip,Grid,SmallToggleButton,- theme,} from "@webstudio-is/design-system";import {toValue,@@ -70,7 +70,7 @@ export const AnimationTransforms = ({}}return (- <Grid gap={2} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} gap={2}><Grid gap={1}><FieldLabelresettable={styles.translate !== undefined}@@ -294,6 +294,6 @@ export const AnimationTransforms = ({/></Grid></Grid>- </Grid>+ </PanelContent>);};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 a9aa41030d..70b124991a 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@@ -1,4 +1,5 @@import { useState } from "react";+import { parseError } from "~/shared/error/error-parse";import { computed } from "nanostores";import { useStore } from "@nanostores/react";import { matchSorter } from "match-sorter";@@ -68,7 +69,7 @@ import { updateExternalContentFrontmatter } from "~/shared/external-content-rootimport {getSelectedContentBlockDocumentBindingPath,getSelectedContentBlockExpressionMode,- isObjectPathWritable,+ getFrontmatterWriteTarget,} from "~/shared/content-block-document";import {createMdxAssetReferenceValues,@@ -586,10 +587,12 @@ export const PropsSectionContainer = ({return;}if (- isObjectPathWritable({+ getFrontmatterWriteTarget({+ assetId: externalRoot.assetId ?? "",+ sources: externalRoot.frontmatterSources,value: externalRoot.document.frontmatter.properties,path: targetPath,- }) === false+ }) === undefined) {toast.error("Open the referenced file to edit this value.");return;@@ -606,11 +609,7 @@ export const PropsSectionContainer = ({value: nextValue,resolvedValue: nextResolvedValue,}).catch((error) => {- toast.error(- error instanceof Error- ? error.message- : "Unable to update MDX frontmatter"- );+ toast.error(parseError(error).message);});return;}diff --git a/apps/builder/app/builder/features/settings-panel/request-inspector.tsx b/apps/builder/app/builder/features/settings-panel/request-inspector.tsxindex 8102b2a0c9..b412c930cd 100644--- a/apps/builder/app/builder/features/settings-panel/request-inspector.tsx+++ b/apps/builder/app/builder/features/settings-panel/request-inspector.tsx@@ -6,6 +6,7 @@ import {type Ref,} from "react";import {+ PanelContent,cssVar,Flex,Grid,@@ -39,9 +40,9 @@ export const RequestDiagnosticsContent = ({}) => (<ScrollAreaNative css={{ height: "100%", overflow: "auto" }}>{padded ? (- <Flex direction="column" gap={3} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} direction="column" gap={3}>{children}- </Flex>+ </PanelContent>) : (children)}@@ -97,7 +98,11 @@ export const RequestDiagnosticsRow = ({<Text color="moreSubtle">{label}</Text>{description !== undefined && (<Tooltip variant="wrapped" content={description}>- <InfoCircleIcon data-diagnostics-info tabIndex={0} />+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ data-diagnostics-info+ tabIndex={0}+ /></Tooltip>)}</DiagnosticsLabel>diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsxindex 3665f5e49b..dcc17edfd2 100644--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx@@ -48,6 +48,7 @@ import {TextArea,Tooltip,theme,+ cssVar,} from "@webstudio-is/design-system";import { TrashIcon, InfoCircleIcon, PlusIcon } from "@webstudio-is/icons";import { humanizeString } from "~/shared/string-utils";@@ -123,7 +124,10 @@ export const UrlField = ({variant="wrapped"disableHoverableContent={true}>- <InfoCircleIcon tabIndex={0} />+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ /></Tooltip></Label><input type="hidden" readOnly={true} name="url" value={value} />diff --git a/apps/builder/app/builder/features/style-panel/property-label.test.tsx b/apps/builder/app/builder/features/style-panel/property-label.test.tsxnew file mode 100644index 0000000000..0ddb96f619--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/property-label.test.tsx@@ -0,0 +1,35 @@+import { act } from "react-dom/test-utils";+import { afterEach, expect, test } from "vitest";+import { userEvent } from "@vitest/browser/context";+import { TooltipProvider } from "@webstudio-is/design-system";+import { createAssetManagerTestRenderer } from "~/builder/shared/asset-manager/test-utils";+import { PropertyInlineLabel } from "./property-label";++const renderer = createAssetManagerTestRenderer();+afterEach(renderer.cleanup);++test("inline property labels offer keyboard-accessible information without a reset action", async () => {+ const container = renderer.render(+ <TooltipProvider>+ <PropertyInlineLabel+ label="Position"+ title="Background position"+ properties={["background-position-x", "background-position-y"]}+ description="Position within this background layer."+ />+ <button>Next control</button>+ </TooltipProvider>+ );+ const label = container.querySelector("button")!;+ await act(async () => userEvent.tab());+ expect(document.activeElement).toBe(label);+ await act(async () => userEvent.keyboard("{Enter}"));+ const tooltip = document.querySelector(+ "[data-radix-popper-content-wrapper]"+ )!;+ expect(tooltip).not.toBeNull();+ // The property names identify the information associated with this control.+ expect(tooltip.textContent).toContain("background-position-x");+ expect(tooltip.textContent).toContain("background-position-y");+ expect(tooltip.querySelector("button")).toBeNull();+});diff --git a/apps/builder/app/builder/features/style-panel/property-label.tsx b/apps/builder/app/builder/features/style-panel/property-label.tsxindex ef1f49aa02..6dd65b2868 100644--- a/apps/builder/app/builder/features/style-panel/property-label.tsx+++ b/apps/builder/app/builder/features/style-panel/property-label.tsx@@ -9,7 +9,7 @@ import {cssVar,Flex,Kbd,- Label,+ ResettableLabel,SectionTitleLabel,Text,theme,@@ -73,7 +73,7 @@ export const PropertyInfo = ({link?: string;description: ReactNode;styles: ComputedStyleDecl[];- onReset: () => void;+ onReset?: () => void;resetType?: "reset" | "delete";}) => {const readonly = useReadonly();@@ -187,7 +187,7 @@ export const PropertyInfo = ({</Flex></Flex>)}- {resettable && readonly === false && (+ {resettable && readonly === false && onReset && (<Buttoncolor="neutral-destructive"prefix={@@ -239,7 +239,7 @@ export const PropertyLabel = ({const styles = useComputedStyles(properties);const readonly = useReadonly();const styleValueSourceColor = getPriorityStyleValueSource(styles);- const [isOpen, setIsOpen] = useState(false);+const resetProperty = () => {if (readonly) {return;@@ -252,47 +252,29 @@ export const PropertyLabel = ({};return (- <Flex align="center">- <Tooltip- open={isOpen}- onOpenChange={setIsOpen}- triggerProps={{- onClick: (event) => {- if (readonly) {- return;- }- if (event.altKey) {- event.preventDefault();- // If not, when mixed with ToogleGroupControl.- // The will trigger the reset of the toggle group.- // And resets all of the properties in the toggle group.- event.stopPropagation();- resetProperty();- return;- }- setIsOpen(true);- },- }}- content={- <PropertyInfo- title={label}- description={description}- styles={styles}- onReset={() => {- resetProperty();- setIsOpen(false);- }}- link={propertiesData[properties[0]]?.mdnUrl}- />- }- >- <Flex shrink gap={1} align="center">- <Label color={styleValueSourceColor} truncate disabled={disabled}>- {label}- </Label>- </Flex>- </Tooltip>- </Flex>+ <ResettableLabel+ disabled={disabled}+ color={styleValueSourceColor}+ onReset={+ styles.some(+ ({ source }) =>+ source.name === "local" || source.name === "overwritten"+ )+ ? resetProperty+ : undefined+ }+ resetDisabled={readonly}+ content={+ <PropertyInfo+ title={label}+ description={description}+ styles={styles}+ link={propertiesData[properties[0]]?.mdnUrl}+ />+ }+ >+ {label}+ </ResettableLabel>);};@@ -308,7 +290,7 @@ export const PropertySectionLabel = ({const styles = useComputedStyles(properties);const readonly = useReadonly();const styleValueSourceColor = getPriorityStyleValueSource(styles);- const [isOpen, setIsOpen] = useState(false);+const resetProperty = () => {if (readonly) {return;@@ -321,45 +303,29 @@ export const PropertySectionLabel = ({};return (- <Flex align="center">- <Tooltip- open={isOpen}- onOpenChange={setIsOpen}- // prevent closing tooltip on content click- onPointerDown={(event) => event.preventDefault()}- triggerProps={{- onClick: (event) => {- if (readonly) {- return;- }- if (event.altKey) {- event.preventDefault();- resetProperty();- return;- }- setIsOpen(true);- },- }}- content={- <PropertyInfo- title={label}- description={description}- styles={styles}- onReset={() => {- resetProperty();- setIsOpen(false);- }}- link={propertiesData[properties[0]]?.mdnUrl}- />- }- >- <Flex shrink gap={1} align="center">- <SectionTitleLabel color={styleValueSourceColor}>- {label}- </SectionTitleLabel>- </Flex>- </Tooltip>- </Flex>+ <ResettableLabel+ asChild+ color={styleValueSourceColor}+ onReset={+ styles.some(+ ({ source }) =>+ source.name === "local" || source.name === "overwritten"+ )+ ? resetProperty+ : undefined+ }+ resetDisabled={readonly}+ content={+ <PropertyInfo+ title={label}+ description={description}+ styles={styles}+ link={propertiesData[properties[0]]?.mdnUrl}+ />+ }+ >+ <SectionTitleLabel>{label}</SectionTitleLabel>+ </ResettableLabel>);};@@ -382,47 +348,28 @@ export const PropertyInlineLabel = ({properties?: [CssProperty, ...CssProperty[]];disabled?: boolean;}) => {- const [isOpen, setIsOpen] = useState(false);return (- <Flex align="center">- <Tooltip- open={isOpen}- onOpenChange={setIsOpen}- // prevent closing tooltip on content click- onPointerDown={(event) => event.preventDefault()}- triggerProps={{- onClick: () => setIsOpen(true),- }}- content={- <>- <Flex- direction="column"- gap="2"- css={{ maxWidth: theme.spacing[28] }}+ <ResettableLabel+ disabled={disabled}+ content={+ <>+ <Text variant="titles">{title ?? label}</Text>+ {properties && (+ <Text+ variant="monoBold"+ color="moreSubtle"+ userSelect="text"+ css={{ whiteSpace: "break-spaces", cursor: "text" }}>- <Text variant="titles">{title ?? label}</Text>- {properties && (- <Text- variant="monoBold"- color="moreSubtle"- userSelect="text"- css={{ whiteSpace: "break-spaces", cursor: "text" }}- >- {properties.join("\n")}- </Text>- )}- <Text>{description}</Text>- </Flex>- </>- }- >- <Flex shrink gap={1} align="center">- <Label color="default" disabled={disabled} truncate>- {label}- </Label>- </Flex>- </Tooltip>- </Flex>+ {properties.join("\n")}+ </Text>+ )}+ <Text>{description}</Text>+ </>+ }+ >+ {label}+ </ResettableLabel>);};diff --git a/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.tsx b/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.tsxindex 17832752f7..3af5ffbcf0 100644--- a/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.tsx@@ -3,7 +3,7 @@ import {type CssProperty,type StyleValue,} from "@webstudio-is/css-engine";-import { Tooltip, Flex, Text } from "@webstudio-is/design-system";+import { Tooltip, Flex, Text, cssVar } from "@webstudio-is/design-system";import { InfoCircleIcon } from "@webstudio-is/icons";import { humanizeString } from "~/shared/string-utils";import { RepeatedStyleSection } from "../../shared/style-section";@@ -81,7 +81,7 @@ export const Section = () => {</Flex>}>- <InfoCircleIcon />+ <InfoCircleIcon color={cssVar("--foreground-secondary")} /></Tooltip>}/>diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsxindex 2ee3ec2a3e..64bb0f6dc6 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsx@@ -17,6 +17,7 @@ import {} from "@webstudio-is/icons";import { type StyleValue, toValue } from "@webstudio-is/css-engine";import {+ PanelContent,cssVar,theme,Flex,@@ -422,11 +423,11 @@ export const BackgroundContent = ({ index }: { index: number }) => {return (<>- <Flex+ <PanelContent+ as={Flex}align="center"gap="2"justify="between"- css={{ padding: theme.panel.padding }}shrink={false}><PropertyInlineLabel@@ -442,7 +443,7 @@ export const BackgroundContent = ({ index }: { index: number }) => {index={index}cachedValues={cachedValuesRef}/>- </Flex>+ </PanelContent><Separator />diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsxindex 4c1aa546c4..64ff797c53 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx@@ -13,6 +13,7 @@ import {keywordValues,} from "@webstudio-is/css-data";import {+ PanelContent,Flex,theme,Tooltip,@@ -265,13 +266,13 @@ export const BackgroundGradient = ({return (<Flex direction="column" justify="center" gap="2" shrink={false}>{isSolidVariant ? (- <Box css={{ padding: theme.panel.padding }}>+ <PanelContent as={Box}><SolidColorControlsdisabled={readonly}gradient={gradient}applyGradient={applyGradient}/>- </Box>+ </PanelContent>) : (<><GradientPickerSection@@ -378,12 +379,7 @@ const GradientPickerSection = ({}, [computedGradientForPicker]);return (- <Flex- direction="column"- shrink={false}- gap="2"- css={{ padding: theme.panel.padding }}- >+ <PanelContent as={Flex} direction="column" shrink={false} gap="2"><GradientPickerdisabled={disabled}gradient={computedGradientForPicker}@@ -404,7 +400,7 @@ const GradientPickerSection = ({setHintOverrides={setHintOverrides}applyGradient={applyGradient}/>- </Flex>+ </PanelContent>);};diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsxindex 8f7c1b1de1..a6b7db9f15 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsx@@ -1,5 +1,5 @@import type { StyleValue } from "@webstudio-is/css-engine";-import { Flex, theme, Grid, Box } from "@webstudio-is/design-system";+import { PanelContent, Flex, Grid, Box } from "@webstudio-is/design-system";import { useRef, useCallback } from "react";import { ImageControl } from "../../controls";import { PropertyInlineLabel } from "../../property-label";@@ -54,12 +54,7 @@ export const BackgroundImage = ({);return (- <Flex- direction="column"- gap={1}- css={{ padding: theme.panel.padding }}- ref={elementRef}- >+ <PanelContent as={Flex} direction="column" gap={1} ref={elementRef}><Grid gap="2" columns="3" align="start"><PropertyInlineLabellabel="Image"@@ -78,6 +73,6 @@ export const BackgroundImage = ({</Box></Grid><BackgroundCodeEditor index={index} onValidate={handleValidate} />- </Flex>+ </PanelContent>);};diff --git a/apps/builder/app/builder/features/style-panel/sections/filter/filter.tsx b/apps/builder/app/builder/features/style-panel/sections/filter/filter.tsxindex 22c7d56b8a..977f3e770b 100644--- a/apps/builder/app/builder/features/style-panel/sections/filter/filter.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/filter/filter.tsx@@ -1,4 +1,4 @@-import { Flex, Tooltip, Text } from "@webstudio-is/design-system";+import { Flex, Tooltip, Text, cssVar } from "@webstudio-is/design-system";import { InfoCircleIcon } from "@webstudio-is/icons";import {toValue,@@ -78,7 +78,7 @@ export const Section = () => {</Flex>}>- <InfoCircleIcon />+ <InfoCircleIcon color={cssVar("--foreground-secondary")} /></Tooltip>}/>diff --git a/apps/builder/app/builder/features/style-panel/sections/flex-child/flex-child.tsx b/apps/builder/app/builder/features/style-panel/sections/flex-child/flex-child.tsxindex adb74e3e26..a0178443df 100644--- a/apps/builder/app/builder/features/style-panel/sections/flex-child/flex-child.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/flex-child/flex-child.tsx@@ -1,4 +1,5 @@import {+ PanelContent,Flex,Grid,theme,@@ -224,11 +225,11 @@ const FlexChildSectionSizingPopover = () => {title="Sizing"placement="bottom-within"content={- <Grid+ <PanelContent+ as={Grid}gap="3"css={{gridTemplateColumns: "1fr 1fr 1.5fr",- padding: theme.panel.padding,}}><Grid css={{ gridTemplateColumns: "auto", gap: theme.spacing[3] }}>@@ -255,7 +256,7 @@ const FlexChildSectionSizingPopover = () => {/><TextControl property="flex-basis" /></Grid>- </Grid>+ </PanelContent>}><Flex>diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.tsxindex 2a97946741..847f2aa678 100644--- a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.tsx@@ -1,5 +1,6 @@import { useState, useCallback, useEffect } from "react";import {+ PanelContent,theme,Flex,Text,@@ -322,7 +323,7 @@ const AreaEditor = ({);return (- <Flex direction="column" gap="2" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} direction="column" gap="2"><Gridcss={{gridTemplateColumns: "60px 1fr 1fr",@@ -428,7 +429,7 @@ const AreaEditor = ({Area overlaps with another area</Text>)}- </Flex>+ </PanelContent>);};@@ -629,13 +630,9 @@ export const GridAreas = () => {<CssValueListArrowFocus><Flex direction="column">{areas.length === 0 && (- <Text- color="subtle"- align="center"- css={{ padding: theme.panel.padding }}- >+ <PanelContent as={Text} color="subtle" align="center">No Areas- </Text>+ </PanelContent>)}{areas.map((area, index) => (<FloatingPaneldiff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsxindex 9025061fd7..5a894feea6 100644--- a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx@@ -1,6 +1,7 @@import { useMemo, useState } from "react";import { useStore } from "@nanostores/react";import {+ PanelContent,Box,Button,cssVar,@@ -491,31 +492,23 @@ export const GridGenerator = ({ open, onOpenChange }: GridGeneratorProps) => {placement="left-start"content={<Flex direction="column">- <Flex- direction="column"- gap="3"- css={{ padding: theme.panel.padding }}- >+ <PanelContent as={Flex} direction="column" gap="3"><GridGeneratorSelectoronSelect={handleSelectorSelect}initialColumns={columnCount}initialRows={rowCount}/>- </Flex>+ </PanelContent><Separator />- <Flex- direction="column"- gap="3"- css={{ padding: theme.panel.padding }}- >+ <PanelContent as={Flex} direction="column" gap="3"><GridPresetsPicker onSelect={handlePresetSelect} />- </Flex>+ </PanelContent><Separator />- <Flex css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex}><Button css={{ width: "100%" }} onClick={handleFillGrid}>Fill grid</Button>- </Flex>+ </PanelContent></Flex>}open={open}diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.tsxindex 286f09e1fd..b5380eaae2 100644--- a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.tsx@@ -1,5 +1,6 @@import { useMemo, useState, useCallback, useEffect } from "react";import {+ PanelContent,theme,Flex,Text,@@ -153,7 +154,7 @@ const TrackItem = ({placement="bottom-within"title={`Edit ${trackType}`}content={- <Flex direction="column" gap="2" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} direction="column" gap="2">{isMinmax ? (<Grid columns={2} gap="2"><Flex direction="column" gap="1">@@ -228,7 +229,7 @@ const TrackItem = ({/><Label htmlFor={`minmax-${id}`}>Use min/max</Label></Flex>- </Flex>+ </PanelContent>}open={isEditing}onOpenChange={onEditingChange}@@ -409,13 +410,9 @@ const TrackEditor = ({<CssValueListArrowFocus dragItemId={dragItemId}><Flex direction="column" ref={sortableRefCallback}>{tracks.length === 0 && (- <Text- color="subtle"- align="center"- css={{ padding: theme.panel.padding }}- >+ <PanelContent as={Text} color="subtle" align="center">No {trackType}- </Text>+ </PanelContent>)}{tracks.map((track, index) => {const id = String(index);diff --git a/apps/builder/app/builder/features/style-panel/sections/shared/order.tsx b/apps/builder/app/builder/features/style-panel/sections/shared/order.tsxindex fd7f5a88c6..1e12f8abdf 100644--- a/apps/builder/app/builder/features/style-panel/sections/shared/order.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/shared/order.tsx@@ -1,9 +1,9 @@import { useState } from "react";import {+ PanelContent,Flex,FloatingPanel,Grid,- theme,ToggleGroup,ToggleGroupButton,} from "@webstudio-is/design-system";@@ -28,10 +28,10 @@ const OrderPopover = () => {title="Order"placement="bottom-within"content={- <Grid+ <PanelContent+ as={Grid}css={{gridTemplateColumns: "4fr 6fr",- padding: theme.panel.padding,}}gap={2}>@@ -41,7 +41,7 @@ const OrderPopover = () => {properties={["order"]}/><TextControl property="order" />- </Grid>+ </PanelContent>}><Flex>diff --git a/apps/builder/app/builder/features/style-panel/sections/size/size.tsx b/apps/builder/app/builder/features/style-panel/sections/size/size.tsxindex 24ca1ab460..027c0a8883 100644--- a/apps/builder/app/builder/features/style-panel/sections/size/size.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/size/size.tsx@@ -4,6 +4,7 @@ import {} from "@webstudio-is/css-data";import type { CssProperty } from "@webstudio-is/css-engine";import {+ PanelContent,Flex,Grid,IconButton,@@ -50,9 +51,9 @@ const ObjectPosition = () => {title="Object position"placement="bottom-within"content={- <Flex css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex}><PositionControl property="object-position" styleDecl={styleDecl} />- </Flex>+ </PanelContent>}><IconButtondiff --git a/apps/builder/app/builder/features/style-panel/sections/transforms/transforms.tsx b/apps/builder/app/builder/features/style-panel/sections/transforms/transforms.tsxindex 337188ab66..5c42703d2c 100644--- a/apps/builder/app/builder/features/style-panel/sections/transforms/transforms.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/transforms/transforms.tsx@@ -18,6 +18,7 @@ import {Grid,IconButton,Label,+ PanelContent,SectionTitle,SectionTitleButton,SmallIconButton,@@ -156,12 +157,7 @@ const TransformAdvancedPopover = ({title="Advanced transform"placement="bottom-within"content={- <Grid- gap="2"- css={{- padding: theme.panel.padding,- }}- >+ <PanelContent as={Grid} gap="2"><Grid css={{ gridTemplateColumns: `2fr 1fr` }}><PropertyLabellabel="Backface visibility"@@ -186,7 +182,7 @@ const TransformAdvancedPopover = ({property="perspective-origin"disabled={readonly}/>- </Grid>+ </PanelContent>}><TransformAdvancedButton unavailable={unavailable || readonly} />@@ -323,19 +319,14 @@ const TransformSection = ({<FloatingPaneltitle={humanizeString(panel)}content={- <Flex- direction="column"- css={{- padding: theme.panel.padding,- }}- >+ <PanelContent as={Flex} direction="column">{panel === "translate" && (<TranslatePanelContent disabled={readonly} />)}{panel === "scale" && <ScalePanelContent disabled={readonly} />}{panel === "rotate" && <RotatePanelContent disabled={readonly} />}{panel === "skew" && <SkewPanelContent disabled={readonly} />}- </Flex>+ </PanelContent>}><CssValueListItemdiff --git a/apps/builder/app/builder/features/style-panel/sections/transitions/transition-content.tsx b/apps/builder/app/builder/features/style-panel/sections/transitions/transition-content.tsxindex 2aade2dacc..0abbf44a8e 100644--- a/apps/builder/app/builder/features/style-panel/sections/transitions/transition-content.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/transitions/transition-content.tsx@@ -6,6 +6,7 @@ import {type TupleValueItem,} from "@webstudio-is/css-engine";import {+ PanelContent,Flex,Label,TextArea,@@ -16,6 +17,7 @@ import {Text,Grid,toast,+ cssVar,} from "@webstudio-is/design-system";import { InfoCircleIcon } from "@webstudio-is/icons";import { propertiesData, propertyDescriptions } from "@webstudio-is/css-data";@@ -120,10 +122,10 @@ export const TransitionContent = ({ index }: { index: number }) => {return (<Flex direction="column">- <Grid+ <PanelContent+ as={Grid}gap="2"css={{- padding: theme.panel.padding,gridTemplateColumns: `1fr ${theme.spacing[23]}`,gridTemplateRows: theme.spacing[13],}}@@ -241,13 +243,13 @@ export const TransitionContent = ({ index }: { index: number }) => {}}}/>- </Grid>+ </PanelContent><Separator css={{ gridColumn: "span 2" }} />- <Flex+ <PanelContent+ as={Flex}direction="column"css={{- padding: theme.panel.padding,gap: theme.spacing[3],minWidth: theme.spacing[30],}}@@ -267,7 +269,7 @@ export const TransitionContent = ({ index }: { index: number }) => {</Text>}>- <InfoCircleIcon />+ <InfoCircleIcon color={cssVar("--foreground-secondary")} /></Tooltip></Flex></Label>@@ -289,7 +291,7 @@ export const TransitionContent = ({ index }: { index: number }) => {}}}/>- </Flex>+ </PanelContent></Flex>);};diff --git a/apps/builder/app/builder/features/style-panel/sections/typography/typography.tsx b/apps/builder/app/builder/features/style-panel/sections/typography/typography.tsxindex 32459971fc..6d5a129d64 100644--- a/apps/builder/app/builder/features/style-panel/sections/typography/typography.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/typography/typography.tsx@@ -1,5 +1,6 @@import { forwardRef, type ComponentProps } from "react";import {+ PanelContent,Flex,Grid,EnhancedTooltip,@@ -283,9 +284,9 @@ const TypographySectionAdvancedPopover = () => {title="Advanced typography"placement="bottom-within"content={- <Grid+ <PanelContent+ as={Grid}css={{- padding: theme.panel.padding,gap: theme.spacing[9],width: theme.spacing[30],}}@@ -382,7 +383,7 @@ const TypographySectionAdvancedPopover = () => {/></Box></Grid>- </Grid>+ </PanelContent>}><AdvancedOptionsButton />diff --git a/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx b/apps/builder/app/builder/features/style-panel/shared/filter-content.tsxindex 3683504527..1594320abc 100644--- a/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx@@ -5,6 +5,7 @@ import {type StyleValue,} from "@webstudio-is/css-engine";import {+ PanelContent,Flex,theme,Label,@@ -172,7 +173,7 @@ export const FilterSectionContent = ({return (<Flex direction="column">- <Flex direction="column" gap="2" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} direction="column" gap="2"><Gridgap="2"css={{@@ -224,7 +225,7 @@ export const FilterSectionContent = ({/></Grid>) : undefined}- </Flex>+ </PanelContent>{filterFunction === "drop-shadow" && layer.type === "function" && (<ShadowContent@@ -243,10 +244,10 @@ export const FilterSectionContent = ({)}<Separator css={{ gridAutoColumns: "span 2" }} />- <Flex+ <PanelContent+ as={Flex}direction="column"css={{- padding: theme.panel.padding,gap: theme.spacing[3],minWidth: theme.spacing[30],}}@@ -282,7 +283,7 @@ export const FilterSectionContent = ({}}}/>- </Flex>+ </PanelContent></Flex>);};diff --git a/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsx b/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsxindex 2562f20dcb..cae3b6e74c 100644--- a/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsx@@ -15,6 +15,7 @@ import {propertySyntaxes,} from "@webstudio-is/css-data";import {+ PanelContent,Flex,Grid,Label,@@ -25,6 +26,7 @@ import {ToggleGroupButton,Tooltip,toast,+ cssVar,} from "@webstudio-is/design-system";import {InfoCircleIcon,@@ -215,10 +217,10 @@ export const ShadowContent = ({return (<Flex direction="column">- <Grid+ <PanelContent+ as={Grid}gap="2"css={{- padding: theme.panel.padding,gridTemplateColumns:property === "box-shadow" ? "1fr 1fr" : "1fr 1fr 1fr",}}@@ -322,13 +324,15 @@ export const ShadowContent = ({/></Flex>) : null}- </Grid>+ </PanelContent>- <Grid+ <PanelContent+ as={Grid}gap="2"css={{- padding: theme.panel.padding,- ...(property === "box-shadow" && { gridTemplateColumns: "3fr 1fr" }),+ ...(property === "box-shadow" && {+ gridTemplateColumns: "3fr 1fr",+ }),}}><Flex direction="column" gap="1">@@ -399,15 +403,15 @@ export const ShadowContent = ({</ToggleGroup></Flex>) : null}- </Grid>+ </PanelContent>{hideCodeEditor === false ? (<><Separator css={{ gridColumn: "span 2" }} />- <Flex+ <PanelContent+ as={Flex}direction="column"css={{- padding: theme.panel.padding,gap: theme.spacing[3],minWidth: theme.spacing[30],}}@@ -428,7 +432,7 @@ export const ShadowContent = ({</Text>}>- <InfoCircleIcon />+ <InfoCircleIcon color={cssVar("--foreground-secondary")} /></Tooltip></Flex></Label>@@ -444,7 +448,7 @@ export const ShadowContent = ({/>}/>- </Flex>+ </PanelContent></>) : undefined}</Flex>diff --git a/apps/builder/app/builder/features/style-panel/style-panel.tsx b/apps/builder/app/builder/features/style-panel/style-panel.tsxindex 61a1589c65..be93a7c713 100644--- a/apps/builder/app/builder/features/style-panel/style-panel.tsx+++ b/apps/builder/app/builder/features/style-panel/style-panel.tsx@@ -2,6 +2,7 @@ import { useState } from "react";import { computed } from "nanostores";import { useStore } from "@nanostores/react";import {+ PanelContent,theme,Box,Card,@@ -171,12 +172,12 @@ export const StylePanel = () => {return (<ReadonlyProvider value={readonly}>- <Box css={{ padding: theme.panel.padding }}>+ <PanelContent as={Box}><Text variant="titles" css={{ paddingBlock: theme.panel.paddingBlock }}>Style sources</Text><StyleSourcesSection />- </Box>+ </PanelContent><Separator /><ScrollArea><CollapsibleProviderdiff --git a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.tsindex 00165ec365..0d94f3e006 100644--- a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts+++ b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts@@ -46,17 +46,35 @@ test("accepts supported text names and rejects invalid or duplicate names", () =getTextFileNameError({name: "readme.md",assets: [existing],+ folderId: "docs",})).toBe("A file with this name already exists.");});-test("compares global complete display names after an asset is renamed", () => {+test("scopes complete display names to the target folder", () => {expect(getTextFileNameError({name: "guide.md",assets: [{ ...existing, filename: "guide", folderId: "other" }],+ folderId: "docs",+ })+ ).toBeUndefined();++ expect(+ getTextFileNameError({+ name: "guide.md",+ assets: [{ ...existing, filename: "guide", folderId: "docs" }],+ folderId: "docs",})).toBe("A file with this name already exists.");++ expect(+ getTextFileNameError({+ name: "guide.json",+ assets: [{ ...existing, filename: "guide", folderId: "docs" }],+ folderId: "docs",+ })+ ).toBeUndefined();});test("can restrict creation to the requested text format", () => {@@ -90,6 +108,40 @@ test("can restrict creation to the requested text format", () => {).toBe("Use a supported editable text extension.");});+test("requires collection configuration permission to create a folder manifest", () => {+ expect(+ getTextFileNameError({+ name: "collection.json",+ assets: [],+ folderId: "posts",+ canCreateCollectionConfig: false,+ })+ ).toBe("You don't have permission to create a content collection.");+ expect(+ getTextFileNameError({+ name: "collection.json",+ assets: [],+ canCreateCollectionConfig: false,+ })+ ).toBeUndefined();+ expect(+ getTextFileNameError({+ name: "collection.json",+ assets: [],+ folderId: "posts",+ canCreateCollectionConfig: true,+ })+ ).toBeUndefined();+ expect(+ getTextFileNameError({+ name: "Collection.json",+ assets: [],+ folderId: "posts",+ canCreateCollectionConfig: false,+ })+ ).toBeUndefined();+});+test("creates valid initial content for editable file types", async () => {const jsonFile = createTextFileData("data.json");if (jsonFile === undefined) {diff --git a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsxindex 36de22dfff..c1adf8a77f 100644--- a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx+++ b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx@@ -1,6 +1,7 @@import { useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";import isValidFilename from "valid-filename";import {+ PanelContent,Button,Dialog,DialogContent,@@ -10,25 +11,29 @@ import {InputField,Label,Text,- theme,} from "@webstudio-is/design-system";import {- formatAssetName,getFileExtension,getMimeTypeByExtension,isTextFileAsset,type Asset,} from "@webstudio-is/sdk";+import { collectionConfigFilename } from "@webstudio-is/content-engine";import { $assets } from "~/shared/sync/data-stores";import { uploadSingleAsset } from "~/builder/shared/assets/upload-assets";+import { isAssetFilenameUsed } from "~/builder/shared/assets/asset-utils";export const getTextFileNameError = ({name,assets,+ folderId,+ canCreateCollectionConfig = false,allowedExtensions,}: {name: string;assets: Iterable<Asset>;+ folderId?: string;+ canCreateCollectionConfig?: boolean;allowedExtensions?: readonly string[];}) => {if (isValidFilename(name) === false) {@@ -44,10 +49,15 @@ export const getTextFileNameError = ({) {return "Use a supported editable text extension.";}- for (const asset of assets) {- if (formatAssetName(asset) === name) {- return "A file with this name already exists.";- }+ if (+ folderId !== undefined &&+ canCreateCollectionConfig === false &&+ name === collectionConfigFilename+ ) {+ return "You don't have permission to create a content collection.";+ }+ if (isAssetFilenameUsed({ assets, filename: name, folderId })) {+ return "A file with this name already exists.";}};@@ -90,6 +100,7 @@ export const CreateTextFileDialog = ({allowedExtensions,title = "New text file",disabled = false,+ canCreateCollectionConfig = false,onOpenChange,onCreated,}: {@@ -99,6 +110,7 @@ export const CreateTextFileDialog = ({allowedExtensions?: readonly string[];title?: string;disabled?: boolean;+ canCreateCollectionConfig?: boolean;onOpenChange: (open: boolean) => void;onCreated: (assetId: string) => void;}) => {@@ -124,6 +136,8 @@ export const CreateTextFileDialog = ({const validationError = getTextFileNameError({name: normalizedName,assets: $assets.get().values(),+ folderId,+ canCreateCollectionConfig,allowedExtensions,});setError(validationError);@@ -169,7 +183,7 @@ export const CreateTextFileDialog = ({}}><DialogTitle>{title}</DialogTitle>- <Grid gap={3} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} gap={3}><Grid gap={1}><Label htmlFor="asset-text-file-name">File name</Label><InputField@@ -203,7 +217,7 @@ export const CreateTextFileDialog = ({{creating ? "Creating…" : "Create file"}</Button></Flex>- </Grid>+ </PanelContent></DialogContent></Dialog>);diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor-validation.test.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor-validation.test.tsxnew file mode 100644index 0000000000..786f323c97--- /dev/null+++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor-validation.test.tsx@@ -0,0 +1,137 @@+import { act } from "react-dom/test-utils";+import { createRoot } from "react-dom/client";+import { expect, test, vi } from "vitest";+import { userEvent } from "@vitest/browser/context";+import { TooltipProvider } from "@webstudio-is/design-system";+import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";+import type { Asset } from "@webstudio-is/sdk";+import { $assets } from "~/shared/sync/data-stores";+import { $authPermit } from "~/shared/nano-states";+import {+ createAssetContentBridge,+ __testing__,+} from "~/shared/asset-content-bridge.client";+import { TextFileEditor } from "./text-file-editor";+import { __testing__ as navigatorTesting } from "../navigator/navigator-tree";++const { initBridge, clearBridge } = __testing__;+const { MdxContentMenu } = navigatorTesting;+(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++test.each(["repair", "discard", "navigator"])(+ "keeps invalid MDX drafts open until %s without replacing the saved article",+ async (action) => {+ const asset: Asset = {+ id: "validation-article",+ projectId: "validation-project",+ name: "article.mdx",+ format: "mdx",+ type: "file",+ size: 9,+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ const writes: string[] = [];+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset,+ data: (async function* () {+ yield new TextEncoder().encode("# Article");+ })(),+ }),+ updateContent: async ({ data }) => {+ writes.push(await new Response(data).text());+ return asset;+ },+ },+ authorize: () => true,+ debounceMilliseconds: 0,+ });+ initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $assets.set(new Map([[asset.id, asset]]));+ const previousPermit = $authPermit.get();+ $authPermit.set("own");+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const onOpenChange = vi.fn();+ try {+ await act(async () =>+ root.render(+ <TooltipProvider>+ {action === "navigator" ? (+ <MdxContentMenu assetId={asset.id} />+ ) : (+ <TextFileEditor assetId={asset.id} onOpenChange={onOpenChange} />+ )}+ </TooltipProvider>+ )+ );+ if (action === "navigator") {+ await act(async () =>+ userEvent.click(+ document.querySelector('[aria-label="MDX content settings"]')!+ )+ );+ await act(async () =>+ userEvent.click(document.querySelector('[role="menuitem"]')!)+ );+ }+ await vi.waitFor(() =>+ expect(+ document.querySelector('[aria-label="Markdown source"]')+ ).not.toBeNull()+ );+ const editor = document.querySelector<HTMLElement>(+ '[aria-label="Markdown source"]'+ )!;+ await vi.waitFor(() => expect(document.activeElement).toBe(editor));+ if (action === "navigator") {+ return;+ }+ await act(async () => userEvent.fill(editor, "<YouTube url={ />"));+ const close = document.querySelector<HTMLButtonElement>(+ 'button[aria-label="Close"]'+ )!;+ await act(async () => userEvent.click(close));+ await vi.waitFor(() =>+ expect(document.querySelector('[role="alert"]')).not.toBeNull()+ );+ expect(onOpenChange).not.toHaveBeenCalled();+ expect(session.get(asset.id)?.source).toBe("# Article");+ expect(writes).toEqual([]);+ if (action === "repair") {+ await act(async () => userEvent.fill(editor, "# Repaired article"));+ await act(async () => userEvent.click(close));+ } else {+ const discard = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Discard changes"+ )!;+ await act(async () => userEvent.click(discard));+ }+ await vi.waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));+ await act(async () => session.flush(asset.id));+ expect(session.get(asset.id)?.source).toBe(+ action === "repair" ? "# Repaired article" : "# Article"+ );+ } finally {+ await act(async () => root.unmount());+ container.remove();+ clearBridge();+ session.dispose();+ $authPermit.set(previousPermit);+ $assets.set(new Map());+ }+ }+);diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor.test.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor.test.tsxindex 05298d0f7a..59fd6d5154 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-editor.test.tsx+++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor.test.tsx@@ -11,81 +11,121 @@ import {type Prop,} from "@webstudio-is/sdk";import { $instances, $props } from "~/shared/sync/data-stores";+import { $externalContentRoots } from "~/shared/external-content-mutations";import { __testing__ } from "./text-file-editor";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";const { getMdxCompletionComponents } = __testing__;afterEach(() => {$instances.set(new Map());$props.set(new Map());+ $externalContentRoots.set(new Map());});-test("derives MDX completions from template names instead of labels", () => {- const instances = new Map<string, Instance>([- [- "block",- {- type: "instance",- id: "block",- component: blockComponent,- children: [{ type: "id", value: "templates" }],- },- ],- [- "templates",- {- type: "instance",- id: "templates",- component: blockTemplateComponent,- children: [{ type: "id", value: "promotion-card" }],- },- ],- [- "promotion-card",- {- type: "instance",- id: "promotion-card",- component: elementComponent,- tag: "section",- name: "PromotionCard",- label: "Heading 1",- children: [],- },- ],- ]);- const props = new Map<string, Prop>([- [- "source",- {+test.each(["direct", "dynamic"])(+ "derives MDX completions from template names for a %s source",+ (sourceType) => {+ const instances = new Map<string, Instance>([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "promotion-card" }],+ },+ ],+ [+ "promotion-card",+ {+ type: "instance",+ id: "promotion-card",+ component: elementComponent,+ tag: "section",+ name: "PromotionCard",+ label: "Heading 1",+ children: [],+ },+ ],+ ]);+ const props = new Map<string, Prop>([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset",+ value: "article",+ },+ ],+ [+ "title",+ {+ id: "title",+ instanceId: "promotion-card",+ name: "title",+ type: "string",+ value: "Launch offer",+ },+ ],+ ]);+ $instances.set(instances);+ $props.set(props);+ if (sourceType === "dynamic") {+ props.set("source", {id: "source",instanceId: "block",name: contentBlockSourceProp,- type: "asset",- value: "article",- },- ],- [- "title",- {- id: "title",- instanceId: "promotion-card",- name: "title",- type: "string",- value: "Launch offer",- },- ],- ]);- $instances.set(instances);- $props.set(props);+ type: "expression",+ value: "collection.data._id",+ });+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ sourceBlockInstanceId: "block",+ blockInstanceId: "scoped-block",+ assetId: "article",+ instanceIds: new Set(),+ mutationRevision: 0,+ },+ ],+ ])+ );+ }++ const completions = getMdxCompletionComponents({+ assetId: "article",+ metas: new Map(Object.entries(coreMetas)),+ });+ const promotionCard = completions.find(+ ({ name }) => name === "PromotionCard"+ );+ expect(promotionCard?.props).toContainEqual({ name: "title" });+ expect(completions.some(({ name }) => name === "Heading 1")).toBe(false);+ }+);++test("does not suggest registered custom components without templates", () => {const completions = getMdxCompletionComponents({assetId: "article",- metas: new Map(Object.entries(coreMetas)),+ metas: componentMetas,});- const promotionCard = completions.find(- ({ name }) => name === "PromotionCard"- );-- expect(promotionCard?.props).toContainEqual({ name: "title" });- expect(completions.some(({ name }) => name === "Heading 1")).toBe(false);+ expect(completions.map(({ name }) => name).sort()).toEqual([+ "CodeText",+ "Image",+ ]);});diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsxindex 369df9029e..f2a783a3b8 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx+++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx@@ -6,8 +6,14 @@ import {type ReactNode,type RefObject,} from "react";+import type { Extension } from "@codemirror/state";+import { linter } from "@codemirror/lint";+import { getCollectionEntrySourceIssues } from "@webstudio-is/content-engine";+import { validateTextAssetSource } from "@webstudio-is/content-engine/mdx";+import { useContentCollections } from "~/builder/shared/assets/content-collections";import { useStore } from "@nanostores/react";import {+ PanelContent,Box,Button,cssVar,@@ -49,6 +55,8 @@ import {} from "@webstudio-is/project-build/runtime";import { getJsxPropName } from "@webstudio-is/content-engine/jsx-attributes";import {+ contentBlockMdxTemplateDescriptors,+ getAssetDisplayNameParts,getAssetUrl,getComponentJsxName,getContentBlockTemplateName,@@ -124,6 +132,21 @@ const getStaticMdxCompletionProps = (];});+const getMdxEditorSourceBlockInstanceIds = (assetId: string) =>+ Array.from(+ new Set([+ ...getMdxAssetSourceBlockInstanceIds({+ assetId,+ state: readBuilderStateStores(),+ }),+ ...Array.from($externalContentRoots.get().values()).flatMap((root) =>+ root.assetId === assetId+ ? [root.sourceBlockInstanceId ?? root.blockInstanceId]+ : []+ ),+ ])+ );+const getMdxCompletionComponents = ({assetId,metas,@@ -134,6 +157,14 @@ const getMdxCompletionComponents = ({const components = new Map<string, MdxCompletionComponent>();const componentIds = Array.from(metas.keys());for (const [component, meta] of metas) {+ if (+ contentBlockMdxTemplateDescriptors.some(+ (descriptor) =>+ descriptor.kind === "component" && descriptor.component === component+ ) === false+ ) {+ continue;+ }const name = getComponentJsxName({component,components: componentIds,@@ -165,10 +196,7 @@ const getMdxCompletionComponents = ({propsByInstanceId.set(prop.instanceId, props);}const templates = new Map<string, MdxCompletionComponent>();- for (const blockInstanceId of getMdxAssetSourceBlockInstanceIds({- assetId,- state,- })) {+ for (const blockInstanceId of getMdxEditorSourceBlockInstanceIds(assetId)) {for (const [template] of findBlockTemplates({anchor: [blockInstanceId],instances,@@ -455,11 +483,7 @@ const MarkdownLinkPicker = ({}}content={open && (- <Flex- direction="column"- gap={5}- css={{ padding: theme.panel.padding }}- >+ <PanelContent as={Flex} direction="column" gap={5}><UrlInputinstanceId="markdown-link"prop={value}@@ -489,7 +513,7 @@ const MarkdownLinkPicker = ({Insert link</Button></Flex>- </Flex>+ </PanelContent>)}>@@ -534,7 +558,6 @@ const MarkdownToolbar = ({align="center"gap={2}css={{- minWidth: 0,flex: 1,overflowX: "auto",scrollbarWidth: "none",@@ -573,34 +596,102 @@ const MarkdownToolbar = ({</Flex>);+export const MarkdownEditor = ({+ asset,+ ariaLabel = "Markdown source",+ defaultPreviewOpen = true,+ autoFocus = false,+ value,+ readOnly,+ languageExtensions = [],+ onChange,+ onChangeComplete,+}: {+ asset: Asset;+ ariaLabel?: string;+ defaultPreviewOpen?: boolean;+ autoFocus?: boolean;+ value: string;+ readOnly: boolean;+ languageExtensions?: Extension[];+ onChange: (value: string) => void;+ onChangeComplete: (value: string) => void;+}) => {+ const assetFolders = useStore($assetFolders);+ const { assetContainers } = useAssets();+ const [previewOpen, setPreviewOpen] = useState(defaultPreviewOpen);+ const editorApiRef = useRef<EditorApi>();++ return (+ <Box+ css={{+ display: "grid",+ gridTemplateRows: "auto minmax(0, 1fr)",+ height: "100%",+ minHeight: 0,+ }}+ >+ <MarkdownToolbar+ editorApiRef={editorApiRef}+ disabled={readOnly}+ previewOpen={previewOpen}+ onPreviewOpenChange={setPreviewOpen}+ />+ <MarkdownSplitView+ open={previewOpen}+ source={value}+ sourceAsset={asset}+ folders={assetFolders}+ assetContainers={assetContainers}+ >+ <CodeEditor+ autoFocus={autoFocus}+ ariaLabel={ariaLabel}+ editorApiRef={editorApiRef}+ value={value}+ languageExtensions={languageExtensions}+ size="full"+ expandable={false}+ chromeless+ readOnly={readOnly}+ onChange={onChange}+ onChangeComplete={onChangeComplete}+ />+ </MarkdownSplitView>+ </Box>+ );+};+export const TextFileEditor = ({assetId,onOpenChange,+ readOnly = false,}: {assetId: string;onOpenChange: (open: boolean) => void;+ readOnly?: boolean;}) => {const assets = useStore($assets);- const assetFolders = useStore($assetFolders);const externalContentRoots = useStore($externalContentRoots);const registeredComponentMetas = useStore($registeredComponentMetas);const instances = useStore($instances);const props = useStore($props);const dataSources = useStore($dataSources);const asset = assets.get(assetId);- const { assetContainers } = useAssets();- const canEdit = useStore($authPermit) !== "view";+ const collections = useContentCollections(asset?.folderId);+ const collection =+ asset?.folderId === undefined ? undefined : collections.get(asset.folderId);+ const canEdit = useStore($authPermit) !== "view" && readOnly === false;const [state, setState] = useState<TextFileState>({ status: "loading" });const [persistenceFeedback, setPersistenceFeedback] =useState<MdxPersistenceFeedback>();- const [previewOpen, setPreviewOpen] = useState(true);const currentAssetRef = useRef<Asset>();const persistedContentRef = useRef<string>();const requestedContentRef = useRef<string>();const pendingMdxSavesRef = useRef(0);const saveQueueRef = useRef(Promise.resolve());- const editorApiRef = useRef<EditorApi>();const reportedConflictRef = useRef<string>();+ const saveAttemptRef = useRef(0);const mdxSession =asset !== undefined &&isMdxFileAsset(asset) &&@@ -622,13 +713,14 @@ export const TextFileEditor = ({return getTextFileEditorExtensions(asset);}const projectId = asset.projectId;- return getTextFileEditorExtensions(+ const extensions = getTextFileEditorExtensions(asset,[],async ({ source }) =>inspectMdxAssetSource({source,assetId,+ sourceBlockInstanceIds: getMdxEditorSourceBlockInstanceIds(assetId),state: readBuilderStateStores(),metas: registeredComponentMetas,projectId,@@ -638,12 +730,41 @@ export const TextFileEditor = ({metas: registeredComponentMetas,}));+ if (+ collection?.status === "ready" &&+ collection.config.matchesEntry(formatAssetName(asset))+ ) {+ extensions.push(+ linter(async (view) => {+ try {+ return (+ await getCollectionEntrySourceIssues({+ config: collection.config,+ source: view.state.doc.toString(),+ basename: getAssetDisplayNameParts(asset).basename,+ })+ ).map(({ from, to, message }) => ({+ from,+ to,+ message,+ severity: "error" as const,+ source: "collection-field",+ }));+ } catch {+ // The Markdown linter already reports malformed frontmatter.+ return [];+ }+ })+ );+ }+ return extensions;},// Recreate the linter after a Content Block is materialized or refreshed so// contextual template and content-model diagnostics are recalculated.[asset,assetId,+ collection,dataSources,externalContentRoots,instances,@@ -743,26 +864,45 @@ export const TextFileEditor = ({}): undefined;return () => {+ saveAttemptRef.current += 1;controller.abort();unsubscribe?.();};}, [assetId]);- const save = (content: string) => {+ const save = async (content: string) => {+ const attempt = ++saveAttemptRef.current;if (canEdit === false) {- return;+ return true;}const currentAsset = currentAssetRef.current;if (currentAsset === undefined) {toast.error("Unable to save: asset not found");- return;+ return false;}const normalized = normalizeTextFileContent(currentAsset, content);if ("error" in normalized) {toast.error(normalized.error);- return;+ return false;}const normalizedContent = normalized.content;+ if (isMdxFileAsset(currentAsset)) {+ const { diagnostics } = await validateTextAssetSource({+ source: normalizedContent,+ format: "mdx",+ });+ if (attempt !== saveAttemptRef.current) {+ return false;+ }+ const error = diagnostics.find(({ severity }) => severity === "error");+ if (error !== undefined) {+ setPersistenceFeedback({ kind: "invalid", message: error.message });+ return false;+ }+ setPersistenceFeedback((feedback) =>+ feedback?.kind === "invalid" ? undefined : feedback+ );+ }if (normalizedContent !== content) {setState({ status: "loaded", content: normalizedContent });}@@ -774,7 +914,7 @@ export const TextFileEditor = ({currentAsset.projectId === undefined) {toast.error("Unable to save: MDX content is not loaded");- return;+ return false;}pendingMdxSavesRef.current += 1;void replaceExternalContentAssetSource({@@ -800,7 +940,7 @@ export const TextFileEditor = ({.finally(() => {pendingMdxSavesRef.current -= 1;});- return;+ return true;}saveQueueRef.current = saveQueueRef.current.then(async () => {const requestedContent = requestedContentRef.current;@@ -829,24 +969,37 @@ export const TextFileEditor = ({toast.error(error instanceof Error ? error.message : "Unable to save");}});+ return true;};const title = asset === undefined ? "Text file" : formatAssetName(asset);const isMarkdown = asset !== undefined && isMarkdownAsset(asset);let editor: ReactNode;if (state.status === "loaded" && asset !== undefined) {- editor = (+ const onChange = (content: string) => {+ saveAttemptRef.current += 1;+ setState({ status: "loaded", content });+ };+ editor = isMarkdown ? (+ <MarkdownEditor+ autoFocus+ asset={asset}+ value={state.content}+ readOnly={canEdit === false}+ languageExtensions={languageExtensions}+ onChange={onChange}+ onChangeComplete={save}+ />+ ) : (<CodeEditor- editorApiRef={editorApiRef}+ autoFocusvalue={state.content}languageExtensions={languageExtensions}size="full"expandable={false}chromelessreadOnly={canEdit === false}- onChange={(content) => {- setState({ status: "loaded", content });- }}+ onChange={onChange}onChangeComplete={save}/>);@@ -861,7 +1014,12 @@ export const TextFileEditor = ({openonOpenChange={(open) => {if (open === false && state.status === "loaded") {- save(state.content);+ void save(state.content).then((saved) => {+ if (saved) {+ onOpenChange(false);+ }+ });+ return;}onOpenChange(open);}}@@ -884,11 +1042,10 @@ export const TextFileEditor = ({<Boxcss={{display: "grid",- gridTemplateRows: isMarkdown- ? persistenceFeedback === undefined- ? "auto minmax(0, 1fr)"- : "auto auto minmax(0, 1fr)"- : "minmax(0, 1fr)",+ gridTemplateRows:+ persistenceFeedback === undefined+ ? "minmax(0, 1fr)"+ : "auto minmax(0, 1fr)",height: "100%",}}>@@ -898,9 +1055,20 @@ export const TextFileEditor = ({align="center"css={{ padding: rawTheme.spacing[5] }}>- <Text role="alert" color="destructive" variant="tiny">+ <Text role="alert" color="destructive">{persistenceFeedback.message}</Text>+ {persistenceFeedback.kind === "invalid" && (+ <Button+ color="ghost"+ onClick={() => {+ saveAttemptRef.current += 1;+ onOpenChange(false);+ }}+ >+ Discard changes+ </Button>+ )}{persistenceFeedback.kind === "failed" &&mdxSession !== undefined && (<Button@@ -925,27 +1093,7 @@ export const TextFileEditor = ({)}</Flex>)}- {isMarkdown && (- <MarkdownToolbar- editorApiRef={editorApiRef}- disabled={canEdit === false}- previewOpen={previewOpen}- onPreviewOpenChange={setPreviewOpen}- />- )}- {isMarkdown ? (- <MarkdownSplitView- open={previewOpen}- source={state.content}- sourceAsset={asset}- folders={assetFolders}- assetContainers={assetContainers}- >- {editor}- </MarkdownSplitView>- ) : (- editor- )}+ {editor}</Box>)}</Box>diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.tsindex d258a88679..129805761e 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts@@ -302,7 +302,7 @@ describe("text file assets", () => {{from: 0,to: 6,- severity: "warning",+ severity: "error",source: "unresolved-template",message:'Template "Card" is not available and was skipped. Line 1, column 1.',diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.tsindex b7dd86cf46..dfb85c4dc0 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts@@ -39,7 +39,7 @@ import type { AssetContentSessionState } from "@webstudio-is/content-engine/asseimport { formatContentBlockDiagnostic } from "~/shared/content-block-diagnostics";export type MdxPersistenceFeedback = Readonly<{- kind: "failed" | "conflicting";+ kind: "failed" | "conflicting" | "invalid";message: string;}>;@@ -240,7 +240,10 @@ export const getTextFileEditorDiagnostics = async ({return {from,to,- severity: diagnostic.severity,+ severity:+ diagnostic.code === "unresolved-template"+ ? ("error" as const)+ : diagnostic.severity,source: diagnostic.code,message:"message" in diagnosticdiff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsxindex 74aa613bbb..9e896d3990 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsx@@ -1,11 +1,15 @@-import type { ReactNode } from "react";+import { useState, type ReactNode } from "react";import { act } from "react-dom/test-utils";import { afterEach, beforeEach, expect, test, vi } from "vitest";import { TooltipProvider } from "@webstudio-is/design-system";-import { $assetFolders } from "~/shared/sync/data-stores";+import { $assetFolders, $pages, $project } from "~/shared/sync/data-stores";+import { createDefaultPages } from "@webstudio-is/project-build";+import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";import {AssetFolderSettingsDialog,+ assertCollectionSetupProject,CreateAssetFolderDialog,+ createContentCollectionFolder,MoveAssetManagerItemsDialog,} from "./asset-folder-dialogs";import {@@ -15,10 +19,12 @@ import {import { createAssetManagerTestRenderer } from "./test-utils";const renderer = createAssetManagerTestRenderer();+registerContainers();const render = (children: ReactNode) =>renderer.render(<TooltipProvider>{children}</TooltipProvider>);beforeEach(() => {+ $pages.set(createDefaultPages({ rootInstanceId: "root" }));vi.stubGlobal("ResizeObserver",class {@@ -36,7 +42,13 @@ beforeEach(() => {afterEach(() => {renderer.cleanup();$assetFolders.set(new Map());+ $project.set(undefined);+ $pages.set(undefined);vi.unstubAllGlobals();+ vi.useRealTimers();+ serverSyncStore.popAll();+ serverSyncStore.transactionManager.currentStack = [];+ serverSyncStore.transactionManager.undoneStack = [];});test("Escape closes folder settings without closing the assets panel", () => {@@ -74,12 +86,9 @@ test("Escape closes folder settings without closing the assets panel", () => {expect(onPanelClose).not.toHaveBeenCalled();});-test.each([- { initialDeleteConfirmation: false, focusedAction: "Save" },- { initialDeleteConfirmation: true, focusedAction: "Delete folder" },-])(- "focuses $focusedAction as the rightmost folder settings action",- ({ initialDeleteConfirmation, focusedAction }) => {+test.each([false, true])(+ "focuses the name or the delete confirmation (confirmation: %s)",+ (initialDeleteConfirmation) => {const folder = createAssetFolderFixture({id: "folder",name: "Documents",@@ -95,7 +104,96 @@ test.each([/>);- expect(document.activeElement?.textContent).toBe(focusedAction);+ if (initialDeleteConfirmation) {+ expect(document.activeElement?.textContent).toBe("Delete folder");+ } else {+ expect(document.activeElement).toBe(+ document.getElementById("asset-folder-name-folder")+ );+ }+ }+);++test.each(["debounce", "close"])(+ "saves a folder name without submitting and keeps settings open (%s)",+ (saveBy) => {+ vi.useFakeTimers();+ const folder = createAssetFolderFixture({+ id: "folder",+ name: "Documents",+ });+ $assetFolders.set(createAssetFoldersFixture(folder));+ $project.set({ id: folder.projectId } as never);+ const onOpenChange = vi.fn();+ render(+ <AssetFolderSettingsDialog+ folder={folder}+ open+ onOpenChange={onOpenChange}+ />+ );+ const name = document.querySelector<HTMLInputElement>(+ "#asset-folder-name-folder"+ )!;+ act(() => {+ Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )!.set!.call(name, "Renamed");+ name.dispatchEvent(new InputEvent("input", { bubbles: true }));+ });+ expect($assetFolders.get().get(folder.id)?.name).toBe("Documents");+ act(() => {+ if (saveBy === "debounce") {+ vi.advanceTimersByTime(500);+ } else {+ renderer.cleanup();+ }+ });+ expect($assetFolders.get().get(folder.id)?.name).toBe("Renamed");+ expect(onOpenChange).not.toHaveBeenCalled();+ }+);++test.each(["", "Existing"])(+ "saves a corrected folder name after rejecting an invalid value: %s",+ (value) => {+ vi.useFakeTimers();+ const folder = createAssetFolderFixture({+ id: "folder",+ name: "Documents",+ });+ $assetFolders.set(+ createAssetFoldersFixture(+ folder,+ createAssetFolderFixture({ id: "other", name: "Existing" })+ )+ );+ $project.set({ id: folder.projectId } as never);+ render(+ <AssetFolderSettingsDialog folder={folder} open onOpenChange={vi.fn()} />+ );+ const name = document.querySelector<HTMLInputElement>(+ "#asset-folder-name-folder"+ )!;+ act(() => {+ Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )!.set!.call(name, value);+ name.dispatchEvent(new InputEvent("input", { bubbles: true }));+ });+ act(() => vi.advanceTimersByTime(500));+ expect($assetFolders.get().get(folder.id)?.name).toBe("Documents");+ act(() => {+ Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )!.set!.call(name, "Corrected");+ name.dispatchEvent(new InputEvent("input", { bubbles: true }));+ });+ act(() => vi.advanceTimersByTime(500));+ expect($assetFolders.get().get(folder.id)?.name).toBe("Corrected");});@@ -142,6 +240,214 @@ test("focuses the folder name while the rightmost Create action is disabled", ()).toBe(true);});+test("hides collection creation from content editors", () => {+ render(+ <CreateAssetFolderDialog+ open+ onOpenChange={vi.fn()}+ currentFolderId={undefined}+ canCreateContentCollection={false}+ />+ );++ expect(document.body.textContent).not.toContain("Use as content collection");+});++test("stops collection setup after the active project changes", () => {+ expect(() =>+ assertCollectionSetupProject({+ expectedProjectId: "original-project",+ currentProjectId: "next-project",+ })+ ).toThrow("project changed");+});++test("keeps an incomplete collection setup when the dialog closes", async () => {+ $project.set({ id: "project" } as never);+ const folder = createAssetFolderFixture({ id: "new-folder", name: "Posts" });+ const createFolder = vi.fn();+ const createCollection = vi+ .fn()+ .mockRejectedValueOnce(new Error("The collection could not be created."))+ .mockResolvedValue(folder);+ const Harness = () => {+ const [open, setOpen] = useState(true);+ return (+ <>+ <button onClick={() => setOpen(true)}>Reopen</button>+ <CreateAssetFolderDialog+ open={open}+ onOpenChange={setOpen}+ currentFolderId={undefined}+ createFolder={createFolder}+ createCollection={createCollection}+ />+ </>+ );+ };+ render(<Harness />);++ const name = document.querySelector<HTMLInputElement>("#asset-folder-name");+ if (name === null) {+ throw new Error("Expected folder name field");+ }+ act(() => {+ const valueSetter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set;+ valueSetter?.call(name, "Posts");+ name.dispatchEvent(new InputEvent("input", { bubbles: true }));+ document+ .querySelector<HTMLElement>("#asset-folder-content-collection")+ ?.click();+ });+ await act(async () => {+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Create folder")+ ?.click();+ });+ expect(document.body.textContent).toContain(+ "The collection could not be created."+ );++ act(() => {+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Finish later")+ ?.click();+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Reopen")+ ?.click();+ });++ expect(document.body.textContent).toContain("Finish collection setup");+ expect(createFolder).not.toHaveBeenCalled();+ await act(async () => {+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Retry setup")+ ?.click();+ });+ await vi.waitFor(() => expect(createCollection).toHaveBeenCalledTimes(2));+ expect(createCollection.mock.calls[1]).toEqual(+ createCollection.mock.calls[0]+ );+});++test("creates the collection folder and seed files together", async () => {+ $project.set({ id: "project" } as never);+ const folder = createAssetFolderFixture({ id: "new-folder", name: "Posts" });+ const createFolder = vi.fn();+ const createCollection = vi.fn<typeof createContentCollectionFolder>(+ async () => folder+ );+ const onConfigureCollection = vi.fn();+ render(+ <CreateAssetFolderDialog+ open+ onOpenChange={vi.fn()}+ onConfigureCollection={onConfigureCollection}+ currentFolderId={undefined}+ createFolder={createFolder}+ createCollection={createCollection}+ />+ );++ const name = document.querySelector<HTMLInputElement>("#asset-folder-name");+ if (name === null) {+ throw new Error("Expected folder name field");+ }+ act(() => {+ const valueSetter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set;+ valueSetter?.call(name, "Posts");+ name.dispatchEvent(new InputEvent("input", { bubbles: true }));+ document+ .querySelector<HTMLElement>("#asset-folder-content-collection")+ ?.click();+ });+ await act(async () => {+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Create folder")+ ?.click();+ });++ await vi.waitFor(() => expect(createCollection).toHaveBeenCalledOnce());+ await vi.waitFor(() =>+ expect(document.body.textContent).toContain("Collection created")+ );+ act(() => {+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Configure collection")+ ?.click();+ });+ const collectionId = createCollection.mock.calls[0]?.[0].id;+ expect(onConfigureCollection).toHaveBeenCalledWith(collectionId);+ expect(createFolder).not.toHaveBeenCalled();+ expect(createCollection).toHaveBeenCalledWith({+ id: expect.any(String),+ name: "Posts",+ parentId: undefined,+ projectId: "project",+ });+});++test("sets up a collection using the existing folder identity from settings", async () => {+ const folder = {+ ...createAssetFolderFixture({ id: "existing", name: "Posts" }),+ projectId: "project",+ };+ $project.set({ id: "project" } as never);+ $assetFolders.set(createAssetFoldersFixture(folder));+ const createCollection = vi.fn<typeof createContentCollectionFolder>(+ async () => folder+ );+ const createFolder = vi.fn();+ const configure = vi.fn();+ const Harness = () => {+ const [setup, setSetup] = useState(false);+ return (+ <>+ <AssetFolderSettingsDialog+ folder={folder}+ open={!setup}+ onOpenChange={vi.fn()}+ onUseAsCollection={() => setSetup(true)}+ />+ <CreateAssetFolderDialog+ existingFolder={folder}+ open={setup}+ onOpenChange={vi.fn()}+ currentFolderId={undefined}+ createCollection={createCollection}+ createFolder={createFolder}+ onConfigureCollection={configure}+ />+ </>+ );+ };+ render(<Harness />);+ const clickAction = (name: string) => {+ const button = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === name+ );+ expect(button).toBeInstanceOf(HTMLButtonElement);+ button!.click();+ };+ act(() => clickAction("Use as content collection"));+ await act(async () => clickAction("Use as content collection"));+ expect(createCollection).toHaveBeenCalledWith({+ id: folder.id,+ name: folder.name,+ parentId: folder.parentId,+ projectId: folder.projectId,+ });+ expect(createFolder).not.toHaveBeenCalled();+ act(() => clickAction("Configure collection"));+ expect(configure).toHaveBeenCalledWith(folder.id);+});+test("moves items to the selected folder from the folder-only dialog", () => {const destination = createAssetFolderFixture({id: "destination",diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsxindex 647424994f..455a19b70a 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsx@@ -7,8 +7,11 @@ import {} from "react";import { useStore } from "@nanostores/react";import {+ PanelContent,Box,Button,+ Checkbox,+ CheckboxAndLabel,Dialog,DialogContent,DialogTitle,@@ -18,21 +21,34 @@ import {Label,SmallIconButton,Text,+ toast,theme,} from "@webstudio-is/design-system";import {+ createId,createAssetFolderHierarchy,+ type Asset,type AssetFolder,} from "@webstudio-is/sdk";import { CopyIcon, TrashIcon } from "@webstudio-is/icons";-import { $assetFolders } from "~/shared/sync/data-stores";-import { executeRuntimeMutation } from "~/shared/instance-utils/data";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";+import { $assetFolders, $assets, $project } from "~/shared/sync/data-stores";+import {+ executeRuntimeMutation,+ getWebstudioData,+} from "~/shared/instance-utils/data";import { CopyToClipboard } from "~/shared/copy-to-clipboard";import { AssetFolderSelector } from "./asset-folder-selector";+import { fetch } from "~/shared/fetch.client";+import { createTransactionFromBuilderPatchPayload } from "~/shared/sync/builder-patch";+import { onNextTransactionComplete } from "~/shared/sync/project-queue";+import { invalidateAssets } from "~/shared/resources";+import { useDraftValue } from "~/builder/shared/use-draft-value";type AssetFolderFormValues = {name: string;parentId: string | undefined;+ useAsContentCollection?: boolean;};const closeOnSuccess = (@@ -50,27 +66,121 @@ const stopEscapePropagation = (event: KeyboardEvent) => {}};+export const assertCollectionSetupProject = ({+ expectedProjectId,+ currentProjectId,+}: {+ expectedProjectId: string;+ currentProjectId: string | undefined;+}) => {+ if (currentProjectId !== expectedProjectId) {+ throw new Error(+ "The project changed before collection setup finished. Return to the original project to retry."+ );+ }+};++const createAssetFolder = (values: AssetFolderFormValues) => {+ const result = executeRuntimeMutation({+ id: "assetFolders.create",+ input: { name: values.name, parentId: values.parentId },+ });+ if (result === undefined) {+ return;+ }+ return result.result;+};++export const createContentCollectionFolder = async ({+ id,+ name,+ parentId,+ projectId,+ request = fetch,+}: {+ id: string;+ name: string;+ parentId: string | undefined;+ projectId: string;+ request?: typeof fetch;+}) => {+ const response = await request(+ `/rest/assets/collection-folders?projectId=${encodeURIComponent(projectId)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ id, name, parentId }),+ }+ );+ const payload = (await response.json()) as+ | { folder: AssetFolder; assets: Asset[] }+ | { errors?: string };+ if (response.ok === false || "folder" in payload === false) {+ throw new Error(+ "errors" in payload && typeof payload.errors === "string"+ ? payload.errors+ : "The collection could not be created."+ );+ }+ assertCollectionSetupProject({+ expectedProjectId: projectId,+ currentProjectId: $project.get()?.id,+ });+ const changes: BuilderPatchChange[] = [];+ if ($assetFolders.get().has(payload.folder.id) === false) {+ changes.push({+ namespace: "assetFolders",+ patches: [+ { op: "add", path: [payload.folder.id], value: payload.folder },+ ],+ });+ }+ const newAssets = payload.assets.filter(+ (asset) => $assets.get().has(asset.id) === false+ );+ if (newAssets.length > 0) {+ changes.push({+ namespace: "assets",+ patches: newAssets.map((asset) => ({+ op: "add",+ path: [asset.id],+ value: asset,+ })),+ });+ }+ if (changes.length === 0) {+ invalidateAssets();+ } else {+ createTransactionFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: changes,+ });+ onNextTransactionComplete(invalidateAssets);+ }+ return payload.folder;+};+const AssetFolderForm = ({id,- open,initialName,initialParentId,excludedFolderId,folderId,- autoFocusSubmit = false,submitLabel,secondaryAction,+ showCollectionOption = false,+ onUseAsCollection,onSubmit,}: {id: string;- open: boolean;initialName: string;initialParentId: string | undefined;excludedFolderId?: string;folderId?: string;- autoFocusSubmit?: boolean;- submitLabel: string;+ submitLabel?: string;secondaryAction?: ReactNode;+ showCollectionOption?: boolean;+ onUseAsCollection?: () => void;onSubmit: (values: AssetFolderFormValues) => void;}) => {const folders = useStore($assetFolders);@@ -83,15 +193,28 @@ const AssetFolderForm = ({excludedFolderId === undefined ? undefined : new Set([excludedFolderId]),[excludedFolderId]);- const [name, setName] = useState(initialName);- const [parentId, setParentId] = useState(initialParentId);-- useLayoutEffect(() => {- if (open) {- setName(initialName);- setParentId(initialParentId);+ const savedValues = useMemo(+ () => ({ name: initialName, parentId: initialParentId }),+ [initialName, initialParentId]+ );+ const draft = useDraftValue(+ savedValues,+ (values) =>+ onSubmit({+ ...values,+ name: values.name.trim(),+ }),+ {+ autoSave: folderId !== undefined,+ shouldSave: (values) =>+ folderId !== undefined &&+ values.name.trim().length > 0 &&+ hierarchy.findByName({ ...values, excludeIds: excludedFolderIds }) ===+ undefined,}- }, [initialName, initialParentId, open]);+ );+ const { name, parentId } = draft.value;+ const [useAsContentCollection, setUseAsContentCollection] = useState(false);const normalizedName = name.trim();const duplicate =@@ -102,21 +225,32 @@ const AssetFolderForm = ({}) !== undefined;const canSubmit = normalizedName.length > 0 && duplicate === false;const submit = () => {+ if (folderId !== undefined) {+ draft.save();+ return;+ }if (canSubmit) {- onSubmit({ name: normalizedName, parentId });+ onSubmit({+ name: normalizedName,+ parentId,+ ...(showCollectionOption ? { useAsContentCollection } : {}),+ });}};return (- <Grid gap={3} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} gap={3}><Grid gap={1}><Label htmlFor={id}>Name</Label><InputFieldid={id}- autoFocus={autoFocusSubmit === false}+ autoFocusvalue={name}color={duplicate ? "error" : undefined}- onChange={(event) => setName(event.target.value)}+ onChange={(event) =>+ draft.set({ ...draft.value, name: event.target.value })+ }+ onBlur={folderId === undefined ? undefined : draft.save}onKeyDown={(event) => {if (event.key === "Enter") {submit();@@ -131,10 +265,25 @@ const AssetFolderForm = ({</Grid><AssetFolderSelectorvalue={parentId}- onChange={setParentId}+ onChange={(parentId) => draft.set({ ...draft.value, parentId })}+ deferChangesUntilBlur={folderId !== undefined}excludedFolderIds={excludedFolderIds}rootLabel="Parent folder"/>+ {showCollectionOption && (+ <CheckboxAndLabel>+ <Checkbox+ id="asset-folder-content-collection"+ checked={useAsContentCollection}+ onCheckedChange={(checked) =>+ setUseAsContentCollection(checked === true)+ }+ />+ <Label htmlFor="asset-folder-content-collection">+ Use as content collection+ </Label>+ </CheckboxAndLabel>+ )}{folderId !== undefined && (<Grid gap={1}><Label htmlFor={`asset-folder-id-${folderId}`}>ID</Label>@@ -155,55 +304,241 @@ const AssetFolderForm = ({/></Grid>)}- <Flex justify="end" gap={2}>- {secondaryAction}- <Button- color="primary"- autoFocus={autoFocusSubmit}- disabled={canSubmit === false}- onClick={submit}- >- {submitLabel}- </Button>- </Flex>- </Grid>+ {onUseAsCollection !== undefined && (+ <Button onClick={onUseAsCollection}>Use as content collection</Button>+ )}+ {(secondaryAction !== undefined || submitLabel !== undefined) && (+ <Flex justify="end" gap={2}>+ {secondaryAction}+ {submitLabel !== undefined && (+ <Button+ color="primary"+ disabled={canSubmit === false}+ onClick={submit}+ >+ {submitLabel}+ </Button>+ )}+ </Flex>+ )}+ </PanelContent>);};export const CreateAssetFolderDialog = ({open,onOpenChange,+ onConfigureCollection,currentFolderId,+ existingFolder,+ canCreateContentCollection = true,+ createFolder = createAssetFolder,+ createCollection = createContentCollectionFolder,}: {open: boolean;onOpenChange: (open: boolean) => void;+ onConfigureCollection?: (folderId: string) => void;currentFolderId: string | undefined;+ existingFolder?: AssetFolder;+ canCreateContentCollection?: boolean;+ createFolder?: (+ values: AssetFolderFormValues+ ) => { folderId: string } | undefined;+ createCollection?: typeof createContentCollectionFolder;}) => {- const create = (values: AssetFolderFormValues) =>- closeOnSuccess(- executeRuntimeMutation({- id: "assetFolders.create",- input: values,- }),- onOpenChange- );+ const [pendingCollection, setPendingCollection] = useState<{+ folderId: string;+ projectId: string;+ name: string;+ parentId: string | undefined;+ }>();+ const [initializing, setInitializing] = useState(false);+ const [initializationError, setInitializationError] = useState<string>();+ const [createdCollectionFolderId, setCreatedCollectionFolderId] =+ useState<string>();++ const finishCollectionSetup = (pending: {+ folderId: string;+ projectId: string;+ name: string;+ parentId: string | undefined;+ }) => {+ setInitializing(true);+ setInitializationError(undefined);+ void (async () => {+ assertCollectionSetupProject({+ expectedProjectId: pending.projectId,+ currentProjectId: $project.get()?.id,+ });+ await createCollection({+ id: pending.folderId,+ name: pending.name,+ parentId: pending.parentId,+ projectId: pending.projectId,+ });+ })()+ .then(() => {+ setPendingCollection(undefined);+ setCreatedCollectionFolderId(pending.folderId);+ toast.success("Collection folder created.");+ })+ .catch((error) => {+ const message =+ error instanceof Error+ ? error.message+ : "The collection could not be created.";+ setInitializationError(message);+ toast.error(message);+ })+ .finally(() => setInitializing(false));+ };++ const create = (values: AssetFolderFormValues) => {+ const projectId = $project.get()?.id;+ if (projectId === undefined) {+ toast.error("Project not found");+ return;+ }+ if (values.useAsContentCollection !== true) {+ const result = createFolder(values);+ if (result === undefined) {+ return;+ }+ onOpenChange(false);+ return;+ }+ const pending = {+ folderId: existingFolder?.id ?? createId(),+ projectId: existingFolder?.projectId ?? projectId,+ name: values.name,+ parentId: values.parentId,+ };+ setPendingCollection(pending);+ finishCollectionSetup(pending);+ };return (- <Dialog open={open} onOpenChange={onOpenChange}>+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (initializing === false) {+ if (nextOpen === false) {+ setCreatedCollectionFolderId(undefined);+ }+ onOpenChange(nextOpen);+ }+ }}+ ><DialogContent- minWidth={360}+ css={{ width: "min(420px, calc(100vw - 32px))" }}aria-describedby={undefined}onKeyDown={stopEscapePropagation}>- <DialogTitle>New folder</DialogTitle>- <AssetFolderForm- id="asset-folder-name"- open={open}- initialName=""- initialParentId={currentFolderId}- submitLabel="Create folder"- onSubmit={create}- />+ <DialogTitle>+ {createdCollectionFolderId !== undefined+ ? "Collection created"+ : pendingCollection === undefined+ ? existingFolder === undefined+ ? "New folder"+ : "Use as content collection"+ : "Finish collection setup"}+ </DialogTitle>+ {createdCollectionFolderId !== undefined ? (+ <PanelContent as={Grid} gap={3}>+ <Text>+ The collection files are ready. You can configure its fields and+ entry rules now.+ </Text>+ <Flex justify="end" gap={2}>+ <Button+ autoFocus={onConfigureCollection === undefined}+ onClick={() => {+ setCreatedCollectionFolderId(undefined);+ onOpenChange(false);+ }}+ >+ Done+ </Button>+ {onConfigureCollection !== undefined && (+ <Button+ autoFocus+ color="primary"+ onClick={() => {+ setCreatedCollectionFolderId(undefined);+ onOpenChange(false);+ onConfigureCollection(createdCollectionFolderId);+ }}+ >+ Configure collection+ </Button>+ )}+ </Flex>+ </PanelContent>+ ) : pendingCollection === undefined && existingFolder !== undefined ? (+ <PanelContent as={Grid} gap={3}>+ <Text>+ Add collection.json and template.mdx to “{existingFolder.name}” so+ editors can create entries. Existing files stay unchanged. MDX+ files become entries; other files are ignored by collection+ validation.+ </Text>+ <Flex justify="end">+ <Button+ autoFocus+ color="primary"+ onClick={() =>+ create({+ name: existingFolder.name,+ parentId: existingFolder.parentId,+ useAsContentCollection: true,+ })+ }+ >+ Use as content collection+ </Button>+ </Flex>+ </PanelContent>+ ) : pendingCollection === undefined ? (+ <AssetFolderForm+ id="asset-folder-name"+ initialName=""+ initialParentId={currentFolderId}+ submitLabel="Create folder"+ showCollectionOption={canCreateContentCollection}+ onSubmit={create}+ />+ ) : (+ <PanelContent as={Grid} gap={3}>+ <Text>+ {initializing+ ? "Creating the collection template and configuration…"+ : "The folder was created, but its collection files are incomplete."}+ </Text>+ {initializationError !== undefined && (+ <Text role="alert" color="destructive" variant="tiny">+ {initializationError}+ </Text>+ )}+ <Flex justify="end" gap={2} wrap="wrap">+ {initializing === false && (+ <Button+ onClick={() => {+ onOpenChange(false);+ }}+ >+ Finish later+ </Button>+ )}+ <Button+ color="primary"+ disabled={initializing}+ onClick={() => finishCollectionSetup(pendingCollection)}+ >+ {initializing ? "Setting up…" : "Retry setup"}+ </Button>+ </Flex>+ </PanelContent>+ )}</DialogContent></Dialog>);@@ -214,33 +549,35 @@ export const AssetFolderSettingsDialog = ({open,onOpenChange,initialDeleteConfirmation = false,+ canDelete = true,+ onUseAsCollection,}: {folder: AssetFolder;open: boolean;onOpenChange: (open: boolean) => void;initialDeleteConfirmation?: boolean;+ canDelete?: boolean;+ onUseAsCollection?: () => void;}) => {const [confirmDelete, setConfirmDelete] = useState(false);useLayoutEffect(() => {if (open) {- setConfirmDelete(initialDeleteConfirmation);+ setConfirmDelete(canDelete && initialDeleteConfirmation);}- }, [initialDeleteConfirmation, open]);+ }, [canDelete, initialDeleteConfirmation, open]);- const save = (values: AssetFolderFormValues) =>- closeOnSuccess(- executeRuntimeMutation({- id: "assetFolders.update",- input: {- folderId: folder.id,- values: {- name: values.name,- parentId: values.parentId ?? null,- },+ const save = (values: AssetFolderFormValues) => {+ executeRuntimeMutation({+ id: "assetFolders.update",+ input: {+ folderId: folder.id,+ values: {+ name: values.name,+ parentId: values.parentId ?? null,},- }),- onOpenChange- );+ },+ });+ };const remove = () =>closeOnSuccess(@@ -261,8 +598,8 @@ export const AssetFolderSettingsDialog = ({<DialogTitle>{confirmDelete ? "Delete folder" : "Folder settings"}</DialogTitle>- {confirmDelete ? (- <Box css={{ padding: theme.panel.padding }}>+ {canDelete && confirmDelete ? (+ <PanelContent as={Box}><Text>Delete “{folder.name}”? Everything inside this folder, includingnested folders and assets, will be deleted.@@ -277,26 +614,26 @@ export const AssetFolderSettingsDialog = ({Delete folder</Button></Flex>- </Box>+ </PanelContent>) : (<AssetFolderFormid={`asset-folder-name-${folder.id}`}- open={open}initialName={folder.name}initialParentId={folder.parentId}excludedFolderId={folder.id}folderId={folder.id}- autoFocusSubmit- submitLabel="Save"onSubmit={save}+ onUseAsCollection={onUseAsCollection}secondaryAction={- <Button- color="destructive"- prefix={<TrashIcon />}- onClick={() => setConfirmDelete(true)}- >- Delete- </Button>+ canDelete ? (+ <Button+ color="destructive"+ prefix={<TrashIcon />}+ onClick={() => setConfirmDelete(true)}+ >+ Delete+ </Button>+ ) : undefined}/>)}@@ -335,7 +672,7 @@ export const MoveAssetManagerItemsDialog = ({onKeyDown={stopEscapePropagation}><DialogTitle>Move items</DialogTitle>- <Grid gap={3} css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid} gap={3}><AssetFolderSelectorvalue={folderId}onChange={setFolderId}@@ -355,7 +692,7 @@ export const MoveAssetManagerItemsDialog = ({Move</Button></Flex>- </Grid>+ </PanelContent></DialogContent></Dialog>);diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.test.tsindex 5ed134dc86..de0317d77d 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.test.ts+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.test.ts@@ -1,5 +1,8 @@-import { describe, expect, test } from "vitest";+import { createElement, Fragment } from "react";+import { act } from "react-dom/test-utils";+import { afterEach, describe, expect, test, vi } from "vitest";import {+ AssetFolderSelector,createAssetFolderSelectorLevels,getAssetFolderSelectValue,} from "./asset-folder-selector";@@ -7,9 +10,56 @@ import {createAssetFolderFixture,createAssetFoldersFixture as folders,} from "@webstudio-is/sdk/testing";+import { $assetFolders } from "~/shared/sync/data-stores";+import { createAssetManagerTestRenderer } from "./test-utils";const folder = (id: string, parentId?: string) =>createAssetFolderFixture({ id, parentId });+const renderer = createAssetManagerTestRenderer();++afterEach(() => {+ renderer.cleanup();+ $assetFolders.set(new Map());+});++const selectOption = (triggerLabel: string, optionLabel: string) => {+ const trigger = document.querySelector<HTMLButtonElement>(+ `[aria-label="${triggerLabel}"]`+ );+ expect(trigger).toBeInstanceOf(HTMLButtonElement);+ act(() => {+ trigger?.dispatchEvent(+ new PointerEvent("pointerdown", {+ bubbles: true,+ button: 0,+ pointerId: 1,+ pointerType: "mouse",+ })+ );+ });+ const option = Array.from(+ document.querySelectorAll<HTMLElement>('[role="option"]')+ ).find((candidate) => candidate.textContent === optionLabel);+ expect(option).toBeInstanceOf(HTMLElement);+ act(() => {+ option?.dispatchEvent(+ new PointerEvent("pointerdown", {+ bubbles: true,+ button: 0,+ pointerId: 1,+ pointerType: "mouse",+ })+ );+ option?.dispatchEvent(+ new PointerEvent("pointerup", {+ bubbles: true,+ button: 0,+ pointerId: 1,+ pointerType: "mouse",+ })+ );+ });+};describe("asset folder selector levels", () => {const values = folders(@@ -83,15 +133,106 @@ describe("asset folder selector levels", () => {expect(level.selected).toEqual({label: "Root",folderId: undefined,+ canUseAsDestination: true,});});- test("uses non-empty unique select values for Root and folders", () => {+ test("blocks only exact unavailable destinations while preserving their descendants", () => {+ const levels = createAssetFolderSelectorLevels({+ folders: values,+ value: "grandchild",+ unavailableDestinationFolderIds: new Set(["parent"]),+ });+expect(- getAssetFolderSelectValue({ label: "Root", folderId: undefined })- ).toBe("no-folder");+ levels.flatMap(({ options }) =>+ options+ .filter(({ folderId }) => folderId === "parent")+ .map(({ canUseAsDestination }) => canUseAsDestination)+ )+ ).toEqual([false, false]);expect(- getAssetFolderSelectValue({ label: "Folder", folderId: "no-folder" })- ).toBe("folder:no-folder");+ levels.flatMap(({ options }) =>+ options+ .filter(+ ({ folderId }) => folderId === "child" || folderId === "grandchild"+ )+ .map(({ canUseAsDestination }) => canUseAsDestination)+ )+ ).toEqual([true, true, true]);+ });++ test("navigates through an unavailable destination and commits its descendant", () => {+ $assetFolders.set(values);+ const onChange = vi.fn();+ renderer.render(+ createElement(AssetFolderSelector, {+ value: undefined,+ onChange,+ unavailableDestinationFolderIds: new Set(["parent"]),+ })+ );++ selectOption("Top level folder", "parent");++ expect(onChange).not.toHaveBeenCalled();+ expect(+ document.querySelector('[aria-label="Asset subfolder level 1"]')+ ).toBeInstanceOf(HTMLButtonElement);++ selectOption("Asset subfolder level 1", "child");++ expect(onChange).toHaveBeenCalledOnce();+ expect(onChange).toHaveBeenCalledWith("child");+ });++ test("announces an unavailable destination and restores the committed folder on blur", async () => {+ $assetFolders.set(values);+ const onChange = vi.fn();+ renderer.render(+ createElement(+ Fragment,+ {},+ createElement(AssetFolderSelector, {+ value: undefined,+ onChange,+ unavailableDestinationFolderIds: new Set(["parent"]),+ deferChangesUntilBlur: true,+ }),+ createElement("button", { type: "button" }, "Outside")+ )+ );++ selectOption("Top level folder", "parent");++ expect(document.querySelector('[role="status"]')?.textContent).toContain(+ "Choose a subfolder"+ );+ expect(+ document.querySelector('[aria-label="Top level folder"]')?.textContent+ ).toContain("parent");+ expect(onChange).not.toHaveBeenCalled();++ await act(async () => {+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Outside")+ ?.focus();+ await Promise.resolve();+ });++ expect(+ document.querySelector('[aria-label="Top level folder"]')?.textContent+ ).toContain("Root");+ expect(document.querySelector('[role="status"]')).toBeNull();+ expect(onChange).not.toHaveBeenCalled();+ });++ test("uses non-empty unique select values for Root and folders", () => {+ expect(getAssetFolderSelectValue({ folderId: undefined })).toBe(+ "no-folder"+ );+ expect(getAssetFolderSelectValue({ folderId: "no-folder" })).toBe(+ "folder:no-folder"+ );});});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.tsxindex 6f733e6c07..869e829114 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.tsx@@ -7,7 +7,7 @@ import {useState,} from "react";import { useStore } from "@nanostores/react";-import { Flex, Grid, Label, Select } from "@webstudio-is/design-system";+import { Flex, Grid, Label, Select, Text } from "@webstudio-is/design-system";import { ChevronRightIcon } from "@webstudio-is/icons";import {createAssetFolderHierarchy,@@ -15,21 +15,27 @@ import {} from "@webstudio-is/sdk";import { $assetFolders } from "~/shared/sync/data-stores";-type Option = { label: string; folderId: string | undefined };+type Option = {+ label: string;+ folderId: string | undefined;+ canUseAsDestination: boolean;+};const defaultRootLabel = "Top level folder";-export const getAssetFolderSelectValue = (option: Option) =>+export const getAssetFolderSelectValue = (option: Pick<Option, "folderId">) =>option.folderId === undefined ? "no-folder" : `folder:${option.folderId}`;export const createAssetFolderSelectorLevels = ({folders,value,excludedFolderIds,+ unavailableDestinationFolderIds,rootLabel = defaultRootLabel,}: {folders: AssetFolders;value: string | undefined;excludedFolderIds?: ReadonlySet<string>;+ unavailableDestinationFolderIds?: ReadonlySet<string>;rootLabel?: string;}) => {const hierarchy = createAssetFolderHierarchy(folders);@@ -48,10 +54,12 @@ export const createAssetFolderSelectorLevels = ({.getPath(value).filter(({ id }) => excludedIds.has(id) === false);const topOptions: Option[] = [- { label: "Root", folderId: undefined },+ { label: "Root", folderId: undefined, canUseAsDestination: true },...getChildren(undefined).map((folder) => ({label: folder.name,folderId: folder.id,+ canUseAsDestination:+ unavailableDestinationFolderIds?.has(folder.id) !== true,})),];const levels = [@@ -73,10 +81,14 @@ export const createAssetFolderSelectorLevels = ({{label: "This folder",folderId: folder.id,+ canUseAsDestination:+ unavailableDestinationFolderIds?.has(folder.id) !== true,},...children.map((child) => ({label: child.name,folderId: child.id,+ canUseAsDestination:+ unavailableDestinationFolderIds?.has(child.id) !== true,})),];const nextId = path[index + 1]?.id;@@ -94,6 +106,7 @@ export const AssetFolderSelector = ({value,onChange,excludedFolderIds,+ unavailableDestinationFolderIds,rootLabel = defaultRootLabel,disabled,deferChangesUntilBlur = false,@@ -101,6 +114,7 @@ export const AssetFolderSelector = ({value: string | undefined;onChange: (folderId: string | undefined) => void;excludedFolderIds?: ReadonlySet<string>;+ unavailableDestinationFolderIds?: ReadonlySet<string>;rootLabel?: string;disabled?: boolean;deferChangesUntilBlur?: boolean;@@ -109,7 +123,12 @@ export const AssetFolderSelector = ({const selectId = useId();const [draftValue, setDraftValue] = useState(value);const pendingValue = useRef<{ folderId: string | undefined }>();+ const selectorRef = useRef<HTMLDivElement | null>(null);+ const committedValue = useRef(value);+ committedValue.current = value;+ const navigatingUnavailableDestination = useRef(false);const openSelects = useRef(new Set<number>());+ const [destinationNotice, setDestinationNotice] = useState<string>();const onChangeRef = useRef(onChange);onChangeRef.current = onChange;@@ -121,10 +140,20 @@ export const AssetFolderSelector = ({pendingValue.current = undefined;onChangeRef.current(pending.folderId);}, []);+ const restoreCommittedValue = useCallback(() => {+ if (navigatingUnavailableDestination.current === false) {+ return;+ }+ navigatingUnavailableDestination.current = false;+ setDraftValue(committedValue.current);+ setDestinationNotice(undefined);+ }, []);useEffect(() => {if (pendingValue.current === undefined) {+ navigatingUnavailableDestination.current = false;setDraftValue(value);+ setDestinationNotice(undefined);}}, [value]);@@ -143,27 +172,45 @@ export const AssetFolderSelector = ({folders,value: draftValue,excludedFolderIds,+ unavailableDestinationFolderIds,rootLabel,}),- [draftValue, excludedFolderIds, folders, rootLabel]+ [+ draftValue,+ excludedFolderIds,+ folders,+ rootLabel,+ unavailableDestinationFolderIds,+ ]);return (<Grid+ ref={selectorRef}gap={1}onBlurCapture={(event) => {- if (deferChangesUntilBlur === false) {+ if (+ deferChangesUntilBlur === false &&+ navigatingUnavailableDestination.current === false+ ) {return;}const selector = event.currentTarget;queueMicrotask(() => {+ if (selectorRef.current !== selector) {+ return;+ }if (openSelects.current.size > 0 ||selector.contains(document.activeElement)) {return;}- commitPendingValue();+ if (pendingValue.current !== undefined) {+ commitPendingValue();+ return;+ }+ restoreCommittedValue();});}}>@@ -185,10 +232,29 @@ export const AssetFolderSelector = ({openSelects.current.add(index);} else {openSelects.current.delete(index);+ queueMicrotask(() => {+ if (+ openSelects.current.size === 0 &&+ selectorRef.current?.contains(document.activeElement) ===+ false+ ) {+ restoreCommittedValue();+ }+ });}}}onChange={(option: Option) => {setDraftValue(option.folderId);+ if (option.canUseAsDestination === false) {+ pendingValue.current = undefined;+ navigatingUnavailableDestination.current = true;+ setDestinationNotice(+ `${option.label} is a collection folder. Choose a subfolder.`+ );+ return;+ }+ navigatingUnavailableDestination.current = false;+ setDestinationNotice(undefined);if (deferChangesUntilBlur) {pendingValue.current = { folderId: option.folderId };} else {@@ -200,6 +266,11 @@ export const AssetFolderSelector = ({</Flex>))}</Flex>+ {destinationNotice !== undefined && (+ <Text role="status" color="subtle" variant="tiny">+ {destinationNotice}+ </Text>+ )}</Grid>);};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-thumbnail.stories.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-thumbnail.stories.tsxnew file mode 100644index 0000000000..e938130925--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-thumbnail.stories.tsx@@ -0,0 +1,87 @@+import type { Meta, StoryObj } from "@storybook/react";+import { Grid } from "@webstudio-is/design-system";+import {+ createDefaultCollectionConfig,+ parseCollectionConfig,+} from "@webstudio-is/content-engine";+import type { Asset } from "@webstudio-is/sdk";+import { FolderThumbnail } from "./asset-folder-thumbnail";+import type { ContentCollection } from "../assets/content-collections";++const configAsset: Asset = {+ id: "config",+ projectId: "project",+ name: "collection.json",+ filename: "collection",+ format: "json",+ type: "file",+ size: 1,+ createdAt: "2026-09-07T00:00:00.000Z",+ meta: {},+};+const collection: ContentCollection = {+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset: {+ ...configAsset,+ id: "template",+ name: "template.mdx",+ filename: "template",+ format: "mdx",+ },+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: {},+};+const invalidCollection: ContentCollection = {+ status: "invalid",+ folderId: "invalid",+ configAsset,+ reservedAssets: [configAsset],+ siblingAssets: [configAsset],+ repairAsset: configAsset,+ message: "Invalid collection configuration",+};++export default {+ title: "Asset Manager/Folder thumbnails",+ component: FolderThumbnail,+} satisfies Meta<typeof FolderThumbnail>;++export const Default: StoryObj = {+ render: () => (+ <Grid gap={3} css={{ width: 280, gridTemplateColumns: "repeat(3, 1fr)" }}>+ {[false, true].flatMap((selected) =>+ [undefined, collection, invalidCollection].map((collection, index) => {+ const name = ["Folder", "Collection", "Invalid"][index];+ return (+ <FolderThumbnail+ key={`${selected}-${name}`}+ folder={{+ id: `${selected}-${name}`,+ projectId: "project",+ name,+ createdAt: "2026-09-07T00:00:00.000Z",+ }}+ collection={collection}+ selected={selected}+ canManage+ onOpen={() => undefined}+ canMoveItems={() => false}+ onMoveItems={() => undefined}+ interactions={{+ onSelectionChange: () => undefined,+ onItemPointerDown: () => undefined,+ onItemClick: () => undefined,+ onModifiedArrow: () => undefined,+ onContextMenuSelection: () => undefined,+ onContextMenuActions: () => undefined,+ getDragItems: (item) => [item],+ }}+ />+ );+ })+ )}+ </Grid>+ ),+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-thumbnail.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-thumbnail.tsxindex a251be1eae..40b45e3951 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-folder-thumbnail.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-thumbnail.tsx@@ -1,12 +1,23 @@import { useEffect, useRef, useState } from "react";-import { ChevronRightIcon, FolderIcon } from "@webstudio-is/icons";+import { useStore } from "@nanostores/react";+import { Grid, theme } from "@webstudio-is/design-system";+import {+ AlertCircleIcon,+ ChevronRightIcon,+ FolderIcon,+ ListViewIcon,+} from "@webstudio-is/icons";import type { AssetFolder } from "@webstudio-is/sdk";import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine";import {draggable,dropTargetForElements,} from "@atlaskit/pragmatic-drag-and-drop/element/adapter";-import { AssetFolderSettingsDialog } from "./asset-folder-dialogs";+import {+ AssetFolderSettingsDialog,+ CreateAssetFolderDialog,+ type createContentCollectionFolder,+} from "./asset-folder-dialogs";import {AssetThumbnailCard,AssetThumbnailGroup,@@ -25,6 +36,17 @@ import {AssetManagerThumbnailMenu,type AssetManagerThumbnailInteractions,} from "./asset-manager-thumbnail";+import {+ canConfigureContentCollections,+ canAddAssetToContentCollection,+ type ContentCollection,+} from "../assets/content-collections";+import {+ CollectionSettingsDialog,+ ConvertCollectionDialog,+} from "./collection-settings-dialog";+import { $authPermit, $isContentMode } from "~/shared/nano-states";+import { $assets } from "~/shared/sync/data-stores";export const FolderThumbnail = ({folder,@@ -32,6 +54,9 @@ export const FolderThumbnail = ({interactions,onOpen,canManage,+ canCopyOrDelete = true,+ canPasteClipboard,+ onPasteClipboard,canMoveItems,onMoveItems,onMove,@@ -39,12 +64,18 @@ export const FolderThumbnail = ({onElementChange,forcedSelection,selectionActions,+ collection,+ createCollection,+ onConfigureCollection,}: {folder: AssetFolder;selected: boolean;interactions: AssetManagerThumbnailInteractions;onOpen: () => void;canManage: boolean;+ canCopyOrDelete?: boolean;+ canPasteClipboard?: boolean;+ onPasteClipboard?: () => void;canMoveItems: (items: readonly AssetManagerSelection[],folderId: string@@ -58,10 +89,59 @@ export const FolderThumbnail = ({onElementChange?: (element: HTMLElement | null) => void;forcedSelection?: boolean;selectionActions?: AssetManagerItemActions;+ collection?: ContentCollection;+ createCollection?: typeof createContentCollectionFolder;+ onConfigureCollection?: (folderId: string) => void;}) => {const [settingsOpen, setSettingsOpen] = useState(false);+ const [collectionSetupOpen, setCollectionSetupOpen] = useState(false);const [deleteConfirmationOpen, setDeleteConfirmationOpen] = useState(false);const [isDropTarget, setIsDropTarget] = useState(false);+ const [settingsCollection, setSettingsCollection] = useState<+ Extract<ContentCollection, { status: "ready" }> | undefined+ >();+ const isContentMode = useStore($isContentMode);+ const [convertingCollection, setConvertingCollection] =+ useState<ContentCollection>();+ const authPermit = useStore($authPermit);+ const canConfigureCollections = canConfigureContentCollections(authPermit);+ const canSetUpCollection =+ canManage && !isContentMode && canConfigureCollections;+ const canUseAsCollection = canSetUpCollection && collection === undefined;+ const canUseAsCollectionRef = useRef(canUseAsCollection);+ canUseAsCollectionRef.current = canUseAsCollection;+ const openCollectionSetup = () => {+ if (canUseAsCollectionRef.current) {+ setSettingsOpen(false);+ setCollectionSetupOpen(true);+ }+ };+ useEffect(() => {+ if (!canSetUpCollection) {+ setCollectionSetupOpen(false);+ }+ }, [canSetUpCollection]);+ const canConvertCollection =+ canManage &&+ isContentMode === false &&+ canConfigureCollections &&+ collection !== undefined;+ const canConfigureCollection =+ canConvertCollection && collection?.status === "ready";+ const convertibleCollectionRef = useRef<ContentCollection>();+ convertibleCollectionRef.current = canConvertCollection+ ? collection+ : undefined;+ const canManageRef = useRef(canManage);+ canManageRef.current = canManage;+ const canCopyOrDeleteRef = useRef(canCopyOrDelete);+ canCopyOrDeleteRef.current = canCopyOrDelete;+ const configurableCollectionRef = useRef<+ Extract<ContentCollection, { status: "ready" }> | undefined+ >();+ configurableCollectionRef.current = canConfigureCollection+ ? collection+ : undefined;const elementRef = useRef<HTMLElement | null>(null);const getDragItems = interactions.getDragItems;@@ -74,17 +154,116 @@ export const FolderThumbnail = ({id: folder.id,projectId: folder.projectId,};+ const clipboardActions = createAssetManagerClipboardActions(item);+ const assets = useStore($assets);+ const acceptClipboardItems = (items: readonly AssetManagerSelection[]) =>+ items.every(+ (item) =>+ item.type === "folder" ||+ canAddAssetToContentCollection(collection, assets.get(item.id))+ );+ const clipboardCanBePasted =+ canPasteClipboard ??+ canPasteAssetManagerClipboard(folder.id, acceptClipboardItems);+ const clipboardCanBePastedRef = useRef(clipboardCanBePasted);+ clipboardCanBePastedRef.current = clipboardCanBePasted;+ useEffect(() => {+ if (canManage === false) {+ setSettingsOpen(false);+ setDeleteConfirmationOpen(false);+ }+ }, [canManage]);+ useEffect(() => {+ if (canConfigureCollection === false) {+ setSettingsCollection(undefined);+ }+ }, [canConfigureCollection]);+ useEffect(() => {+ if (!canConvertCollection) {+ setConvertingCollection(undefined);+ }+ }, [canConvertCollection]);const actions: AssetManagerItemActions = {open: onOpen,+ useAsCollection: canUseAsCollection ? openCollectionSetup : undefined,...(canManage? {- settings: () => openSettings(),- ...createAssetManagerClipboardActions(item),- move: onMove,- paste: canPasteAssetManagerClipboard(folder.id)- ? () => pasteAssetManagerClipboard(folder.id)+ settings: () => {+ if (canManageRef.current) {+ openSettings();+ }+ },+ ...(canConfigureCollection+ ? {+ collectionSettings: () => {+ const currentCollection = configurableCollectionRef.current;+ if (currentCollection !== undefined) {+ setSettingsCollection(currentCollection);+ }+ },+ }+ : {}),+ ...(canConvertCollection+ ? {+ convertCollection: () => {+ const currentCollection = convertibleCollectionRef.current;+ if (currentCollection !== undefined) {+ setConvertingCollection(currentCollection);+ }+ },+ }+ : {}),+ cut: () => {+ if (canManageRef.current) {+ clipboardActions.cut();+ }+ },+ ...(canCopyOrDelete+ ? {+ copy: () => {+ if (canManageRef.current && canCopyOrDeleteRef.current) {+ clipboardActions.copy();+ }+ },+ duplicate: () => {+ if (canManageRef.current && canCopyOrDeleteRef.current) {+ clipboardActions.duplicate();+ }+ },+ }+ : {}),+ move:+ onMove === undefined+ ? undefined+ : () => {+ if (canManageRef.current) {+ onMove();+ }+ },+ paste: clipboardCanBePasted+ ? () => {+ if (+ canManageRef.current === false ||+ clipboardCanBePastedRef.current === false+ ) {+ return;+ }+ if (onPasteClipboard !== undefined) {+ onPasteClipboard();+ return;+ }+ pasteAssetManagerClipboard(folder.id, acceptClipboardItems);+ }: undefined,- delete: () => openSettings(true),+ ...(canCopyOrDelete+ ? {+ delete: () => {+ if (canManageRef.current && canCopyOrDeleteRef.current) {+ openSettings(true);+ }+ },+ }+ : {}),}: {}),};@@ -148,9 +327,33 @@ export const FolderThumbnail = ({}}label={folder.name}path={path}- preview={<FolderIcon size={40} />}+ preview={+ <Grid css={{ position: "relative" }}>+ <FolderIcon size={40} />+ {collection !== undefined && (+ <Grid+ css={{+ position: "absolute",+ inset: 0,+ placeItems: "center",+ paddingTop: theme.spacing[3],+ }}+ >+ {collection.status === "invalid" ? (+ <AlertCircleIcon size={16} fill="currentColor" />+ ) : (+ <ListViewIcon data-collection-folder-icon="" size={16} />+ )}+ </Grid>+ )}+ </Grid>+ }aria-label={`Folder ${folder.name}`}- aria-description="Double-click to open. Drag assets or folders here to move them."+ aria-description={+ collection === undefined+ ? "Double-click to open. Drag assets or folders here to move them."+ : "Content collection. Double-click to open. Move supporting assets or folders here."+ }data-is-drop-over={isDropTarget ? "true" : undefined}clickabledropTarget={isDropTarget}@@ -177,6 +380,37 @@ export const FolderThumbnail = ({open={settingsOpen}onOpenChange={setSettingsOpen}initialDeleteConfirmation={deleteConfirmationOpen}+ canDelete={canCopyOrDelete}+ onUseAsCollection={+ canUseAsCollection ? openCollectionSetup : undefined+ }+ />+ )}+ {canSetUpCollection && (+ <CreateAssetFolderDialog+ open={collectionSetupOpen}+ onOpenChange={setCollectionSetupOpen}+ existingFolder={folder}+ createCollection={createCollection}+ currentFolderId={folder.parentId}+ onConfigureCollection={onConfigureCollection}+ />+ )}+ {canConfigureCollection && settingsCollection !== undefined && (+ <CollectionSettingsDialog+ collection={settingsCollection}+ open+ onOpenChange={(open) => {+ if (open === false) {+ setSettingsCollection(undefined);+ }+ }}+ />+ )}+ {canConvertCollection && convertingCollection !== undefined && (+ <ConvertCollectionDialog+ configAsset={convertingCollection.configAsset}+ onClose={() => setConvertingCollection(undefined)}/>)}</>diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.test.tsindex b0e38956fc..b6ba781b49 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.test.ts+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.test.ts@@ -77,6 +77,20 @@ test("does not paste into a folder that no longer exists", () => {expect($assetManagerClipboard.get()).toBeDefined();});+test("filters clipboard items before allowing a paste", () => {+ const folder = createAssetFolderFixture({ id: "folder" });+ $project.set({ id: "project" } as never);+ $assetFolders.set(new Map([[folder.id, folder]]));+ $assets.set(new Map([["asset", { folderId: undefined } as never]]));+ copyAssetManagerItems([{ type: "asset", id: "asset", projectId: "project" }]);++ const acceptsFolders = (items: readonly { type: string }[]) =>+ items.every((item) => item.type === "folder");+ expect(canPasteAssetManagerClipboard(folder.id, acceptsFolders)).toBe(false);+ expect(pasteAssetManagerClipboard(folder.id, acceptsFolders)).toBeUndefined();+ expect($assetManagerClipboard.get()).toBeDefined();+});+test("prevents cutting a folder into one of its descendants", () => {const parent = createAssetFolderFixture({ id: "parent" });const child = createAssetFolderFixture({ id: "child", parentId: parent.id });diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.tsindex ac0afc285e..d6f9f21c2a 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.ts+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.ts@@ -82,12 +82,28 @@ const canPasteToFolder = ();};-export const canPasteAssetManagerClipboard = (folderId: string | undefined) => {+type AcceptClipboardItems = (+ items: readonly AssetManagerSelection[]+) => boolean;++const acceptAllClipboardItems: AcceptClipboardItems = () => true;++export const canPasteAssetManagerClipboard = (+ folderId: string | undefined,+ acceptItems: AcceptClipboardItems = acceptAllClipboardItems+) => {const data = getClipboardItems();- return data !== undefined && canPasteToFolder(data, folderId);+ return (+ data !== undefined &&+ acceptItems(data.items) &&+ canPasteToFolder(data, folderId)+ );};-export const pasteAssetManagerClipboard = (folderId: string | undefined) => {+export const pasteAssetManagerClipboard = (+ folderId: string | undefined,+ acceptItems: AcceptClipboardItems = acceptAllClipboardItems+) => {const data = getClipboardItems();if (data === undefined) {const clipboard = $assetManagerClipboard.get();@@ -100,7 +116,10 @@ export const pasteAssetManagerClipboard = (folderId: string | undefined) => {$assetManagerClipboard.set(undefined);return;}- if (canPasteToFolder(data, folderId) === false) {+ if (+ acceptItems(data.items) === false ||+ canPasteToFolder(data, folderId) === false+ ) {return;}const { clipboard, items } = data;diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-item-menu.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager-item-menu.tsxindex 8682d73f74..1dabf21969 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-manager-item-menu.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-item-menu.tsx@@ -20,6 +20,10 @@ export type AssetManagerItemActions = Partial<Record<| "open"| "settings"+ | "entrySettings"+ | "collectionSettings"+ | "useAsCollection"+ | "convertCollection"| "cut"| "copy"| "paste"@@ -28,6 +32,7 @@ export type AssetManagerItemActions = Partial<| "download"| "replace"| "createFolder"+ | "createEntry"| "createFile"| "upload"| "deleteUnusedAssets"@@ -46,11 +51,20 @@ type ItemDefinition = {};const itemDefinitions: readonly ItemDefinition[] = [+ { name: "createEntry", label: "New entry" },{ name: "createFolder", label: "Create folder" },{ name: "createFile", label: "Create text file" },{ name: "upload", label: "Upload asset" },{ name: "open", label: "Open" },{ name: "settings", label: "Settings" },+ { name: "entrySettings", label: "Entry settings" },+ { name: "collectionSettings", label: "Collection settings" },+ { name: "useAsCollection", label: "Use as content collection" },+ {+ name: "convertCollection",+ label: "Convert to regular folder",+ destructive: true,+ },{name: "cut",label: "Cut",diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-thumbnail.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager-thumbnail.tsxindex ddb3a7a659..7e5a60a473 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-manager-thumbnail.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-thumbnail.tsx@@ -36,7 +36,10 @@ export type AssetManagerThumbnailInteractions = {) => void;onExitMultiselect?: () => void;onContextMenuSelection: (item: AssetManagerSelection) => void;- onContextMenuActions: (actions: AssetManagerItemActions) => void;+ onContextMenuActions: (+ actions: AssetManagerItemActions,+ disabledActions?: ReadonlySet<keyof AssetManagerItemActions>+ ) => void;getDragItems: (item: AssetManagerSelection) => AssetManagerSelection[];};@@ -45,6 +48,7 @@ type AssetManagerThumbnailProps = Omit<"aria-pressed" | "as" | "onContextMenu" | "ref" | "selected" | "type"> & {actions: AssetManagerItemActions;+ disabledActions?: ReadonlySet<keyof AssetManagerItemActions>;interactions: AssetManagerThumbnailInteractions;item: AssetManagerSelection;header?: ReactNode;@@ -55,6 +59,7 @@ type AssetManagerThumbnailProps = Omit<export const AssetManagerThumbnail = ({actions,+ disabledActions,interactions,item,header,@@ -75,7 +80,7 @@ export const AssetManagerThumbnail = ({}onContextMenu={(event) => {interactions.onContextMenuSelection(item);- interactions.onContextMenuActions(actions);+ interactions.onContextMenuActions(actions, disabledActions);event.currentTarget.querySelector<HTMLElement>("[data-asset-manager-thumbnail-button]")?.focus();@@ -133,6 +138,7 @@ export const AssetManagerThumbnail = ({type AssetManagerThumbnailMenuProps = {actions: AssetManagerItemActions;+ disabledActions?: ReadonlySet<keyof AssetManagerItemActions>;label: string;onPointerDown?: () => void;};@@ -140,10 +146,11 @@ type AssetManagerThumbnailMenuProps = {export const AssetManagerThumbnailMenu = forwardRef<HTMLDivElement,AssetManagerThumbnailMenuProps->(({ actions, label, onPointerDown }, ref) => (+>(({ actions, disabledActions, label, onPointerDown }, ref) => (<AssetThumbnailMenu ref={ref} onPointerDown={onPointerDown}><AssetManagerItemActionsDropdownactions={actions}+ disabledActions={disabledActions}triggerLabel={label}triggerTabIndex={-1}/>diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsxindex 8ec5b4500c..730c3f7571 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsx@@ -1,8 +1,13 @@+import { useState } from "react";import { act } from "react-dom/test-utils";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { TooltipProvider } from "@webstudio-is/design-system";import type { Asset } from "@webstudio-is/sdk";import { createDefaultPages } from "@webstudio-is/project-build";+import {+ createDefaultCollectionConfig,+ parseCollectionConfig,+} from "@webstudio-is/content-engine";import {$assetFolders,$assets,@@ -25,6 +30,9 @@ import {} from "~/shared/nano-states";import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";import { AssetManager } from "./asset-manager";+import { FolderThumbnail } from "./asset-folder-thumbnail";+import type { AssetManagerThumbnailInteractions } from "./asset-manager-thumbnail";+import type { ContentCollection } from "../assets/content-collections";import { $assetManagerClipboard } from "./asset-manager-clipboard";import {createAssetFolderFixture,@@ -121,10 +129,13 @@ afterEach(() => {vi.unstubAllGlobals();});-const renderManager = (canManageFolders = true) =>+const renderManager = (+ canManageFolders = true,+ props: { collections?: ReadonlyMap<string, ContentCollection> } = {}+) =>renderer.render(<TooltipProvider>- <AssetManager canManageFolders={canManageFolders} />+ <AssetManager canManageFolders={canManageFolders} {...props} /></TooltipProvider>);@@ -216,7 +227,171 @@ const createAsset = (id: string): Asset => ({createdAt: "2026-01-01T00:00:00.000Z",});+const createLoadingCollection = (folderId: string): ContentCollection => {+ const configAsset: Asset = {+ id: `${folderId}-config`,+ projectId: "project",+ name: "collection.json",+ filename: "collection",+ folderId,+ format: "json",+ size: 1,+ type: "file",+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ return {+ status: "loading",+ folderId,+ configAsset,+ siblingAssets: [configAsset],+ };+};++const createReadyCollection = (+ folderId: string+): Extract<ContentCollection, { status: "ready" }> => {+ const configAsset = createLoadingCollection(folderId).configAsset;+ const templateAsset: Asset = {+ id: `${folderId}-template`,+ projectId: "project",+ name: "template.mdx",+ filename: "template",+ folderId,+ format: "mdx",+ size: 1,+ type: "file",+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ return {+ status: "ready",+ folderId,+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ };+};++const openMdxMultiselectAction = (label: "Move" | "Delete") => {+ const entry: Asset = {+ ...createAsset("entry"),+ name: "entry.mdx",+ filename: "entry",+ folderId: "alpha",+ type: "file",+ format: "mdx",+ meta: {},+ };+ const companion: Asset = {+ ...createAsset("companion"),+ folderId: "alpha",+ };+ $authPermit.set("edit");+ $assets.set(+ new Map<string, Asset>([+ [entry.id, entry],+ [companion.id, companion],+ ])+ );+ const container = renderManager();+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ act(() => {+ folderButton.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));+ });+ const options = getOptions(container);+ const entryOption = options.find(({ button }) =>+ button.textContent?.includes("entry.mdx")+ )!;+ const companionOption = options.find(({ button }) =>+ button.textContent?.includes("companion.png")+ )!;+ act(() => entryOption.button.focus());+ pointerDown(companionOption.button, { ctrlKey: true });+ openContextMenu(entryOption.button);+ const action = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent?.startsWith(label));+ expect(action).toBeDefined();+ return {+ action: action!,+ reserveEntry: () => {+ const configAsset = createLoadingCollection("alpha").configAsset;+ act(() => {+ $assets.set(+ new Map<string, Asset>([+ [entry.id, entry],+ [companion.id, companion],+ [configAsset.id, configAsset],+ ])+ );+ });+ },+ };+};++const setNestedCollectionFolders = () => {+ $assetFolders.set(+ createAssetFoldersFixture(+ createAssetFolderFixture({ id: "alpha", name: "Alpha" }),+ createAssetFolderFixture({+ id: "bravo",+ name: "Bravo",+ parentId: "alpha",+ }),+ createAssetFolderFixture({ id: "charlie", name: "Charlie" })+ )+ );+ return new Map([["bravo", createLoadingCollection("bravo")]]);+};+describe("Asset Manager multiselect interactions", () => {+ test("shows collection configuration and template files", () => {+ const configAsset = createLoadingCollection("alpha").configAsset;+ const templateAsset: Asset = {+ id: "alpha-template",+ projectId: "project",+ name: "template.mdx",+ filename: "template",+ folderId: "alpha",+ format: "mdx",+ size: 1,+ type: "file",+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ act(() => {+ $assets.set(+ new Map([+ [configAsset.id, configAsset],+ [templateAsset.id, templateAsset],+ ])+ );+ });+ const collection: ContentCollection = {+ status: "loading",+ folderId: "alpha",+ configAsset,+ siblingAssets: [configAsset, templateAsset],+ };+ const container = renderManager(true, {+ collections: new Map([["alpha", collection]]),+ });+ const alphaFolder = getOptions(container).find(({ button }) =>+ button.textContent?.includes("Alpha")+ )?.button;++ act(() => {+ alphaFolder?.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));+ });++ expect(container.textContent).toContain("collection.json");+ expect(container.textContent).toContain("template.mdx");+ });+test("keeps the selected asset in the path while focusing the copy action", () => {const asset = createAsset("asset");act(() => $assets.set(new Map([[asset.id, asset]])));@@ -662,6 +837,546 @@ describe("Asset Manager multiselect interactions", () => {});});+describe("Asset Manager collection folder permissions", () => {+ test("blocks a stale Move callback after a selected asset becomes reserved", () => {+ const { action, reserveEntry } = openMdxMultiselectAction("Move");++ reserveEntry();+ act(() => action.click());++ expect(document.body.textContent).not.toContain("Move items");+ });++ test.each([+ {+ name: "the selected asset becomes reserved",+ updateProtection: (reserveEntry: () => void) => reserveEntry(),+ },+ {+ name: "authorization changes to view-only",+ updateProtection: () => act(() => $authPermit.set("view")),+ },+ ])("closes an open Move dialog when $name", ({ updateProtection }) => {+ const { action, reserveEntry } = openMdxMultiselectAction("Move");+ act(() => action.click());+ expect(document.body.textContent).toContain("Move items");++ updateProtection(reserveEntry);++ expect(document.body.textContent).not.toContain("Move items");+ });++ test("closes an open Delete dialog when authorization changes to view-only", () => {+ const { action } = openMdxMultiselectAction("Delete");+ act(() => action.click());+ expect(document.body.textContent).toContain("Delete selected items");++ act(() => $authPermit.set("view"));++ expect(document.body.textContent).not.toContain("Delete selected items");+ });++ test("does not reopen collection settings after configuration access is restored", () => {+ const collection = createReadyCollection("alpha");+ const container = renderManager(true, {+ collections: new Map([[collection.folderId, collection]]),+ });+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ openContextMenu(folderButton);+ const settings = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent === "Collection settings");+ expect(settings).toBeDefined();+ act(() => settings?.click());+ expect(document.body.textContent).toContain("Collection settings");++ act(() => $authPermit.set("edit"));+ expect(document.body.textContent).not.toContain("Collection settings");++ act(() => $authPermit.set("build"));+ expect(document.body.textContent).not.toContain("Collection settings");+ });++ test("does not reopen folder settings after management access is restored", async () => {+ const folder = createAssetFolderFixture({ id: "managed", name: "Managed" });+ const interactions: AssetManagerThumbnailInteractions = {+ onSelectionChange: vi.fn(),+ onItemPointerDown: vi.fn(),+ onItemClick: vi.fn(),+ onModifiedArrow: vi.fn(),+ onContextMenuSelection: vi.fn(),+ onContextMenuActions: vi.fn(),+ getDragItems: (item) => [item],+ };+ let setCanManage: (canManage: boolean) => void = () => undefined;+ const Thumbnail = () => {+ const [canManage, updateCanManage] = useState(true);+ setCanManage = updateCanManage;+ return (+ <TooltipProvider>+ <FolderThumbnail+ folder={folder}+ selected={false}+ interactions={interactions}+ onOpen={vi.fn()}+ canManage={canManage}+ canMoveItems={() => false}+ onMoveItems={vi.fn()}+ />+ </TooltipProvider>+ );+ };+ const container = renderer.render(<Thumbnail />);+ const actions = container.querySelector<HTMLButtonElement>(+ '[aria-label="Actions for Managed"]'+ )!;+ act(() => {+ actions.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });+ const settings = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent === "Settings");+ expect(settings).toBeDefined();+ act(() => settings?.click());+ expect(document.body.textContent).toContain("Folder settings");++ await act(async () => setCanManage(false));+ expect(document.body.textContent).not.toContain("Folder settings");++ await act(async () => setCanManage(true));+ expect(document.body.textContent).not.toContain("Folder settings");+ });++ test("closes collection settings when the folder is no longer a ready collection", () => {+ const collection = createReadyCollection("alpha");+ let setCollectionReady: (ready: boolean) => void = () => undefined;+ const Manager = () => {+ const [ready, setReady] = useState(true);+ setCollectionReady = setReady;+ return (+ <TooltipProvider>+ <AssetManager+ canManageFolders+ collections={+ ready ? new Map([[collection.folderId, collection]]) : new Map()+ }+ />+ </TooltipProvider>+ );+ };+ const container = renderer.render(<Manager />);+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ openContextMenu(folderButton);+ const settings = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent === "Collection settings");+ expect(settings).toBeDefined();+ act(() => settings?.click());+ expect(document.body.textContent).toContain("Collection settings");++ act(() => setCollectionReady(false));+ expect(document.body.textContent).not.toContain("Collection settings");++ act(() => setCollectionReady(true));+ expect(document.body.textContent).not.toContain("Collection settings");+ });++ test.each(["Copy", "Duplicate", "Delete"] as const)(+ "blocks a stale %s callback after a folder becomes a collection ancestor",+ (action) => {+ $assetFolders.set(+ createAssetFoldersFixture(+ createAssetFolderFixture({ id: "alpha", name: "Alpha" }),+ createAssetFolderFixture({+ id: "bravo",+ name: "Bravo",+ parentId: "alpha",+ }),+ createAssetFolderFixture({ id: "charlie", name: "Charlie" })+ )+ );+ $authPermit.set("edit");+ const container = renderManager();+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ openContextMenu(folderButton);+ const staleAction = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent?.startsWith(action));+ expect(staleAction).toBeDefined();++ const collection = createLoadingCollection("bravo");+ act(() => {+ $assets.set(+ new Map([[collection.configAsset.id, collection.configAsset]])+ );+ });+ act(() => staleAction?.click());++ if (action === "Copy") {+ expect($assetManagerClipboard.get()).toBeUndefined();+ }+ if (action === "Duplicate") {+ expect($assetFolders.get()).toHaveLength(3);+ }+ if (action === "Delete") {+ expect(document.body.textContent).not.toContain("Folder settings");+ expect(document.body.textContent).not.toContain("Delete folder");+ }+ }+ );++ test.each(["edit", "build", "admin", "own"] as const)(+ "removes relocate and destructive actions when a selection contains a reserved file (%s)",+ (permit) => {+ const collection = createLoadingCollection("alpha");+ const entry: Asset = {+ ...createAsset("entry"),+ name: "entry.mdx",+ filename: "entry",+ folderId: "alpha",+ type: "file",+ format: "mdx",+ meta: {},+ };+ act(() => {+ $authPermit.set(permit);+ $assets.set(+ new Map([+ [collection.configAsset.id, collection.configAsset],+ [entry.id, entry],+ ])+ );+ });+ const container = renderManager(true, {+ collections: new Map([["alpha", collection]]),+ });+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ act(() => {+ folderButton.dispatchEvent(+ new MouseEvent("dblclick", { bubbles: true })+ );+ });+ const options = getOptions(container);+ const config = options.find(({ button }) =>+ button.textContent?.includes("collection.json")+ )!;+ const entryOption = options.find(({ button }) =>+ button.textContent?.includes("entry.mdx")+ )!;+ act(() => config.button.focus());+ pointerDown(entryOption.button, { ctrlKey: true });+ openContextMenu(config.button);++ const labels = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).map((item) => item.textContent);+ expect(labels.some((label) => label?.startsWith("Cut"))).toBe(false);+ expect(labels).not.toContain("Move");+ expect(labels.some((label) => label?.startsWith("Copy"))).toBe(false);+ expect(labels.some((label) => label?.startsWith("Delete"))).toBe(false);++ dismissContextMenu();+ keyDown(config.button, "x", { ctrlKey: true });+ expect($assetManagerClipboard.get()).toBeUndefined();+ }+ );++ test("detects collection folders and protects reserved files without caller configuration", () => {+ const configAsset = createLoadingCollection("alpha").configAsset;+ const templateAsset: Asset = {+ id: "alpha-template",+ projectId: "project",+ name: "template.mdx",+ filename: "template",+ folderId: "alpha",+ format: "mdx",+ size: 1,+ type: "file",+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ act(() => {+ $authPermit.set("edit");+ $assets.set(+ new Map([+ [configAsset.id, configAsset],+ [templateAsset.id, templateAsset],+ ])+ );+ });+ const container = renderManager();+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ expect(+ folderButton.querySelector("[data-collection-folder-icon]")+ ).not.toBeNull();++ act(() => {+ folderButton.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));+ });+ const configButton = getOptions(container).find(({ button }) =>+ button.textContent?.includes("collection.json")+ )!.button;+ openContextMenu(configButton);+ const labels = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).map((item) => item.textContent);+ expect(labels).not.toContain("Settings");+ const disabledItems = Array.from(+ document.querySelectorAll<HTMLElement>(+ '[role="menuitem"][aria-disabled="true"]'+ )+ );+ expect(disabledItems).toHaveLength(5);+ expect(+ disabledItems.some((item) => item.textContent?.startsWith("Cut"))+ ).toBe(true);+ expect(disabledItems.some((item) => item.textContent === "Move")).toBe(+ true+ );+ expect(+ disabledItems.some((item) => item.textContent?.startsWith("Delete"))+ ).toBe(true);+ });++ test("hides generic panel actions in a detected collection folder", () => {+ const convertCollection = vi.fn();+ const configAsset = createLoadingCollection("alpha").configAsset;+ act(() => $assets.set(new Map([[configAsset.id, configAsset]])));+ const container = renderer.render(+ <TooltipProvider>+ <AssetManager+ canManageFolders+ panelActions={{+ upload: vi.fn(),+ createFile: vi.fn(),+ createFolder: vi.fn(),+ createEntry: vi.fn(),+ convertCollection,+ }}+ />+ </TooltipProvider>+ );+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ act(() => {+ folderButton.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));+ });++ openContextMenu(+ container.querySelector<HTMLElement>("[data-asset-manager-scroll-area]")!+ );++ const labels = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).map((item) => item.textContent);+ expect(labels).toContain("Create folder");+ expect(labels).toContain("New entry");+ expect(labels).not.toContain("Upload asset");+ expect(labels).not.toContain("Create text file");+ const convert = Array.from(+ document.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent === "Convert to regular folder");+ expect(convert).toBeDefined();+ act(() => convert?.click());+ expect(convertCollection).toHaveBeenCalledOnce();+ });++ test("offers conversion from the parent folder before collection settings are loaded", async () => {+ const collection = createLoadingCollection("alpha");+ act(() => {+ $authPermit.set("own");+ $assets.set(+ new Map([[collection.configAsset.id, collection.configAsset]])+ );+ });+ const container = renderManager(true);+ const folderButton = container.querySelector<HTMLElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ openContextMenu(folderButton);+ const convert = Array.from(+ document.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent === "Convert to regular folder");+ expect(convert).toBeDefined();+ await act(async () => convert?.click());+ await vi.waitFor(() =>+ expect(document.querySelector('[role="dialog"]')).not.toBeNull()+ );+ });++ test("hides copy, duplicate, and delete for a collection ancestor from edit users", () => {+ let collections: ReadonlyMap<string, ContentCollection> = new Map();+ act(() => {+ $authPermit.set("edit");+ collections = setNestedCollectionFolders();+ });+ const container = renderManager(true, { collections });+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;++ openContextMenu(folderButton);++ const labels = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).map((item) => item.textContent);+ expect(labels).toContain("Settings");+ expect(labels.some((label) => label?.startsWith("Cut"))).toBe(true);+ expect(labels).toContain("Move");+ expect(labels.some((label) => label?.startsWith("Copy"))).toBe(false);+ expect(labels.some((label) => label?.startsWith("Duplicate"))).toBe(false);+ expect(labels.some((label) => label?.startsWith("Delete"))).toBe(false);+ });++ test("keeps collection ancestor rename settings but hides folder deletion", () => {+ let collections: ReadonlyMap<string, ContentCollection> = new Map();+ act(() => {+ $authPermit.set("edit");+ collections = setNestedCollectionFolders();+ });+ const container = renderManager(true, { collections });+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ openContextMenu(folderButton);+ const settings = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent === "Settings");++ act(() => settings?.click());++ expect(document.body.textContent).toContain("Folder settings");+ expect(+ document.querySelector<HTMLInputElement>("#asset-folder-name-alpha")+ ).not.toBeNull();+ expect(+ Array.from(document.body.querySelectorAll("button")).some(+ (button) => button.textContent === "Delete"+ )+ ).toBe(false);+ });++ test("removes unsafe actions from a multiselection containing a collection ancestor", () => {+ let collections: ReadonlyMap<string, ContentCollection> = new Map();+ act(() => {+ $authPermit.set("edit");+ collections = setNestedCollectionFolders();+ });+ const container = renderManager(true, { collections });+ const options = getOptions(container);+ const alpha = options.find(+ ({ button }) => button.getAttribute("aria-label") === "Folder Alpha"+ )!;+ const charlie = options.find(+ ({ button }) => button.getAttribute("aria-label") === "Folder Charlie"+ )!;+ act(() => alpha.button.focus());+ pointerDown(charlie.button, { ctrlKey: true });++ openContextMenu(alpha.button);++ const labels = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).map((item) => item.textContent);+ expect(labels.some((label) => label?.startsWith("Cut"))).toBe(true);+ expect(labels).toContain("Move");+ expect(labels.some((label) => label?.startsWith("Copy"))).toBe(false);+ expect(labels.some((label) => label?.startsWith("Duplicate"))).toBe(false);+ expect(labels.some((label) => label?.startsWith("Delete"))).toBe(false);+ });++ test("blocks unsafe collection ancestor shortcuts but preserves cut", () => {+ let collections: ReadonlyMap<string, ContentCollection> = new Map();+ act(() => {+ $authPermit.set("edit");+ collections = setNestedCollectionFolders();+ });+ const container = renderManager(true, { collections });+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ act(() => folderButton.focus());++ keyDown(folderButton, "c", { metaKey: true });+ expect($assetManagerClipboard.get()).toBeUndefined();++ keyDown(folderButton, "d", { ctrlKey: true });+ expect($assetFolders.get()).toHaveLength(3);++ keyDown(folderButton, "Delete");+ expect(document.body.textContent).not.toContain("Delete selected items");++ keyDown(folderButton, "x", { ctrlKey: true });+ expect($assetManagerClipboard.get()).toMatchObject({+ operation: "cut",+ items: [{ type: "folder", id: "alpha" }],+ });+ });++ test("blocks a stale copied collection ancestor from being pasted", () => {+ let collections: ReadonlyMap<string, ContentCollection> = new Map();+ act(() => {+ $authPermit.set("edit");+ collections = setNestedCollectionFolders();+ $assetManagerClipboard.set({+ operation: "copy",+ items: [{ type: "folder", id: "alpha" }],+ projectId: "project",+ });+ });+ const container = renderManager(true, { collections });+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Charlie"]'+ )!;+ act(() => folderButton.focus());++ openContextMenu(folderButton);+ expect(+ Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).some((item) => item.textContent?.startsWith("Paste"))+ ).toBe(false);+ dismissContextMenu();++ keyDown(folderButton, "v", { metaKey: true });++ expect($assetFolders.get()).toHaveLength(3);+ });++ test("keeps collection folder copy, duplicate, and delete available to builders", () => {+ let collections: ReadonlyMap<string, ContentCollection> = new Map();+ act(() => {+ collections = setNestedCollectionFolders();+ });+ const container = renderManager(true, { collections });+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;++ openContextMenu(folderButton);++ const labels = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).map((item) => item.textContent);+ expect(labels.some((label) => label?.startsWith("Copy"))).toBe(true);+ expect(labels.some((label) => label?.startsWith("Duplicate"))).toBe(true);+ expect(labels.some((label) => label?.startsWith("Delete"))).toBe(true);+ });+});+describe("Asset Manager shortcuts", () => {test("prevents handled shortcuts from reaching global builder commands", () => {const container = renderManager();diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager.tsxindex 3bf39dd3d4..20e1c69ff8 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx@@ -14,6 +14,7 @@ import {import { flushSync } from "react-dom";import { useStore } from "@nanostores/react";import {+ PanelContent,Box,Button,Dialog,@@ -42,7 +43,7 @@ import { AssetThumbnail } from "./asset-thumbnail";import { BackThumbnail, FolderThumbnail } from "./asset-folder-thumbnail";import { AssetFilters } from "./asset-filters";import { AssetSortSelect } from "./asset-sort";-import { $assetFolders, $project } from "~/shared/sync/data-stores";+import { $assetFolders, $assets, $project } from "~/shared/sync/data-stores";import { AssetFolderBreadcrumbs } from "./asset-folder-breadcrumbs";import {filterAssetFolders,@@ -94,7 +95,20 @@ import {import { getAssetManagerDragItems } from "./asset-manager-drag";import type { AssetManagerThumbnailInteractions } from "./asset-manager-thumbnail";import { $authPermit } from "~/shared/nano-states";-import { MoveAssetManagerItemsDialog } from "./asset-folder-dialogs";+import {+ MoveAssetManagerItemsDialog,+ type createContentCollectionFolder,+} from "./asset-folder-dialogs";+import {+ canConfigureContentCollections,+ canAddAssetToContentCollection,+ createLoadingContentCollections,+ getCollectionReservedAssetIds,+ type ContentCollection,+} from "../assets/content-collections";++const emptyContentCollections: ReadonlyMap<string, ContentCollection> =+ new Map();type FolderNavigationProps =| { folderId?: never; onFolderChange?: never }@@ -104,17 +118,32 @@ type FolderNavigationProps =};type AssetManagerProps = FolderNavigationProps & {+ entryIssues?: ReadonlyMap<+ string,+ readonly { fieldKey?: string; message: string }[]+ >;onChange?: (assetId: Asset["id"]) => void;onOpen?: (assetId: Asset["id"]) => void;+ onEntrySettings?: (assetId: Asset["id"]) => void;/** acceptable file types in the `<input accept>` attribute format */accept?: string;canManageFolders?: boolean;panelActions?: Partial<Pick<AssetManagerItemActions,- "createFolder" | "createFile" | "upload" | "deleteUnusedAssets"+ | "createFolder"+ | "createFile"+ | "upload"+ | "deleteUnusedAssets"+ | "createEntry"+ | "convertCollection">>;+ collections?: ReadonlyMap<string, ContentCollection>;+ onConfigureCollection?: (folderId: string) => void;+ createCollection?: typeof createContentCollectionFolder;+ emptyMessage?: string;+ folderNotice?: ReactNode;};const AssetGrid = ({@@ -148,9 +177,57 @@ export const AssetManager = ({onFolderChange,canManageFolders = false,panelActions,+ collections = emptyContentCollections,+ onConfigureCollection,+ createCollection,+ emptyMessage,+ folderNotice,+ entryIssues,+ onEntrySettings,}: AssetManagerProps) => {+ const assets = useStore($assets);+ const effectiveCollections = useMemo(() => {+ const detected = new Map<string, ContentCollection>(+ createLoadingContentCollections(Array.from(assets.values()))+ );+ for (const [folderId, collection] of collections) {+ detected.set(folderId, collection);+ }+ return detected;+ }, [assets, collections]);+ const collectionFolderIds = useMemo(+ () => new Set(effectiveCollections.keys()),+ [effectiveCollections]+ );+ const collectionReservedAssetIds = useMemo(+ () =>+ getCollectionReservedAssetIds(effectiveCollections, {+ includeInvalid: true,+ }),+ [effectiveCollections]+ );+ const collectionFileIds = new Set<string>();+ for (const collection of effectiveCollections.values()) {+ collectionFileIds.add(collection.configAsset.id);+ if (+ collection.status !== "loading" &&+ collection.templateAsset !== undefined+ ) {+ collectionFileIds.add(collection.templateAsset.id);+ }+ }const { assetContainers } = useAssets();const folders = useStore($assetFolders);+ const collectionEntryAssetIds = new Set(+ Array.from(assets.values()).flatMap((asset) => {+ const collection = effectiveCollections.get(asset.folderId ?? "");+ return collection !== undefined &&+ (collection.status !== "ready" ||+ collection.config.matchesEntry(formatAssetName(asset)))+ ? [asset.id]+ : [];+ })+ );const project = useStore($project);const authPermit = useStore($authPermit);const clipboard = useStore($assetManagerClipboard);@@ -158,6 +235,65 @@ export const AssetManager = ({() => createAssetFolderHierarchy(folders),[folders]);+ const canConfigureCollections = canConfigureContentCollections(authPermit);+ const collectionProtectedFolderIds = useMemo(() => {+ const protectedFolderIds = new Set<string>();+ for (const collectionFolderId of collectionFolderIds) {+ for (const folder of folderHierarchy.getPath(collectionFolderId)) {+ protectedFolderIds.add(folder.id);+ }+ }+ return protectedFolderIds;+ }, [collectionFolderIds, folderHierarchy]);+ const canCopyOrDeleteItems = useCallback(+ (items: readonly AssetManagerSelection[]) => {+ if (authPermit === "view") {+ return false;+ }+ const currentAuthPermit = $authPermit.get();+ return (+ currentAuthPermit !== "view" &&+ items.every(+ (item) =>+ (item.type !== "folder" ||+ canConfigureContentCollections(currentAuthPermit) ||+ collectionProtectedFolderIds.has(item.id) === false) &&+ (item.type !== "asset" ||+ collectionReservedAssetIds.has(item.id) === false)+ )+ );+ },+ [authPermit, collectionProtectedFolderIds, collectionReservedAssetIds]+ );+ const canRelocateItems = useCallback(+ (items: readonly AssetManagerSelection[]) => {+ if (authPermit === "view") {+ return false;+ }+ const currentAuthPermit = $authPermit.get();+ return (+ currentAuthPermit !== "view" &&+ items.every(+ (item) =>+ item.type !== "asset" ||+ collectionReservedAssetIds.has(item.id) === false+ )+ );+ },+ [authPermit, collectionReservedAssetIds]+ );+ const currentProtectionRef = useRef({+ canManageAssets: authPermit !== "view",+ canCopyOrDeleteItems,+ canRelocateItems,+ collectionEntryAssetIds,+ });+ currentProtectionRef.current = {+ canManageAssets: authPermit !== "view",+ canCopyOrDeleteItems,+ canRelocateItems,+ collectionEntryAssetIds,+ };const mimePatterns = useMemo(() => acceptToMimePatterns(accept), [accept]);const [internalFolderId, setInternalFolderId] = useState(folderId);const [selection, setSelection] = useState<AssetManagerSelection>();@@ -173,6 +309,7 @@ export const AssetManager = ({const [marqueeRect, setMarqueeRect] = useState<AssetManagerMarqueeRect>();const [itemContextMenu, setItemContextMenu] = useState<{actions?: AssetManagerItemActions;+ disabledActions?: ReadonlySet<keyof AssetManagerItemActions>;instance: number;}>({ instance: 0 });const itemElements = useRef(new Map<string, HTMLElement>());@@ -190,6 +327,68 @@ export const AssetManager = ({}, [clearMultiselect]);const currentFolderId =onFolderChange === undefined ? internalFolderId : folderId;+ const currentFolderIsCollection =+ currentFolderId !== undefined && collectionFolderIds.has(currentFolderId);+ const canPasteClipboardToFolder = useCallback(+ (targetFolderId: string | undefined) => {+ if (+ clipboard !== undefined &&+ ((clipboard.operation === "copy" &&+ canCopyOrDeleteItems(clipboard.items) === false) ||+ (clipboard.operation === "cut" &&+ canRelocateItems(clipboard.items) === false))+ ) {+ return false;+ }+ return canPasteAssetManagerClipboard(targetFolderId, (items) =>+ items.every(+ (item) =>+ item.type === "folder" ||+ canAddAssetToContentCollection(+ effectiveCollections.get(targetFolderId ?? ""),+ assets.get(item.id)+ )+ )+ );+ },+ [+ canCopyOrDeleteItems,+ canRelocateItems,+ clipboard,+ effectiveCollections,+ assets,+ ]+ );+ const pasteClipboardToFolder = useCallback(+ (targetFolderId: string | undefined) => {+ if (+ clipboard !== undefined &&+ ((clipboard.operation === "copy" &&+ canCopyOrDeleteItems(clipboard.items) === false) ||+ (clipboard.operation === "cut" &&+ canRelocateItems(clipboard.items) === false))+ ) {+ return;+ }+ pasteAssetManagerClipboard(targetFolderId, (items) =>+ items.every(+ (item) =>+ item.type === "folder" ||+ canAddAssetToContentCollection(+ effectiveCollections.get(targetFolderId ?? ""),+ assets.get(item.id)+ )+ )+ );+ },+ [+ canCopyOrDeleteItems,+ canRelocateItems,+ clipboard,+ effectiveCollections,+ assets,+ ]+ );const setCurrentFolderId = useCallback((nextFolderId: string | undefined) => {if (onFolderChange === undefined) {@@ -609,15 +808,48 @@ export const AssetManager = ({...item,projectId: project.id,}));+ const selectionContainsCollectionEntry = normalizedShortcutSelection.some(+ (item) => item.type === "asset" && collectionEntryAssetIds.has(item.id)+ );+ const canCopyOrDeleteSelection = canCopyOrDeleteItems(+ normalizedShortcutSelection+ );+ const canRelocateSelection = canRelocateItems(normalizedShortcutSelection);const copyItems = (items: readonly AssetManagerItem[]) => {+ const selections = items.map(({ type, id }) => ({ type, id }));+ if (+ currentProtectionRef.current.canManageAssets === false ||+ currentProtectionRef.current.canCopyOrDeleteItems(selections) === false+ ) {+ return;+ }copyAssetManagerItems(items);setAnnouncement(`${getItemCountLabel(items.length)} copied.`);};const cutItems = (items: readonly AssetManagerItem[]) => {+ const selections = items.map(({ type, id }) => ({ type, id }));+ if (+ currentProtectionRef.current.canManageAssets === false ||+ currentProtectionRef.current.canRelocateItems(selections) === false+ ) {+ return;+ }cutAssetManagerItems(items);setAnnouncement(`${getItemCountLabel(items.length)} cut.`);};const duplicateItems = (items: readonly AssetManagerItem[]) => {+ const selections = items.map(({ type, id }) => ({ type, id }));+ if (+ currentProtectionRef.current.canManageAssets === false ||+ currentProtectionRef.current.canCopyOrDeleteItems(selections) === false ||+ selections.some(+ (item) =>+ item.type === "asset" &&+ currentProtectionRef.current.collectionEntryAssetIds.has(item.id)+ )+ ) {+ return;+ }duplicateAssetManagerItems(items);setAnnouncement(`${getItemCountLabel(items.length)} duplicated.`);};@@ -625,15 +857,68 @@ export const AssetManager = ({forcedSelection === undefined || shortcutItems.length === 0? {}: {- cut: () => cutItems(shortcutItems),- copy: () => copyItems(shortcutItems),- duplicate: () => duplicateItems(shortcutItems),- move: () => setPendingMoveItems(normalizedShortcutSelection),- delete: () => setPendingDeleteItems(normalizedShortcutSelection),+ cut: canRelocateSelection ? () => cutItems(shortcutItems) : undefined,+ copy: canCopyOrDeleteSelection+ ? () => copyItems(shortcutItems)+ : undefined,+ duplicate:+ canCopyOrDeleteSelection &&+ selectionContainsCollectionEntry === false+ ? () => duplicateItems(shortcutItems)+ : undefined,+ move: canRelocateSelection+ ? () => {+ if (+ currentProtectionRef.current.canManageAssets &&+ currentProtectionRef.current.canRelocateItems(+ normalizedShortcutSelection+ )+ ) {+ setPendingMoveItems(normalizedShortcutSelection);+ }+ }+ : undefined,+ delete: canCopyOrDeleteSelection+ ? () => {+ if (+ currentProtectionRef.current.canManageAssets &&+ currentProtectionRef.current.canCopyOrDeleteItems(+ normalizedShortcutSelection+ )+ ) {+ setPendingDeleteItems(normalizedShortcutSelection);+ }+ }+ : undefined,};+ useEffect(() => {+ if (+ pendingDeleteItems !== undefined &&+ canCopyOrDeleteItems(pendingDeleteItems) === false+ ) {+ setPendingDeleteItems(undefined);+ }+ }, [canCopyOrDeleteItems, pendingDeleteItems]);++ useEffect(() => {+ if (+ pendingMoveItems !== undefined &&+ canRelocateItems(pendingMoveItems) === false+ ) {+ setPendingMoveItems(undefined);+ }+ }, [canRelocateItems, pendingMoveItems]);+const moveItems = useCallback((items: readonly AssetManagerSelection[], parentId: string | undefined) => {+ if (+ currentProtectionRef.current.canManageAssets === false ||+ currentProtectionRef.current.canRelocateItems(items) === false+ ) {+ setPendingMoveItems(undefined);+ return;+ }const normalizedItems = normalizeItems(items);moveAssetManagerItems(normalizedItems, parentId);clearMultiselect();@@ -649,13 +934,29 @@ export const AssetManager = ({(items: readonly AssetManagerSelection[],targetFolderId: string | undefined- ) =>- canMoveAssetManagerItems({+ ) => {+ if (canRelocateItems(items) === false) {+ return false;+ }+ if (+ items.some(+ (item) =>+ item.type === "asset" &&+ !canAddAssetToContentCollection(+ effectiveCollections.get(targetFolderId ?? ""),+ assets.get(item.id)+ )+ )+ ) {+ return false;+ }+ return canMoveAssetManagerItems({items,targetFolderId,hierarchy: folderHierarchy,- }),- [folderHierarchy]+ });+ },+ [canRelocateItems, effectiveCollections, assets, folderHierarchy]);const moveExcludedFolderIds = useMemo(() => {if (pendingMoveItems === undefined) {@@ -713,14 +1014,24 @@ export const AssetManager = ({/>);+ const collectionPanelActions =+ currentFolderIsCollection &&+ effectiveCollections.get(currentFolderId!)?.status !== "ready"+ ? {+ createFolder: panelActions?.createFolder,+ createEntry: panelActions?.createEntry,+ convertCollection: panelActions?.convertCollection,+ deleteUnusedAssets: panelActions?.deleteUnusedAssets,+ }+ : panelActions;const panelContextMenuActions: AssetManagerItemActions = {- ...panelActions,+ ...collectionPanelActions,...(canManageFolders- ? { paste: () => pasteAssetManagerClipboard(currentFolderId) }+ ? { paste: () => pasteClipboardToFolder(currentFolderId) }: {}),};const canPaste =- canManageFolders && canPasteAssetManagerClipboard(currentFolderId);+ canManageFolders && canPasteClipboardToFolder(currentFolderId);const disabledPanelActions = new Set<keyof AssetManagerItemActions>();if (canPaste === false) {disabledPanelActions.add("paste");@@ -775,31 +1086,52 @@ export const AssetManager = ({setSelection(renderedItems[0]);announceSelection(renderedItems);}- } else if (key === "c" && shortcutItems.length > 0) {+ } else if (+ key === "c" &&+ shortcutItems.length > 0 &&+ canCopyOrDeleteSelection+ ) {copyItems(shortcutItems);- } else if (key === "x" && shortcutItems.length > 0) {+ } else if (+ key === "x" &&+ shortcutItems.length > 0 &&+ canRelocateSelection+ ) {cutItems(shortcutItems);- } else if (key === "d" && shortcutItems.length > 0) {+ } else if (+ key === "d" &&+ shortcutItems.length > 0 &&+ canCopyOrDeleteSelection &&+ selectionContainsCollectionEntry === false+ ) {duplicateItems(shortcutItems);} else if (key === "v" && canPaste) {const pastedItemCount = clipboard?.items.length ?? 0;- pasteAssetManagerClipboard(currentFolderId);+ pasteClipboardToFolder(currentFolderId);setAnnouncement(`${getItemCountLabel(pastedItemCount)} pasted into ${getFolderName(currentFolderId)}.`);- } else if (isDeleteCommand && shortcutItems.length > 0) {+ } else if (+ isDeleteCommand &&+ shortcutItems.length > 0 &&+ canCopyOrDeleteSelection+ ) {setPendingDeleteItems(normalizedShortcutSelection);}};const hasPanelContextMenuActions = Object.values(panelContextMenuActions).some((action) => action !== undefined);- const showItemContextMenu = (actions: AssetManagerItemActions) => {+ const showItemContextMenu = (+ actions: AssetManagerItemActions,+ disabledActions?: ReadonlySet<keyof AssetManagerItemActions>+ ) => {flushSync(() => {setItemContextMenu(({ instance }) => ({actions,+ disabledActions,instance: instance + 1,}));});@@ -899,6 +1231,7 @@ export const AssetManager = ({return (<><AssetsShell+ contentNotice={folderNotice}filters={<Flex gap="2" grow><AssetFilters@@ -911,7 +1244,9 @@ export const AssetManager = ({}searchProps={searchProps}isEmpty={filteredItems.length === 0 && visibleFolders.length === 0}- emptyMessage={isSearching ? "No matching assets or folders" : undefined}+ emptyMessage={+ isSearching ? "No matching assets or folders" : emptyMessage+ }emptyContent={backCard === undefined ? undefined : (<AssetGrid role="listbox" aria-multiselectable={canManageFolders}>@@ -961,6 +1296,10 @@ export const AssetManager = ({onKeyDown={handleShortcut}autoScrollOnElementDrag={canManageFolders}allowFolderDrop={canManageFolders}+ allowExternalDrop={+ !currentFolderIsCollection ||+ effectiveCollections.get(currentFolderId!)?.status === "ready"+ }contextMenu={hasPanelContextMenuActions ? (<AssetManagerItemContextMenuContent@@ -969,7 +1308,7 @@ export const AssetManager = ({disabledActions={itemContextMenu.actions === undefined? disabledPanelActions- : undefined+ : itemContextMenu.disabledActions}/>) : undefined@@ -980,10 +1319,8 @@ export const AssetManager = ({folderId={currentFolderId}selectedItem={selectedBreadcrumbItem}onChange={setCurrentFolderId}- canPaste={- canManageFolders ? canPasteAssetManagerClipboard : undefined- }- onPaste={canManageFolders ? pasteAssetManagerClipboard : undefined}+ canPaste={canManageFolders ? canPasteClipboardToFolder : undefined}+ onPaste={canManageFolders ? pasteClipboardToFolder : undefined}/>}>@@ -1008,6 +1345,9 @@ export const AssetManager = ({<FolderThumbnailkey={folder.id}folder={folder}+ collection={effectiveCollections.get(folder.id)}+ onConfigureCollection={onConfigureCollection}+ createCollection={createCollection}interactions={thumbnailInteractions}selected={isItemSelected({ type: "folder", id: folder.id })}forcedSelection={forcedSelection !== undefined}@@ -1015,6 +1355,12 @@ export const AssetManager = ({forcedSelection === undefined ? undefined : selectionActions}canManage={canManageFolders}+ canCopyOrDelete={+ canConfigureCollections ||+ collectionProtectedFolderIds.has(folder.id) === false+ }+ canPasteClipboard={canPasteClipboardToFolder(folder.id)}+ onPasteClipboard={() => pasteClipboardToFolder(folder.id)}canMoveItems={canMoveItems}onOpen={() => openFolder(folder.id)}path={@@ -1037,6 +1383,19 @@ export const AssetManager = ({{filteredItems.map((assetContainer) => (<AssetThumbnailkey={assetContainer.asset.id}+ onEntrySettings={+ onEntrySettings !== undefined &&+ collectionEntryAssetIds.has(assetContainer.asset.id) &&+ effectiveCollections.get(+ assetContainer.asset.folderId ?? ""+ )?.status === "ready"+ ? () => onEntrySettings(assetContainer.asset.id)+ : undefined+ }+ entryError={entryIssues+ ?.get(assetContainer.asset.id)+ ?.map((issue) => issue.message)+ .join("\n")}assetContainer={assetContainer}interactions={thumbnailInteractions}selectionActions={@@ -1063,7 +1422,37 @@ export const AssetManager = ({): undefined}- canDrag={canManageFolders}+ canDrag={+ canManageFolders &&+ canRelocateItems(+ getDragItems({+ type: "asset",+ id: assetContainer.asset.id,+ })+ )+ }+ isCollectionEntry={collectionEntryAssetIds.has(+ assetContainer.asset.id+ )}+ isCollectionReserved={collectionReservedAssetIds.has(+ assetContainer.asset.id+ )}+ isCollectionFile={collectionFileIds.has(+ assetContainer.asset.id+ )}+ unavailableDestinationFolderIds={+ new Set(+ Array.from(effectiveCollections)+ .filter(+ ([, collection]) =>+ !canAddAssetToContentCollection(+ collection,+ assetContainer.asset+ )+ )+ .map(([id]) => id)+ )+ }onMove={() =>setPendingMoveItems([{ type: "asset", id: assetContainer.asset.id },@@ -1091,7 +1480,7 @@ export const AssetManager = ({><DialogContent minWidth={360} aria-describedby={undefined}><DialogTitle>Delete selected items</DialogTitle>- <Box css={{ padding: theme.panel.padding }}>+ <PanelContent as={Box}><Text>Delete{" "}{getItemCountLabel(pendingDeleteItems?.length ?? 0, "selected")}?@@ -1104,6 +1493,14 @@ export const AssetManager = ({prefix={<TrashIcon />}onClick={() => {const items = pendingDeleteItems ?? [];+ if (+ currentProtectionRef.current.canManageAssets === false ||+ currentProtectionRef.current.canCopyOrDeleteItems(items) ===+ false+ ) {+ setPendingDeleteItems(undefined);+ return;+ }deleteAssetManagerItems(items);setPendingDeleteItems(undefined);clearMultiselect();@@ -1115,7 +1512,7 @@ export const AssetManager = ({Delete</Button></Flex>- </Box>+ </PanelContent></DialogContent></Dialog>{pendingMoveItems !== undefined && (diff --git a/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsxindex 81d5de44a2..6590e32b97 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx@@ -7,6 +7,42 @@ import { createAssetManagerTestRenderer } from "./test-utils";import { AssetDeleteDialog, AssetSettings } from "./asset-settings";const renderer = createAssetManagerTestRenderer();++test.each([+ { name: "collection.json", format: "json", isCollectionFile: true },+ { name: "custom-template.mdx", format: "mdx", isCollectionFile: true },+ { name: "entry.mdx", format: "mdx", isCollectionFile: false },+])(+ "protects collection files from deletion in settings: $name",+ ({ name, format, isCollectionFile }) => {+ const onDelete = vi.fn();+ const onOpenChange = vi.fn();+ $authPermit.set("build");+ renderer.render(+ <TooltipProvider>+ <AssetSettings+ open+ asset={{ ...assetBase, name, format, type: "file", meta: {} }}+ isCollectionFile={isCollectionFile}+ onDelete={onDelete}+ onOpenChange={onOpenChange}+ >+ <button>Anchor</button>+ </AssetSettings>+ </TooltipProvider>+ );+ // The accessible action name identifies the control, not incidental prose.+ const button = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Delete"+ )!;+ expect(button).toBeInstanceOf(HTMLButtonElement);+ expect(button.disabled).toBe(isCollectionFile);+ act(() => button.click());+ expect(onDelete).toHaveBeenCalledTimes(isCollectionFile ? 0 : 1);+ expect(onOpenChange).toHaveBeenCalledTimes(isCollectionFile ? 0 : 1);+ }+);+type ImageAsset = Extract<Asset, { type: "image" }>;const assetBase = {id: "asset",diff --git a/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx b/apps/builder/app/builder/shared/asset-manager/asset-settings.tsxindex 49fa67e9d9..5d5b6219f0 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx@@ -12,6 +12,7 @@ import {} from "@webstudio-is/sdk";import type { Asset, Instance } from "@webstudio-is/sdk";import {+ PanelContent,Box,Button,css,@@ -45,6 +46,7 @@ import {DimensionsIcon,DownloadIcon,InfoCircleIcon,+ ListViewIcon,PageIcon,RefreshCcwIcon,TrashIcon,@@ -55,7 +57,7 @@ import {$editingPageId,$permissions,} from "~/shared/nano-states";-import { $assets } from "~/shared/sync/data-stores";+import { $assets, $project } from "~/shared/sync/data-stores";import { $styleSourceSelections } from "~/shared/sync/data-stores";import { $openProjectSettings } from "~/shared/nano-states/project-settings";import { $styles } from "~/shared/sync/data-stores";@@ -66,6 +68,7 @@ import { $selectedPageId } from "~/shared/nano-states";import { executeRuntimeMutation } from "~/shared/instance-utils/data";import { deleteAssets, updateAssetContent } from "~/builder/shared/assets";import { normalizeTextFileConversion } from "~/builder/features/text-file-editor/text-file-utils";+import { isAssetFilenameUsed } from "~/builder/shared/assets/asset-utils";import {$activeInspectorPanel,setActiveSidebarPanel,@@ -266,12 +269,13 @@ const AssetUsageIndicator = styled(Box, {const useLocalValue = <Type extends string>(savedValue: Type,- onSave: (value: Type) => void+ onSave: (value: Type) => void,+ canSave: () => boolean) => {const [localValue, setLocalValue] = useState(savedValue);const save = () => {- if (localValue !== savedValue) {+ if (canSave() && localValue !== savedValue) {// To synchronize with setState immediately followed by saveonSave(localValue);}@@ -312,19 +316,37 @@ const AssetSettingsContent = ({onDelete,onReplace,focusName,+ canRename,+ canMove,+ isCollectionFile,+ canSaveChanges,+ canPersistChanges,+ unavailableDestinationFolderIds,}: {asset: Asset;usages: AssetUsage[];onDelete?: () => void;onReplace?: () => void;focusName: boolean;+ canRename: boolean;+ canMove: boolean;+ isCollectionFile: boolean;+ canSaveChanges: boolean;+ canPersistChanges: (expectedAssetName?: string) => boolean;+ unavailableDestinationFolderIds?: ReadonlySet<string>;}) => {const { canDownloadAssets } = useStore($permissions);const { size, meta, id } = asset;const { ext } = getAssetDisplayNameParts(asset);const [filenameError, setFilenameError] = useState<string>();+ const permissionsRef = useRef({ canRename, canMove });+ permissionsRef.current = { canRename, canMove };const saveFilename = async (newFilename: string) => {+ if (!permissionsRef.current.canRename || canPersistChanges() === false) {+ return;+ }const assetId = asset.id;+ let expectedAssetName = asset.name;if (!isValidFilename(newFilename)) {setFilenameError("Invalid filename");return;@@ -338,14 +360,16 @@ const AssetSettingsContent = ({return;}- for (const candidate of $assets.get().values()) {- if (- candidate.id !== assetId &&- formatAssetName(candidate) === newFilename- ) {- setFilenameError("Filename already used");- return;- }+ if (+ isAssetFilenameUsed({+ assets: $assets.get().values(),+ filename: newFilename,+ folderId: currentAsset.folderId,+ excludeAssetId: assetId,+ })+ ) {+ setFilenameError("Filename already used");+ return;}if (extension.toLowerCase() !== currentExtension.toLowerCase()) {@@ -372,11 +396,18 @@ const AssetSettingsContent = ({setFilenameError(normalized.error);return;}- await updateAssetContent({+ if (+ !permissionsRef.current.canRename ||+ canPersistChanges() === false+ ) {+ return;+ }+ const updatedAsset = await updateAssetContent({asset: currentAsset,content: normalized.content,extension,});+ expectedAssetName = updatedAsset.name;} catch (error) {const message =error instanceof Error ? error.message : "Unable to rename file";@@ -386,6 +417,12 @@ const AssetSettingsContent = ({}}+ if (+ !permissionsRef.current.canRename ||+ canPersistChanges(expectedAssetName) === false+ ) {+ return;+ }executeRuntimeMutation({id: "assets.update",input: {@@ -396,7 +433,8 @@ const AssetSettingsContent = ({};const [filename, setFilename] = useLocalValue(formatAssetName(asset),- (newFilename) => void saveFilename(newFilename)+ (newFilename) => void saveFilename(newFilename),+ canPersistChanges);const [description, setDescription] = useLocalValue(asset.description ?? "",@@ -409,11 +447,16 @@ const AssetSettingsContent = ({values: { description: newDescription },},});- }+ },+ canPersistChanges);- const moveToFolder = (newFolderId: string | undefined) =>+ const moveToFolder = (newFolderId: string | undefined) => {+ if (!permissionsRef.current.canMove || canPersistChanges() === false) {+ return;+ }moveAssetManagerItems([{ type: "asset", id: asset.id }], newFolderId);+ };const authPermit = useStore($authPermit);let downloadError: undefined | string;@@ -432,7 +475,7 @@ const AssetSettingsContent = ({return (<>- <Box css={{ padding: theme.panel.padding }}>+ <PanelContent as={Box}><Gridcolumns={2}css={{ gridTemplateColumns: "auto auto" }}@@ -472,17 +515,25 @@ const AssetSettingsContent = ({alignItems: "center",}}>- <AssetUsageIndicator data-asset-settings-usage-indicator="" />+ {isCollectionFile ? (+ <ListViewIcon aria-label="Used by collection" />+ ) : (+ <AssetUsageIndicator data-asset-settings-usage-indicator="" />+ )}</Flex>- <Text variant="labels">{usages.length} uses</Text>+ <Text variant="labels">+ {isCollectionFile+ ? "Used by collection"+ : `${usages.length} uses`}+ </Text></Flex></Grid>- </Box>+ </PanelContent>- <Grid+ <PanelContent+ as={Grid}columns={2}css={{- padding: theme.panel.padding,gridTemplateColumns: "auto 1fr",columnGap: theme.spacing[5],rowGap: theme.spacing[3],@@ -500,9 +551,9 @@ const AssetSettingsContent = ({</Text></>)}- </Grid>+ </PanelContent>- <Grid css={{ padding: theme.panel.padding, gap: 4 }}>+ <PanelContent as={Grid} css={{ gap: 4 }}><Label htmlFor="asset-manager-filename">Name</Label><InputErrorsTooltiperrors={filenameError ? [filenameError] : undefined}@@ -510,7 +561,11 @@ const AssetSettingsContent = ({<InputFieldid="asset-manager-filename"autoFocus={focusName}- readOnly={authPermit === "view"}+ readOnly={+ authPermit === "view" ||+ canRename === false ||+ canSaveChanges === false+ }color={filenameError ? "error" : undefined}value={filename}onChange={(event) => {@@ -519,19 +574,22 @@ const AssetSettingsContent = ({}}/></InputErrorsTooltip>- </Grid>+ </PanelContent>- <Grid css={{ padding: theme.panel.padding, gap: 4 }}>+ <PanelContent as={Grid} css={{ gap: 4 }}><AssetFolderSelectorvalue={asset.folderId}onChange={moveToFolder}+ unavailableDestinationFolderIds={unavailableDestinationFolderIds}rootLabel="Folder"- disabled={authPermit === "view"}+ disabled={+ authPermit === "view" || !canMove || canSaveChanges === false+ }deferChangesUntilBlur/>- </Grid>+ </PanelContent>- <Grid css={{ padding: theme.panel.padding, gap: 4 }}>+ <PanelContent as={Grid} css={{ gap: 4 }}><LabelhtmlFor="asset-manager-description"css={{ display: "flex", alignItems: "center", gap: 4 }}@@ -541,12 +599,12 @@ const AssetSettingsContent = ({variant="wrapped"content="The description is used as the default “alt” text for the image.">- <InfoCircleIcon />+ <InfoCircleIcon color={cssVar("--foreground-secondary")} /></Tooltip></Label><TextAreaid="asset-manager-description"- readOnly={authPermit === "view"}+ readOnly={authPermit === "view" || canSaveChanges === false}placeholder='Enter "alt" text'rows={1}maxRows={6}@@ -554,9 +612,9 @@ const AssetSettingsContent = ({value={description}onChange={setDescription}/>- </Grid>+ </PanelContent>- <Grid css={{ padding: theme.panel.padding, gap: 4 }}>+ <PanelContent as={Grid} css={{ gap: 4 }}><Label htmlFor="asset-manager-id">ID</Label><InputFieldid="asset-manager-id"@@ -570,25 +628,9 @@ const AssetSettingsContent = ({</Flex>}/>- </Grid>-- <Flex justify="between" css={{ padding: theme.panel.padding }}>- {authPermit === "view" ? (- <Tooltip side="bottom" content="View mode. You can't delete assets.">- <Button disabled color="destructive" prefix={<TrashIcon />}>- Delete- </Button>- </Tooltip>- ) : usages.length === 0 ? (- <Button color="destructive" onClick={onDelete} prefix={<TrashIcon />}>- Delete- </Button>- ) : (- <Button color="primary" onClick={onDelete}>- Review & delete- </Button>- )}+ </PanelContent>+ <PanelContent as={Flex} justify="between"><Flex gap="1">{isImage && (<>@@ -625,7 +667,29 @@ const AssetSettingsContent = ({</Tooltip>)}</Flex>- </Flex>+ {authPermit === "view" || isCollectionFile ? (+ <Tooltip+ side="bottom"+ content={+ isCollectionFile+ ? "This file is required by the collection."+ : "View mode. You can't delete assets."+ }+ >+ <Button disabled color="destructive" prefix={<TrashIcon />}>+ Delete+ </Button>+ </Tooltip>+ ) : usages.length === 0 ? (+ <Button color="destructive" onClick={onDelete} prefix={<TrashIcon />}>+ Delete+ </Button>+ ) : (+ <Button color="primary" onClick={onDelete}>+ Review & delete+ </Button>+ )}+ </PanelContent></>);};@@ -645,7 +709,7 @@ export const AssetDeleteDialog = ({<Dialog open={open} onOpenChange={onOpenChange}><DialogContent minWidth={360} aria-describedby={undefined}><DialogTitle>Delete asset?</DialogTitle>- <Box css={{ padding: theme.panel.padding }}>+ <PanelContent as={Box}><Text>Delete “{formatAssetName(asset)}”?</Text>{usages.length > 0 && (<>@@ -665,7 +729,7 @@ export const AssetDeleteDialog = ({Delete</Button></Flex>- </Box>+ </PanelContent></DialogContent></Dialog>);@@ -678,6 +742,11 @@ export const AssetSettings = ({onDelete,onReplace,focusName = false,+ canRename = true,+ canMove = true,+ isCollectionFile = false,+ canSaveChanges = true,+ unavailableDestinationFolderIds,children,}: {asset: Asset;@@ -686,8 +755,27 @@ export const AssetSettings = ({onDelete?: () => void;onReplace?: () => void;focusName?: boolean;+ canRename?: boolean;+ canMove?: boolean;+ isCollectionFile?: boolean;+ canSaveChanges?: boolean;+ unavailableDestinationFolderIds?: ReadonlySet<string>;children: ReactNode;}) => {+ const canSaveChangesRef = useRef(canSaveChanges);+ canSaveChangesRef.current = canSaveChanges;+ const canPersistChanges = (expectedAssetName = asset.name) => {+ if (canSaveChangesRef.current === false || $authPermit.get() === "view") {+ return false;+ }+ const currentProject = $project.get();+ const currentAsset = $assets.get().get(asset.id);+ return (+ currentProject?.id === asset.projectId &&+ currentAsset?.projectId === asset.projectId &&+ currentAsset.name === expectedAssetName+ );+ };const usagesByAssetId = useStore($usagesByAssetId);const usages = usagesByAssetId.get(asset.id) ?? [];const deleteAsset =@@ -706,7 +794,7 @@ export const AssetSettings = ({};return (<Popover modal open={open} onOpenChange={onOpenChange}>- {usages.length === 0 && (+ {usages.length === 0 && !isCollectionFile && (<AssetUsageIndicatorrole="img"aria-label="Unused asset"@@ -722,6 +810,12 @@ export const AssetSettings = ({onDelete={deleteAsset}onReplace={replaceAsset}focusName={focusName}+ canRename={canRename}+ canMove={canMove}+ isCollectionFile={isCollectionFile}+ canSaveChanges={canSaveChanges}+ canPersistChanges={canPersistChanges}+ unavailableDestinationFolderIds={unavailableDestinationFolderIds}/></PopoverContent></Popover>diff --git a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsxindex cd408ccd94..c543da6449 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsx@@ -1,15 +1,45 @@-import { Fragment, type ComponentProps } from "react";+import { Fragment, useState, type ComponentProps } from "react";import { act } from "react-dom/test-utils";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { TooltipProvider } from "@webstudio-is/design-system";import { AssetThumbnail } from "./asset-thumbnail";import { BackThumbnail, FolderThumbnail } from "./asset-folder-thumbnail";+import type { Asset } from "@webstudio-is/sdk";import { createAssetFolderFixture } from "@webstudio-is/sdk/testing";import { $assetManagerClipboard } from "./asset-manager-clipboard";import { createAssetManagerTestRenderer } from "./test-utils";-import { $authPermit } from "~/shared/nano-states";+import {+ $authPermit,+ $builderMode,+ $selectedPageId,+} from "~/shared/nano-states";import type { AssetManagerThumbnailInteractions } from "./asset-manager-thumbnail";-import { $assetFolders, $assets, $project } from "~/shared/sync/data-stores";+import {+ $assetFolders,+ $assets,+ $pages,+ $project,+} from "~/shared/sync/data-stores";+import {+ createDefaultCollectionConfig,+ parseCollectionConfig,+} from "@webstudio-is/content-engine";+import { createDefaultPages } from "@webstudio-is/project-build";+import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";+import { createContentCollectionFolder } from "./asset-folder-dialogs";+import { AssetsPanel } from "~/builder/features/assets/assets";+import { getSetting, setSetting } from "../client-settings";+import { clientSettingsStorageKey } from "~/shared/color-scheme";+import {+ createAssetContentBridge,+ __testing__ as bridgeTesting,+} from "~/shared/asset-content-bridge.client";+import {+ assetContentDescriptorHeader,+ serializeAssetContentDescriptor,+} from "@webstudio-is/protocol/asset-resource-api";++const { initBridge, clearBridge } = bridgeTesting;const folder = createAssetFolderFixture({ id: "folder", name: "Documents" });const uploadedAssetContainer: ComponentProps<@@ -94,7 +124,89 @@ const openSettingsFromActionsMenu = ({act(() => settings?.click());};+const setControlValue = (+ control: HTMLInputElement | HTMLTextAreaElement,+ value: string+) => {+ const valueSetter = Object.getOwnPropertyDescriptor(+ control instanceof HTMLInputElement+ ? HTMLInputElement.prototype+ : HTMLTextAreaElement.prototype,+ "value"+ )?.set;+ valueSetter?.call(control, value);+ control.dispatchEvent(new InputEvent("input", { bubbles: true }));+};++const selectFolderOption = (label: string) => {+ const trigger = document.querySelector<HTMLButtonElement>(+ '[aria-label="Folder"]'+ );+ act(() => {+ trigger?.dispatchEvent(+ new PointerEvent("pointerdown", {+ bubbles: true,+ button: 0,+ pointerId: 1,+ pointerType: "mouse",+ })+ );+ });+ const option = Array.from(+ document.querySelectorAll<HTMLElement>('[role="option"]')+ ).find((candidate) => candidate.textContent === label);+ if (option === undefined) {+ throw new Error(`Expected folder option ${label}`);+ }+ act(() => {+ option.dispatchEvent(+ new PointerEvent("pointerdown", {+ bubbles: true,+ button: 0,+ pointerId: 1,+ pointerType: "mouse",+ })+ );+ option.dispatchEvent(+ new PointerEvent("pointerup", {+ bubbles: true,+ button: 0,+ pointerId: 1,+ pointerType: "mouse",+ })+ );+ });+};+const renderer = createAssetManagerTestRenderer();+test.each([false, true])(+ "opens the available entry editor from its validation indicator (settings: %s)",+ (hasEntrySettings) => {+ const onOpen = vi.fn();+ const onEntrySettings = hasEntrySettings ? vi.fn() : undefined;+ const container = renderer.render(+ <TooltipProvider>+ {createUploadedAssetThumbnail({+ entryError: "Title needs a value",+ onOpen,+ onEntrySettings,+ })}+ </TooltipProvider>+ );+ const indicator = container.querySelector<HTMLButtonElement>(+ '[aria-label="Review errors in document.pdf"]'+ );+ expect(indicator).not.toBeNull();+ expect(indicator).toBeEnabled();+ expect(getComputedStyle(indicator!).pointerEvents).toBe("auto");+ act(() => indicator?.click());+ expect(onEntrySettings ?? onOpen).toHaveBeenCalledOnce();+ if (hasEntrySettings) {+ expect(onOpen).not.toHaveBeenCalled();+ }+ }+);+registerContainers();vi.stubGlobal("ResizeObserver",class {@@ -104,7 +216,15 @@ vi.stubGlobal(});beforeEach(() => {+ setSetting("lastAssetFolderIds", {});+ serverSyncStore.transactionManager.currentStack = [];+ serverSyncStore.transactionManager.undoneStack = [];+ serverSyncStore.popAll();+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);$authPermit.set("build");+ $builderMode.set("design");$project.set({ id: "project" } as never);$assetFolders.set(new Map([[folder.id, folder]]));if (uploadedAssetContainer.status === "uploaded") {@@ -115,13 +235,849 @@ beforeEach(() => {});afterEach(() => {renderer.cleanup();+ setSetting("lastAssetFolderIds", {});$assetManagerClipboard.set(undefined);$assetFolders.set(new Map());$assets.set(new Map());$project.set(undefined);+ $pages.set(undefined);});describe("AssetThumbnail", () => {+ test("restores the Assets folder on reopen and persists returning to root", () => {+ const panel = (+ <TooltipProvider>+ <AssetsPanel publish={vi.fn()} onClose={vi.fn()} />+ </TooltipProvider>+ );+ let container = renderer.render(panel);+ act(() =>+ container+ .querySelector<HTMLElement>('[aria-label="Folder Documents"]')!+ .dispatchEvent(new MouseEvent("dblclick", { bubbles: true }))+ );+ expect(getSetting("lastAssetFolderIds")).toEqual({ project: folder.id });+ expect(+ JSON.parse(localStorage.getItem(clientSettingsStorageKey)!)+ .lastAssetFolderIds+ ).toEqual({ project: folder.id });+ renderer.cleanup();+ container = renderer.render(panel);+ expect(+ container.querySelector('[aria-label="Folder Documents"]')+ ).toBeNull();+ const root = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent === "Root"+ )!;+ act(() => root.click());+ expect(getSetting("lastAssetFolderIds")).toEqual({});+ renderer.cleanup();+ container = renderer.render(panel);+ expect(+ container.querySelector('[aria-label="Folder Documents"]')+ ).not.toBeNull();+ });++ test("restores folders per project and forgets deleted folders", () => {+ setSetting("lastAssetFolderIds", { project: folder.id, other: "deleted" });+ const panel = (+ <TooltipProvider>+ <AssetsPanel publish={vi.fn()} onClose={vi.fn()} />+ </TooltipProvider>+ );+ const container = renderer.render(panel);+ expect(+ container.querySelector('[aria-label="Folder Documents"]')+ ).toBeNull();+ act(() => $project.set({ id: "other" } as never));+ expect(+ container.querySelector('[aria-label="Folder Documents"]')+ ).not.toBeNull();+ expect(getSetting("lastAssetFolderIds")).toEqual({ project: folder.id });+ act(() => $project.set({ id: "project" } as never));+ expect(+ container.querySelector('[aria-label="Folder Documents"]')+ ).toBeNull();+ act(() => $assetFolders.set(new Map()));+ expect(getSetting("lastAssetFolderIds")).toEqual({});+ });+ test("opens collection settings after configuring an existing folder from its menu", async () => {+ const existingFolder = { ...folder, projectId: "project" };+ $assetFolders.set(new Map([[folder.id, existingFolder]]));+ const sources = [+ createDefaultCollectionConfig(),+ "---\ndraft: true\n---\n",+ ];+ const files: Asset[] = ["collection.json", "template.mdx"].map(+ (name, index) => ({+ id: `setup-${index}`,+ name,+ type: "file",+ format: index === 0 ? "json" : "mdx",+ projectId: "project",+ folderId: folder.id,+ size: sources[index].length,+ createdAt: folder.createdAt,+ meta: {},+ })+ );+ const request: typeof fetch = async (input) => {+ const url = new URL(String(input), location.origin);+ if (url.pathname === "/rest/assets/collection-folders") {+ return Response.json({ folder: existingFolder, assets: files });+ }+ throw new Error(`Unexpected request: ${url.pathname}`);+ };+ initBridge(+ createAssetContentBridge({+ origin: location.origin,+ authorize: () => true,+ requireReload: vi.fn(),+ request: async (input) => {+ const id = new URL(input).pathname.split("/")[3];+ const index = files.findIndex((file) => file.id === id);+ if (index === -1) {+ throw new Error("Unknown test asset");+ }+ return new Response(sources[index], {+ headers: {+ [assetContentDescriptorHeader]: serializeAssetContentDescriptor(+ files[index]+ ),+ "content-length": String(files[index].size),+ },+ });+ },+ })+ );+ try {+ const container = renderer.render(+ <TooltipProvider>+ <AssetsPanel+ publish={vi.fn()}+ onClose={vi.fn()}+ createCollection={(input) =>+ createContentCollectionFolder({ ...input, request })+ }+ />+ </TooltipProvider>+ );+ act(() =>+ container+ .querySelector<HTMLButtonElement>(+ '[aria-label="Actions for Documents"]'+ )!+ .dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ )+ );+ act(() =>+ Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]'))+ .find((item) => item.textContent === "Use as content collection")!+ .click()+ );+ await act(async () =>+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Use as content collection")!+ .click()+ );+ await vi.waitFor(() =>+ expect(+ Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Configure collection"+ )+ ).toBeDefined()+ );+ await act(async () =>+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Configure collection")!+ .click()+ );+ await vi.waitFor(() => {+ const dialog = Array.from(+ document.querySelectorAll('[role="dialog"]')+ ).find(+ (element) =>+ document.getElementById(+ element.getAttribute("aria-labelledby") ?? ""+ )?.textContent === "Collection settings"+ );+ expect(dialog).toBeDefined();+ expect(+ dialog!.querySelector('input[aria-label="Title label"]')+ ).not.toBeNull();+ });+ } finally {+ renderer.cleanup();+ clearBridge();+ }+ });+ test("opens collection setup from a regular folder actions menu", () => {+ $authPermit.set("own");+ $builderMode.set("design");+ const container = renderer.render(+ createFolderThumbnail({ canManage: true })+ );+ act(() =>+ container+ .querySelector<HTMLButtonElement>(+ '[aria-label="Actions for Documents"]'+ )!+ .dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ )+ );+ const action = Array.from(+ document.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent === "Use as content collection");+ expect(action).toBeDefined();+ act(() => action!.click());+ expect(document.querySelector('[role="dialog"]')).not.toBeNull();+ expect(document.activeElement?.textContent).toBe(+ "Use as content collection"+ );+ });+ test.each([+ { action: "Settings", openTitle: "Asset settings" },+ { action: "Delete", openTitle: "Delete asset?" },+ ])(+ "closes an open $action control when the asset becomes collection-reserved",+ ({ action, openTitle }) => {+ const templateAsset: Asset = {+ id: "template",+ projectId: "project",+ name: "template.mdx",+ filename: "template",+ folderId: folder.id,+ format: "mdx",+ size: 1,+ type: "file",+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ $authPermit.set("edit");+ $assets.set(new Map([[templateAsset.id, templateAsset]]));+ let reserveAsset: () => void = () => undefined;+ const DynamicAssetThumbnail = () => {+ const [reserved, setReserved] = useState(false);+ reserveAsset = () => setReserved(true);+ return (+ <AssetThumbnail+ assetContainer={{ status: "uploaded", asset: templateAsset }}+ interactions={createInteractions()}+ isCollectionEntry={reserved}+ isCollectionReserved={reserved}+ />+ );+ };+ const container = renderer.render(+ <TooltipProvider>+ <DynamicAssetThumbnail />+ </TooltipProvider>+ );+ act(() => {+ container+ .querySelector<HTMLButtonElement>(+ '[aria-label="Actions for template.mdx"]'+ )+ ?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });+ const actionItem = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent?.startsWith(action));+ expect(actionItem).toBeDefined();+ act(() => actionItem?.click());+ expect(document.body.textContent).toContain(openTitle);++ act(reserveAsset);++ expect(document.body.textContent).not.toContain(openTitle);+ }+ );++ test("closes an open asset delete confirmation when authorization becomes view-only", () => {+ const container = renderer.render(+ <TooltipProvider>{createUploadedAssetThumbnail()}</TooltipProvider>+ );+ act(() => {+ container+ .querySelector<HTMLButtonElement>(+ '[aria-label="Actions for document.pdf"]'+ )+ ?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });+ const deleteAction = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent?.startsWith("Delete"));+ expect(deleteAction).toBeDefined();+ act(() => deleteAction?.click());+ expect(document.body.textContent).toContain("Delete asset?");++ act(() => $authPermit.set("view"));++ expect(document.body.textContent).not.toContain("Delete asset?");+ });++ test("discards pending settings when an asset becomes collection-reserved", async () => {+ const targetFolder = createAssetFolderFixture({+ id: "target",+ name: "Target",+ });+ const templateAsset: Asset = {+ id: "template",+ projectId: "project",+ name: "template.mdx",+ filename: "template",+ description: "Original description",+ folderId: folder.id,+ format: "mdx",+ size: 1,+ type: "file",+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ $authPermit.set("edit");+ $assetFolders.set(+ new Map([+ [folder.id, folder],+ [targetFolder.id, targetFolder],+ ])+ );+ $assets.set(new Map([[templateAsset.id, templateAsset]]));+ let reserveAsset: () => void = () => undefined;+ const DynamicAssetThumbnail = () => {+ const [reserved, setReserved] = useState(false);+ reserveAsset = () => setReserved(true);+ return (+ <AssetThumbnail+ assetContainer={{ status: "uploaded", asset: templateAsset }}+ interactions={createInteractions()}+ isCollectionEntry={reserved}+ isCollectionReserved={reserved}+ />+ );+ };+ const container = renderer.render(+ <TooltipProvider>+ <DynamicAssetThumbnail />+ </TooltipProvider>+ );+ openSettingsFromActionsMenu({+ container,+ triggerLabel: "Actions for template.mdx",+ settingsTitle: "Asset settings",+ });+ const filename = document.querySelector<HTMLInputElement>(+ "#asset-manager-filename"+ );+ const description = document.querySelector<HTMLTextAreaElement>(+ "#asset-manager-description"+ );+ if (filename === null || description === null) {+ throw new Error("Expected editable asset settings");+ }+ act(() => {+ setControlValue(filename, "renamed.mdx");+ setControlValue(description, "Pending description");+ });+ selectFolderOption(targetFolder.name);++ act(reserveAsset);+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 550));+ });++ expect($assets.get().get(templateAsset.id)).toMatchObject({+ filename: templateAsset.filename,+ description: templateAsset.description,+ folderId: templateAsset.folderId,+ });+ });++ test("saves pending settings on an ordinary unmount", () => {+ const targetFolder = createAssetFolderFixture({+ id: "target",+ name: "Target",+ });+ $assetFolders.set(+ new Map([+ [folder.id, folder],+ [targetFolder.id, targetFolder],+ ])+ );+ const container = renderer.render(+ <TooltipProvider>{createUploadedAssetThumbnail()}</TooltipProvider>+ );+ openSettingsFromActionsMenu({+ container,+ triggerLabel: "Actions for document.pdf",+ settingsTitle: "Asset settings",+ });+ const filename = document.querySelector<HTMLInputElement>(+ "#asset-manager-filename"+ );+ const description = document.querySelector<HTMLTextAreaElement>(+ "#asset-manager-description"+ );+ if (filename === null || description === null) {+ throw new Error("Expected editable asset settings");+ }+ act(() => {+ setControlValue(filename, "renamed.pdf");+ setControlValue(description, "Saved description");+ });+ selectFolderOption(targetFolder.name);++ renderer.cleanup();++ expect($assets.get().get("asset")).toMatchObject({+ filename: "renamed",+ description: "Saved description",+ folderId: targetFolder.id,+ });+ });++ test.each([+ {+ context: "a different project",+ projectId: "other-project",+ name: uploadedAssetContainer.asset.name,+ },+ {+ context: "a replacement asset revision",+ projectId: uploadedAssetContainer.asset.projectId,+ name: "replacement-document.pdf",+ },+ ])("does not save pending settings into $context", ({ projectId, name }) => {+ const targetFolder = createAssetFolderFixture({+ id: "target",+ name: "Target",+ });+ $assetFolders.set(+ new Map([+ [folder.id, folder],+ [targetFolder.id, targetFolder],+ ])+ );+ const container = renderer.render(+ <TooltipProvider>{createUploadedAssetThumbnail()}</TooltipProvider>+ );+ openSettingsFromActionsMenu({+ container,+ triggerLabel: "Actions for document.pdf",+ settingsTitle: "Asset settings",+ });+ const filename = document.querySelector<HTMLInputElement>(+ "#asset-manager-filename"+ );+ const description = document.querySelector<HTMLTextAreaElement>(+ "#asset-manager-description"+ );+ if (filename === null || description === null) {+ throw new Error("Expected editable asset settings");+ }+ act(() => {+ setControlValue(filename, "pending.pdf");+ setControlValue(description, "Pending description");+ });+ selectFolderOption(targetFolder.name);++ const currentAsset = {+ ...uploadedAssetContainer.asset,+ projectId,+ name,+ filename: "current-document",+ description: "Current description",+ };+ act(() => {+ $project.set({ id: projectId } as never);+ $assets.set(new Map([[currentAsset.id, currentAsset]]));+ });+ renderer.cleanup();++ expect($assets.get().get(currentAsset.id)).toEqual(currentAsset);+ });++ test("hides collection settings from edit-only users", () => {+ const configAsset: Asset = {+ id: "config",+ projectId: "project",+ name: "collection.json",+ filename: "collection",+ format: "json",+ folderId: folder.id,+ type: "file",+ size: 1,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ id: "template",+ projectId: "project",+ name: "template.mdx",+ filename: "template",+ format: "mdx",+ folderId: folder.id,+ type: "file",+ size: 1,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ $authPermit.set("edit");+ const container = renderer.render(+ createFolderThumbnail({+ canManage: true,+ collection: {+ status: "ready",+ folderId: folder.id,+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ },+ })+ );+ const actions = container.querySelector<HTMLButtonElement>(+ '[aria-label="Actions for Documents"]'+ );++ act(() => {+ actions?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });++ const labels = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).map((item) => item.textContent);+ expect(labels).toContain("Settings");+ expect(labels).not.toContain("Collection settings");+ });++ test("keeps the opened collection revision while settings have unsaved edits", async () => {+ const configAsset: Asset = {+ id: "config",+ projectId: "project",+ name: "collection.json",+ filename: "collection",+ format: "json",+ folderId: folder.id,+ type: "file",+ size: 1,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ id: "template",+ projectId: "project",+ name: "template.mdx",+ filename: "template",+ format: "mdx",+ folderId: folder.id,+ type: "file",+ size: 1,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const initialCollection = {+ status: "ready" as const,+ folderId: folder.id,+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ };+ let receiveRemoteUpdate: () => void = () => undefined;+ const DynamicFolderThumbnail = () => {+ const [collection, setCollection] = useState(initialCollection);+ receiveRemoteUpdate = () =>+ setCollection({+ ...initialCollection,+ templateAsset: {+ ...templateAsset,+ name: "remote-template.mdx",+ filename: "remote-template",+ },+ });+ return createFolderThumbnail({+ canManage: true,+ collection,+ });+ };+ const container = renderer.render(+ <TooltipProvider>+ <DynamicFolderThumbnail />+ </TooltipProvider>+ );+ act(() => {+ container+ .querySelector<HTMLButtonElement>(+ '[aria-label="Actions for Documents"]'+ )+ ?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });+ const collectionSettings = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent === "Collection settings");+ expect(collectionSettings).toBeDefined();+ await act(async () => collectionSettings?.click());+ const templateName = document.querySelector<HTMLInputElement>(+ '[aria-label="Entry template name"]'+ );+ if (templateName === null) {+ throw new Error("Expected entry template name");+ }+ act(() => {+ const valueSetter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set;+ valueSetter?.call(templateName, "draft-template");+ templateName.dispatchEvent(new InputEvent("input", { bubbles: true }));+ });++ await act(async () => receiveRemoteUpdate());++ expect(templateName.value).toBe("draft-template");+ });++ test("marks collection folders with a collection icon", () => {+ const configAsset: Asset = {+ id: "config",+ projectId: "project",+ name: "collection.json",+ filename: "collection",+ format: "json",+ folderId: folder.id,+ type: "file",+ size: 1,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ id: "template",+ projectId: "project",+ name: "template.mdx",+ filename: "template",+ format: "mdx",+ folderId: folder.id,+ type: "file",+ size: 1,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const container = renderer.render(+ createFolderThumbnail({+ collection: {+ status: "ready",+ folderId: folder.id,+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ },+ })+ );++ const thumbnail = container.querySelector(+ '[aria-label="Folder Documents"]'+ );+ const collectionIcon = thumbnail?.querySelector(+ "[data-collection-folder-icon]"+ );+ expect(collectionIcon).toBeInstanceOf(SVGElement);+ expect(+ collectionIcon?.querySelector('path[stroke="currentColor"]')+ ).toBeInstanceOf(SVGElement);+ });++ test("keeps collection entry filenames read-only", () => {+ const container = renderer.render(+ <TooltipProvider>+ {createUploadedAssetThumbnail({ isCollectionEntry: true })}+ </TooltipProvider>+ );+ openSettingsFromActionsMenu({+ container,+ triggerLabel: "Actions for document.pdf",+ settingsTitle: "Asset settings",+ });++ expect(+ document.querySelector<HTMLInputElement>("#asset-manager-filename")+ ?.readOnly+ ).toBe(true);+ });++ test.each(["context", "dropdown"])(+ "opens conversion confirmation from the collection folder %s menu",+ async (menu) => {+ act(() => $authPermit.set("own"));+ const interactions = createInteractions();+ let convertFromContext: (() => void) | undefined;+ interactions.onContextMenuActions = (actions) => {+ convertFromContext = actions.convertCollection;+ };+ const container = renderer.render(+ <TooltipProvider>+ {createFolderThumbnail({+ canManage: true,+ interactions,+ collection: {+ status: "ready",+ folderId: folder.id,+ configAsset: {+ ...uploadedAssetContainer.asset,+ id: "config",+ name: "collection.json",+ format: "json",+ type: "file",+ meta: {},+ },+ templateAsset: {+ ...uploadedAssetContainer.asset,+ id: "template",+ name: "template.mdx",+ format: "mdx",+ type: "file",+ meta: {},+ },+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: {},+ },+ })}+ </TooltipProvider>+ );+ const target = container.querySelector<HTMLElement>(+ menu === "context"+ ? '[aria-label="Folder Documents"]'+ : '[aria-label="Actions for Documents"]'+ )!;+ act(() =>+ target.dispatchEvent(+ new MouseEvent(menu === "context" ? "contextmenu" : "pointerdown", {+ bubbles: true,+ button: menu === "context" ? 2 : 0,+ })+ )+ );+ const convert = Array.from(+ document.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent === "Convert to regular folder");+ if (menu === "context") {+ expect(convertFromContext).toBeDefined();+ await act(async () => convertFromContext?.());+ } else {+ expect(convert).toBeDefined();+ await act(async () => convert?.click());+ }+ await vi.waitFor(() =>+ expect(document.querySelector('[role="dialog"]')).not.toBeNull()+ );+ const cancel = Array.from(+ document.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Keep collection")!;+ expect(cancel).toBeDefined();+ await act(async () => cancel.click());+ await vi.waitFor(() =>+ expect(document.querySelector('[role="dialog"]')).toBeNull()+ );+ }+ );++ test.each(["collection.json", "custom-template.mdx"])(+ "marks and protects collection file %s for owners",+ (filename) => {+ act(() => $authPermit.set("own"));+ const onOpen = vi.fn();+ const container = renderer.render(+ <TooltipProvider>+ {createUploadedAssetThumbnail({+ assetContainer: {+ status: "uploaded",+ asset: {+ ...uploadedAssetContainer.asset,+ name: filename,+ filename: undefined,+ },+ },+ isCollectionFile: true,+ isCollectionReserved: true,+ onOpen,+ onMove: vi.fn(),+ })}+ </TooltipProvider>+ );+ expect(+ container.querySelector('[aria-label="Collection file"]')+ ).not.toBeNull();+ expect(container.querySelector('[aria-label="Unused asset"]')).toBeNull();+ act(() =>+ container+ .querySelector<HTMLButtonElement>(+ `[aria-label="Actions for ${filename}"]`+ )+ ?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ )+ );+ const items = Array.from(+ document.querySelectorAll<HTMLElement>('[role="menuitem"]')+ );+ expect(items.length).toBeGreaterThan(0);+ expect(+ items.every(+ (item) =>+ item.getAttribute("aria-disabled") === "true" ||+ item.textContent === "Open" ||+ item.textContent === "Download" ||+ item.textContent === "Settings"+ )+ ).toBe(true);+ const disabledItems = items.filter(+ (item) => item.getAttribute("aria-disabled") === "true"+ );+ expect(disabledItems).toHaveLength(5);+ act(() => items.find((item) => item.textContent === "Open")?.click());+ expect(onOpen).toHaveBeenCalledOnce();+ openSettingsFromActionsMenu({+ container,+ triggerLabel: `Actions for ${filename}`,+ settingsTitle: "Asset settings",+ });+ expect(+ document.querySelector('[aria-label="Used by collection"]')+ ).not.toBeNull();+ expect(+ document.querySelector("[data-asset-settings-usage-indicator]")+ ).toBeNull();+ expect(+ document.querySelector<HTMLInputElement>("#asset-manager-filename")+ ?.readOnly+ ).toBe(true);+ expect(+ document.querySelector<HTMLButtonElement>('[role="combobox"]')?.disabled+ ).toBe(true);+ expect(+ document.querySelector<HTMLTextAreaElement>(+ "#asset-manager-description"+ )?.readOnly+ ).toBe(false);+ }+ );+test.each([{triggerLabel: "Actions for Documents",@@ -297,7 +1253,8 @@ describe("AssetThumbnail", () => {}));expect(interactions.onContextMenuActions).toHaveBeenCalledWith(- expect.objectContaining({ open: onOpen })+ expect.objectContaining({ open: onOpen }),+ undefined);act(() => {diff --git a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsxindex fa15518121..c06b2a8b77 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx@@ -1,7 +1,19 @@import { useEffect, useRef, useState, type KeyboardEvent } from "react";import { useStore } from "@nanostores/react";-import { Box, styled, Text } from "@webstudio-is/design-system";-import { PageIcon, TextCapitalizeIcon } from "@webstudio-is/icons";+import {+ Box,+ styled,+ Text,+ Tooltip,+ IconButton,+ cssVar,+} from "@webstudio-is/design-system";+import {+ ListViewIcon,+ AlertCircleIcon,+ PageIcon,+ TextCapitalizeIcon,+} from "@webstudio-is/icons";import { wsVideoLoader } from "@webstudio-is/image";import { UploadingAnimation } from "./uploading-animation";import { AssetDeleteDialog, AssetSettings } from "./asset-settings";@@ -24,6 +36,7 @@ import {import type { MimeCategory } from "@webstudio-is/sdk";import { draggable } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";import { $authPermit, $permissions } from "~/shared/nano-states";+import { canConfigureContentCollections } from "../assets/content-collections";import { replaceAsset } from "~/builder/shared/assets";import { validateFiles } from "~/builder/shared/assets/asset-upload";import { createAssetManagerClipboardActions } from "./asset-manager-clipboard";@@ -87,9 +100,11 @@ const StyledWebstudioVideo = styled("video", mediaPreviewStyle);const GenericFilePreview = ({ext,format,+ isCollectionFile = false,}: {ext: string;format: string;+ isCollectionFile?: boolean;}) => {const Icon = getFileIcon(format);const showExtension = Icon === PageIcon;@@ -97,19 +112,32 @@ const GenericFilePreview = ({return (<Box css={{ position: "relative" }}><Icon size={48} strokeWidth={0.5} />- {showExtension && (- <Text- variant="tiny"- color="subtle"+ {isCollectionFile ? (+ <Boxcss={{position: "absolute",- top: 30,- left: "50%",- transform: "translateX(-50%)",+ inset: 0,+ display: "grid",+ placeItems: "center",}}>- {ext.toUpperCase()}- </Text>+ <ListViewIcon size={16} aria-label="Collection file" />+ </Box>+ ) : (+ showExtension && (+ <Text+ variant="tiny"+ color="subtle"+ css={{+ position: "absolute",+ top: 30,+ left: "50%",+ transform: "translateX(-50%)",+ }}+ >+ {ext.toUpperCase()}+ </Text>+ ))}</Box>);@@ -141,10 +169,12 @@ const VideoPreview = ({};type AssetThumbnailProps = {+ entryError?: string;assetContainer: AssetContainer;interactions: AssetManagerThumbnailInteractions;onChange?: (assetContainer: AssetContainer) => void;onOpen?: () => void;+ onEntrySettings?: () => void;selected?: boolean;forcedSelection?: boolean;folderPath?: string;@@ -152,6 +182,10 @@ type AssetThumbnailProps = {onElementChange?: (element: HTMLElement | null) => void;selectionActions?: AssetManagerItemActions;onMove?: () => void;+ isCollectionEntry?: boolean;+ isCollectionReserved?: boolean;+ isCollectionFile?: boolean;+ unavailableDestinationFolderIds?: ReadonlySet<string>;};export const AssetThumbnail = ({@@ -159,6 +193,7 @@ export const AssetThumbnail = ({interactions,onChange,onOpen,+ onEntrySettings,selected,forcedSelection,folderPath,@@ -166,12 +201,35 @@ export const AssetThumbnail = ({onElementChange,selectionActions,onMove,+ isCollectionEntry = false,+ isCollectionReserved = false,+ isCollectionFile = false,+ unavailableDestinationFolderIds,+ entryError,}: AssetThumbnailProps) => {const elementRef = useRef<HTMLElement | null>(null);const replaceInputRef = useRef<HTMLInputElement>(null);const [settingsOpen, setSettingsOpen] = useState(false);const [deleteOpen, setDeleteOpen] = useState(false);const authPermit = useStore($authPermit);+ const collectionActionBlocked = isCollectionReserved;+ const settingsBlocked =+ isCollectionReserved && !canConfigureContentCollections(authPermit);+ const settingsBlockedRef = useRef(settingsBlocked);+ settingsBlockedRef.current = settingsBlocked;+ const canMutate = authPermit !== "view" && collectionActionBlocked === false;+ const canMutateRef = useRef(canMutate);+ canMutateRef.current = canMutate;+ const isCollectionEntryRef = useRef(isCollectionEntry);+ isCollectionEntryRef.current = isCollectionEntry;+ useEffect(() => {+ if (canMutate === false) {+ setDeleteOpen(false);+ }+ if (settingsBlocked) {+ setSettingsOpen(false);+ }+ }, [canMutate, settingsBlocked]);const { canDownloadAssets } = useStore($permissions);const { asset } = assetContainer;const getDragItems = interactions.getDragItems;@@ -187,6 +245,7 @@ export const AssetThumbnail = ({? assetContainer.asset.projectId: "uploading",};+ const clipboardActions = createAssetManagerClipboardActions(item);const download = () => {if (assetContainer.status !== "uploaded") {return;@@ -201,21 +260,69 @@ export const AssetThumbnail = ({? {}: {open: onOpen,- settings: () => setSettingsOpen(true),+ entrySettings: onEntrySettings,+ settings: settingsBlocked+ ? undefined+ : () => {+ if (settingsBlockedRef.current === false) {+ setSettingsOpen(true);+ }+ },...(authPermit === "view"? {}: {- ...createAssetManagerClipboardActions(item),- move: onMove,- delete: () => setDeleteOpen(true),+ cut: () => {+ if (canMutateRef.current) {+ clipboardActions.cut();+ }+ },+ copy: () => {+ if (canMutateRef.current) {+ clipboardActions.copy();+ }+ },+ duplicate: () => {+ if (+ canMutateRef.current &&+ isCollectionEntryRef.current === false+ ) {+ clipboardActions.duplicate();+ }+ },+ ...(isCollectionEntry && !isCollectionReserved+ ? { duplicate: undefined }+ : {}),+ move:+ onMove === undefined+ ? undefined+ : () => {+ if (canMutateRef.current) {+ onMove();+ }+ },+ delete: () => {+ if (canMutateRef.current) {+ setDeleteOpen(true);+ }+ },...(asset.type === "image"- ? { replace: () => replaceInputRef.current?.click() }+ ? {+ replace: () => {+ if (canMutateRef.current) {+ replaceInputRef.current?.click();+ }+ },+ }: {}),}),...(authPermit !== "view" && canDownloadAssets ? { download } : {}),};const handleReplaceFile = (event: React.ChangeEvent<HTMLInputElement>) => {+ if (canMutateRef.current === false) {+ event.target.value = "";+ return;+ }const file = validateFiles(Array.from(event.target.files ?? []))[0];if (file !== undefined) {replaceAsset(asset.id, file);@@ -225,7 +332,12 @@ export const AssetThumbnail = ({useEffect(() => {const element = elementRef.current;- if (element === null || canDrag === false || isUploading) {+ if (+ element === null ||+ canDrag === false ||+ isUploading ||+ isCollectionReserved+ ) {return;}return draggable({@@ -244,10 +356,19 @@ export const AssetThumbnail = ({items: getDragItems({ type: "asset", id: asset.id }),}),});- }, [asset.id, canDrag, getDragItems, isUploading]);+ }, [asset.id, canDrag, getDragItems, isUploading, isCollectionReserved]);const displayedActions =forcedSelection && selected ? (selectionActions ?? actions) : actions;+ const disabledActions = isCollectionReserved+ ? new Set<keyof AssetManagerItemActions>([+ "cut",+ "copy",+ "duplicate",+ "move",+ "delete",+ ])+ : undefined;return (<>@@ -261,6 +382,7 @@ export const AssetThumbnail = ({<AssetManagerThumbnailitem={{ type: "asset", id: asset.id }}actions={displayedActions}+ disabledActions={disabledActions}interactions={interactions}selected={selected}forcedSelection={forcedSelection}@@ -293,7 +415,11 @@ export const AssetThumbnail = ({format={asset.format}/>) : (- <GenericFilePreview ext={ext} format={asset.format} />+ <GenericFilePreview+ ext={ext}+ format={asset.format}+ isCollectionFile={isCollectionFile}+ />)}label={basename}@@ -312,21 +438,44 @@ export const AssetThumbnail = ({}}header={assetContainer.status === "uploaded" ? (- <AssetSettings- asset={assetContainer.asset}- open={settingsOpen}- onOpenChange={(open) => {- setSettingsOpen(open);- }}- onDelete={actions.delete}- onReplace={actions.replace}- >- <AssetManagerThumbnailMenu- actions={displayedActions}- label={`Actions for ${formatAssetName(asset)}`}- onPointerDown={() => interactions.onContextMenuSelection(item)}- />- </AssetSettings>+ <>+ {entryError !== undefined && (+ <Tooltip content={entryError} variant="wrapped">+ <IconButton+ aria-label={`Review errors in ${formatAssetName(asset)}`}+ css={{ pointerEvents: "auto" }}+ onClick={onEntrySettings ?? onOpen}+ >+ <AlertCircleIcon color={cssVar("--foreground-negative")} />+ </IconButton>+ </Tooltip>+ )}+ <AssetSettings+ asset={assetContainer.asset}+ open={settingsOpen && settingsBlocked === false}+ onOpenChange={(open) => {+ setSettingsOpen(open);+ }}+ onDelete={actions.delete}+ onReplace={actions.replace}+ canRename={!isCollectionEntry && !isCollectionReserved}+ canMove={!isCollectionReserved}+ isCollectionFile={isCollectionFile}+ canSaveChanges={authPermit !== "view" && !settingsBlocked}+ unavailableDestinationFolderIds={+ unavailableDestinationFolderIds+ }+ >+ <AssetManagerThumbnailMenu+ actions={displayedActions}+ disabledActions={disabledActions}+ label={`Actions for ${formatAssetName(asset)}`}+ onPointerDown={() =>+ interactions.onContextMenuSelection(item)+ }+ />+ </AssetSettings>+ </>) : undefined}>@@ -335,7 +484,7 @@ export const AssetThumbnail = ({{assetContainer.status === "uploaded" && (<AssetDeleteDialogasset={assetContainer.asset}- open={deleteOpen}+ open={deleteOpen && canMutate}onOpenChange={setDeleteOpen}/>)}diff --git a/apps/builder/app/builder/shared/asset-manager/collection-entry-fields.tsx b/apps/builder/app/builder/shared/asset-manager/collection-entry-fields.tsxnew file mode 100644index 0000000000..86b5c36a92--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/collection-entry-fields.tsx@@ -0,0 +1,175 @@+import {+ collectionEntryFieldClearValue,+ type CollectionField,+ type ContentCollectionConfig,+} from "@webstudio-is/content-engine";+import {+ Grid,+ InputField,+ ResettableLabel,+ ToggleGroup,+ ToggleGroupButton,+ Text,+ TextArea,+ theme,+} from "@webstudio-is/design-system";++const optionalBooleanOptions = [+ { value: "unset", label: "Not set" },+ { value: "true", label: "Yes" },+ { value: "false", label: "No" },+] as const;++/** The same field controls for creation and editing; callers own persistence. */+export const CollectionEntryFields = ({+ config,+ values,+ errors = [],+ disabled = false,+ onChange,+ onReset,+ readOnlySlug = false,+}: {+ config: ContentCollectionConfig;+ values: Readonly<Record<string, unknown>>;+ errors?: readonly { fieldKey?: string; message: string }[];+ disabled?: boolean;+ readOnlySlug?: boolean;+ onChange: (field: CollectionField, value: unknown) => void;+ onReset: (field: CollectionField) => void;+}) => (+ <>+ {config.fields.map((field) => {+ const value = values[field.key];+ const hasValue =+ value !== "" &&+ value !== undefined &&+ value !== collectionEntryFieldClearValue;+ const id = `collection-entry-${field.key}`;+ const error = errors.find((issue) => issue.fieldKey === field.key);+ const hasFieldError = error !== undefined;+ const errorId = hasFieldError ? `${id}-error` : undefined;+ const booleanField = field.type === "boolean";+ return (+ <Grid+ key={field.key}+ gap={1}+ css={{+ gridTemplateColumns: booleanField ? "1fr auto" : undefined,+ alignItems: "center",+ }}+ >+ <ResettableLabel+ htmlFor={id}+ color={hasValue ? "local" : "default"}+ disabled={+ disabled || (readOnlySlug && field.key === config.slugField)+ }+ onReset={hasValue ? () => onReset(field) : undefined}+ description={+ field.key === config.slugField+ ? readOnlySlug+ ? "The slug identifies this entry’s filename and cannot be renamed."+ : config.generateSlugFrom === undefined+ ? "Enter a slug for this entry. It becomes the MDX filename."+ : `Generated from ${config.fields.find(({ key }) => key === config.generateSlugFrom)?.label ?? config.generateSlugFrom}. You can edit it before creating the entry. It becomes the MDX filename.`+ : undefined+ }+ >+ {field.label}+ {field.required ? " *" : ""}+ </ResettableLabel>+ {booleanField ? (+ <ToggleGroup+ id={id}+ type="single"+ aria-label={field.label}+ aria-describedby={errorId}+ aria-invalid={hasFieldError || undefined}+ value={+ value === true ? "true" : value === false ? "false" : "unset"+ }+ disabled={+ disabled || (readOnlySlug && field.key === config.slugField)+ }+ onValueChange={(value) =>+ value === "unset"+ ? onReset(field)+ : onChange(field, value === "true")+ }+ >+ {optionalBooleanOptions+ .filter(({ value }) => !field.required || value !== "unset")+ .map(({ value, label }) => (+ <ToggleGroupButton+ key={value}+ value={value}+ css={{+ width: "auto",+ paddingInline: theme.spacing[3],+ }}+ >+ {label}+ </ToggleGroupButton>+ ))}+ </ToggleGroup>+ ) : field.control === "textarea" ? (+ <TextArea+ id={id}+ required={field.required}+ aria-required={field.required}+ aria-describedby={errorId}+ aria-invalid={hasFieldError || undefined}+ value={typeof value === "string" ? value : ""}+ disabled={+ disabled || (readOnlySlug && field.key === config.slugField)+ }+ onChange={(value) => onChange(field, value)}+ />+ ) : (+ <InputField+ id={id}+ type={+ field.type === "number" || field.type === "integer"+ ? "number"+ : "text"+ }+ min={field.minimum}+ max={field.maximum}+ step={field.type === "integer" ? 1 : undefined}+ required={field.required}+ aria-required={field.required}+ aria-describedby={errorId}+ aria-invalid={hasFieldError || undefined}+ color={hasFieldError ? "error" : undefined}+ value={typeof value === "string" ? value : String(value ?? "")}+ disabled={+ disabled || (readOnlySlug && field.key === config.slugField)+ }+ onChange={(event) => {+ if (+ (field.type === "number" || field.type === "integer") &&+ event.target.value === ""+ ) {+ onReset(field);+ return;+ }+ onChange(field, event.target.value);+ }}+ />+ )}+ {hasFieldError && (+ <Text+ id={errorId}+ role="alert"+ color="destructive"+ css={{ gridColumn: "1 / -1" }}+ >+ {error.message}+ </Text>+ )}+ </Grid>+ );+ })}+ </>+);diff --git a/apps/builder/app/builder/shared/asset-manager/collection-entry-settings-dialog.test.tsx b/apps/builder/app/builder/shared/asset-manager/collection-entry-settings-dialog.test.tsxnew file mode 100644index 0000000000..44c80aa5c7--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/collection-entry-settings-dialog.test.tsx@@ -0,0 +1,228 @@+import { act } from "react-dom/test-utils";+import { TooltipProvider } from "@webstudio-is/design-system";+import { afterEach, expect, test, vi } from "vitest";+import {+ createDefaultCollectionConfig,+ extractMarkdownFrontmatter,+ parseCollectionConfig,+} from "@webstudio-is/content-engine";+import type { Asset } from "@webstudio-is/sdk";+import { $assets } from "~/shared/sync/data-stores";+import { $authPermit } from "~/shared/nano-states";+import { CollectionEntrySettingsDialog } from "./collection-entry-settings-dialog";+import { createAssetManagerTestRenderer } from "./test-utils";++const renderer = createAssetManagerTestRenderer();+const asset: Asset = {+ id: "post",+ projectId: "project",+ name: "post.mdx",+ filename: "post",+ folderId: "posts",+ type: "file",+ format: "mdx",+ size: 1,+ meta: {},+ createdAt: "2026-09-08T00:00:00Z",+};+afterEach(() => {+ renderer.cleanup();+ $assets.set(new Map());+ $authPermit.set("own");+});++test("edits existing fields without losing the body or unknown properties, keeps slug immutable, and saves invalid fields", async () => {+ $assets.set(new Map([[asset.id, asset]]));+ $authPermit.set("own");+ const source =+ "---\ntitle: Old\nslug: post\nlegacy: Keep me\n---\n\n# Exact body\n\n<Unknown />\n";+ const updateContent = vi.fn(async () => ({ ...asset, name: "next.mdx" }));+ const onClose = vi.fn();+ renderer.render(+ <TooltipProvider>+ <CollectionEntrySettingsDialog+ asset={asset}+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset: asset,+ templateAsset: asset,+ templateProperties: {},+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ }}+ readSource={async () => source}+ updateContent={updateContent}+ onClose={onClose}+ onOpenFile={vi.fn()}+ />+ </TooltipProvider>+ );+ await vi.waitFor(() =>+ expect(+ document.querySelector<HTMLInputElement>("#collection-entry-title")?.value+ ).toBe("Old")+ );+ expect(document.querySelector("#collection-entry-slug")).toBeDisabled();+ const input = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ )!;+ expect(document.activeElement).toBe(input);+ act(() => {+ Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )!.set!.call(input, "");+ input.dispatchEvent(new InputEvent("input", { bubbles: true }));+ });+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledOnce());+ const call = updateContent.mock.calls[0] as unknown as [+ { asset: Asset; content: string },+ ];+ expect(call[0].asset.name).toBe(asset.name);+ expect(+ (await extractMarkdownFrontmatter(call[0].content)).properties+ ).toEqual({ title: "", slug: "post", legacy: "Keep me" });+ expect(call[0].content.endsWith("# Exact body\n\n<Unknown />\n")).toBe(true);+ expect(input.getAttribute("aria-invalid")).toBe("true");+ expect(onClose).not.toHaveBeenCalled();+});++test("retains edits after a failed save and retries with the same expected revision", async () => {+ $assets.set(new Map([[asset.id, asset]]));+ $authPermit.set("own");+ const updateContent = vi.fn(+ async (_input: { asset: Asset; content: string }): Promise<Asset> => ({+ ...asset,+ name: "next.mdx",+ })+ );+ updateContent.mockRejectedValueOnce(+ new Error("The upload failed. Try again.")+ );+ renderer.render(+ <TooltipProvider>+ <CollectionEntrySettingsDialog+ asset={asset}+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset: asset,+ templateAsset: asset,+ templateProperties: {},+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ }}+ readSource={async () => "---\ntitle: Old\nslug: post\n---\nBody"}+ updateContent={updateContent}+ onClose={vi.fn()}+ onOpenFile={vi.fn()}+ />+ </TooltipProvider>+ );+ await vi.waitFor(() =>+ expect(+ document.querySelector<HTMLInputElement>("#collection-entry-title")?.value+ ).toBe("Old")+ );+ const input = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ )!;+ act(() => {+ Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )!.set!.call(input, "New");+ input.dispatchEvent(new InputEvent("input", { bubbles: true }));+ });+ await vi.waitFor(() =>+ expect(document.querySelector('[role="alert"]')).not.toBeNull()+ );+ expect(input.value).toBe("New");+ expect(updateContent).toHaveBeenCalledOnce();+ const retry = [...document.querySelectorAll("button")].find(+ (button) => button.textContent === "Retry save"+ )!;+ act(() => retry.click());+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledTimes(2));+ expect(updateContent.mock.calls.map(([input]) => input.asset.name)).toEqual([+ asset.name,+ asset.name,+ ]);+ expect(updateContent.mock.calls[0][0].content).toBe(+ updateContent.mock.calls[1][0].content+ );+});++test("keeps typing available during autosave and saves the newer draft against the returned revision", async () => {+ $assets.set(new Map([[asset.id, asset]]));+ $authPermit.set("own");+ const onClose = vi.fn();+ let finishFirstSave: (asset: Asset) => void = () => {};+ const firstSave = new Promise<Asset>((resolve) => {+ finishFirstSave = resolve;+ });+ const updateContent = vi.fn(+ async (_input: { asset: Asset; content: string }): Promise<Asset> => ({+ ...asset,+ name: "last.mdx",+ })+ );+ updateContent.mockReturnValueOnce(firstSave);+ renderer.render(+ <TooltipProvider>+ <CollectionEntrySettingsDialog+ asset={asset}+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset: asset,+ templateAsset: asset,+ templateProperties: {},+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ }}+ readSource={async () => "---\ntitle: Old\nslug: post\n---\nBody"}+ updateContent={updateContent}+ onClose={onClose}+ onOpenFile={vi.fn()}+ />+ </TooltipProvider>+ );+ await vi.waitFor(() =>+ expect(+ document.querySelector<HTMLInputElement>("#collection-entry-title")?.value+ ).toBe("Old")+ );+ const input = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ )!;+ const type = (value: string) =>+ act(() => {+ Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )!.set!.call(input, value);+ input.dispatchEvent(new InputEvent("input", { bubbles: true }));+ });+ type("First");+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledOnce());+ await vi.waitFor(() =>+ expect(document.querySelector('[role="status"]')).not.toBeNull()+ );+ expect(input).not.toBeDisabled();+ expect(document.activeElement).toBe(input);+ type("Old");+ await act(async () => {+ document.querySelector<HTMLButtonElement>('[aria-label="Close"]')!.click();+ await new Promise<void>((resolve) =>+ requestAnimationFrame(() => resolve())+ );+ });+ expect(onClose).not.toHaveBeenCalled();+ type("Second");+ await act(async () => finishFirstSave({ ...asset, name: "next.mdx" }));+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledTimes(2));+ expect(updateContent.mock.calls[1][0].asset.name).toBe("next.mdx");+ expect(+ (await extractMarkdownFrontmatter(updateContent.mock.calls[1][0].content))+ .properties.title+ ).toBe("Second");+});diff --git a/apps/builder/app/builder/shared/asset-manager/collection-entry-settings-dialog.tsx b/apps/builder/app/builder/shared/asset-manager/collection-entry-settings-dialog.tsxnew file mode 100644index 0000000000..951ca89b00--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/collection-entry-settings-dialog.tsx@@ -0,0 +1,311 @@+import { useEffect, useRef, useState } from "react";+import { useStore } from "@nanostores/react";+import {+ extractMarkdownFrontmatter,+ getCollectionEntryValidationIssues,+ type CollectionField,+} from "@webstudio-is/content-engine";+import {+ formatAssetName,+ getAssetDisplayNameParts,+ type Asset,+} from "@webstudio-is/sdk";+import {+ Button,+ Dialog,+ DialogContent,+ DialogTitle,+ Grid,+ PanelContent,+ Text,+} from "@webstudio-is/design-system";+import { $authPermit } from "~/shared/nano-states";+import { $assets } from "~/shared/sync/data-stores";+import {+ readBuilderAssetSource,+ type ContentCollection,+} from "../assets/content-collections";+import { updateAssetContent } from "../assets/update-asset-content";+import { CollectionEntryFields } from "./collection-entry-fields";+import { replaceMdxFrontmatter } from "@webstudio-is/content-engine/mdx";++export const CollectionEntrySettingsDialog = ({+ asset,+ collection,+ onClose,+ onOpenFile,+ readSource = readBuilderAssetSource,+ updateContent = updateAssetContent,+}: {+ asset: Asset;+ collection: Extract<ContentCollection, { status: "ready" }>;+ onClose: () => void;+ onOpenFile: () => void;+ readSource?: typeof readBuilderAssetSource;+ updateContent?: typeof updateAssetContent;+}) => {+ const permit = useStore($authPermit);+ const [loaded, setLoaded] = useState<{+ asset: Asset;+ source: string;+ properties: Readonly<Record<string, unknown>>;+ }>();+ const [values, setValues] = useState<Readonly<Record<string, unknown>>>({});+ const [error, setError] = useState<string>();+ const [saving, setSaving] = useState(false);+ const [closing, setClosing] = useState(false);+ const [attempt, setAttempt] = useState(0);+ const [discard, setDiscard] = useState(false);+ const formRef = useRef<HTMLDivElement>(null);+ const focused = useRef(false);+ const savingRef = useRef(false);+ const attemptedDraft = useRef<string>();+ const uncertain = useRef(false);++ useEffect(() => {+ let cancelled = false;+ void (async () => {+ try {+ const source = await readSource({+ projectId: asset.projectId,+ assetId: asset.id,+ });+ if ($assets.get().get(asset.id)?.name !== asset.name) {+ throw new Error(+ "This entry changed while opening. Close and reopen its settings."+ );+ }+ const { properties } = await extractMarkdownFrontmatter(source);+ if (!cancelled) {+ setLoaded({ asset, source, properties });+ setValues(properties);+ setError(undefined);+ }+ } catch (error) {+ if (!cancelled) {+ setError(+ error instanceof Error+ ? error.message+ : "The entry could not be loaded."+ );+ }+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [asset, readSource, attempt]);++ const draft = JSON.stringify(values);+ const dirty =+ loaded !== undefined && draft !== JSON.stringify(loaded.properties);+ useEffect(() => {+ if (loaded !== undefined && !focused.current) {+ formRef.current+ ?.querySelector<HTMLElement>(+ 'input:not(:disabled), textarea:not(:disabled), [role="group"] button:not(:disabled)'+ )+ ?.focus();+ focused.current = true;+ }+ }, [loaded]);+ const issues =+ loaded === undefined+ ? []+ : getCollectionEntryValidationIssues({+ config: collection.config,+ properties: values,+ basename: getAssetDisplayNameParts(asset).basename,+ });+ const unconfiguredIssues = issues.filter(+ (issue) =>+ !collection.config.fields.some((field) => field.key === issue.fieldKey)+ );+ const save = async () => {+ if (savingRef.current) {+ return false;+ }+ if (!dirty) {+ return true;+ }+ if (loaded === undefined || permit === "view" || uncertain.current) {+ return false;+ }+ savingRef.current = true;+ setSaving(true);+ attemptedDraft.current = draft;+ try {+ const source = await replaceMdxFrontmatter({+ source: loaded.source,+ properties: values,+ });+ const updatedAsset = await updateContent({+ asset: loaded.asset,+ content: source,+ });+ setLoaded({ asset: updatedAsset, source, properties: values });+ setError(undefined);+ return true;+ } catch (error) {+ if (+ error instanceof Error &&+ "code" in error &&+ error.code === "ASSET_UPDATE_COMMIT_UNCERTAIN"+ ) {+ uncertain.current = true;+ setError(+ "We couldn’t confirm whether your changes were saved. Keep a copy of your edits, then reload to check the saved version."+ );+ } else {+ setError(+ error instanceof Error+ ? error.message+ : "The entry could not be saved."+ );+ }+ return false;+ } finally {+ savingRef.current = false;+ setSaving(false);+ }+ };+ const saveRef = useRef(save);+ saveRef.current = save;+ useEffect(() => {+ if (!dirty || saving || attemptedDraft.current === draft) {+ return;+ }+ const timeout = setTimeout(() => void saveRef.current(), 600);+ return () => clearTimeout(timeout);+ }, [draft, dirty, saving]);+ const close = async (openFile = false) => {+ setClosing(true);+ if (await save()) {+ onClose();+ if (openFile) {+ onOpenFile();+ }+ } else if (!savingRef.current) {+ setDiscard(true);+ }+ setClosing(false);+ };+ const change = (field: CollectionField, value: unknown) => {+ setValues((current) => ({+ ...current,+ [field.key]:+ (field.type === "number" || field.type === "integer") && value !== ""+ ? Number(value)+ : value,+ }));+ };+ return (+ <>+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open) {+ void close();+ }+ }}+ >+ <DialogContent width={560} aria-describedby={undefined}>+ <DialogTitle>Entry settings</DialogTitle>+ <PanelContent+ as={Grid}+ ref={formRef}+ gap={3}+ css={{ maxHeight: "70vh", overflow: "auto" }}+ >+ <Text color="subtle">{formatAssetName(asset)}</Text>+ {error !== undefined && (+ <Text role="alert" color="destructive">+ {error}+ </Text>+ )}+ {loaded === undefined ? (+ error === undefined ? (+ <Text role="status">Loading entry…</Text>+ ) : (+ <Button onClick={() => setAttempt((value) => value + 1)}>+ Retry+ </Button>+ )+ ) : (+ <CollectionEntryFields+ config={collection.config}+ values={values}+ errors={issues}+ disabled={closing || permit === "view" || uncertain.current}+ readOnlySlug+ onChange={change}+ onReset={(field) =>+ setValues((current) => {+ const next = { ...current };+ delete next[field.key];+ return next;+ })+ }+ />+ )}+ {loaded !== undefined &&+ collection.config.slugField !== undefined &&+ values[collection.config.slugField] !==+ getAssetDisplayNameParts(asset).basename && (+ <Button+ disabled={saving || permit === "view" || uncertain.current}+ onClick={() =>+ setValues((current) => ({+ ...current,+ [collection.config.slugField!]:+ getAssetDisplayNameParts(asset).basename,+ }))+ }+ >+ Repair slug to match filename+ </Button>+ )}+ {saving && <Text role="status">Saving…</Text>}+ {unconfiguredIssues.length > 0 && (+ <Grid gap={2}>+ <Text>+ These fields need collection configuration or an MDX edit:+ </Text>+ {unconfiguredIssues.map((issue) => (+ <Text key={issue.fieldKey} role="alert" color="destructive">+ {issue.message}+ </Text>+ ))}+ </Grid>+ )}+ <Button disabled={saving} onClick={() => void close(true)}>+ Open MDX file+ </Button>+ {loaded !== undefined &&+ error !== undefined &&+ !uncertain.current && (+ <Button disabled={saving} onClick={() => void save()}>+ Retry save+ </Button>+ )}+ </PanelContent>+ </DialogContent>+ </Dialog>+ <Dialog open={discard} onOpenChange={setDiscard}>+ <DialogContent width={420} aria-describedby={undefined}>+ <DialogTitle>Close without saving?</DialogTitle>+ <PanelContent as={Grid} gap={3}>+ <Text>+ Your latest edits could not be saved. Keep editing to retry, or+ close and discard the local edits.+ </Text>+ <Button onClick={() => setDiscard(false)}>Keep editing</Button>+ <Button color="destructive" onClick={onClose}>+ Discard local edits+ </Button>+ </PanelContent>+ </DialogContent>+ </Dialog>+ </>+ );+};diff --git a/apps/builder/app/builder/shared/asset-manager/collection-settings-dialog.stories.tsx b/apps/builder/app/builder/shared/asset-manager/collection-settings-dialog.stories.tsxnew file mode 100644index 0000000000..b00d8dbaa6--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/collection-settings-dialog.stories.tsx@@ -0,0 +1,157 @@+import { useLayoutEffect, useState, type ComponentProps } from "react";+import type { Meta, StoryObj } from "@storybook/react";+import {+ createDefaultCollectionConfig,+ parseCollectionConfig,+} from "@webstudio-is/content-engine";+import type { Asset } from "@webstudio-is/sdk";+import { $assets, $project } from "~/shared/sync/data-stores";+import { CollectionSettingsDialog } from "./collection-settings-dialog";++const createAsset = ({+ id,+ filename,+ format,+}: {+ id: string;+ filename: string;+ format: string;+}): Asset => ({+ id,+ projectId: "storybook-project",+ name: `${filename}.${format}`,+ filename,+ folderId: "posts",+ type: "file",+ format,+ size: 1,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+});++const configAsset = createAsset({+ id: "collection-config",+ filename: "collection",+ format: "json",+});+const templateAsset = createAsset({+ id: "collection-template",+ filename: "template",+ format: "mdx",+});+const configValue = JSON.parse(createDefaultCollectionConfig());+configValue.properties.summary = {+ title: "Summary",+ type: "string",+ minLength: 20,+ maxLength: 240,+ "x-webstudio": { control: "textarea" },+};+configValue.properties.readingTime = {+ title: "Reading time",+ type: "integer",+ minimum: 1,+ maximum: 60,+};+const template = `---+title: Untitled post+slug: untitled-post+summary: A short description of this post.+draft: true+readingTime: 5+---++# Untitled post++Start writing here.+`;+configValue.properties = {+ title: configValue.properties.title,+ slug: configValue.properties.slug,+ summary: configValue.properties.summary,+ readingTime: configValue.properties.readingTime,+ draft: configValue.properties.draft,+};++const CollectionSettingsStory = (+ props: ComponentProps<typeof CollectionSettingsDialog>+) => {+ const [ready, setReady] = useState(false);+ useLayoutEffect(() => {+ const previousProject = $project.get();+ const previousAssets = $assets.get();+ $project.set({ id: "storybook-project" } as never);+ $assets.set(+ new Map([+ [configAsset.id, configAsset],+ [templateAsset.id, templateAsset],+ ])+ );+ setReady(true);+ return () => {+ $project.set(previousProject);+ $assets.set(previousAssets);+ };+ }, []);+ return ready && <CollectionSettingsDialog {...props} />;+};++const meta = {+ title: "Asset Manager/Collection settings",+ component: CollectionSettingsDialog,+ parameters: {+ layout: "fullscreen",+ },+} satisfies Meta<typeof CollectionSettingsDialog>;++export default meta;++type Story = StoryObj<typeof meta>;++export const Default: Story = {+ render: (args) => <CollectionSettingsStory {...args} />,+ args: {+ open: true,+ onOpenChange: () => undefined,+ readTemplateSource: async () => template,+ updateContent: async ({ asset }) => asset,+ convertCollection: async () => undefined,+ updateConfigAndTemplateName: async ({ collection, templateFilename }) => ({+ configAsset: collection.configAsset,+ templateAsset: {+ ...collection.templateAsset,+ filename: templateFilename,+ },+ }),+ collection: {+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: {+ title: "Untitled post",+ slug: "untitled-post",+ summary: "A short description of this post.",+ draft: true,+ readingTime: 5,+ },+ },+ },+};++export const UnconfirmedSave: Story = {+ ...Default,+ args: {+ ...Default.args,+ updateContent: async () => {+ throw Object.assign(+ new Error("Internal asset update recovery instructions"),+ {+ code: "ASSET_UPDATE_COMMIT_UNCERTAIN",+ }+ );+ },+ },+};diff --git a/apps/builder/app/builder/shared/asset-manager/collection-settings-dialog.test.tsx b/apps/builder/app/builder/shared/asset-manager/collection-settings-dialog.test.tsxnew file mode 100644index 0000000000..182177c0c4--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/collection-settings-dialog.test.tsx@@ -0,0 +1,1357 @@+import { act } from "react-dom/test-utils";+import { userEvent } from "@vitest/browser/context";+import { useState, type ReactNode } from "react";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import {+ createDefaultCollectionConfig,+ createDefaultCollectionTemplate,+ parseCollectionConfig,+} from "@webstudio-is/content-engine";+import {+ assetContentDescriptorHeader,+ serializeAssetContentDescriptor,+} from "@webstudio-is/protocol/asset-resource-api";+import type { Asset } from "@webstudio-is/sdk";+import {+ __testing__,+ createAssetContentBridge,+} from "~/shared/asset-content-bridge.client";+import { $assets, $project } from "~/shared/sync/data-stores";+import {+ CollectionSettingsDialog,+ updateCollectionConfigAndTemplateName,+} from "./collection-settings-dialog";+import { createAssetManagerTestRenderer } from "./test-utils";++const createAsset = ({+ id,+ filename,+ format,+}: {+ id: string;+ filename: string;+ format: string;+}): Asset => ({+ id,+ projectId: "project",+ name: `${filename}-storage.${format}`,+ filename,+ folderId: "posts",+ type: "file",+ format,+ size: 1,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+});++const renderer = createAssetManagerTestRenderer();+const { initBridge, clearBridge } = __testing__;+const render = (children: ReactNode) =>+ renderer.render(<TooltipProvider>{children}</TooltipProvider>);++test("marks the limit input rather than placing its error in the Fields heading", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ render(+ <CollectionSettingsDialog+ open+ onOpenChange={vi.fn()}+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ />+ );+ const maximum = document.querySelector<HTMLInputElement>(+ '[aria-label="Title maximum length"]'+ )!;+ await vi.waitFor(() => expect(maximum.disabled).toBe(false));+ input(maximum, "0");+ expect(maximum.getAttribute("aria-invalid")).toBe("true");+ expect(+ document+ .querySelector('[aria-label="Title minimum length"]')+ ?.getAttribute("aria-invalid")+ ).not.toBe("true");+ expect(document.querySelector('[role="alert"]')).toBeNull();+});++test("does not commit collection settings after the active project changes", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const collection = {+ status: "ready" as const,+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ };+ const request = vi.fn(async () => {+ $project.set({ id: "another-project" } as never);+ return Response.json({+ configAsset: { ...configAsset, name: "config-revision.json" },+ templateAsset: { ...templateAsset, filename: "post-template" },+ });+ });++ await expect(+ updateCollectionConfigAndTemplateName({+ projectId: "project",+ collection,+ templateFilename: "post-template",+ configSource: createDefaultCollectionConfig(),+ request,+ })+ ).rejects.toThrow("updated in the previous project");+});++const input = (element: HTMLInputElement, value: string) => {+ act(() => {+ const valueSetter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set;+ valueSetter?.call(element, value);+ element.dispatchEvent(new InputEvent("input", { bubbles: true }));+ });+};++beforeEach(() => {+ $project.set({ id: "project" } as never);+ initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ authorize: () => true,+ requireReload: () => undefined,+ request: async () => {+ const template = "---\ndraft: true\n---\n\nStart writing.\n";+ const asset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ asset.size = new TextEncoder().encode(template).length;+ return new Response(template, {+ headers: {+ "content-length": String(new TextEncoder().encode(template).length),+ [assetContentDescriptorHeader]:+ serializeAssetContentDescriptor(asset),+ },+ });+ },+ })+ );+});++test("asks before discarding invalid collection settings", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const onOpenChange = vi.fn();+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={onOpenChange}+ readTemplateSource={async () =>+ "---\ndraft: true\n---\n\nStart writing.\n"+ }+ />+ );+ await act(async () => undefined);+ const templateName = document.querySelector<HTMLInputElement>(+ '[aria-label="Entry template name"]'+ );+ if (templateName === null) {+ throw new Error("Expected template name control");+ }+ input(templateName, "");+ await act(async () => {+ document.querySelector<HTMLButtonElement>('[aria-label="Close"]')?.click();+ });++ await vi.waitFor(() =>+ expect(document.body.textContent).toContain("Discard changes?")+ );+ expect(onOpenChange).not.toHaveBeenCalled();+ act(() => {+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Discard changes")+ ?.click();+ });+ expect(onOpenChange).toHaveBeenCalledWith(false);+});++test("asks before discarding non-template edits after the template fails to load", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const onOpenChange = vi.fn();+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={onOpenChange}+ readTemplateSource={async () => {+ throw new Error("Template unavailable");+ }}+ />+ );+ await vi.waitFor(() =>+ expect(document.body.textContent).toContain("Template unavailable")+ );++ const templateName = document.querySelector<HTMLInputElement>(+ '[aria-label="Entry template name"]'+ );+ if (templateName === null) {+ throw new Error("Expected template name control");+ }+ input(templateName, "article-template");+ await act(async () => {+ document.querySelector<HTMLButtonElement>('[aria-label="Close"]')?.click();+ });++ await vi.waitFor(() =>+ expect(document.body.textContent).toContain("Discard changes?")+ );+ expect(onOpenChange).not.toHaveBeenCalled();+});++afterEach(() => {+ renderer.cleanup();+ clearBridge();+ $assets.set(new Map());+ $project.set(undefined);+});++test("allows text type edits for the slug source while protecting the slug", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={() => undefined}+ />+ );++ await act(async () => undefined);++ const typeControl = document.querySelector<HTMLButtonElement>(+ '[aria-label="Title type"]'+ );+ expect(typeControl).not.toBeNull();+ expect(typeControl?.disabled).toBe(false);+ const requiredControl = document.querySelector<HTMLButtonElement>(+ '[aria-label="Title required"]'+ );+ expect(requiredControl).not.toBeNull();+ expect(requiredControl?.disabled).toBe(false);+ const titleKey = document.querySelector<HTMLInputElement>(+ '[aria-label="Title key"]'+ );+ expect(titleKey?.disabled).toBe(false);+ if (titleKey === null) {+ throw new Error("Expected title key control");+ }+ input(titleKey, "headline");+ act(() => {+ document+ .querySelector<HTMLButtonElement>('[aria-label="Edit URL slug"]')+ ?.click();+ });+ expect(+ document.querySelector<HTMLButtonElement>(+ '[aria-label="Generate slug from"]'+ )?.textContent+ ).toContain("headline");+ const slugKey = document.querySelector<HTMLInputElement>(+ '[aria-label="URL slug key"]'+ );+ if (slugKey === null) {+ throw new Error("Expected slug key control");+ }+ input(slugKey, "permalink");+ expect(+ document.querySelector<HTMLButtonElement>('[aria-label="URL slug type"]')+ ?.textContent+ ).toContain("Slug");+});++test("saves a collection without a slug after changing the slug type", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const updateContent = vi.fn(+ async ({ asset }: { asset: Asset; content: string }) => asset+ );+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={() => undefined}+ readTemplateSource={async () => createDefaultCollectionTemplate()}+ updateContent={updateContent}+ />+ );+ await act(async () => undefined);+ act(() =>+ document+ .querySelector<HTMLButtonElement>('[aria-label="Edit URL slug"]')+ ?.click()+ );+ const chooseType = async (value: string) => {+ const control = document.querySelector<HTMLButtonElement>(+ '[aria-label="URL slug type"]'+ )!;+ expect(control.disabled).toBe(false);+ await act(async () => userEvent.click(control));+ const option = Array.from(+ document.querySelectorAll<HTMLElement>('[role="option"]')+ ).find((option) => option.textContent === value)!;+ expect(option).toBeDefined();+ await act(async () => userEvent.click(option));+ };+ await chooseType("Text");+ expect(+ document.querySelector('[aria-label="URL slug type"]')?.textContent+ ).toBe("Text");+ expect(+ document.querySelector('[aria-label="Generate slug from"]')+ ).toBeNull();+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledOnce());+ const withoutSlug = parseCollectionConfig(+ updateContent.mock.calls[0][0].content+ );+ expect(withoutSlug.slugField).toBeUndefined();+ expect(withoutSlug.generateSlugFrom).toBeUndefined();+ expect(+ withoutSlug.fields.find((field) => field.key === "slug")?.control+ ).toBe("text");+ expect(document.querySelector('[role="alert"]')).toBeNull();+ await chooseType("Slug");+ input(+ document.querySelector<HTMLInputElement>('[aria-label="URL slug label"]')!,+ "Permalink"+ );+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledTimes(2));+ await vi.waitFor(() =>+ expect(document.querySelector('[role="alert"]')).toBeNull()+ );+ const saved = parseCollectionConfig(updateContent.mock.calls[1][0].content);+ expect(+ saved.fields.find((field) => field.key === saved.slugField)+ ).toMatchObject({ control: "slug", label: "Permalink" });+});++test("shows template loading failures without save or cancel buttons", async () => {+ initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ authorize: () => true,+ requireReload: () => undefined,+ request: async () => {+ throw new Error("Template unavailable");+ },+ })+ );+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={() => undefined}+ />+ );++ await act(async () => undefined);++ const buttons = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).map((button) => button.textContent);+ expect(document.body.textContent).toContain("Template unavailable");+ expect(buttons).not.toContain("Save");+ expect(buttons).not.toContain("Cancel");+});++test("closes while the entry template is loading and ignores the late result", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const onOpenChange = vi.fn();+ let resolveTemplate: (source: string) => void = () => void 0;+ const readTemplateSource = vi.fn(+ () =>+ new Promise<string>((resolve) => {+ resolveTemplate = resolve;+ })+ );+ const Dialog = () => {+ const [open, setOpen] = useState(true);+ return (+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open={open}+ onOpenChange={(nextOpen) => {+ onOpenChange(nextOpen);+ setOpen(nextOpen);+ }}+ readTemplateSource={readTemplateSource}+ />+ );+ };+ render(<Dialog />);++ await act(async () => {+ document.querySelector<HTMLButtonElement>('[aria-label="Close"]')?.click();+ });++ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(document.querySelector('[role="dialog"]')).toBeNull();++ await act(async () => resolveTemplate(createDefaultCollectionTemplate()));++ expect(document.querySelector('[role="dialog"]')).toBeNull();+});++test("does not close while collection settings are saving", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const onOpenChange = vi.fn();+ const updateContent = vi.fn(() => new Promise<Asset>(() => undefined));+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={onOpenChange}+ readTemplateSource={async () => createDefaultCollectionTemplate()}+ updateContent={updateContent}+ />+ );+ await act(async () => undefined);+ act(() => {+ document.querySelector<HTMLButtonElement>('[aria-label="Bold"]')?.click();+ });++ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledOnce());+ await act(async () => {+ document.querySelector<HTMLButtonElement>('[aria-label="Close"]')?.click();+ });++ expect(onOpenChange).not.toHaveBeenCalled();+});++test("keeps focus while editing a field key", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const configValue = JSON.parse(createDefaultCollectionConfig());+ configValue.properties.summary = {+ title: "Summary",+ type: "string",+ };+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={() => undefined}+ />+ );++ await act(async () => undefined);++ act(() => {+ document+ .querySelector<HTMLButtonElement>('[aria-label="Edit Summary"]')+ ?.click();+ });++ const keyControl = document.querySelector<HTMLInputElement>(+ '[aria-label="Summary key"]'+ );+ if (keyControl === null) {+ throw new Error("Expected Summary key control");+ }+ keyControl.focus();+ input(keyControl, "summaryText");++ expect(document.activeElement).toBe(keyControl);+});++test("switches between field and template settings", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={() => undefined}+ />+ );++ await act(async () => undefined);++ const sections = Array.from(+ document.querySelectorAll<HTMLElement>(+ '[role="listbox"]:not([aria-label="Collection fields"]) [role="option"]'+ )+ );+ expect(sections).toHaveLength(2);+ expect(sections[0]?.getAttribute("aria-current")).toBe("true");+ act(() => sections[1]?.click());+ expect(sections[0]?.hasAttribute("aria-current")).toBe(false);+ expect(sections[1]?.getAttribute("aria-current")).toBe("true");+ expect(+ document.querySelector('[role="toolbar"][aria-label="Markdown formatting"]')+ ).toBeInstanceOf(HTMLElement);+ expect(document.querySelector('[aria-label="Show preview"]')).toBeInstanceOf(+ HTMLButtonElement+ );+ expect(+ document+ .querySelector('[aria-label="Entry template Markdown"]')+ ?.classList.contains("cm-content")+ ).toBe(true);+ const templateName = document.querySelector<HTMLInputElement>(+ '[aria-label="Entry template name"]'+ );+ expect(templateName?.value).toBe("template");+ if (templateName === null) {+ throw new Error("Expected template name control");+ }+ input(templateName, "post-template");+ expect(templateName.value).toBe("post-template");+ expect(document.querySelector("#collection-entry-template")).toBeNull();+});++test("persists a template rename without rewriting unchanged template content", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const order: string[] = [];+ const updateConfigAndTemplateName = vi.fn(async () => {+ order.push("config-and-name");+ return {+ configAsset: { ...configAsset, name: "config-revision.json" },+ templateAsset: { ...templateAsset, filename: "post-template" },+ };+ });+ const updateContent = vi.fn(async ({ asset }: { asset: Asset }) => {+ order.push("template-content");+ return { ...asset, name: "template-revision.mdx" };+ });+ const onOpenChange = vi.fn();+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={onOpenChange}+ readTemplateSource={async () =>+ "---\ndraft: true\n---\n\nStart writing.\n"+ }+ updateContent={updateContent}+ updateConfigAndTemplateName={updateConfigAndTemplateName}+ />+ );+ await act(async () => undefined);+ const templateName = document.querySelector<HTMLInputElement>(+ '[aria-label="Entry template name"]'+ );+ if (templateName === null) {+ throw new Error("Expected template name control");+ }+ input(templateName, "post-template");+ await vi.waitFor(() => expect(order).toHaveLength(1));++ expect(order).toEqual(["config-and-name"]);+ expect(updateContent).not.toHaveBeenCalled();+ expect(updateConfigAndTemplateName).toHaveBeenCalledWith(+ expect.objectContaining({+ templateFilename: "post-template",+ configSource: expect.stringContaining('"template": "post-template.mdx"'),+ })+ );+ expect(onOpenChange).not.toHaveBeenCalled();+});++test("retries settings after template content was already saved", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const updatedTemplateAsset = {+ ...templateAsset,+ name: "template-revision.mdx",+ };+ const updateContent = vi.fn(async ({ asset }: { asset: Asset }) => {+ expect(asset).toBe(templateAsset);+ return updatedTemplateAsset;+ });+ const updateConfigAndTemplateName = vi+ .fn()+ .mockRejectedValueOnce(new Error("Temporary failure"))+ .mockResolvedValueOnce({+ configAsset: { ...configAsset, name: "config-revision.json" },+ templateAsset: { ...updatedTemplateAsset, filename: "post-template" },+ });+ const onOpenChange = vi.fn();+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={onOpenChange}+ readTemplateSource={async () => createDefaultCollectionTemplate()}+ updateContent={updateContent}+ updateConfigAndTemplateName={updateConfigAndTemplateName}+ />+ );+ await act(async () => undefined);++ act(() => {+ document.querySelector<HTMLButtonElement>('[aria-label="Bold"]')?.click();+ });+ const templateName = document.querySelector<HTMLInputElement>(+ '[aria-label="Entry template name"]'+ );+ if (templateName === null) {+ throw new Error("Expected template name control");+ }+ input(templateName, "post-template");+ await vi.waitFor(() =>+ expect(document.body.textContent).toContain("Temporary failure")+ );+ await act(async () => {+ document.querySelector<HTMLButtonElement>('[aria-label="Close"]')?.click();+ });+ await vi.waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));++ expect(updateContent).toHaveBeenCalledOnce();+ expect(updateConfigAndTemplateName).toHaveBeenLastCalledWith(+ expect.objectContaining({+ collection: expect.objectContaining({+ templateAsset: updatedTemplateAsset,+ }),+ })+ );+});++test("preserves edits and stops writes after an unconfirmed save", async () => {+ const failure = Object.assign(new Error("Internal recovery instructions"), {+ code: "ASSET_UPDATE_COMMIT_UNCERTAIN",+ });+ const updateContent = vi.fn(async () => {+ throw failure;+ });+ const onOpenChange = vi.fn();+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset: createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ }),+ templateAsset: createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ }),+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={onOpenChange}+ updateContent={updateContent}+ readTemplateSource={async () => createDefaultCollectionTemplate()}+ />+ );+ await act(async () => undefined);+ const label = document.querySelector<HTMLInputElement>(+ '[aria-label="Title label"]'+ )!;+ input(label, "Headline");+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledOnce());+ await vi.waitFor(() =>+ expect(document.querySelector('[role="alert"]')).not.toBeNull()+ );+ // Developer recovery instructions must not leak into the editing UI.+ expect(document.querySelector('[role="alert"]')?.textContent).not.toContain(+ failure.message+ );+ input(label, "Post title");+ await act(async () => new Promise((resolve) => setTimeout(resolve, 750)));+ expect(updateContent).toHaveBeenCalledOnce();+ expect(label.value).toBe("Post title");+ await act(async () =>+ document.querySelector<HTMLButtonElement>('[aria-label="Close"]')?.click()+ );+ expect(updateContent).toHaveBeenCalledOnce();+ expect(onOpenChange).not.toHaveBeenCalled();+ await vi.waitFor(() =>+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(2)+ );+});++test("starts new fields with empty label and key inputs", async () => {+ const updateContent = vi.fn(+ async ({ asset }: { asset: Asset; content: string }) => asset+ );+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const configValue = JSON.parse(createDefaultCollectionConfig());+ configValue.properties.field1 = { title: "Field one", type: "string" };+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={() => undefined}+ updateContent={updateContent}+ />+ );++ await act(async () => undefined);+ act(() => {+ document+ .querySelector<HTMLButtonElement>('[aria-label="Edit Field one"]')+ ?.click();+ });+ const key = document.querySelector<HTMLInputElement>(+ '[aria-label="Field one key"]'+ );+ if (key === null) {+ throw new Error("Expected Field one key control");+ }+ input(key, "summary");+ act(() => {+ Array.from(document.querySelectorAll("button"))+ .find((button) => button.textContent === "Add field")+ ?.click();+ });++ expect(+ document.querySelector<HTMLInputElement>('[aria-label="New field key"]')+ ?.value+ ).toBe("");+ expect(+ document.querySelector<HTMLInputElement>('[aria-label="New field label"]')+ ?.value+ ).toBe("");+ const newKey = document.querySelector<HTMLInputElement>(+ '[aria-label="New field key"]'+ )!;+ const newLabel = document.querySelector<HTMLInputElement>(+ '[aria-label="New field label"]'+ )!;+ expect(document.activeElement).toBe(newLabel);+ // Wait past autosave: an untouched new field must remain free of errors.+ await act(async () => new Promise((resolve) => setTimeout(resolve, 700)));+ expect(document.querySelector('[aria-invalid="true"]')).toBeNull();+ expect(document.querySelector('[role="alert"]')).toBeNull();+ act(() => {+ newKey.focus();+ newLabel.focus();+ });+ await vi.waitFor(() =>+ expect(newKey.getAttribute("aria-invalid")).toBe("true")+ );+ const keyError = document.getElementById(+ newKey.getAttribute("aria-describedby")!+ );+ expect(keyError?.textContent).not.toBe("");+ expect(newKey.parentElement?.parentElement?.contains(keyError)).toBe(true);+ expect(updateContent).not.toHaveBeenCalled();+ input(+ document.querySelector<HTMLInputElement>('[aria-label="New field label"]')!,+ "Author"+ );+ input(+ document.querySelector<HTMLInputElement>('[aria-label="Author key"]')!,+ "author"+ );+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledOnce());+ expect(+ parseCollectionConfig(updateContent.mock.calls[0][0].content).fields.find(+ ({ key }) => key === "author"+ )+ ).toMatchObject({ label: "Author", type: "string" });+ const authorKey = document.querySelector<HTMLInputElement>(+ '[aria-label="Author key"]'+ )!;+ input(authorKey, " title ");+ await vi.waitFor(() =>+ expect(authorKey.getAttribute("aria-invalid")).toBe("true")+ );+ expect(+ document.getElementById(authorKey.getAttribute("aria-describedby")!)+ ?.textContent+ ).not.toBe("");+ act(() =>+ document+ .querySelector<HTMLButtonElement>('[aria-label="Edit Title"]')+ ?.click()+ );+ expect(+ document+ .querySelector('[aria-label="Title key"]')+ ?.getAttribute("aria-invalid")+ ).toBe("true");+ act(() =>+ document+ .querySelector<HTMLButtonElement>('[aria-label="Edit Author"]')+ ?.click()+ );+ const currentAuthorKey = document.querySelector<HTMLInputElement>(+ '[aria-label="Author key"]'+ )!;+ input(currentAuthorKey, "");+ await vi.waitFor(() =>+ expect(document.querySelector('[role="alert"]')).not.toBeNull()+ );+ input(currentAuthorKey, "author");+ await vi.waitFor(() =>+ expect(document.querySelector('[role="alert"]')).toBeNull()+ );+ expect(updateContent).toHaveBeenCalledOnce();+});++test("serializes automatic saves, preserves newer edits, and flushes on close", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const configValue = JSON.parse(createDefaultCollectionConfig());+ configValue.properties.summary = {+ title: "Summary",+ type: "string",+ description: "An entry summary",+ };+ let resolveFirstSave: (asset: Asset) => void = () => {};+ const updateContent = vi.fn(+ async ({ asset, content }: { asset: Asset; content: string }) => {+ expect(+ parseCollectionConfig(content).fields.some(+ ({ key }) => key === "summaryText"+ )+ ).toBe(true);+ if (updateContent.mock.calls.length === 1) {+ return new Promise<Asset>((resolve) => {+ resolveFirstSave = resolve;+ });+ }+ return { ...asset, name: "latest-config.json" };+ }+ );+ const onOpenChange = vi.fn();+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={onOpenChange}+ readTemplateSource={async () => createDefaultCollectionTemplate()}+ updateContent={updateContent}+ />+ );+ await act(async () => undefined);+ act(() =>+ document+ .querySelector<HTMLButtonElement>('[aria-label="Edit Summary"]')+ ?.click()+ );+ const key = document.querySelector<HTMLInputElement>(+ '[aria-label="Summary key"]'+ )!;+ input(key, "summaryText");+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledOnce());+ const label = document.querySelector<HTMLInputElement>(+ '[aria-label="Summary label"]'+ )!;+ expect(label.disabled).toBe(false);+ input(label, "Description");+ expect(updateContent).toHaveBeenCalledOnce();+ const updatedAsset = { ...configAsset, name: "first-config.json" };+ await act(async () => resolveFirstSave(updatedAsset));+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledTimes(2));+ const secondSave = updateContent.mock.calls[1][0];+ expect(secondSave.asset).toEqual(updatedAsset);+ const schema = JSON.parse(secondSave.content);+ expect(schema.properties.summary).toBeUndefined();+ expect(schema.properties.summaryText).toMatchObject({+ title: "Description",+ description: "An entry summary",+ });+ expect(label.value).toBe("Description");+ expect(onOpenChange).not.toHaveBeenCalled();+ input(label, "Excerpt");+ await act(async () =>+ document.querySelector<HTMLButtonElement>('[aria-label="Close"]')?.click()+ );+ await vi.waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));+ expect(updateContent).toHaveBeenCalledTimes(3);+ expect(+ JSON.parse(updateContent.mock.calls[2][0].content).properties.summaryText+ .title+ ).toBe("Excerpt");+});++test("associates a missing label error with its input and clears it when corrected", async () => {+ const updateContent = vi.fn(+ async ({ asset }: { asset: Asset; content: string }) => asset+ );+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset: createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ }),+ templateAsset: createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ }),+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: {},+ }}+ open+ onOpenChange={() => undefined}+ updateContent={updateContent}+ readTemplateSource={async () => createDefaultCollectionTemplate()}+ />+ );+ await act(async () => undefined);+ const label = document.querySelector<HTMLInputElement>(+ '[aria-label="Title label"]'+ )!;+ input(label, " ");+ await vi.waitFor(() =>+ expect(label.getAttribute("aria-invalid")).toBe("true")+ );+ const message = document.getElementById(+ label.getAttribute("aria-describedby")!+ );+ expect(message?.getAttribute("role")).toBe("alert");+ expect(document.querySelectorAll('[role="alert"]')).toHaveLength(1);+ expect(updateContent).not.toHaveBeenCalled();+ input(label, "Headline");+ await vi.waitFor(() => expect(updateContent).toHaveBeenCalledOnce());+ expect(label.hasAttribute("aria-invalid")).toBe(false);+ expect(document.querySelector('[role="alert"]')).toBeNull();+});++test("navigates fields with arrows and tabs out of the list", async () => {+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset: createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ }),+ templateAsset: createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ }),+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: {},+ }}+ open+ onOpenChange={() => undefined}+ readTemplateSource={async () => createDefaultCollectionTemplate()}+ />+ );+ await act(async () => undefined);+ const title = document.querySelector<HTMLElement>(+ '[aria-label="Edit Title"]'+ )!;+ const slug = document.querySelector<HTMLElement>(+ '[aria-label="Edit URL slug"]'+ )!;+ const draft = document.querySelector<HTMLElement>(+ '[aria-label="Edit Draft"]'+ )!;+ act(() => title.focus());+ await userEvent.keyboard("{ArrowDown}");+ expect(document.activeElement).toBe(slug);+ await userEvent.keyboard("{Enter}");+ expect(slug.getAttribute("aria-current")).toBe("true");+ expect(+ document.querySelector('[aria-label="URL slug label"]')+ ).not.toBeNull();+ await userEvent.keyboard("{ArrowDown}");+ expect(document.activeElement).toBe(draft);+ await userEvent.keyboard("{ArrowDown}");+ expect(document.activeElement).toBe(title);+ await userEvent.keyboard("{ArrowUp}");+ expect(document.activeElement).toBe(draft);+ await userEvent.tab();+ expect(document.activeElement).toBe(+ document.querySelector('[aria-label="URL slug label"]')+ );+ act(() => title.focus());+ await userEvent.tab();+ expect(document.activeElement).toBe(+ document.querySelector('[aria-label="URL slug label"]')+ );+});++test("confirms conversion, keeps focus on cancellation, and retries failures", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ let finish: () => void = () => undefined;+ const convertCollection = vi+ .fn<(asset: Asset) => Promise<void>>()+ .mockRejectedValueOnce(new Error("Conversion failed"))+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ })+ );+ const onOpenChange = vi.fn();+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={onOpenChange}+ convertCollection={convertCollection}+ readTemplateSource={async () => createDefaultCollectionTemplate()}+ />+ );+ await act(async () => undefined);+ const openConfirmation = async () => {+ const action = document.querySelector<HTMLButtonElement>(+ 'button[aria-label="Convert to regular folder"]'+ );+ expect(action).not.toBeNull();+ await act(async () => action?.click());+ };+ const button = (label: string) =>+ Array.from(document.querySelectorAll<HTMLButtonElement>("button"))+ .filter((button) => button.textContent === label)+ .at(-1)!;+ await openConfirmation();+ await vi.waitFor(() =>+ expect(document.activeElement).toBe(button("Convert to regular folder"))+ );+ expect(convertCollection).not.toHaveBeenCalled();+ await act(async () => button("Keep collection").click());+ expect(onOpenChange).not.toHaveBeenCalled();+ await openConfirmation();+ await act(async () => button("Convert to regular folder").click());+ await vi.waitFor(() =>+ expect(document.querySelector('[role="alert"]')?.textContent).toBe(+ "Conversion failed"+ )+ );+ expect(onOpenChange).not.toHaveBeenCalled();+ await act(async () => button("Convert to regular folder").click());+ expect(button("Converting…").disabled).toBe(true);+ expect(button("Keep collection").disabled).toBe(true);+ await act(async () =>+ document+ .querySelectorAll<HTMLButtonElement>('[aria-label="Close"]')+ .forEach((button) => button.click())+ );+ expect(onOpenChange).not.toHaveBeenCalled();+ await act(async () => finish());+ await vi.waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));+ expect(convertCollection).toHaveBeenCalledTimes(2);+ expect(convertCollection).toHaveBeenLastCalledWith(configAsset);+});++test("allows collection fields to change while existing entries are repaired", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const entryAsset = createAsset({+ id: "entry",+ filename: "first-post",+ format: "mdx",+ });+ const configValue = JSON.parse(createDefaultCollectionConfig());+ configValue.properties.summary = { title: "Summary", type: "string" };+ $assets.set(new Map([[entryAsset.id, entryAsset]]));+ render(+ <CollectionSettingsDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={() => undefined}+ />+ );++ await act(async () => undefined);++ act(() => {+ document+ .querySelector<HTMLButtonElement>('[aria-label="Edit URL slug"]')+ ?.click();+ });+ expect(+ document.querySelector<HTMLButtonElement>('[aria-label="URL slug type"]')+ ?.disabled+ ).toBe(false);+ act(() => {+ document+ .querySelector<HTMLButtonElement>('[aria-label="Edit Summary"]')+ ?.click();+ });+ expect(+ document.querySelector<HTMLInputElement>('[aria-label="Summary key"]')+ ?.disabled+ ).toBe(false);+ expect(+ document.querySelector<HTMLButtonElement>('[aria-label="Summary type"]')+ ?.disabled+ ).toBe(false);+ expect(+ document.querySelector<HTMLButtonElement>('[aria-label="Remove Summary"]')+ ?.disabled+ ).toBe(false);+});diff --git a/apps/builder/app/builder/shared/asset-manager/collection-settings-dialog.tsx b/apps/builder/app/builder/shared/asset-manager/collection-settings-dialog.tsxnew file mode 100644index 0000000000..366e8a7810--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/collection-settings-dialog.tsx@@ -0,0 +1,1567 @@+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import isValidFilename from "valid-filename";+import { useStore } from "@nanostores/react";+import {+ getCollectionTemplateValidationError,+ getCollectionFieldLimitsIssue,+ getCollectionEntryCreationError,+ parseCollectionConfig,+ serializeCollectionConfig,+ type CollectionField,+} from "@webstudio-is/content-engine";+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import {+ PanelContent,+ InsetList,+ InsetListItem,+ Button,+ Checkbox,+ CheckboxAndLabel,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogTitle,+ DialogTitleActions,+ DialogClose,+ Flex,+ Grid,+ InputField,+ Label,+ List,+ ListItem,+ PanelBanner,+ panelBannerIconColor,+ rawTheme,+ ScrollAreaNative,+ Select,+ Separator,+ Text,+ Tooltip,+ cssVar,+ theme,+} from "@webstudio-is/design-system";+import {+ AlertCircleIcon,+ InfoCircleIcon,+ PlusIcon,+ TrashIcon,+ ListViewIcon,+} from "@webstudio-is/icons";+import { formatAssetName, getAssetDisplayNameParts } from "@webstudio-is/sdk";+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";+import { $assets, $project } from "~/shared/sync/data-stores";+import {+ executeRuntimeMutationAsync,+ getWebstudioData,+} from "~/shared/instance-utils/data";+import { onNextTransactionComplete } from "~/shared/sync/project-queue";+import { createTransactionFromBuilderPatchPayload } from "~/shared/sync/builder-patch";+import { invalidateAssets } from "~/shared/resources";+import { fetch } from "~/shared/fetch.client";+import { updateAssetContent as updateBuilderAssetContent } from "../assets/update-asset-content";+import { isAssetFilenameUsed } from "../assets/asset-utils";+import {+ readBuilderAssetSource,+ type ContentCollection,+} from "../assets/content-collections";+import { MarkdownEditor } from "~/builder/features/text-file-editor/text-file-editor";+import { getTextFileEditorExtensions } from "~/builder/features/text-file-editor/text-file-utils";++type EditableType =+ | "Text"+ | "Long text"+ | "Slug"+ | "Number"+ | "Whole number"+ | "Boolean";+type EditableCollectionField = CollectionField & { rowId: string };+type SettingsSection = "fields" | "template";+const settingsSections: readonly {+ id: SettingsSection;+ label: string;+}[] = [+ { id: "fields", label: "Fields" },+ { id: "template", label: "Entry template" },+];+const fieldTypes: readonly EditableType[] = [+ "Text",+ "Long text",+ "Slug",+ "Number",+ "Whole number",+ "Boolean",+];+const createEditableFields = (+ collectionFields: readonly CollectionField[]+): EditableCollectionField[] =>+ collectionFields.map((field) => ({+ ...field,+ rowId: `original:${field.originalKey ?? field.key}`,+ }));++const getEditableType = (field: CollectionField): EditableType => {+ if (field.control === "slug") {+ return "Slug";+ }+ if (field.type === "boolean") {+ return "Boolean";+ }+ if (field.type === "integer") {+ return "Whole number";+ }+ if (field.type === "number") {+ return "Number";+ }+ return field.control === "textarea" ? "Long text" : "Text";+};++const setFieldType = (+ field: EditableCollectionField,+ type: EditableType+): EditableCollectionField => {+ const shared = {+ rowId: field.rowId,+ key: field.key,+ originalKey: field.originalKey,+ label: field.label,+ required: field.required,+ };+ if (type === "Boolean") {+ return { ...shared, type: "boolean", control: "checkbox" };+ }+ if (type === "Number" || type === "Whole number") {+ return {+ ...shared,+ type: type === "Number" ? "number" : "integer",+ control: "number",+ };+ }+ if (type === "Slug") {+ return {+ ...shared,+ ...(field.type === "string"+ ? {+ minLength: field.minLength,+ maxLength: field.maxLength,+ }+ : {}),+ type: "string",+ control: "slug",+ };+ }+ return {+ ...shared,+ ...(field.type === "string"+ ? {+ minLength: field.minLength,+ maxLength: field.maxLength,+ }+ : {}),+ type: "string",+ control: type === "Long text" ? "textarea" : "text",+ };+};++const optionalNumber = (value: string) =>+ value.trim() === "" || Number.isFinite(Number(value)) === false+ ? undefined+ : Number(value);++export const updateCollectionConfigAndTemplateName = async ({+ projectId,+ collection,+ templateFilename,+ configSource,+ request = fetch,+}: {+ projectId: string;+ collection: Extract<ContentCollection, { status: "ready" }>;+ templateFilename: string;+ configSource: string;+ request?: typeof fetch;+}) => {+ const response = await request(+ `/rest/assets/folders/${encodeURIComponent(+ collection.folderId+ )}/collection-settings?projectId=${encodeURIComponent(projectId)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ configAssetId: collection.configAsset.id,+ expectedConfigName: collection.configAsset.name,+ templateAssetId: collection.templateAsset.id,+ expectedTemplateFilename: collection.templateAsset.filename ?? null,+ templateFilename,+ configSource,+ }),+ }+ );+ const payload = (await response.json()) as+ | {+ configAsset: typeof collection.configAsset;+ templateAsset: typeof collection.templateAsset;+ }+ | { errors?: string };+ if (response.ok === false || "configAsset" in payload === false) {+ throw new Error(+ "errors" in payload && typeof payload.errors === "string"+ ? payload.errors+ : "Collection settings could not be saved"+ );+ }+ if ($project.get()?.id !== projectId) {+ throw new Error(+ "Collection settings were updated in the previous project. Return to that project to view them."+ );+ }+ createTransactionFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: [+ {+ namespace: "assets",+ patches: [+ {+ op: "replace",+ path: [payload.configAsset.id],+ value: payload.configAsset,+ },+ {+ op: "replace",+ path: [payload.templateAsset.id],+ value: payload.templateAsset,+ },+ ],+ },+ ],+ });+ onNextTransactionComplete(invalidateAssets);+ return payload;+};++const convertCollectionToFolder = async (+ configAsset: Extract<ContentCollection, { status: "ready" }>["configAsset"]+) => {+ if ($project.get()?.id !== configAsset.projectId) {+ throw new Error("The collection belongs to another project.");+ }+ const result = await executeRuntimeMutationAsync({+ id: "assets.delete",+ input: { assetIds: [configAsset.id], force: true },+ });+ if (result === undefined) {+ throw new Error("The collection could not be converted.");+ }+ onNextTransactionComplete(invalidateAssets);+};++export const ConvertCollectionDialog = ({+ configAsset,+ onClose,+ onConverted,+ onConvertingChange,+ hasUnsavedChanges = false,+ convertCollection = convertCollectionToFolder,+}: {+ configAsset: Extract<ContentCollection, { status: "ready" }>["configAsset"];+ onClose: () => void;+ onConverted?: () => void;+ onConvertingChange?: (converting: boolean) => void;+ hasUnsavedChanges?: boolean;+ convertCollection?: typeof convertCollectionToFolder;+}) => {+ const [converting, setConverting] = useState(false);+ const convertingRef = useRef(false);+ const [error, setError] = useState<string>();+ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !convertingRef.current) {+ onClose();+ }+ }}+ >+ <DialogContent width={420}>+ <DialogTitle>Convert to regular folder?</DialogTitle>+ <PanelContent as={Grid} gap={3}>+ <DialogDescription asChild>+ <Text>+ Your entries and template will stay. Collection rules and the New+ entry action will be removed.+ </Text>+ </DialogDescription>+ {hasUnsavedChanges && (+ <Text>Unsaved collection settings will not be applied.</Text>+ )}+ {error !== undefined && (+ <Text role="alert" color="destructive">+ {error}+ </Text>+ )}+ <Flex justify="end" gap={2}>+ <Button disabled={converting} onClick={onClose}>+ Keep collection+ </Button>+ <Button+ color="destructive"+ disabled={converting}+ onClick={async () => {+ if (convertingRef.current) {+ return;+ }+ convertingRef.current = true;+ setConverting(true);+ onConvertingChange?.(true);+ setError(undefined);+ try {+ await convertCollection(configAsset);+ onConverted?.();+ onClose();+ } catch (error) {+ setError(+ error instanceof Error+ ? error.message+ : "The collection could not be converted."+ );+ } finally {+ convertingRef.current = false;+ setConverting(false);+ onConvertingChange?.(false);+ }+ }}+ >+ {converting ? "Converting…" : "Convert to regular folder"}+ </Button>+ </Flex>+ </PanelContent>+ </DialogContent>+ </Dialog>+ );+};++export const CollectionSettingsDialog = ({+ collection: incomingCollection,+ open,+ onOpenChange,+ readTemplateSource = readBuilderAssetSource,+ updateContent = updateBuilderAssetContent,+ updateConfigAndTemplateName = updateCollectionConfigAndTemplateName,+ convertCollection = convertCollectionToFolder,+}: {+ collection: Extract<ContentCollection, { status: "ready" }>;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ readTemplateSource?: typeof readBuilderAssetSource;+ updateContent?: typeof updateBuilderAssetContent;+ updateConfigAndTemplateName?: typeof updateCollectionConfigAndTemplateName;+ convertCollection?: typeof convertCollectionToFolder;+}) => {+ // Keep the editing session stable when our own saves refresh asset metadata.+ const collectionRef = useRef(incomingCollection);+ const editingFolderRef = useRef<string>();+ const collection = collectionRef.current;+ const persistedFields = useRef(+ createEditableFields(collection.config.fields)+ );+ const savedDraft = useRef<string>();+ const attemptedDraft = useRef<string>();+ const savingRef = useRef(false);+ const nextRowId = useRef(0);+ const [fields, setFields] = useState<EditableCollectionField[]>(() =>+ createEditableFields(collection.config.fields)+ );+ const [selectedFieldRowId, setSelectedFieldRowId] = useState<+ string | undefined+ >(() => createEditableFields(collection.config.fields)[0]?.rowId);+ const [activeSection, setActiveSection] = useState<SettingsSection>("fields");+ const [template, setTemplate] = useState("");+ const loadedTemplateRef = useRef("");+ const currentTemplateAssetRef = useRef(collection.templateAsset);+ const [templateName, setTemplateName] = useState(+ () => getAssetDisplayNameParts(collection.templateAsset).basename+ );+ const [loadedTemplateKey, setLoadedTemplateKey] = useState<string>();+ const [slugField, setSlugField] = useState(collection.config.slugField);+ const [generateSlugFrom, setGenerateSlugFrom] = useState(+ collection.config.generateSlugFrom+ );+ const [loading, setLoading] = useState(false);+ const [saving, setSaving] = useState(false);+ const [closing, setClosing] = useState(false);+ const [error, setError] = useState<string>();+ const [fieldsError, setFieldsError] = useState<string>();+ const [templateError, setTemplateError] = useState<string>();+ const [saveUncertain, setSaveUncertain] = useState(false);+ const [showKeyErrors, setShowKeyErrors] = useState(false);+ const [pristineInputs, setPristineInputs] = useState(new Set<string>());+ const focusLabelRowId = useRef<string>();+ const [confirmRemove, setConfirmRemove] = useState(false);+ const [converting, setConverting] = useState(false);+ const [confirmDiscard, setConfirmDiscard] = useState(false);+ const assets = useStore($assets);+ const templateKey = collection.templateAsset.id;+ const templateReady = loadedTemplateKey === templateKey;+ const formDisabled = loading || closing || converting;+ const templateLanguageExtensions = useMemo(+ () => getTextFileEditorExtensions(collection.templateAsset),+ [collection.templateAsset]+ );++ useLayoutEffect(() => {+ if (open === false) {+ editingFolderRef.current = undefined;+ return;+ }+ if (editingFolderRef.current === incomingCollection.folderId) {+ return;+ }+ editingFolderRef.current = incomingCollection.folderId;+ collectionRef.current = incomingCollection;+ const collection = incomingCollection;+ const nextFields = createEditableFields(collection.config.fields);+ persistedFields.current = nextFields;+ savedDraft.current = undefined;+ attemptedDraft.current = undefined;+ setFields(nextFields);+ setSelectedFieldRowId(nextFields[0]?.rowId);+ setActiveSection("fields");+ setTemplateName(+ getAssetDisplayNameParts(collection.templateAsset).basename+ );+ currentTemplateAssetRef.current = collection.templateAsset;+ setSlugField(collection.config.slugField);+ setGenerateSlugFrom(collection.config.generateSlugFrom);+ setError(undefined);+ setSaveUncertain(false);+ setShowKeyErrors(false);+ setPristineInputs(new Set());+ focusLabelRowId.current = undefined;+ setFieldsError(undefined);+ setTemplateError(undefined);+ setConfirmRemove(false);+ setConfirmDiscard(false);+ }, [incomingCollection, open]);++ useLayoutEffect(() => {+ if (open === false) {+ return;+ }+ setTemplate("");+ setLoadedTemplateKey(undefined);+ const projectId = $project.get()?.id;+ if (projectId === undefined) {+ setLoading(false);+ setError("Project not found");+ return;+ }+ let cancelled = false;+ setLoading(true);+ void readTemplateSource({+ projectId,+ assetId: collection.templateAsset.id,+ })+ .then((source) => {+ if (cancelled === false) {+ setTemplate(source);+ loadedTemplateRef.current = source;+ setLoadedTemplateKey(templateKey);+ }+ })+ .catch((error) => {+ if (cancelled === false) {+ setError(+ error instanceof Error+ ? error.message+ : "Template could not be loaded"+ );+ }+ })+ .finally(() => {+ if (cancelled === false) {+ setLoading(false);+ }+ });+ return () => {+ cancelled = true;+ };+ }, [collection.templateAsset.id, open, readTemplateSource, templateKey]);++ const updateField = (index: number, field: EditableCollectionField) =>+ setFields((current) =>+ current.map((candidate, fieldIndex) =>+ fieldIndex === index ? field : candidate+ )+ );++ const keyErrors = new Map<string, string>();+ const labelErrors = new Map<string, string>();+ for (const field of fields) {+ if (field.label.trim() === "") {+ labelErrors.set(field.rowId, "Enter a field label.");+ }+ const key = field.key.trim();+ if (key === "") {+ keyErrors.set(field.rowId, "Enter a field key.");+ } else if (+ fields.some(+ (candidate) =>+ candidate.rowId !== field.rowId && candidate.key.trim() === key+ )+ ) {+ keyErrors.set(field.rowId, "This key is already used by another field.");+ }+ }++ const touchInput = (id: string) => {+ setPristineInputs((current) => {+ if (!current.has(id)) {+ return current;+ }+ const next = new Set(current);+ next.delete(id);+ return next;+ });+ };++ const draft = JSON.stringify({+ fields,+ template,+ templateName,+ slugField,+ generateSlugFrom,+ });+ const initialDraft = JSON.stringify({+ fields: persistedFields.current,+ template: loadedTemplateRef.current,+ templateName: getAssetDisplayNameParts(collection.templateAsset).basename,+ slugField: collection.config.slugField,+ generateSlugFrom: collection.config.generateSlugFrom,+ });+ const isDirty = draft !== (savedDraft.current ?? initialDraft);+ const requestClose = async () => {+ if (savingRef.current) {+ return;+ }+ setClosing(true);+ setPristineInputs(new Set());+ try {+ if (saveUncertain || (isDirty && (await save()) !== true)) {+ setConfirmDiscard(true);+ return;+ }+ onOpenChange(false);+ } finally {+ setClosing(false);+ }+ };++ const save = async () => {+ if (+ saveUncertain ||+ savingRef.current ||+ loading ||+ templateReady === false+ ) {+ return;+ }+ attemptedDraft.current = draft;+ const keys = fields.map(({ key }) => key.trim());+ setFieldsError(undefined);+ setTemplateError(undefined);+ if (keyErrors.size > 0 || labelErrors.size > 0) {+ setShowKeyErrors(true);+ setError(undefined);+ return;+ }+ if (+ fields.some((field) => getCollectionFieldLimitsIssue(field) !== undefined)+ ) {+ return;+ }+ savingRef.current = true;+ setSaving(true);+ setError(undefined);+ let errorTarget: "fields" | "template" | "dialog" = "template";+ try {+ const nextTemplateName = templateName.trim();+ const nextTemplateFilename = formatAssetName({+ ...collection.templateAsset,+ filename: nextTemplateName,+ });+ if (+ nextTemplateName === "" ||+ isValidFilename(nextTemplateFilename) === false+ ) {+ throw new Error("Enter a valid template name.");+ }+ if (+ isAssetFilenameUsed({+ assets: assets.values(),+ filename: nextTemplateFilename,+ folderId: collection.folderId,+ excludeAssetId: collection.templateAsset.id,+ })+ ) {+ throw new Error("That template name is already used in this folder.");+ }+ const nextFields = fields.map((field, index) => {+ const { rowId, ...collectionField } = field;+ return {+ ...collectionField,+ originalKey: persistedFields.current.find(+ (candidate) => candidate.rowId === rowId+ )?.key,+ key: keys[index],+ };+ });+ const normalizeLinkedFieldKey = (linkedKey: string | undefined) => {+ if (linkedKey === undefined) {+ return;+ }+ const fieldIndex = fields.findIndex(({ key }) => key === linkedKey);+ return fieldIndex === -1 ? linkedKey.trim() : keys[fieldIndex];+ };+ const nextSlugField = normalizeLinkedFieldKey(slugField);+ const nextGenerateSlugFrom = normalizeLinkedFieldKey(generateSlugFrom);+ errorTarget = "fields";+ const configSource = serializeCollectionConfig({+ config: collection.config,+ fields: nextFields,+ settings: {+ template: nextTemplateFilename,+ slugField: nextSlugField,+ generateSlugFrom: nextGenerateSlugFrom,+ },+ });+ const nextConfig = parseCollectionConfig(configSource);+ const creationError = getCollectionEntryCreationError(nextConfig);+ if (creationError !== undefined) {+ throw new Error(creationError);+ }+ errorTarget = "template";+ const templateDocument = await parseMdxDocument({ source: template });+ const templateValidationError = getCollectionTemplateValidationError(+ nextConfig,+ templateDocument.frontmatter.properties+ );+ if (templateValidationError !== undefined) {+ throw new Error(`Entry template: ${templateValidationError}`);+ }+ const currentTemplateName = getAssetDisplayNameParts(+ collection.templateAsset+ ).basename;+ const renamesTemplate = nextTemplateName !== currentTemplateName;+ const projectId = collection.configAsset.projectId;+ errorTarget = "dialog";+ if ($project.get()?.id !== projectId) {+ throw new Error("The collection belongs to another project.");+ }+ if (template !== loadedTemplateRef.current) {+ currentTemplateAssetRef.current = await updateContent({+ asset: currentTemplateAssetRef.current,+ content: template,+ });+ loadedTemplateRef.current = template;+ // A later config save can fail; track the template write separately.+ savedDraft.current = undefined;+ }+ const currentCollection = {+ ...collection,+ templateAsset: currentTemplateAssetRef.current,+ };+ if (renamesTemplate) {+ const updated = await updateConfigAndTemplateName({+ projectId,+ collection: currentCollection,+ templateFilename: nextTemplateName,+ configSource,+ });+ collectionRef.current = {+ ...currentCollection,+ ...updated,+ config: nextConfig,+ };+ currentTemplateAssetRef.current = updated.templateAsset;+ } else if (+ JSON.stringify(nextConfig.schema) !==+ JSON.stringify(collection.config.schema)+ ) {+ const configAsset = await updateContent({+ asset: collection.configAsset,+ content: configSource,+ });+ collectionRef.current = {+ ...currentCollection,+ configAsset,+ config: nextConfig,+ };+ } else {+ collectionRef.current = currentCollection;+ }+ persistedFields.current = fields.map((field, index) => ({+ ...field,+ key: keys[index],+ }));+ savedDraft.current = draft;+ return true;+ } catch (error) {+ if (errorTarget !== "dialog") {+ const message =+ error instanceof Error ? error.message : "Check these settings.";+ if (errorTarget === "fields") {+ setFieldsError(message);+ } else {+ setTemplateError(message);+ }+ return;+ }+ if (+ error instanceof Error &&+ "code" in error &&+ error.code === "ASSET_UPDATE_COMMIT_UNCERTAIN"+ ) {+ setSaveUncertain(true);+ setError(+ "We couldn’t confirm whether your changes were saved. Your edits are still here. Keep a copy of them, then reload the page to check the saved version before editing again."+ );+ return;+ }+ setError(+ error instanceof Error+ ? error.message+ : "Collection settings could not be saved"+ );+ } finally {+ savingRef.current = false;+ setSaving(false);+ }+ };++ const saveRef = useRef(save);+ saveRef.current = save;+ useEffect(() => {+ if (saveUncertain) {+ return;+ }+ if (templateReady && !isDirty) {+ attemptedDraft.current = undefined;+ setError(undefined);+ setFieldsError(undefined);+ setTemplateError(undefined);+ return;+ }+ if (+ !open ||+ !templateReady ||+ loading ||+ saving ||+ confirmRemove ||+ converting ||+ !isDirty ||+ attemptedDraft.current === draft+ ) {+ return;+ }+ const timeout = setTimeout(() => void saveRef.current(), 600);+ return () => clearTimeout(timeout);+ }, [+ draft,+ open,+ templateReady,+ loading,+ saving,+ isDirty,+ confirmRemove,+ converting,+ saveUncertain,+ ]);++ return (+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (saving === false && converting === false && nextOpen === false) {+ void requestClose();+ }+ }}+ >+ <DialogContent+ width={880}+ height={640}+ css={{ maxWidth: "calc(100vw - 32px)" }}+ aria-describedby={undefined}+ >+ <DialogTitle+ suffix={+ <DialogTitleActions>+ <Tooltip content="Convert to regular folder">+ <Button+ color="ghost-destructive"+ prefix={<ListViewIcon />}+ aria-label="Convert to regular folder"+ disabled={saving || converting || saveUncertain}+ onClick={() => setConfirmRemove(true)}+ />+ </Tooltip>+ <DialogClose />+ </DialogTitleActions>+ }+ >+ Collection settings+ </DialogTitle>+ {error !== undefined && (+ <PanelBanner variant="error" role="alert" css={{ flexShrink: 0 }}>+ <Flex align="center" gap={1}>+ <AlertCircleIcon+ color={panelBannerIconColor}+ fill="currentColor"+ />+ <Text variant="regularBold">+ {saveUncertain+ ? "Saving paused"+ : "Collection settings need attention"}+ </Text>+ </Flex>+ <Text>{error}</Text>+ </PanelBanner>+ )}+ <Flex grow>+ <List asChild>+ <InsetList+ css={{+ width: rawTheme.spacing[26],+ borderRight: `1px solid ${cssVar("--border-default")}`,+ }}+ >+ {settingsSections.map(({ id, label }, index) => (+ <ListItem+ current={activeSection === id}+ asChild+ index={index}+ key={id}+ onSelect={() => setActiveSection(id)}+ >+ <InsetListItem>+ <Text variant="labels">{label}</Text>+ </InsetListItem>+ </ListItem>+ ))}+ </InsetList>+ </List>+ <ScrollAreaNative css={{ width: "100%", minWidth: 0 }}>+ <Grid+ css={{+ minHeight: "100%",+ height: activeSection === "fields" ? "100%" : undefined,+ }}+ >+ <Grid+ css={{+ display: activeSection === "fields" ? "grid" : "none",+ gridTemplateRows: "auto minmax(0, 1fr)",+ }}+ >+ <PanelContent+ as={Flex}+ justify="between"+ align="center"+ gap={4}+ >+ <Flex gap={1} align="center">+ <Text variant="titles">Fields</Text>+ {fieldsError !== undefined && (+ <Text role="alert" color="destructive">+ {fieldsError}+ </Text>+ )}+ <Tooltip+ variant="wrapped"+ content="Define the information editors fill in for every entry."+ >+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ aria-label="About collection fields"+ />+ </Tooltip>+ </Flex>+ <Button+ css={{ flexShrink: 0 }}+ disabled={formDisabled}+ prefix={<PlusIcon />}+ onClick={() => {+ const rowId = `new:${nextRowId.current}`;+ nextRowId.current += 1;+ focusLabelRowId.current = rowId;+ setPristineInputs(+ (current) =>+ new Set([+ ...current,+ `${rowId}:label`,+ `${rowId}:key`,+ ])+ );+ setSelectedFieldRowId(rowId);+ setFields((current) => [+ ...current,+ {+ key: "",+ rowId,+ label: "",+ type: "string",+ control: "text",+ required: false,+ },+ ]);+ }}+ >+ Add field+ </Button>+ </PanelContent>+ <Grid+ css={{+ borderTop: `1px solid ${cssVar("--border-default")}`,+ gridTemplateColumns: "minmax(0, 1fr) minmax(0, 2fr)",+ }}+ >+ <List asChild aria-label="Collection fields">+ <InsetList css={{ overflow: "auto" }}>+ {fields.map((field, index) => (+ <ListItem+ key={field.rowId}+ asChild+ index={index}+ current={field.rowId === selectedFieldRowId}+ onSelect={() => setSelectedFieldRowId(field.rowId)}+ >+ <InsetListItem+ aria-label={`Edit ${field.label || "New field"}`}+ css={{+ minHeight: theme.spacing[15],+ }}+ >+ <Grid gap={1} css={{ minWidth: 0 }}>+ <Text+ variant="labels"+ truncate+ color={+ showKeyErrors &&+ ((keyErrors.has(field.rowId) &&+ !pristineInputs.has(+ `${field.rowId}:key`+ )) ||+ (labelErrors.has(field.rowId) &&+ !pristineInputs.has(+ `${field.rowId}:label`+ )))+ ? "destructive"+ : undefined+ }+ >+ {field.label || "New field"}+ </Text>+ <Text variant="tiny" color="subtle" truncate>+ {getEditableType(field)}+ {field.required ? " · Required" : ""}+ </Text>+ </Grid>+ </InsetListItem>+ </ListItem>+ ))}+ </InsetList>+ </List>+ <Grid+ css={{+ overflow: "auto",+ alignContent: "start",+ gridAutoRows: "max-content",+ borderLeft: `1px solid ${cssVar("--border-default")}`,+ }}+ >+ {fields.map((field, index) => {+ if (field.rowId !== selectedFieldRowId) {+ return;+ }+ const protectedField =+ field.key === slugField ||+ field.key === generateSlugFrom;+ const requiredField = field.key === slugField;+ const keyError =+ showKeyErrors &&+ !pristineInputs.has(`${field.rowId}:key`)+ ? keyErrors.get(field.rowId)+ : undefined;+ const keyErrorId =+ keyError === undefined+ ? undefined+ : `collection-field-key-error-${field.rowId}`;+ const stringField = field.type === "string";+ const labelError =+ showKeyErrors &&+ !pristineInputs.has(`${field.rowId}:label`)+ ? labelErrors.get(field.rowId)+ : undefined;+ const labelErrorId =+ labelError === undefined+ ? undefined+ : `collection-field-label-error-${field.rowId}`;+ const numberField =+ field.type === "number" || field.type === "integer";+ const limitsIssue = getCollectionFieldLimitsIssue(field);+ return (+ <Grid key={field.rowId} css={{ alignContent: "start" }}>+ <PanelContent as={Grid} gap={3}>+ <Grid+ gap={3}+ css={{+ gridTemplateColumns:+ "minmax(0, 1fr) minmax(0, 1fr)",+ alignItems: "start",+ }}+ >+ <Grid gap={1}>+ <Label+ htmlFor={`collection-field-label-${field.rowId}`}+ >+ Label+ </Label>+ <InputField+ id={`collection-field-label-${field.rowId}`}+ inputRef={(element) => {+ if (+ element &&+ focusLabelRowId.current === field.rowId+ ) {+ focusLabelRowId.current = undefined;+ element.focus();+ }+ }}+ aria-label={`${+ field.label || "New field"+ } label`}+ value={field.label}+ aria-invalid={+ labelError !== undefined || undefined+ }+ color={+ labelError === undefined+ ? undefined+ : "error"+ }+ aria-describedby={labelErrorId}+ disabled={formDisabled}+ onBlur={() =>+ touchInput(`${field.rowId}:label`)+ }+ onChange={(event) => {+ touchInput(`${field.rowId}:label`);+ updateField(index, {+ ...field,+ label: event.target.value,+ });+ }}+ />+ {labelError !== undefined && (+ <Text+ id={labelErrorId}+ role="alert"+ color="destructive"+ >+ {labelError}+ </Text>+ )}+ </Grid>+ <Grid gap={1}>+ <Flex gap={1} align="center">+ <Label+ htmlFor={`collection-field-key-${field.rowId}`}+ >+ Field key+ </Label>+ <Tooltip+ variant="wrapped"+ content="Stored in the entry’s frontmatter. Used to connect this field to your page."+ >+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ aria-label="About field key"+ />+ </Tooltip>+ </Flex>++ <InputField+ id={`collection-field-key-${field.rowId}`}+ aria-label={`${+ field.label || "New field"+ } key`}+ aria-invalid={+ keyError !== undefined || undefined+ }+ aria-describedby={keyErrorId}+ color={+ keyError === undefined ? undefined : "error"+ }+ value={field.key}+ disabled={formDisabled}+ onBlur={() =>+ touchInput(`${field.rowId}:key`)+ }+ onChange={(event) => {+ touchInput(`${field.rowId}:key`);+ const nextKey = event.target.value;+ if (field.control === "slug") {+ setSlugField(nextKey);+ }+ if (generateSlugFrom === field.key) {+ setGenerateSlugFrom(nextKey);+ }+ updateField(index, {+ ...field,+ key: nextKey,+ });+ }}+ />++ {keyError !== undefined && (+ <Text+ id={keyErrorId}+ role="alert"+ color="destructive"+ >+ {keyError}+ </Text>+ )}+ </Grid>+ </Grid>+ <Grid gap={1}>+ <Flex gap={1} align="center">+ <Label>Type</Label>+ {protectedField && (+ <Tooltip+ variant="wrapped"+ content={+ requiredField+ ? "The slug identifies each entry and is always required."+ : "This text field is used to generate the entry slug."+ }+ >+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ aria-label="About field type"+ />+ </Tooltip>+ )}+ </Flex>+ <Select+ aria-label={`${field.label} type`}+ options={+ field.key === generateSlugFrom+ ? ["Text", "Long text"]+ : fieldTypes+ }+ value={getEditableType(field)}+ disabled={formDisabled}+ onChange={(type) => {+ const editableType = type as EditableType;+ if (editableType === "Slug") {+ setSlugField(field.key);+ setFields((current) =>+ current.map((candidate, fieldIndex) => {+ if (fieldIndex === index) {+ return {+ ...setFieldType(candidate, "Slug"),+ required: true,+ };+ }+ if (candidate.control === "slug") {+ return setFieldType(+ candidate,+ "Text"+ );+ }+ return candidate;+ })+ );+ return;+ }+ if (field.control === "slug") {+ setSlugField(undefined);+ setGenerateSlugFrom(undefined);+ }+ updateField(+ index,+ setFieldType(field, editableType)+ );+ }}+ />+ </Grid>+ </PanelContent>+ {field.control === "slug" && (+ <PanelContent+ as={Grid}+ gap={2}+ css={{+ paddingTop: 0,+ }}+ >+ <Flex gap={1} align="center">+ <Label>Generate from</Label>+ <Tooltip+ variant="wrapped"+ content="The slug becomes the MDX filename. It is generated from this field when editors create an entry."+ >+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ aria-label="About slug generation"+ />+ </Tooltip>+ </Flex>+ <Select<{ key: string; label: string }>+ aria-label="Generate slug from"+ options={[+ { key: "", label: "None (manual entry)" },+ ...fields.filter(+ (candidate) =>+ candidate.type === "string" &&+ candidate.key.trim() !== "" &&+ candidate.key !== field.key+ ),+ ]}+ value={+ fields.find(+ ({ key }) => key === generateSlugFrom+ ) ?? { key: "", label: "None (manual entry)" }+ }+ getValue={({ key }) => JSON.stringify(key)}+ getLabel={({ label, key }) =>+ key === "" ? label : `${label} (${key})`+ }+ disabled={formDisabled}+ onChange={({ key }) =>+ setGenerateSlugFrom(key || undefined)+ }+ />+ </PanelContent>+ )}+ <Separator />+ <PanelContent as={Grid} gap={3}>+ <Text variant="labels">Validation</Text>+ <CheckboxAndLabel>+ <Checkbox+ id={`collection-field-required-${field.rowId}`}+ aria-label={`${field.label} required`}+ checked={field.required}+ disabled={formDisabled || requiredField}+ onCheckedChange={(checked) =>+ updateField(index, {+ ...field,+ required: checked === true,+ })+ }+ />+ <Label+ htmlFor={`collection-field-required-${field.rowId}`}+ >+ Required field+ </Label>+ </CheckboxAndLabel>+ <Grid+ gap={3}+ css={{+ gridTemplateColumns:+ "minmax(0, 1fr) minmax(0, 1fr)",+ }}+ >+ {(stringField || numberField) && (+ <>+ <Grid gap={1}>+ <Label>+ {stringField+ ? "Minimum length"+ : "Minimum"}+ </Label>+ <Tooltip+ open={+ limitsIssue?.input ===+ (stringField ? "minLength" : "minimum")+ ? undefined+ : false+ }+ content={+ limitsIssue?.input ===+ (stringField ? "minLength" : "minimum")+ ? limitsIssue.message+ : ""+ }+ >+ <InputField+ aria-label={`${field.label} ${+ stringField+ ? "minimum length"+ : "minimum"+ }`}+ type="number"+ placeholder="No minimum"+ min={stringField ? 0 : undefined}+ color={+ limitsIssue?.input ===+ (stringField+ ? "minLength"+ : "minimum")+ ? "error"+ : undefined+ }+ aria-invalid={+ limitsIssue?.input ===+ (stringField+ ? "minLength"+ : "minimum") || undefined+ }+ value={String(+ stringField+ ? (field.minLength ?? "")+ : (field.minimum ?? "")+ )}+ disabled={formDisabled}+ onChange={(event) =>+ updateField(index, {+ ...field,+ ...(stringField+ ? {+ minLength: optionalNumber(+ event.target.value+ ),+ }+ : {+ minimum: optionalNumber(+ event.target.value+ ),+ }),+ })+ }+ />+ </Tooltip>+ </Grid>+ <Grid gap={1}>+ <Label>+ {stringField+ ? "Maximum length"+ : "Maximum"}+ </Label>+ <Tooltip+ open={+ limitsIssue?.input ===+ (stringField ? "maxLength" : "maximum")+ ? undefined+ : false+ }+ content={+ limitsIssue?.input ===+ (stringField ? "maxLength" : "maximum")+ ? limitsIssue.message+ : ""+ }+ >+ <InputField+ aria-label={`${field.label} ${+ stringField+ ? "maximum length"+ : "maximum"+ }`}+ type="number"+ placeholder="No maximum"+ min={stringField ? 0 : undefined}+ color={+ limitsIssue?.input ===+ (stringField+ ? "maxLength"+ : "maximum")+ ? "error"+ : undefined+ }+ aria-invalid={+ limitsIssue?.input ===+ (stringField+ ? "maxLength"+ : "maximum") || undefined+ }+ value={String(+ stringField+ ? (field.maxLength ?? "")+ : (field.maximum ?? "")+ )}+ disabled={formDisabled}+ onChange={(event) =>+ updateField(index, {+ ...field,+ ...(stringField+ ? {+ maxLength: optionalNumber(+ event.target.value+ ),+ }+ : {+ maximum: optionalNumber(+ event.target.value+ ),+ }),+ })+ }+ />+ </Tooltip>+ </Grid>+ </>+ )}+ </Grid>+ </PanelContent>+ {protectedField === false && (+ <>+ <Separator />+ <PanelContent as={Flex}>+ <Button+ color="destructive"+ prefix={<TrashIcon />}+ aria-label={`Remove ${field.label}`}+ disabled={formDisabled}+ onClick={() => {+ setSelectedFieldRowId(+ fields[index + 1]?.rowId ??+ fields[index - 1]?.rowId+ );+ setFields((current) =>+ current.filter(+ (_, fieldIndex) => fieldIndex !== index+ )+ );+ }}+ >+ Remove field+ </Button>+ </PanelContent>+ </>+ )}+ </Grid>+ );+ })}+ </Grid>+ </Grid>+ </Grid>+ <PanelContent+ as={Grid}+ data-floating-panel-container+ css={{+ display: activeSection === "template" ? "grid" : "none",+ gridTemplateRows: "auto auto minmax(320px, 1fr)",+ gap: theme.spacing[3],+ minHeight: "100%",+ }}+ >+ <Flex gap={1} align="center">+ <Text variant="titles">Entry template</Text>+ <Tooltip+ variant="wrapped"+ content="Every new entry starts as a copy of this template. Add headings, placeholder text, and default field values so editors have a consistent starting point. Changes to the template only affect future entries."+ >+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ aria-label="About entry template"+ />+ </Tooltip>+ </Flex>+ <Grid gap={1} css={{ maxWidth: 320 }}>+ <Label htmlFor="collection-template-name">+ Template name+ </Label>+ <InputField+ id="collection-template-name"+ aria-label="Entry template name"+ value={templateName}+ maxLength={assetResourceLimits.assetFilenameCharacters}+ suffix={+ <Text as="span" color="subtle">+ .mdx+ </Text>+ }+ disabled={formDisabled}+ onChange={(event) => setTemplateName(event.target.value)}+ />+ </Grid>+ <Grid+ css={{+ gridTemplateRows: templateError ? "auto 1fr" : "1fr",+ }}+ >+ {templateError !== undefined && (+ <Text role="alert" color="destructive">+ {templateError}+ </Text>+ )}+ <MarkdownEditor+ asset={{+ ...collection.templateAsset,+ filename: templateName,+ }}+ ariaLabel="Entry template Markdown"+ defaultPreviewOpen={false}+ value={template}+ readOnly={formDisabled || templateReady === false}+ languageExtensions={templateLanguageExtensions}+ onChange={setTemplate}+ onChangeComplete={setTemplate}+ />+ </Grid>+ </PanelContent>+ </Grid>+ </ScrollAreaNative>+ </Flex>+ {saving && (+ <PanelContent as={Flex}>+ <Text role="status" color="subtle" variant="tiny">+ Saving…+ </Text>+ </PanelContent>+ )}+ </DialogContent>+ {confirmRemove && (+ <ConvertCollectionDialog+ configAsset={collectionRef.current.configAsset}+ hasUnsavedChanges={isDirty}+ convertCollection={convertCollection}+ onConvertingChange={setConverting}+ onClose={() => setConfirmRemove(false)}+ onConverted={() => onOpenChange(false)}+ />+ )}+ <Dialog open={confirmDiscard} onOpenChange={setConfirmDiscard}>+ <DialogContent aria-describedby={undefined} width={420}>+ <DialogTitle>Discard changes?</DialogTitle>+ <PanelContent as={Grid} gap={3}>+ <Text>+ Your unsaved collection settings and template changes will be+ lost.+ </Text>+ <Flex justify="end" gap={2}>+ <Button onClick={() => setConfirmDiscard(false)}>+ Keep editing+ </Button>+ <Button+ color="destructive"+ onClick={() => {+ setConfirmDiscard(false);+ onOpenChange(false);+ }}+ >+ Discard changes+ </Button>+ </Flex>+ </PanelContent>+ </DialogContent>+ </Dialog>+ </Dialog>+ );+};diff --git a/apps/builder/app/builder/shared/asset-manager/create-collection-entry-dialog.stories.tsx b/apps/builder/app/builder/shared/asset-manager/create-collection-entry-dialog.stories.tsxnew file mode 100644index 0000000000..2a73215409--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/create-collection-entry-dialog.stories.tsx@@ -0,0 +1,153 @@+import type { Meta, StoryObj } from "@storybook/react";+import { useLayoutEffect, useState, type ComponentProps } from "react";+import {+ createDefaultCollectionConfig,+ parseCollectionConfig,+} from "@webstudio-is/content-engine";+import type { Asset } from "@webstudio-is/sdk";+import { CreateCollectionEntryDialog } from "./create-collection-entry-dialog";+import { $assets, $project } from "~/shared/sync/data-stores";++const createAsset = ({+ id,+ filename,+ format,+}: {+ id: string;+ filename: string;+ format: string;+}): Asset => ({+ id,+ projectId: "storybook-project",+ name: `${filename}.${format}`,+ filename,+ folderId: "posts",+ type: "file",+ format,+ size: 1,+ description: null,+ createdAt: "2026-09-07T00:00:00.000Z",+ meta: {},+});++const configValue = JSON.parse(createDefaultCollectionConfig());+configValue.properties.summary = {+ title: "Summary",+ type: "string",+ maxLength: 240,+ "x-webstudio": { control: "textarea" },+};+configValue.properties.readingTime = {+ title: "Reading time",+ type: "integer",+ minimum: 1,+ maximum: 60,+};+configValue.properties = {+ title: configValue.properties.title,+ slug: configValue.properties.slug,+ summary: configValue.properties.summary,+ readingTime: configValue.properties.readingTime,+ draft: configValue.properties.draft,+};++const createdAsset = createAsset({+ id: "story-entry",+ filename: "entry",+ format: "mdx",+});+const EntryStory = (+ props: ComponentProps<typeof CreateCollectionEntryDialog>+) => {+ const [ready, setReady] = useState(false);+ const [open, setOpen] = useState(props.open);+ useLayoutEffect(() => {+ const project = $project.get();+ const assets = $assets.get();+ $project.set({ id: "storybook-project" } as never);+ $assets.set(new Map([[createdAsset.id, createdAsset]]));+ setReady(true);+ return () => {+ $project.set(project);+ $assets.set(assets);+ };+ }, []);+ return (+ ready && (+ <CreateCollectionEntryDialog+ {...props}+ open={open}+ onOpenChange={setOpen}+ />+ )+ );+};++const meta = {+ title: "Asset Manager/Create collection entry",+ component: CreateCollectionEntryDialog,+ parameters: { layout: "fullscreen" },+} satisfies Meta<typeof CreateCollectionEntryDialog>;++export default meta;++type Story = StoryObj<typeof meta>;++export const Default: Story = {+ render: (args) => <EntryStory {...args} />,+ args: {+ open: true,+ onOpenChange: () => undefined,+ createEntry: async () => createdAsset,+ collection: {+ status: "ready",+ folderId: "posts",+ configAsset: createAsset({+ id: "collection-config",+ filename: "collection",+ format: "json",+ }),+ templateAsset: createAsset({+ id: "collection-template",+ filename: "template",+ format: "mdx",+ }),+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: {+ title: "Untitled post",+ slug: "untitled-post",+ summary: "A short description of this post.",+ draft: true,+ readingTime: 5,+ },+ },+ },+};++export const LongForm: Story = {+ ...Default,+ args: {+ ...Default.args,+ collection: {+ ...Default.args.collection,+ config: parseCollectionConfig(+ JSON.stringify({+ ...configValue,+ properties: {+ ...configValue.properties,+ author: { title: "Author", type: "string" },+ category: { title: "Category", type: "string" },+ image: { title: "Image URL", type: "string" },+ imageDescription: { title: "Image description", type: "string" },+ seoTitle: { title: "SEO title", type: "string" },+ seoDescription: {+ title: "SEO description",+ type: "string",+ "x-webstudio": { control: "textarea" },+ },+ },+ })+ ),+ },+ },+};diff --git a/apps/builder/app/builder/shared/asset-manager/create-collection-entry-dialog.test.tsx b/apps/builder/app/builder/shared/asset-manager/create-collection-entry-dialog.test.tsxnew file mode 100644index 0000000000..9d38609b32--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/create-collection-entry-dialog.test.tsx@@ -0,0 +1,1005 @@+import { act } from "react-dom/test-utils";+import type { ReactNode } from "react";+import { TooltipProvider } from "@webstudio-is/design-system";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import {+ parseCollectionConfig,+ createDefaultCollectionConfig,+} from "@webstudio-is/content-engine";+import { createDefaultPages } from "@webstudio-is/project-build";+import type { Asset } from "@webstudio-is/sdk";+import { $assets, $pages, $project } from "~/shared/sync/data-stores";+import { $selectedPageId } from "~/shared/nano-states";+import {+ CreateCollectionEntryDialog,+ type createCollectionEntryRequest,+} from "./create-collection-entry-dialog";+import { createAssetManagerTestRenderer } from "./test-utils";++const createAsset = ({+ id,+ filename,+ format,+}: {+ id: string;+ filename: string;+ format: string;+}): Asset => ({+ id,+ projectId: "project",+ name: `${filename}.${format}`,+ filename,+ folderId: "posts",+ type: "file",+ format,+ size: 1,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+});++const renderer = createAssetManagerTestRenderer();+const render = (children: ReactNode) =>+ renderer.render(<TooltipProvider>{children}</TooltipProvider>);++const input = (element: HTMLInputElement, value: string) => {+ act(() => {+ const valueSetter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set;+ valueSetter?.call(element, value);+ element.dispatchEvent(new InputEvent("input", { bubbles: true }));+ });+};++beforeEach(() => {+ $project.set({ id: "project" } as never);+ $assets.set(new Map());+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+});++afterEach(() => {+ renderer.cleanup();+ $assets.set(new Map());+ $pages.set(undefined);+ $project.set(undefined);+ $selectedPageId.set(undefined);+ vi.unstubAllGlobals();+});++test("colors only populated entry fields, including zero and false", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.count = { type: "number", title: "Count" };+ render(+ <CreateCollectionEntryDialog+ open+ onOpenChange={vi.fn()}+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset: createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ }),+ templateAsset: createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ }),+ config: parseCollectionConfig(JSON.stringify(schema)),+ templateProperties: { draft: false, count: 0 },+ }}+ />+ );+ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ )!;+ const getLabel = () =>+ document.querySelector<HTMLLabelElement>(+ 'label[for="collection-entry-title"]'+ )!;+ const emptyClass = getLabel().className;+ for (const key of ["draft", "count"]) {+ expect(+ document.querySelector(`label[for="collection-entry-${key}"]`)!.className+ ).not.toBe(emptyClass);+ }+ input(title, "A title");+ expect(getLabel().className).not.toBe(emptyClass);+ input(title, "");+ expect(getLabel().className).toBe(emptyClass);+});++test.each(["tooltip", "alt-click"])(+ "clears a populated required field via %s and still validates it",+ async (method) => {+ const createEntry = vi.fn();+ render(+ <CreateCollectionEntryDialog+ open+ onOpenChange={vi.fn()}+ createEntry={createEntry}+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset: createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ }),+ templateAsset: createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ }),+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { title: "Template title" },+ }}+ />+ );+ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ )!;+ input(title, "New title");+ const label = document.querySelector<HTMLLabelElement>(+ 'label[for="collection-entry-title"]'+ )!;+ if (method === "alt-click") {+ await act(async () =>+ label.dispatchEvent(+ new MouseEvent("click", {+ bubbles: true,+ cancelable: true,+ altKey: true,+ })+ )+ );+ } else {+ await act(async () => label.click());+ const reset = document.querySelector<HTMLButtonElement>(+ '[data-radix-popper-content-wrapper] button[type="button"]'+ );+ expect(reset).not.toBeNull();+ await act(async () => reset?.click());+ }+ expect(title.value).toBe("");+ expect(+ document.querySelector<HTMLInputElement>("#collection-entry-slug")!.value+ ).toBe("");+ expect(createEntry).not.toHaveBeenCalled();+ await act(async () =>+ document.querySelector<HTMLFormElement>("form")!.requestSubmit()+ );+ expect(title).toHaveAttribute("aria-invalid", "true");+ expect(createEntry).not.toHaveBeenCalled();+ }+);++test.each(["text", "textarea", "boolean"])(+ "focuses the first entry control: %s",+ (control) => {+ const config = {+ ...parseCollectionConfig(createDefaultCollectionConfig()),+ fields: [+ {+ key: "first",+ label: "First",+ type:+ control === "boolean" ? ("boolean" as const) : ("string" as const),+ control:+ control === "textarea"+ ? ("textarea" as const)+ : control === "boolean"+ ? ("checkbox" as const)+ : ("text" as const),+ required: false,+ },+ ],+ };+ render(+ <CreateCollectionEntryDialog+ open+ onOpenChange={vi.fn()}+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset: createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ }),+ templateAsset: createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ }),+ config,+ templateProperties: {},+ }}+ />+ );+ const field = document.getElementById("collection-entry-first")!;+ expect(field).not.toBeNull();+ expect(+ control === "boolean"+ ? field.contains(document.activeElement)+ : document.activeElement === field+ ).toBe(true);+ }+);++test("keeps the request ID when retrying a slugless entry", async () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ delete schema.properties.slug;+ schema.required = ["title"];+ delete schema["x-webstudio"].slugField;+ delete schema["x-webstudio"].generateSlugFrom;+ const createEntry = vi.fn<typeof createCollectionEntryRequest>(async () => {+ throw new Error("Response lost");+ });+ render(+ <CreateCollectionEntryDialog+ open+ onOpenChange={vi.fn()}+ createEntry={createEntry}+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset: createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ }),+ templateAsset: createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ }),+ config: parseCollectionConfig(JSON.stringify(schema)),+ templateProperties: {},+ }}+ />+ );+ input(+ document.querySelector<HTMLInputElement>("#collection-entry-title")!,+ "Entry"+ );+ for (let attempt = 0; attempt < 2; attempt += 1) {+ await act(async () =>+ document.querySelector<HTMLFormElement>("form")!.requestSubmit()+ );+ }+ expect(createEntry).toHaveBeenCalledTimes(2);+ const requests = createEntry.mock.calls;+ expect(requests[0][0].requestId).toEqual(expect.any(String));+ expect(requests[1][0].requestId).toBe(requests[0][0].requestId);+});++test.each([true, false])(+ "creates an entry without navigating (slug: %s)",+ async (withSlug) => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const createdAsset = createAsset({+ id: "created",+ filename: "hello-world",+ format: "mdx",+ });+ const configValue = JSON.parse(createDefaultCollectionConfig());+ if (!withSlug) {+ delete configValue["x-webstudio"].slugField;+ delete configValue["x-webstudio"].generateSlugFrom;+ delete configValue.properties.slug;+ configValue.required = configValue.required.filter(+ (key: string) => key !== "slug"+ );+ }+ const createEntry = vi.fn().mockResolvedValue(createdAsset);+ configValue["x-webstudio"].previewPage = "/blog/:slug";+ const pages = createDefaultPages({ rootInstanceId: "home-root" });+ pages.pages.set("blog", {+ id: "blog",+ name: "Blog post",+ title: "Blog post",+ path: "/blog/:slug",+ rootInstanceId: "blog-root",+ meta: {},+ });+ pages.folders.get(pages.rootFolderId)?.children.push("blog");+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: {},+ }}+ open+ onOpenChange={vi.fn()}+ createEntry={createEntry}+ />+ );++ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ );+ if (title === null) {+ throw new Error("Expected collection entry title field");+ }+ input(title, "Hello world");+ const create = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Create entry");+ await act(async () => create?.click());++ expect($selectedPageId.get()).toBe(pages.homePageId);+ expect(createEntry).toHaveBeenCalledOnce();+ const values = createEntry.mock.calls[0][0].values;+ expect(values.title).toBe("Hello world");+ expect(Object.hasOwn(values, "slug")).toBe(withSlug);+ expect(Object.hasOwn(values, "undefined")).toBe(false);+ }+);++test("asks before closing a new entry with unsaved values", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const onOpenChange = vi.fn();+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: {},+ }}+ open+ onOpenChange={onOpenChange}+ />+ );+ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ );+ if (title === null) {+ throw new Error("Expected title input");+ }+ input(title, "Unsaved title");++ await act(async () => {+ document.querySelector<HTMLButtonElement>('[aria-label="Close"]')?.click();+ // Dialog defers onOpenChange until the next frame so pending edits render.+ await new Promise(requestAnimationFrame);+ });++ expect(document.body.textContent).toContain("Discard entry?");+ expect(onOpenChange).not.toHaveBeenCalled();+ expect(title.value).toBe("Unsaved title");+ const discard = Array.from(+ document.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Discard entry");+ if (discard === undefined) {+ throw new Error("Expected discard entry button");+ }+ await act(async () => {+ discard.click();+ });++ expect(onOpenChange).toHaveBeenCalledWith(false);+});++test("validates entry fields before sending a create request", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const onOpenChange = vi.fn();+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: {},+ }}+ open+ onOpenChange={onOpenChange}+ />+ );++ const create = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Create entry");+ await act(async () => {+ create?.click();+ });++ expect(document.body.textContent).toContain(+ "Title must contain at least 1 character"+ );+ expect(document.querySelector("[role=alert]")?.textContent).toContain(+ "Title must contain at least 1 character"+ );+ expect(+ document.querySelector<HTMLInputElement>("#collection-entry-title")+ ).toHaveAttribute("aria-invalid", "true");+ const titleInput = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ )!;+ const fieldError = document.getElementById(+ titleInput.getAttribute("aria-describedby")!+ );+ expect(titleInput.parentElement?.parentElement?.contains(fieldError)).toBe(+ true+ );+ expect(+ document.querySelector<HTMLInputElement>("#collection-entry-slug")+ ).not.toHaveAttribute("aria-invalid");+ expect(document.activeElement).toBe(+ document.querySelector<HTMLInputElement>("#collection-entry-title")+ );+ expect(+ document.querySelector<HTMLInputElement>("#collection-entry-title")+ ?.required+ ).toBe(true);+ expect(onOpenChange).not.toHaveBeenCalled();+});++test("submits an entry through the native form path used by Enter", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const createEntry = vi.fn(async () => {+ throw new Error("Stop after capturing the request");+ });+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: false },+ }}+ open+ onOpenChange={vi.fn()}+ createEntry={createEntry}+ />+ );++ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ );+ const form = document.querySelector<HTMLFormElement>("form");+ if (title === null || form === null) {+ throw new Error("Expected collection entry form");+ }+ input(title, "Keyboard entry");++ await act(async () => {+ form.requestSubmit();+ });++ await vi.waitFor(() =>+ expect(createEntry).toHaveBeenCalledWith({+ folderId: "posts",+ projectId: "project",+ values: {+ draft: false,+ slug: "keyboard-entry",+ title: "Keyboard entry",+ },+ })+ );+});++test("regenerates a cleared slug before validating the entry", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const createEntry = vi.fn(async () => {+ throw new Error("Stop after capturing the request");+ });+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: false },+ }}+ open+ onOpenChange={vi.fn()}+ createEntry={createEntry}+ />+ );++ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ );+ const slug = document.querySelector<HTMLInputElement>(+ "#collection-entry-slug"+ );+ if (title === null || slug === null) {+ throw new Error("Expected collection entry fields");+ }+ input(title, "Hello world");+ input(slug, "");+ const create = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Create entry");+ await act(async () => {+ create?.click();+ });++ expect(createEntry).toHaveBeenCalledWith({+ folderId: "posts",+ projectId: "project",+ values: { draft: false, slug: "hello-world", title: "Hello world" },+ });+});++test("uses only the entry template for optional field defaults", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const createEntry = vi.fn(async () => {+ throw new Error("Stop after capturing the request");+ });+ const configValue = JSON.parse(createDefaultCollectionConfig());+ configValue.properties.draft.default = true;+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: {},+ }}+ open+ onOpenChange={vi.fn()}+ createEntry={createEntry}+ />+ );++ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ );+ if (title === null) {+ throw new Error("Expected collection entry title field");+ }+ input(title, "Hello world");+ const create = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Create entry");+ await act(async () => {+ create?.click();+ });++ expect(createEntry).toHaveBeenCalledWith({+ folderId: "posts",+ projectId: "project",+ values: { slug: "hello-world", title: "Hello world" },+ });+});++test("explicitly clears a template-backed optional value", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const configValue = JSON.parse(createDefaultCollectionConfig());+ configValue.properties.summary = {+ title: "Summary",+ type: "string",+ "x-webstudio": { control: "textarea" },+ };+ const createEntry = vi.fn(async () => {+ throw new Error("Stop after capturing the request");+ });+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: { summary: "Template summary" },+ }}+ open+ onOpenChange={vi.fn()}+ createEntry={createEntry}+ />+ );++ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ );+ const summary = document.querySelector<HTMLTextAreaElement>(+ "#collection-entry-summary"+ );+ if (title === null || summary === null) {+ throw new Error("Expected collection entry fields");+ }+ input(title, "Hello world");+ const summaryLabel = document.querySelector<HTMLLabelElement>(+ 'label[for="collection-entry-summary"]'+ );+ if (summaryLabel === null) {+ throw new Error("Expected summary label");+ }+ await act(async () => summaryLabel.click());+ const reset = document.querySelector<HTMLButtonElement>(+ '[data-radix-popper-content-wrapper] button[type="button"]'+ );+ expect(reset).not.toBeNull();+ await act(async () => reset?.click());+ expect(createEntry).not.toHaveBeenCalled();+ const create = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Create entry");+ await act(async () => {+ create?.click();+ });++ expect(createEntry).toHaveBeenCalledWith({+ folderId: "posts",+ projectId: "project",+ values: {+ slug: "hello-world",+ summary: null,+ title: "Hello world",+ },+ });+ expect(createEntry).toHaveBeenCalledOnce();+});++test("preserves an explicit blank optional string", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const configValue = JSON.parse(createDefaultCollectionConfig());+ configValue.properties.summary = {+ title: "Summary",+ type: "string",+ maxLength: 1,+ };+ const createEntry = vi.fn(async () => {+ throw new Error("Stop after capturing the request");+ });+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: { summary: "Template summary" },+ }}+ open+ onOpenChange={vi.fn()}+ createEntry={createEntry}+ />+ );++ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ );+ const summary = document.querySelector<HTMLInputElement>(+ "#collection-entry-summary"+ );+ if (title === null || summary === null) {+ throw new Error("Expected collection entry fields");+ }+ expect(summary.maxLength).toBe(-1);+ input(title, "Hello world");+ input(summary, "");+ const create = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Create entry");+ await act(async () => {+ create?.click();+ });++ expect(createEntry).toHaveBeenCalledWith({+ folderId: "posts",+ projectId: "project",+ values: {+ slug: "hello-world",+ summary: "",+ title: "Hello world",+ },+ });+});++test("preserves all three optional boolean states in compact controls", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const createEntry = vi.fn(async () => {+ throw new Error("Request captured");+ });+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: { draft: true },+ }}+ open+ onOpenChange={() => undefined}+ createEntry={createEntry}+ />+ );+ input(+ document.querySelector<HTMLInputElement>("#collection-entry-title")!,+ "Hello"+ );+ const group = document.querySelector('[aria-label="Draft"]')!;+ for (const [label, expected] of [+ ["No", false],+ ["Not set", null],+ ["Yes", true],+ ] as const) {+ const choice = Array.from(+ group.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === label)!;+ expect(choice).toBeDefined();+ await act(async () => choice.click());+ expect(choice.getAttribute("aria-checked")).toBe("true");+ await act(async () =>+ document.querySelector<HTMLFormElement>("form")!.requestSubmit()+ );+ expect(createEntry).toHaveBeenLastCalledWith({+ projectId: "project",+ folderId: "posts",+ values: { title: "Hello", slug: "hello", draft: expected },+ });+ }+});++test("scrolls long forms without squeezing fields or hiding the create action", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const configValue = JSON.parse(createDefaultCollectionConfig());+ for (let index = 0; index < 12; index += 1) {+ configValue.properties[`extra${index}`] = {+ title: `Extra ${index}`,+ type: "string",+ };+ }+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(JSON.stringify(configValue)),+ templateProperties: {},+ }}+ open+ onOpenChange={() => undefined}+ />+ );+ await act(async () => undefined);+ const form = document.querySelector("form")!;+ const fields = form.firstElementChild as HTMLElement;+ const create = form.querySelector<HTMLButtonElement>(+ 'button[type="submit"]'+ )!;+ expect(fields.scrollHeight).toBeGreaterThan(fields.clientHeight);+ const before = create.getBoundingClientRect();+ fields.scrollTop = fields.scrollHeight;+ expect(create.getBoundingClientRect().top).toBe(before.top);+ expect(before.bottom).toBeLessThanOrEqual(window.innerHeight - 16);+ const firstInput = document.querySelector("#collection-entry-title")!;+ expect(firstInput.getBoundingClientRect().height).toBeGreaterThanOrEqual(20);+});++test("does not commit an entry after the active project changes", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const createdAsset = createAsset({+ id: "created",+ filename: "hello-world",+ format: "mdx",+ });+ const createEntry = vi.fn(async () => {+ $project.set({ id: "another-project" } as never);+ return createdAsset;+ });+ const onOpenChange = vi.fn();+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: {},+ }}+ open+ onOpenChange={onOpenChange}+ createEntry={createEntry}+ />+ );++ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ );+ if (title === null) {+ throw new Error("Expected collection entry title field");+ }+ input(title, "Hello world");+ const create = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Create entry");+ await act(async () => {+ create?.click();+ });++ expect(document.body.textContent).toContain(+ "The entry was created in the previous project. Return to that project to view it."+ );+ expect(onOpenChange).not.toHaveBeenCalled();+});++test("reconciles an idempotent retry when the entry is already loaded", async () => {+ const configAsset = createAsset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const templateAsset = createAsset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const createdAsset = createAsset({+ id: "created",+ filename: "hello-world",+ format: "mdx",+ });+ $assets.set(new Map([[createdAsset.id, createdAsset]]));+ const onOpenChange = vi.fn();+ render(+ <CreateCollectionEntryDialog+ collection={{+ status: "ready",+ folderId: "posts",+ configAsset,+ templateAsset,+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateProperties: {},+ }}+ open+ onOpenChange={onOpenChange}+ createEntry={vi.fn().mockResolvedValue(createdAsset)}+ />+ );++ const title = document.querySelector<HTMLInputElement>(+ "#collection-entry-title"+ );+ if (title === null) {+ throw new Error("Expected collection entry title field");+ }+ input(title, "Hello world");+ const create = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "Create entry");+ await act(async () => {+ create?.click();+ });++ expect(document.body.textContent).not.toContain("Asset already exists");+ expect(document.body.textContent).not.toContain("Discard entry?");+ expect(onOpenChange).toHaveBeenCalledWith(false);+});diff --git a/apps/builder/app/builder/shared/asset-manager/create-collection-entry-dialog.tsx b/apps/builder/app/builder/shared/asset-manager/create-collection-entry-dialog.tsxnew file mode 100644index 0000000000..1a069dddd2--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/create-collection-entry-dialog.tsx@@ -0,0 +1,379 @@+import { CollectionEntryFields } from "./collection-entry-fields";+import { useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";+import {+ collectionEntryFieldClearValue,+ getCollectionFieldValidationIssue,+ normalizeCollectionSlug,+ type CollectionField,+} from "@webstudio-is/content-engine";+import type { Asset } from "@webstudio-is/sdk";+import {+ PanelContent,+ Button,+ Dialog,+ DialogContent,+ DialogTitle,+ Flex,+ Grid,+ Separator,+ Text,+ toast,+ theme,+} from "@webstudio-is/design-system";+import { fetch } from "~/shared/fetch.client";+import { $assets, $project } from "~/shared/sync/data-stores";+import { getWebstudioData } from "~/shared/instance-utils/data";+import { createTransactionFromBuilderPatchPayload } from "~/shared/sync/builder-patch";+import { onNextTransactionComplete } from "~/shared/sync/project-queue";+import { invalidateAssets } from "~/shared/resources";+import type { ContentCollection } from "../assets/content-collections";++const getInitialValue = (+ field: CollectionField,+ templateProperties: Readonly<Record<string, unknown>>+): unknown => {+ if (Object.hasOwn(templateProperties, field.key)) {+ return templateProperties[field.key];+ }+ if (field.type === "boolean") {+ return field.required ? false : undefined;+ }+ if (field.type === "number" || field.type === "integer") {+ return "";+ }+ return "";+};++const createInitialValues = (+ fields: readonly CollectionField[],+ templateProperties: Readonly<Record<string, unknown>>+) =>+ Object.fromEntries(+ fields.flatMap((field) =>+ field.required || Object.hasOwn(templateProperties, field.key)+ ? [[field.key, getInitialValue(field, templateProperties)]]+ : []+ )+ );++const parseResponse = async (response: Response): Promise<Asset> => {+ const payload = (await response.json()) as+ | { asset: Asset }+ | { errors?: string };+ if (response.ok && "asset" in payload) {+ return payload.asset;+ }+ throw new Error(+ "errors" in payload && typeof payload.errors === "string"+ ? payload.errors+ : "The entry could not be created."+ );+};++export const createCollectionEntryRequest = async ({+ projectId,+ folderId,+ values,+ requestId,+}: {+ projectId: string;+ folderId: string;+ values: Readonly<Record<string, unknown>>;+ requestId?: string;+}) => {+ const response = await fetch(+ `/rest/assets/folders/${encodeURIComponent(+ folderId+ )}/entries?projectId=${encodeURIComponent(projectId)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ values, requestId }),+ }+ );+ return parseResponse(response);+};++const stopEscapePropagation = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.stopPropagation();+ }+};++export const CreateCollectionEntryDialog = ({+ collection,+ open,+ onOpenChange,+ createEntry = createCollectionEntryRequest,+}: {+ collection: Extract<ContentCollection, { status: "ready" }>;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ createEntry?: typeof createCollectionEntryRequest;+}) => {+ const { config } = collection;+ const formRef = useRef<HTMLFormElement>(null);+ const [values, setValues] = useState<Record<string, unknown>>(() =>+ createInitialValues(config.fields, collection.templateProperties)+ );+ const [slugEdited, setSlugEdited] = useState(false);+ const requestId = useRef<string>();+ const [dirty, setDirty] = useState(false);+ const [error, setError] = useState<{+ message: string;+ fieldKey?: string;+ }>();+ const [creating, setCreating] = useState(false);+ const [confirmDiscard, setConfirmDiscard] = useState(false);++ useLayoutEffect(() => {+ if (open) {+ requestId.current = crypto.randomUUID();+ setValues(+ createInitialValues(config.fields, collection.templateProperties)+ );+ setSlugEdited(false);+ setDirty(false);+ setError(undefined);+ setCreating(false);+ setConfirmDiscard(false);+ }+ }, [collection.templateProperties, config.fields, open]);++ const setValue = (field: CollectionField, value: unknown) => {+ setDirty(true);+ setValues((current) => {+ const next = { ...current, [field.key]: value };+ if (+ field.key === config.generateSlugFrom &&+ config.slugField !== undefined &&+ slugEdited === false &&+ typeof value === "string"+ ) {+ next[config.slugField] = normalizeCollectionSlug(value);+ }+ return next;+ });+ setError(undefined);+ };++ const unsetValue = (field: CollectionField) => {+ if (field.required) {+ setValue(field, field.type === "boolean" ? undefined : "");+ return;+ }+ setDirty(true);+ setValues((current) => {+ const next = { ...current };+ delete next[field.key];+ return next;+ });+ setError(undefined);+ };++ const submit = async () => {+ if (creating) {+ return;+ }+ setCreating(true);+ setError(undefined);+ try {+ const projectId = $project.get()?.id;+ if (projectId === undefined) {+ throw new Error("Project not found");+ }+ const submittedValues = Object.fromEntries(+ config.fields.flatMap((field) => {+ if (Object.hasOwn(values, field.key) === false) {+ return field.required === false &&+ Object.hasOwn(collection.templateProperties, field.key)+ ? [[field.key, collectionEntryFieldClearValue]]+ : [];+ }+ const value = values[field.key];+ if (+ (field.type === "number" || field.type === "integer") &&+ value !== ""+ ) {+ return [[field.key, Number(value)]];+ }+ return [[field.key, value]];+ })+ );+ if (config.slugField !== undefined) {+ const submittedSlug = submittedValues[config.slugField];+ if (typeof submittedSlug !== "string" || submittedSlug.trim() === "") {+ const slugSource =+ config.generateSlugFrom === undefined+ ? undefined+ : submittedValues[config.generateSlugFrom];+ if (typeof slugSource === "string") {+ submittedValues[config.slugField] =+ normalizeCollectionSlug(slugSource);+ }+ } else {+ submittedValues[config.slugField] =+ normalizeCollectionSlug(submittedSlug);+ }+ }+ const validationIssue = getCollectionFieldValidationIssue(+ config,+ submittedValues+ );+ if (validationIssue !== undefined) {+ setError(validationIssue);+ requestAnimationFrame(() => {+ document+ .getElementById(`collection-entry-${validationIssue.fieldKey}`)+ ?.focus();+ });+ return;+ }+ const asset = await createEntry({+ projectId,+ folderId: collection.folderId,+ values: submittedValues,+ ...(config.slugField === undefined+ ? { requestId: requestId.current }+ : {}),+ });+ if ($project.get()?.id !== projectId) {+ throw new Error(+ "The entry was created in the previous project. Return to that project to view it."+ );+ }+ if ($assets.get().has(asset.id)) {+ invalidateAssets();+ } else {+ createTransactionFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: [+ {+ namespace: "assets",+ patches: [{ op: "add", path: [asset.id], value: asset }],+ },+ ],+ });+ onNextTransactionComplete(invalidateAssets);+ }+ onOpenChange(false);+ toast.success("Entry created.");+ } catch (error) {+ setError({+ message:+ error instanceof Error+ ? error.message+ : "The entry could not be created.",+ });+ } finally {+ setCreating(false);+ }+ };+ const requestClose = () => {+ if (dirty) {+ setConfirmDiscard(true);+ return;+ }+ onOpenChange(false);+ };++ return (+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (creating === false && nextOpen === false) {+ requestClose();+ }+ }}+ >+ <DialogContent+ css={{+ width: "min(560px, calc(100vw - 32px))",+ }}+ aria-describedby={undefined}+ onKeyDown={stopEscapePropagation}+ onOpenAutoFocus={(event) => {+ const input = formRef.current?.querySelector<HTMLElement>(+ 'input, textarea, [role="group"] button'+ );+ if (input) {+ input.focus();+ event.preventDefault();+ }+ }}+ >+ <DialogTitle>New entry</DialogTitle>+ <Flex+ as="form"+ ref={formRef}+ direction="column"+ noValidate+ onSubmit={(event) => {+ event.preventDefault();+ void submit();+ }}+ css={{ maxHeight: "min(640px, calc(100vh - 96px))" }}+ >+ <Grid+ gap={4}+ css={{+ padding: theme.spacing[9],+ overflow: "auto",+ gridAutoRows: "max-content",+ alignContent: "start",+ }}+ >+ <CollectionEntryFields+ config={config}+ values={values}+ errors={error === undefined ? [] : [error]}+ disabled={creating}+ onChange={(field, value) => {+ if (field.key === config.slugField) {+ setSlugEdited(true);+ }+ setValue(field, value);+ }}+ onReset={unsetValue}+ />+ </Grid>+ <Separator />+ <PanelContent as={Flex} direction="column" shrink={false} gap={2}>+ {error !== undefined && error.fieldKey === undefined && (+ <Text role="alert" color="destructive">+ {error.message}+ </Text>+ )}+ <Flex justify="end">+ <Button type="submit" color="primary" disabled={creating}>+ {creating ? "Creating…" : "Create entry"}+ </Button>+ </Flex>+ </PanelContent>+ </Flex>+ </DialogContent>+ <Dialog open={confirmDiscard} onOpenChange={setConfirmDiscard}>+ <DialogContent aria-describedby={undefined} width={420}>+ <DialogTitle>Discard entry?</DialogTitle>+ <PanelContent as={Grid} gap={3}>+ <Text>Your unsaved entry values will be lost.</Text>+ <Flex justify="end" gap={2}>+ <Button onClick={() => setConfirmDiscard(false)}>+ Keep editing+ </Button>+ <Button+ color="destructive"+ onClick={() => {+ setConfirmDiscard(false);+ onOpenChange(false);+ }}+ >+ Discard entry+ </Button>+ </Flex>+ </PanelContent>+ </DialogContent>+ </Dialog>+ </Dialog>+ );+};diff --git a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.test.tsx b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.test.tsxindex 34f38b6e4d..51f69db2d7 100644--- a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.test.tsx+++ b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.test.tsx@@ -43,6 +43,27 @@ const createAsset = (id: string): Asset => ({createdAt: "2026-01-01T00:00:00.000Z",});+const createFileAsset = ({+ id,+ name,+ folderId,+}: {+ id: string;+ name: string;+ folderId: string;+}): Asset => ({+ id,+ projectId: "project",+ name,+ filename: name.slice(0, name.lastIndexOf(".")),+ format: name.slice(name.lastIndexOf(".") + 1),+ size: 1,+ type: "file",+ meta: {},+ folderId,+ createdAt: "2026-01-01T00:00:00.000Z",+});+beforeEach(() => {vi.stubGlobal("ResizeObserver",@@ -200,3 +221,44 @@ test("does not delete a selected asset that becomes used while open", () => {expect($assets.get().has("first")).toBe(true);expect($assets.get().has("second")).toBe(true);});++test("does not offer collection files as unused assets", () => {+ const config = createFileAsset({+ id: "collection-config",+ name: "collection.json",+ folderId: "posts",+ });+ const template = createFileAsset({+ id: "collection-template",+ name: "template.mdx",+ folderId: "posts",+ });+ const entry = createFileAsset({+ id: "collection-entry",+ name: "hello-world.mdx",+ folderId: "posts",+ });+ act(() => {+ $assets.set(+ new Map([+ ...$assets.get(),+ [config.id, config],+ [template.id, template],+ [entry.id, entry],+ ])+ );+ openDeleteUnusedAssetsDialog();+ });+ renderer.render(+ <TooltipProvider>+ <DeleteUnusedAssetsDialog />+ </TooltipProvider>+ );++ expect(document.querySelector("#unused-asset-first")).not.toBeNull();+ expect(document.querySelector("#unused-asset-collection-config")).toBeNull();+ expect(+ document.querySelector("#unused-asset-collection-template")+ ).toBeNull();+ expect(document.querySelector("#unused-asset-collection-entry")).toBeNull();+});diff --git a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsxindex 58b0ab74d9..75e57eeafb 100644--- a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx+++ b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx@@ -2,6 +2,7 @@ import { atom } from "nanostores";import { useStore } from "@nanostores/react";import { useState } from "react";import {+ PanelContent,Dialog,DialogActions,DialogContent,@@ -12,7 +13,6 @@ import {Button,Text,Flex,- theme,toast,Box,Checkbox,@@ -20,6 +20,7 @@ import {Label,} from "@webstudio-is/design-system";import type { Asset } from "@webstudio-is/sdk";+import { collectionConfigFilename } from "@webstudio-is/content-engine";import {$assets,$pages,@@ -54,8 +55,22 @@ const DeleteUnusedAssetsDialogContent = ({styles,assets,});+ const collectionFolderIds = new Set(+ Array.from(assets.values()).flatMap((asset) =>+ asset.folderId !== undefined &&+ formatAssetName(asset) === collectionConfigFilename+ ? [asset.folderId]+ : []+ )+ );const unusedAssets: Asset[] = [];for (const asset of assets.values()) {+ if (+ asset.folderId !== undefined &&+ collectionFolderIds.has(asset.folderId)+ ) {+ continue;+ }const usages = usagesByAssetId.get(asset.id);if (usages === undefined || usages.length === 0) {unusedAssets.push(asset);@@ -72,7 +87,7 @@ const DeleteUnusedAssetsDialogContent = ({return (<>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column">{unusedAssets.length === 0 ? (<DialogDescription asChild><Text>There are no unused assets to delete.</Text>@@ -122,7 +137,7 @@ const DeleteUnusedAssetsDialogContent = ({</ScrollArea></>)}- </Flex>+ </PanelContent><DialogActions>{unusedAssets.length > 0 && (<Buttondiff --git a/apps/builder/app/builder/shared/assets/asset-utils.test.ts b/apps/builder/app/builder/shared/assets/asset-utils.test.tsindex 6b2e2f248b..b86790a45e 100644--- a/apps/builder/app/builder/shared/assets/asset-utils.test.ts+++ b/apps/builder/app/builder/shared/assets/asset-utils.test.ts@@ -1,11 +1,58 @@import { expect, test, describe } from "vitest";+import type { Asset } from "@webstudio-is/sdk";import {getImageNameAndType,getSha256Hash,getFileUploadFingerprint,+ isAssetFilenameUsed,uploadingFileDataToAsset,} from "./asset-utils";+test("matches full asset filenames only in the requested folder", () => {+ const asset: Asset = {+ id: "guide",+ projectId: "project",+ name: "uploaded_hash.md",+ filename: "guide",+ folderId: "other",+ type: "file",+ format: "md",+ size: 1,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ };++ expect(+ isAssetFilenameUsed({+ assets: [asset],+ filename: "guide.md",+ folderId: "other",+ })+ ).toBe(true);+ expect(+ isAssetFilenameUsed({+ assets: [asset],+ filename: "guide.md",+ folderId: "docs",+ })+ ).toBe(false);+ expect(+ isAssetFilenameUsed({+ assets: [asset],+ filename: "guide.json",+ folderId: "other",+ })+ ).toBe(false);+ expect(+ isAssetFilenameUsed({+ assets: [asset],+ filename: "guide.md",+ folderId: "other",+ excludeAssetId: asset.id,+ })+ ).toBe(false);+});+test("distinguishes upload fingerprints by filename and content", async () => {const first = new File([""], "first.md");const renamed = new File([""], "renamed.md");diff --git a/apps/builder/app/builder/shared/assets/asset-utils.ts b/apps/builder/app/builder/shared/assets/asset-utils.tsindex cfba3ae8dc..2cc3130835 100644--- a/apps/builder/app/builder/shared/assets/asset-utils.ts+++ b/apps/builder/app/builder/shared/assets/asset-utils.ts@@ -7,6 +7,7 @@ import type {} from "@webstudio-is/sdk";import {createId,+ formatAssetName,getMimeTypeByExtension,getFileExtension,IMAGE_EXTENSIONS,@@ -15,6 +16,29 @@ import {} from "@webstudio-is/sdk";import type { UploadingFileData } from "~/shared/nano-states";+export const isAssetFilenameUsed = ({+ assets,+ filename,+ folderId,+ excludeAssetId,+}: {+ assets: Iterable<Asset>;+ filename: string;+ folderId?: string;+ excludeAssetId?: Asset["id"];+}) => {+ for (const asset of assets) {+ if (+ asset.id !== excludeAssetId &&+ asset.folderId === folderId &&+ formatAssetName(asset) === filename+ ) {+ return true;+ }+ }+ return false;+};+export const getImageNameAndType = (fileName: string) => {const extractedExt = getFileExtension(fileName)?.toLowerCase();diff --git a/apps/builder/app/builder/shared/assets/assets-shell.test.tsx b/apps/builder/app/builder/shared/assets/assets-shell.test.tsxindex 7f168724af..ff3362ceb8 100644--- a/apps/builder/app/builder/shared/assets/assets-shell.test.tsx+++ b/apps/builder/app/builder/shared/assets/assets-shell.test.tsx@@ -27,6 +27,45 @@ const renderer = createAssetManagerTestRenderer();afterEach(renderer.cleanup);describe("AssetsShell", () => {+ test.each([true, false])(+ "places folder notices after filters and before content (empty: %s)",+ (isEmpty) => {+ const content = (+ <button type="button" data-folder-content>+ Back+ </button>+ );+ const container = renderer.render(+ <AssetsShell+ searchProps={{}}+ filters={+ <button type="button" data-filter>+ Filter+ </button>+ }+ contentNotice={<div role="alert">Unavailable</div>}+ isEmpty={isEmpty}+ emptyContent={content}+ type="file"+ >+ {content}+ </AssetsShell>+ );+ const notice = container.querySelector('[role="alert"]')!;+ expect(notice).not.toBeNull();+ expect(+ container+ .querySelector("[data-filter]")!+ .compareDocumentPosition(notice) & Node.DOCUMENT_POSITION_FOLLOWING+ ).not.toBe(0);+ expect(+ notice.compareDocumentPosition(+ container.querySelector("[data-folder-content]")!+ ) & Node.DOCUMENT_POSITION_FOLLOWING+ ).not.toBe(0);+ }+ );+test("centers the empty state independently from empty folder content", () => {const container = renderer.render(<AssetsShelldiff --git a/apps/builder/app/builder/shared/assets/assets-shell.tsx b/apps/builder/app/builder/shared/assets/assets-shell.tsxindex 75f82b2a91..b9c892b830 100644--- a/apps/builder/app/builder/shared/assets/assets-shell.tsx+++ b/apps/builder/app/builder/shared/assets/assets-shell.tsx@@ -4,9 +4,11 @@ import {useState,type ComponentProps,type JSX,+ type ReactNode,type PointerEvent,} from "react";import {+ PanelContent,ContextMenu,ContextMenuTrigger,Flex,@@ -57,6 +59,7 @@ type AssetsShellProps = {isEmpty: boolean;emptyMessage?: string;emptyContent?: JSX.Element;+ contentNotice?: ReactNode;folderId?: string;contextMenu?: JSX.Element;onContextMenu?: ComponentProps<typeof Flex>["onContextMenu"];@@ -68,6 +71,7 @@ type AssetsShellProps = {onElementChange?: (element: HTMLDivElement | null) => void;autoScrollOnElementDrag?: boolean;allowFolderDrop?: boolean;+ allowExternalDrop?: boolean;};const containsFilesOrUri = (parameter: ContainsSource) => {@@ -112,6 +116,7 @@ export const AssetsShell = ({isEmpty,emptyMessage,emptyContent,+ contentNotice,children,interactionOverlay,footer,@@ -123,6 +128,7 @@ export const AssetsShell = ({onElementChange,autoScrollOnElementDrag = false,allowFolderDrop = false,+ allowExternalDrop = true,type,accept,}: AssetsShellProps) => {@@ -132,12 +138,16 @@ export const AssetsShell = ({useState<ExternalMonitorDragState>(IDLE);const [dropTargetState, setDropTargetState] = useState<DropTargetState>(IDLE);- const dropMessage = allowFolderDrop- ? "Drop files or folders here"- : "Drop files here";- const dropDescription = allowFolderDrop- ? "Drop files or folders from your computer into this panel."- : "Drop files from anywhere into this panel.";+ const dropMessage = allowExternalDrop+ ? allowFolderDrop+ ? "Drop files or folders here"+ : "Drop files here"+ : "Uploads are unavailable here";+ const dropDescription = allowExternalDrop+ ? allowFolderDrop+ ? "Drop files or folders from your computer into this panel."+ : "Drop files from anywhere into this panel."+ : undefined;const resolvedEmptyMessage = emptyMessage ?? dropMessage;useEffect(() => {@@ -154,7 +164,8 @@ export const AssetsShell = ({useExternalDragStateEffect((state) => {const element = ref.current;- if (element == null) {+ if (element == null || allowExternalDrop === false) {+ setMonitorState(IDLE);return;}@@ -197,7 +208,10 @@ export const AssetsShell = ({return combine(dropTargetForExternal({element: element,- canDrop: isBlockedByBackdropCallback(() => false, containsByType),+ canDrop: isBlockedByBackdropCallback(+ () => false,+ allowExternalDrop ? containsByType : () => false+ ),onDragEnter: () => setDropTargetState(OVER),onDragLeave: () => setDropTargetState(IDLE),onDrop: async ({ source }) => {@@ -285,7 +299,14 @@ export const AssetsShell = ({},}));- }, [accept, allowFolderDrop, containsByType, folderId, type]);+ }, [+ accept,+ allowExternalDrop,+ allowFolderDrop,+ containsByType,+ folderId,+ type,+ ]);const dragState = Math.max(monitorState, dropTargetState);@@ -303,16 +324,10 @@ export const AssetsShell = ({overflow: "hidden",paddingBlock: theme.panel.paddingBlock,flex: 1,- minHeight: 0,position: "relative",}}>- <Flex- css={{ padding: theme.panel.padding }}- gap="2"- wrap="wrap"- shrink={false}- >+ <PanelContent as={Flex} gap="2" wrap="wrap" shrink={false}><SearchFieldcss={{ flexGrow: 1 }}{...searchProps}@@ -320,13 +335,11 @@ export const AssetsShell = ({placeholder="Search"/>{filters}- </Flex>+ </PanelContent><Separator />+ {contentNotice}{isEmpty ? (- <Flex- direction="column"- css={{ flex: 1, minHeight: 0, position: "relative" }}- >+ <Flex direction="column" css={{ flex: 1, position: "relative" }}>{emptyContent}<AssetPanelStateoverlay={emptyContent !== undefined}diff --git a/apps/builder/app/builder/shared/assets/content-collections-hook.test.tsx b/apps/builder/app/builder/shared/assets/content-collections-hook.test.tsxnew file mode 100644index 0000000000..404b5e5865--- /dev/null+++ b/apps/builder/app/builder/shared/assets/content-collections-hook.test.tsx@@ -0,0 +1,240 @@+import { act } from "react-dom/test-utils";+import { createRoot } from "react-dom/client";+import { expect, test, vi } from "vitest";+import type { Asset } from "@webstudio-is/sdk";+import { createDefaultCollectionConfig } from "@webstudio-is/content-engine";+import { $assets, $project } from "~/shared/sync/data-stores";+import {+ createAssetContentBridge,+ __testing__,+} from "~/shared/asset-content-bridge.client";+import {+ assetContentDescriptorHeader,+ serializeAssetContentDescriptor,+} from "@webstudio-is/protocol/asset-resource-api";+import { useContentCollections } from "./content-collections";++const { initBridge, clearBridge } = __testing__;+(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++test("shares collection reads across consumers and refreshes them together", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const files: Asset[] = ["collection.json", "template.mdx"].map((name) => ({+ id: name,+ name,+ projectId: "project",+ folderId: "posts",+ type: "file",+ format: name.endsWith("json") ? "json" : "mdx",+ size: 1,+ meta: {},+ createdAt: "2026-09-08T00:00:00Z",+ }));+ let requests = 0;+ let unavailable = false;+ let title = "Title";+ let holdConfig: Promise<void> | undefined;+ initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ authorize: () => true,+ requireReload: () => undefined,+ request: async (url) => {+ requests += 1;+ if (unavailable) {+ throw new Error("Offline");+ }+ const isConfig = String(url).includes("collection.json");+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.title.title = title;+ const source = isConfig+ ? JSON.stringify(schema)+ : "---\ndraft: true\n---\n";+ if (isConfig) {+ await holdConfig;+ }+ const asset = {+ ...files[isConfig ? 0 : 1],+ size: new TextEncoder().encode(source).length,+ };+ return new Response(source, {+ headers: {+ [assetContentDescriptorHeader]:+ serializeAssetContentDescriptor(asset),+ },+ });+ },+ })+ );+ const Consumer = ({+ refresh = 0,+ folder = "posts",+ }: {+ refresh?: number;+ folder?: string;+ }) => {+ const collection = useContentCollections(folder, refresh).get(folder);+ return (+ <output>+ {collection?.status === "ready"+ ? collection.config.fields[0].label+ : (collection?.status ?? "none")}+ </output>+ );+ };+ try {+ $assets.set(new Map(files.map((file) => [file.id, file])));+ $project.set({ id: "project" } as never);+ act(() =>+ root.render(+ <>+ <Consumer />+ <Consumer />+ <Consumer folder="ordinary" />+ </>+ )+ );+ await vi.waitFor(() =>+ expect(container.textContent).toBe("TitleTitlenone")+ );+ expect(requests).toBe(2);+ act(() =>+ root.render(+ <>+ <Consumer />+ <Consumer />+ <Consumer />+ </>+ )+ );+ await vi.waitFor(() =>+ expect(container.textContent).toBe("TitleTitleTitle")+ );+ expect(requests).toBe(2);++ // An entry edit must not download the unchanged schema and template again.+ act(() =>+ $assets.set(+ new Map([+ ...$assets.get(),+ ["entry", { ...files[1], id: "entry", name: "post.mdx" }],+ ])+ )+ );+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 30));+ });+ expect(requests).toBe(2);++ // Metadata-only collisions still invalidate the cached collection.+ act(() =>+ $assets.set(+ new Map([+ ...$assets.get(),+ ["duplicate", { ...files[1], id: "duplicate", name: "POST.mdx" }],+ ])+ )+ );+ await vi.waitFor(() =>+ expect(container.textContent).toBe("invalidinvalidinvalid")+ );+ act(() => {+ const assets = new Map($assets.get());+ assets.delete("duplicate");+ $assets.set(assets);+ });+ await vi.waitFor(() =>+ expect(container.textContent).toBe("TitleTitleTitle")+ );++ unavailable = true;+ act(() =>+ root.render(+ <>+ <Consumer refresh={1} />+ <Consumer />+ <Consumer />+ </>+ )+ );+ await vi.waitFor(() =>+ expect(container.textContent).toBe("unavailableunavailableunavailable")+ );+ unavailable = false;+ title = "Updated title";+ act(() =>+ root.render(+ <>+ <Consumer refresh={2} />+ <Consumer />+ <Consumer />+ </>+ )+ );+ await vi.waitFor(() =>+ expect(container.textContent).toBe(+ "Updated titleUpdated titleUpdated title"+ )+ );++ let release: () => void = () => {};+ holdConfig = new Promise<void>((resolve) => {+ release = resolve;+ });+ title = "Stale title";+ const beforeRefresh = requests;+ act(() =>+ root.render(+ <>+ <Consumer refresh={3} />+ <Consumer />+ <Consumer />+ </>+ )+ );+ await vi.waitFor(() => expect(requests).toBe(beforeRefresh + 1));+ let releaseLatest: () => void = () => {};+ holdConfig = new Promise<void>((resolve) => {+ releaseLatest = resolve;+ });+ title = "Latest title";+ act(() =>+ root.render(+ <>+ <Consumer refresh={4} />+ <Consumer />+ <Consumer />+ </>+ )+ );+ await vi.waitFor(() => expect(requests).toBe(beforeRefresh + 2));+ await act(async () => {+ release();+ await new Promise((resolve) => setTimeout(resolve, 30));+ });+ expect(container.textContent).toBe(+ "Updated titleUpdated titleUpdated title"+ );+ await act(async () => {+ releaseLatest();+ });+ await vi.waitFor(() =>+ expect(container.textContent).toBe("Latest titleLatest titleLatest title")+ );+ expect(container.textContent).toBe("Latest titleLatest titleLatest title");++ // Project switches cannot expose a previous project's cached collection.+ act(() => $project.set({ id: "other-project" } as never));+ await vi.waitFor(() => expect(container.textContent).toBe("nonenonenone"));+ } finally {+ act(() => root.unmount());+ container.remove();+ $assets.set(new Map());+ $project.set(undefined);+ clearBridge();+ }+});diff --git a/apps/builder/app/builder/shared/assets/content-collections.test.ts b/apps/builder/app/builder/shared/assets/content-collections.test.tsnew file mode 100644index 0000000000..89b3f981ec--- /dev/null+++ b/apps/builder/app/builder/shared/assets/content-collections.test.ts@@ -0,0 +1,507 @@+import { describe, expect, test, vi } from "vitest";+import type { Asset } from "@webstudio-is/sdk";+import {+ ContentCollectionError,+ contentEngineLimits,+ createDefaultCollectionConfig,+} from "@webstudio-is/content-engine";+import {+ createLoadingContentCollections,+ discoverContentCollections,+ getCollectionReservedAssetIds,+ mergeLoadingContentCollections,+ canAddAssetToContentCollection,+} from "./content-collections";++const asset = ({+ id,+ filename,+ format,+}: {+ id: string;+ filename: string;+ format: string;+}): Asset => ({+ id,+ projectId: "project",+ name: `${filename}_${id}.${format}`,+ filename,+ description: null,+ folderId: "folder",+ size: 1,+ createdAt: "2026-09-02T00:00:00.000Z",+ type: "file",+ format,+ meta: {},+});++describe("discoverContentCollections", () => {+ test("allows ordinary files but protects entry and setup filenames", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const template = asset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = ["*.mdx", "!draft-*.mdx"];+ const collections = await discoverContentCollections({+ assets: [config, template],+ readSource: async (file) =>+ file.id === config.id+ ? JSON.stringify(schema)+ : "---\ndraft: true\n---\n",+ });+ const collection = collections.get("folder");+ expect(collection?.status).toBe("ready");+ for (const name of ["notes.md", "cover.png", "draft-idea.mdx"]) {+ expect(canAddAssetToContentCollection(collection, { name })).toBe(true);+ }+ for (const name of ["post.mdx", "collection.json", "template.mdx"]) {+ expect(canAddAssetToContentCollection(collection, { name })).toBe(false);+ }+ expect(+ canAddAssetToContentCollection(+ createLoadingContentCollections([config]).get("folder"),+ { name: "cover.png" }+ )+ ).toBe(false);+ expect(+ canAddAssetToContentCollection(undefined, { name: "post.mdx" })+ ).toBe(true);+ expect(canAddAssetToContentCollection(collection, undefined)).toBe(false);+ });+ test("keeps temporary collection read failures retryable", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const template = asset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const collections = await discoverContentCollections({+ assets: [config, template],+ readSource: async () => {+ throw new Error("Network request failed");+ },+ });++ expect(collections.get("folder")).toMatchObject({+ status: "unavailable",+ message: "Collection files could not be loaded: Network request failed",+ });+ expect(+ mergeLoadingContentCollections({+ current: collections,+ loading: createLoadingContentCollections([config, template]),+ }).get("folder")+ ).toBe(collections.get("folder"));+ expect(+ getCollectionReservedAssetIds(collections, { includeInvalid: true })+ ).toEqual(new Set([config.id, template.id]));+ });++ test("reports permanent collection content errors as invalid", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const collections = await discoverContentCollections({+ assets: [config],+ readSource: async () => {+ throw new ContentCollectionError("Collection file is not valid UTF-8");+ },+ });++ expect(collections.get("folder")).toMatchObject({+ status: "invalid",+ message: "Collection file is not valid UTF-8",+ });+ });++ test("reports oversized collection sources as invalid without reading them", async () => {+ const config = {+ ...asset({+ id: "config",+ filename: "collection",+ format: "json",+ }),+ size: contentEngineLimits.hydratedFileBytes + 1,+ };+ let read = false;+ const collections = await discoverContentCollections({+ assets: [config],+ readSource: async () => {+ read = true;+ return createDefaultCollectionConfig();+ },+ });++ expect(collections.get("folder")).toMatchObject({+ status: "invalid",+ message: 'Collection file "collection.json" exceeds the editing limit',+ });+ expect(read).toBe(false);+ });++ test("does not read every entry while discovering a collection", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const template = asset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const entry = asset({ id: "entry", filename: "hello", format: "mdx" });+ const readSource = vi.fn(async (currentAsset: Asset) =>+ currentAsset.id === config.id+ ? createDefaultCollectionConfig()+ : "---\ndraft: false\n---\n"+ );+ const collections = await discoverContentCollections({+ assets: [config, template, entry],+ readSource,+ });++ expect(collections.get("folder")).toMatchObject({+ status: "ready",+ });+ expect(readSource).toHaveBeenCalledTimes(2);+ });++ test("reserves possible templates while collection settings load", () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const possibleTemplate = asset({+ id: "possible-template",+ filename: "article",+ format: "mdx",+ });+ const loading = createLoadingContentCollections([config, possibleTemplate]);++ expect(+ getCollectionReservedAssetIds(loading, { includeInvalid: true })+ ).toEqual(new Set([config.id, possibleTemplate.id]));+ });++ test("keeps a ready collection stable when an entry changes", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const template = asset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const discovered = await discoverContentCollections({+ assets: [config, template],+ readSource: async (currentAsset) =>+ currentAsset.id === config.id+ ? createDefaultCollectionConfig()+ : "---\ndraft: false\n---\n",+ });+ const ready = discovered.get("folder");+ const entry = asset({ id: "entry", filename: "hello", format: "mdx" });++ const merged = mergeLoadingContentCollections({+ current: discovered,+ loading: createLoadingContentCollections([config, template, entry]),+ });++ expect(merged.get("folder")).toBe(ready);+ });++ test("recognizes collection.json and reserves its referenced template", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const template = asset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const collections = await discoverContentCollections({+ assets: [config, template],+ readSource: async (currentAsset) =>+ currentAsset.id === config.id+ ? createDefaultCollectionConfig()+ : "---\ndraft: false\n---\n\nStart writing.\n",+ });++ expect(collections.get("folder")).toMatchObject({+ status: "ready",+ configAsset: config,+ templateAsset: template,+ templateProperties: { draft: false },+ });+ });++ test("keeps a folder special when collection.json is invalid", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const possibleTemplate = asset({+ id: "possible-template",+ filename: "article",+ format: "mdx",+ });+ const collections = await discoverContentCollections({+ assets: [config, possibleTemplate],+ readSource: async () => "not json",+ });++ expect(collections.get("folder")).toMatchObject({+ status: "invalid",+ message: "collection.json contains invalid JSON",+ });+ expect(+ mergeLoadingContentCollections({+ current: collections,+ loading: createLoadingContentCollections([config, possibleTemplate]),+ }).get("folder")+ ).toBe(collections.get("folder"));+ expect(+ getCollectionReservedAssetIds(collections, { includeInvalid: true })+ ).toEqual(new Set([config.id, possibleTemplate.id]));+ });++ test("returns an invalid collection to loading when a sibling changes", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const possibleTemplate = asset({+ id: "possible-template",+ filename: "article",+ format: "mdx",+ });+ const collections = await discoverContentCollections({+ assets: [config, possibleTemplate],+ readSource: async () => "not json",+ });+ const changedTemplate = {+ ...possibleTemplate,+ name: "article-revision.mdx",+ };++ expect(+ mergeLoadingContentCollections({+ current: collections,+ loading: createLoadingContentCollections([config, changedTemplate]),+ }).get("folder")+ ).toMatchObject({ status: "loading" });+ });++ test("keeps an identified invalid template reserved in content mode", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const template = asset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const collections = await discoverContentCollections({+ assets: [config, template],+ readSource: async (currentAsset) =>+ currentAsset.id === config.id+ ? createDefaultCollectionConfig()+ : "---\ndraft: true\n---\n\n<Broken",+ });++ expect(collections.get("folder")).toMatchObject({+ status: "invalid",+ configAsset: config,+ templateAsset: template,+ repairAsset: template,+ });+ expect(+ getCollectionReservedAssetIds(collections, { includeInvalid: true })+ ).toEqual(new Set([config.id, template.id]));+ });++ test("ignores direct non-entry files when discovering a collection", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const template = asset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const image = asset({ id: "image", filename: "cover", format: "png" });+ const collections = await discoverContentCollections({+ assets: [config, template, image],+ readSource: async (file) => {+ if (file.id === config.id) {+ return createDefaultCollectionConfig();+ }+ if (file.id === template.id) {+ return "---\ndraft: true\n---\nBody";+ }+ throw new Error("Non-entry files must not be read");+ },+ });++ expect(collections.get("folder")).toMatchObject({+ status: "ready",+ configAsset: config,+ templateAsset: template,+ });+ });++ test("keeps collection configuration usable while an entry is invalid", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const template = asset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const entry = asset({ id: "entry", filename: "hello", format: "mdx" });+ const reads = new Map<string, number>();+ const collections = await discoverContentCollections({+ assets: [config, template, entry],+ readSource: async (currentAsset) => {+ reads.set(currentAsset.id, (reads.get(currentAsset.id) ?? 0) + 1);+ if (currentAsset.id === config.id) {+ return createDefaultCollectionConfig();+ }+ if (currentAsset.id === template.id) {+ return "---\ndraft: true\n---\n";+ }+ return "---\ntitle: Hello\nslug: another-slug\ndraft: false\n---\n";+ },+ });++ expect(collections.get("folder")).toMatchObject({+ status: "ready",+ });+ expect(+ getCollectionReservedAssetIds(collections, { includeInvalid: true })+ ).toEqual(new Set([config.id, template.id]));+ expect(reads.get(template.id)).toBe(1);+ expect(reads.get(entry.id)).toBeUndefined();+ });++ test("rejects duplicate logical filenames case-insensitively", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const template = asset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const firstEntry = asset({+ id: "first-entry",+ filename: "hello",+ format: "mdx",+ });+ const duplicateEntry = asset({+ id: "duplicate-entry",+ filename: "HELLO",+ format: "mdx",+ });+ const collections = await discoverContentCollections({+ assets: [config, template, firstEntry, duplicateEntry],+ readSource: async (currentAsset) =>+ currentAsset.id === config.id+ ? createDefaultCollectionConfig()+ : "---\ntitle: Hello\nslug: hello\ndraft: false\n---\n",+ });++ expect(collections.get("folder")).toMatchObject({+ status: "invalid",+ repairAsset: duplicateEntry,+ repairAction: "move",+ message: 'Collection folder contains duplicate filename "HELLO.mdx"',+ });+ expect(+ getCollectionReservedAssetIds(collections, { includeInvalid: true })+ ).toEqual(new Set([config.id, template.id]));+ });++ test("rejects ambiguous collection configuration and templates", async () => {+ const config = asset({+ id: "config",+ filename: "collection",+ format: "json",+ });+ const duplicateConfig = asset({+ id: "duplicate-config",+ filename: "collection",+ format: "json",+ });+ const template = asset({+ id: "template",+ filename: "template",+ format: "mdx",+ });+ const duplicateTemplate = asset({+ id: "duplicate-template",+ filename: "template",+ format: "mdx",+ });+ const readSource = async (currentAsset: Asset) =>+ currentAsset.format === "json"+ ? createDefaultCollectionConfig()+ : "---\ndraft: true\n---\n";++ const duplicateConfigs = await discoverContentCollections({+ assets: [config, duplicateConfig, template],+ readSource,+ });+ expect(duplicateConfigs.get("folder")).toMatchObject({+ status: "invalid",+ message: "A collection folder must contain exactly one collection.json",+ });+ expect(+ getCollectionReservedAssetIds(duplicateConfigs, { includeInvalid: true })+ ).toEqual(new Set([config.id, duplicateConfig.id, template.id]));++ const duplicateTemplates = await discoverContentCollections({+ assets: [config, template, duplicateTemplate],+ readSource,+ });+ expect(duplicateTemplates.get("folder")).toMatchObject({+ status: "invalid",+ message: 'Collection template "template.mdx" is ambiguous',+ });+ expect(+ getCollectionReservedAssetIds(duplicateTemplates, {+ includeInvalid: true,+ })+ ).toEqual(new Set([config.id, template.id, duplicateTemplate.id]));+ });+});diff --git a/apps/builder/app/builder/shared/assets/content-collections.ts b/apps/builder/app/builder/shared/assets/content-collections.tsnew file mode 100644index 0000000000..e0bad773cf--- /dev/null+++ b/apps/builder/app/builder/shared/assets/content-collections.ts@@ -0,0 +1,487 @@+import { useEffect, useRef } from "react";+import { atom, computed } from "nanostores";+import { useStore } from "@nanostores/react";+import {+ collectionConfigFilename,+ ContentCollectionError,+ ContentCollectionInspectionError,+ contentEngineLimits,+ inspectContentCollection,+ type ContentCollectionConfig,+} from "@webstudio-is/content-engine";+import { readAssetContentBytes } from "@webstudio-is/content-engine/asset-content-repository";+import {+ formatAssetName,+ getAssetDisplayNameParts,+ isMdxFileAsset,+ type Asset,+} from "@webstudio-is/sdk";+import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";+import { $assets, $project } from "~/shared/sync/data-stores";+import { $authToken } from "~/shared/nano-states";+import { createBuilderHttpAssetContentRepository } from "./builder-mdx-content-repository.client";++export type ContentCollection =+ | Readonly<{+ status: "ready";+ folderId: string;+ configAsset: Asset;+ templateAsset: Asset;+ config: ContentCollectionConfig;+ templateProperties: Readonly<Record<string, unknown>>;+ }>+ | Readonly<{+ status: "loading";+ folderId: string;+ configAsset: Asset;+ siblingAssets: readonly Asset[];+ }>+ | Readonly<{+ status: "invalid";+ folderId: string;+ configAsset: Asset;+ templateAsset?: Asset;+ reservedAssets: readonly Asset[];+ siblingAssets: readonly Asset[];+ repairAsset: Asset;+ missingTemplateFilename?: string;+ forbiddenAsset?: Asset;+ repairAction?: "edit" | "move";+ message: string;+ }>+ | Readonly<{+ status: "unavailable";+ folderId: string;+ configAsset: Asset;+ templateAsset?: Asset;+ reservedAssets: readonly Asset[];+ siblingAssets: readonly Asset[];+ message: string;+ }>;++type LoadingContentCollection = Extract<+ ContentCollection,+ { status: "loading" }+>;++export const canConfigureContentCollections = (authPermit: AuthPermit) =>+ authPermit === "build" || authPermit === "admin" || authPermit === "own";++export const canAddAssetToContentCollection = (+ collection: ContentCollection | undefined,+ asset: Pick<Asset, "name" | "filename"> | undefined+) => {+ if (asset === undefined) {+ return false;+ }+ if (collection === undefined) {+ return true;+ }+ if (collection.status !== "ready") {+ return false;+ }+ const filename = formatAssetName(asset);+ return (+ filename !== collectionConfigFilename &&+ filename !== collection.config.template &&+ !collection.config.matchesEntry(filename)+ );+};++const getErrorMessage = (error: unknown) =>+ error instanceof Error+ ? error.message+ : "Collection configuration is invalid";++export class ContentCollectionReadError extends Error {}++export const discoverContentCollections = async ({+ assets,+ readSource,+}: {+ assets: readonly Asset[];+ readSource: (asset: Asset) => Promise<string>;+}) => {+ const assetsByFolder = new Map<string, Asset[]>();+ for (const asset of assets) {+ if (asset.folderId === undefined) {+ continue;+ }+ const siblings = assetsByFolder.get(asset.folderId) ?? [];+ siblings.push(asset);+ assetsByFolder.set(asset.folderId, siblings);+ }+ const collections = new Map<string, ContentCollection>();+ const readCollectionSource = async (asset: Asset) => {+ if (asset.size > contentEngineLimits.hydratedFileBytes) {+ throw new ContentCollectionError(+ `Collection file "${formatAssetName(asset)}" exceeds the editing limit`+ );+ }+ try {+ return await readSource(asset);+ } catch (error) {+ if (error instanceof ContentCollectionError) {+ throw error;+ }+ throw new ContentCollectionReadError(getErrorMessage(error));+ }+ };+ for (const [folderId, siblings] of assetsByFolder) {+ const configAssets = siblings.filter(+ (asset) => formatAssetName(asset) === collectionConfigFilename+ );+ const configAsset = configAssets[0];+ if (configAsset === undefined) {+ continue;+ }+ let templateAsset: Asset | undefined;+ let reservedAssets = [...configAssets, ...siblings.filter(isMdxFileAsset)];+ let repairAsset = configAsset;+ let missingTemplateFilename: string | undefined;+ let forbiddenAsset: Asset | undefined;+ let repairAction: "edit" | "move" | undefined;+ try {+ const inspected = await inspectContentCollection({+ files: siblings.map((asset) => ({+ file: asset,+ id: asset.id,+ filename: formatAssetName(asset),+ basename: getAssetDisplayNameParts(asset).basename,+ isMdx: isMdxFileAsset(asset),+ })),+ readSource: ({ file }) => readCollectionSource(file),+ validateEntries: false,+ });+ templateAsset = inspected.templateFile.file;+ reservedAssets = [configAsset, templateAsset];+ collections.set(folderId, {+ status: "ready",+ folderId,+ configAsset,+ templateAsset,+ config: inspected.config,+ templateProperties: inspected.templateProperties,+ });+ } catch (error) {+ if (error instanceof ContentCollectionReadError) {+ collections.set(folderId, {+ status: "unavailable",+ folderId,+ configAsset,+ templateAsset,+ reservedAssets,+ siblingAssets: siblings,+ message: `Collection files could not be loaded: ${error.message}`,+ });+ continue;+ }+ if (error instanceof ContentCollectionInspectionError) {+ repairAsset =+ siblings.find((asset) => asset.id === error.fileId) ?? configAsset;+ templateAsset =+ siblings.find((asset) => asset.id === error.templateFileId) ??+ (repairAsset.id !== configAsset.id && isMdxFileAsset(repairAsset)+ ? repairAsset+ : undefined);+ if (templateAsset !== undefined) {+ const templateFilename = formatAssetName(templateAsset);+ reservedAssets = [+ configAsset,+ ...siblings.filter(+ (asset) =>+ isMdxFileAsset(asset) &&+ formatAssetName(asset) === templateFilename+ ),+ ];+ }+ missingTemplateFilename = error.missingTemplateFilename;+ forbiddenAsset =+ error.forbiddenFileId === undefined+ ? undefined+ : siblings.find((asset) => asset.id === error.forbiddenFileId);+ repairAction = error.repairAction;+ }+ collections.set(folderId, {+ status: "invalid",+ folderId,+ configAsset,+ templateAsset,+ reservedAssets,+ siblingAssets: siblings,+ repairAsset,+ missingTemplateFilename,+ forbiddenAsset,+ repairAction,+ message: getErrorMessage(error),+ });+ }+ }+ return collections;+};++const decodeUtf8 = (bytes: Uint8Array) => {+ try {+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);+ } catch {+ throw new ContentCollectionError("Collection file is not valid UTF-8");+ }+};++export const readBuilderAssetSource = async ({+ projectId,+ assetId,+}: {+ projectId: string;+ assetId: string;+}) => {+ const repository = createBuilderHttpAssetContentRepository({ projectId });+ const { bytes } = await readAssetContentBytes({+ repository,+ assetId,+ maxSize: contentEngineLimits.hydratedFileBytes,+ });+ return decodeUtf8(bytes);+};++const hasSameAssetVersion = (left: Asset, right: Asset) =>+ left.id === right.id &&+ left.projectId === right.projectId &&+ left.folderId === right.folderId &&+ left.name === right.name &&+ left.filename === right.filename &&+ left.format === right.format &&+ left.size === right.size &&+ left.updatedAt === right.updatedAt;++const hasSameAssetVersions = (+ left: readonly Asset[],+ right: readonly Asset[]+) => {+ if (left.length !== right.length) {+ return false;+ }+ const rightById = new Map(right.map((asset) => [asset.id, asset]));+ return left.every((asset) => {+ const candidate = rightById.get(asset.id);+ return candidate !== undefined && hasSameAssetVersion(asset, candidate);+ });+};++export const createLoadingContentCollections = (assets: readonly Asset[]) => {+ const assetsByFolder = new Map<string, Asset[]>();+ for (const asset of assets) {+ if (asset.folderId === undefined) {+ continue;+ }+ const siblings = assetsByFolder.get(asset.folderId) ?? [];+ siblings.push(asset);+ assetsByFolder.set(asset.folderId, siblings);+ }+ const collections = new Map<string, LoadingContentCollection>();+ for (const [folderId, siblings] of assetsByFolder) {+ const configAsset = siblings.find(+ (asset) => formatAssetName(asset) === collectionConfigFilename+ );+ if (configAsset === undefined) {+ continue;+ }+ collections.set(folderId, {+ status: "loading",+ folderId,+ configAsset,+ siblingAssets: siblings,+ });+ }+ return collections;+};++const canKeepReadyCollection = (+ current: ContentCollection,+ loading: LoadingContentCollection+) => {+ if (+ current.status !== "ready" ||+ hasSameAssetVersion(current.configAsset, loading.configAsset) === false+ ) {+ return false;+ }+ const currentTemplate = loading.siblingAssets.find(+ (asset) => asset.id === current.templateAsset.id+ );+ if (+ currentTemplate === undefined ||+ hasSameAssetVersion(current.templateAsset, currentTemplate) === false+ ) {+ return false;+ }+ const filenames = new Set<string>();+ return loading.siblingAssets.every((asset) => {+ const filename = formatAssetName(asset);+ if (+ asset.id === current.configAsset.id ||+ asset.id === current.templateAsset.id ||+ current.config.matchesEntry(filename)+ ) {+ const normalized = filename.toLowerCase();+ if (filenames.has(normalized)) {+ return false;+ }+ filenames.add(normalized);+ }+ return (+ asset.id === current.configAsset.id ||+ asset.id === current.templateAsset.id ||+ (filename !== collectionConfigFilename &&+ filename !== current.config.template &&+ (!current.config.matchesEntry(filename) || isMdxFileAsset(asset)))+ );+ });+};++const canKeepDiscoveredCollection = (+ current: ContentCollection,+ loading: LoadingContentCollection+) => {+ if (current.status === "invalid" || current.status === "unavailable") {+ return hasSameAssetVersions(current.siblingAssets, loading.siblingAssets);+ }+ return canKeepReadyCollection(current, loading);+};++export const mergeLoadingContentCollections = ({+ current,+ loading,+}: {+ current: ReadonlyMap<string, ContentCollection>;+ loading: ReadonlyMap<string, ContentCollection>;+}) => {+ const merged = new Map<string, ContentCollection>();+ for (const [folderId, next] of loading) {+ const previous = current.get(folderId);+ merged.set(+ folderId,+ next.status === "loading" &&+ previous !== undefined &&+ canKeepDiscoveredCollection(previous, next)+ ? previous+ : next+ );+ }+ return merged;+};++// Asset metadata is already synchronized into Builder. Group it once per update,+// not once per property control. Only an active collection loads file content.+const $loadingCollections = computed([$assets, $project], (assets, project) =>+ createLoadingContentCollections(+ Array.from(assets.values()).filter(+ (asset) => asset.projectId === project?.id+ )+ )+);+const $collectionProjectId = computed($project, (project) => project?.id);+const $collectionSession = computed(+ [$collectionProjectId, $authToken],+ (projectId) => {+ const discovered = atom<ReadonlyMap<string, ContentCollection>>(new Map());+ const collections = computed(+ [$loadingCollections, discovered],+ (loading, current) => mergeLoadingContentCollections({ loading, current })+ );+ const pending = new Map<string, { loading: LoadingContentCollection }>();+ const load = async (folderId: string, refresh: boolean) => {+ const loading = $loadingCollections.get().get(folderId);+ if (projectId === undefined || loading === undefined) {+ return;+ }+ if (!refresh && collections.get().get(folderId)?.status !== "loading") {+ return;+ }+ const previous = pending.get(folderId);+ if (+ !refresh &&+ previous !== undefined &&+ hasSameAssetVersions(+ previous.loading.siblingAssets,+ loading.siblingAssets+ )+ ) {+ return;+ }+ const request = { loading };+ pending.set(folderId, request);+ const result = await discoverContentCollections({+ assets: loading.siblingAssets,+ readSource: (asset) =>+ readBuilderAssetSource({ projectId, assetId: asset.id }),+ });+ if (pending.get(folderId) !== request) {+ return;+ }+ pending.delete(folderId);+ const current = $loadingCollections.get().get(folderId);+ if (+ current === undefined ||+ !hasSameAssetVersions(current.siblingAssets, loading.siblingAssets)+ ) {+ return;+ }+ const next = new Map(discovered.get());+ // Drop removed folders rather than retaining their parsed content forever.+ for (const id of next.keys()) {+ if (!$loadingCollections.get().has(id)) {+ next.delete(id);+ }+ }+ for (const [id, collection] of result) {+ next.set(id, collection);+ }+ discovered.set(next);+ };+ return { collections, load };+ }+);++export const useContentCollections = (+ activeFolderId: string | undefined,+ refreshKey = 0+) => {+ const session = useStore($collectionSession);+ const collections = useStore(session.collections);+ const previousRefresh = useRef(refreshKey);+ useEffect(() => {+ const refresh = previousRefresh.current !== refreshKey;+ previousRefresh.current = refreshKey;+ if (activeFolderId !== undefined) {+ void session.load(activeFolderId, refresh);+ }+ }, [session, collections, activeFolderId, refreshKey]);+ return collections;+};++export const getCollectionReservedAssetIds = (+ collections: ReadonlyMap<string, ContentCollection>,+ { includeInvalid = false }: { includeInvalid?: boolean } = {}+) =>+ new Set(+ Array.from(collections.values()).flatMap((collection) =>+ collection.status === "invalid" || collection.status === "unavailable"+ ? includeInvalid+ ? [...collection.reservedAssets.map(({ id }) => id)]+ : []+ : collection.status === "loading"+ ? [+ collection.configAsset.id,+ ...(includeInvalid+ ? collection.siblingAssets.flatMap((asset) =>+ formatAssetName(asset) === collectionConfigFilename ||+ isMdxFileAsset(asset)+ ? [asset.id]+ : []+ )+ : []),+ ]+ : [collection.configAsset.id, collection.templateAsset.id]+ )+ );diff --git a/apps/builder/app/builder/shared/assets/index.ts b/apps/builder/app/builder/shared/assets/index.tsindex 67dddfe1ce..80f2c32252 100644--- a/apps/builder/app/builder/shared/assets/index.ts+++ b/apps/builder/app/builder/shared/assets/index.ts@@ -4,6 +4,7 @@ export { replaceAsset } from "./replace-asset";export { uploadAssets } from "./upload-assets";export { updateAssetContent } from "./update-asset-content";export * from "./types";+export * from "./content-collections";export * from "./separator";export * from "./assets-shell";export * from "./asset-upload";diff --git a/apps/builder/app/builder/shared/assets/update-asset-content.test.ts b/apps/builder/app/builder/shared/assets/update-asset-content.test.tsindex 2f545f773a..9c89982a8b 100644--- a/apps/builder/app/builder/shared/assets/update-asset-content.test.ts+++ b/apps/builder/app/builder/shared/assets/update-asset-content.test.ts@@ -1,8 +1,17 @@import { afterEach, beforeEach, expect, test, vi } from "vitest";import { updateProjectAssetContent } from "@webstudio-is/http-client";import { $authToken } from "~/shared/nano-states";-import { $project } from "~/shared/sync/data-stores";-import { createUpdateAssetContent } from "./update-asset-content";+import { $assets, $pages, $project } from "~/shared/sync/data-stores";+import { createDefaultPages } from "@webstudio-is/project-build";+import {+ commitAssetContentUpdate,+ createUpdateAssetContent,+} from "./update-asset-content";+import {+ externalContentSyncStore,+ registerContainers,+ serverSyncStore,+} from "~/shared/sync/sync-stores";const requestContentUpdate = vi.fn<typeof updateProjectAssetContent>();const commitUpdatedAsset = vi.fn();@@ -63,6 +72,28 @@ test("commits a content revision without changing the asset id", async () => {expect(commitUpdatedAsset).toHaveBeenCalledWith(revision);});+test("shares an already saved revision without writing it to the server again", () => {+ registerContainers();+ $pages.set(createDefaultPages({ rootInstanceId: "body" }));+ $assets.set(new Map([[asset.id, asset]]));+ const serverWrite = vi.fn();+ const canvasUpdate = vi.fn();+ const unsubscribeServer = serverSyncStore.subscribe(serverWrite);+ const unsubscribeCanvas = externalContentSyncStore.subscribe(canvasUpdate);+ try {+ const revision = { ...asset, name: "settings_new.json" };+ commitAssetContentUpdate(revision);+ expect($assets.get().get(asset.id)).toEqual(revision);+ expect(canvasUpdate).toHaveBeenCalledTimes(1);+ expect(serverWrite).not.toHaveBeenCalled();+ } finally {+ unsubscribeServer();+ unsubscribeCanvas();+ $assets.set(new Map());+ $pages.set(undefined);+ }+});+test("does not commit a conflicting revision", async () => {requestContentUpdate.mockRejectedValue(new Error("File changed"));@@ -71,3 +102,23 @@ test("does not commit a conflicting revision", async () => {);expect(commitUpdatedAsset).not.toHaveBeenCalled();});++test("does not commit an updated Asset after the active project changes", async () => {+ const revision = {+ ...asset,+ name: "settings_new.json",+ size: 7,+ createdAt: "2026-07-18T00:00:00.000Z",+ };+ requestContentUpdate.mockImplementation(async () => {+ $project.set({ id: "another-project" } as never);+ return { asset: revision };+ });++ await expect(+ updateAssetContent({ asset, content: '{"a":1}' })+ ).rejects.toThrow(+ "The file was updated in the previous project. Return to that project to view it."+ );+ expect(commitUpdatedAsset).not.toHaveBeenCalled();+});diff --git a/apps/builder/app/builder/shared/assets/update-asset-content.ts b/apps/builder/app/builder/shared/assets/update-asset-content.tsindex b1d9b6cec2..fe1fdac709 100644--- a/apps/builder/app/builder/shared/assets/update-asset-content.ts+++ b/apps/builder/app/builder/shared/assets/update-asset-content.ts@@ -3,10 +3,10 @@ import { updateProjectAssetContent } from "@webstudio-is/http-client";import { fetch } from "~/shared/fetch.client";import { $authToken } from "~/shared/nano-states";import { $project } from "~/shared/sync/data-stores";-import { createTransactionFromBuilderPatchPayload } from "~/shared/sync/builder-patch";+import { createSyncChangesFromBuilderPatchPayload } from "~/shared/sync/builder-patch";import { getWebstudioData } from "~/shared/instance-utils/data";import { invalidateAssets } from "~/shared/resources";-import { onNextTransactionComplete } from "~/shared/sync/project-queue";+import { externalContentSyncStore } from "~/shared/sync/sync-stores";type UpdateAssetContentDependencies = {requestContentUpdate: typeof updateProjectAssetContent;@@ -28,6 +28,9 @@ export const createUpdateAssetContent =if (projectId === undefined) {throw new Error("Project not found");}+ if (asset.projectId !== projectId) {+ throw new Error("The file belongs to another project.");+ }const origin = window.location.origin;const { asset: updatedAsset } = await dependencies.requestContentUpdate({@@ -41,15 +44,21 @@ export const createUpdateAssetContent =request: fetch,requestOrigin: origin,});+ if ($project.get()?.id !== projectId) {+ throw new Error(+ "The file was updated in the previous project. Return to that project to view it."+ );+ }dependencies.commitUpdatedAsset(updatedAsset);return updatedAsset;};-export const updateAssetContent = createUpdateAssetContent({- requestContentUpdate: updateProjectAssetContent,- commitUpdatedAsset: (updatedAsset) => {- createTransactionFromBuilderPatchPayload({+export const commitAssetContentUpdate = (updatedAsset: Asset) => {+ // The content endpoint already saved this revision. Share it with the canvas+ // without a second server write that could restore an older revision.+ externalContentSyncStore.createTransactionFromChanges(+ createSyncChangesFromBuilderPatchPayload({data: getWebstudioData(),payload: [{@@ -63,7 +72,12 @@ export const updateAssetContent = createUpdateAssetContent({],},],- });- onNextTransactionComplete(invalidateAssets);- },+ })+ );+ invalidateAssets();+};++export const updateAssetContent = createUpdateAssetContent({+ requestContentUpdate: updateProjectAssetContent,+ commitUpdatedAsset: commitAssetContentUpdate,});diff --git a/apps/builder/app/builder/shared/assets/upload-assets.test.ts b/apps/builder/app/builder/shared/assets/upload-assets.test.tsindex ec27c21e54..9bbbc29d3a 100644--- a/apps/builder/app/builder/shared/assets/upload-assets.test.ts+++ b/apps/builder/app/builder/shared/assets/upload-assets.test.ts@@ -1,7 +1,15 @@import { beforeEach, describe, test, expect, vi } from "vitest";import { assetType, type Asset } from "@webstudio-is/sdk";+import { createAssetFolderFixture } from "@webstudio-is/sdk/testing";import type { Project } from "@webstudio-is/project";-import { $assets, $project } from "~/shared/sync/data-stores";+import { createDefaultPages } from "@webstudio-is/project-build";+import {+ $assetFolders,+ $assets,+ $pages,+ $project,+} from "~/shared/sync/data-stores";+import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";import { __testing__, importAssets } from "./upload-assets";const {@@ -9,15 +17,62 @@ const {deduplicateAssetName,getFilesData,getUniqueFilesData,+ safeSetAsset,submitAssetUpload,} = __testing__;const request = vi.fn<typeof fetch>();+registerContainers();+describe("upload-assets", () => {beforeEach(() => {request.mockReset();$project.set(undefined);+ $assetFolders.set(new Map());$assets.set(new Map());+ $pages.set(createDefaultPages({ rootInstanceId: "body" }));+ serverSyncStore.transactionManager.currentStack = [];+ serverSyncStore.transactionManager.undoneStack = [];+ serverSyncStore.popAll();+ });++ test("commits a server-validated collection template repair", () => {+ const configAsset: Asset = {+ id: "config",+ projectId: "project-id",+ name: "collection.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: 1,+ createdAt: "2026-09-06T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template.mdx",+ filename: "template",+ format: "mdx",+ };+ $project.set({ id: "project-id" } as Project);+ $assetFolders.set(+ new Map([+ [+ "posts",+ createAssetFolderFixture({+ id: "posts",+ name: "Posts",+ }),+ ],+ ])+ );+ $assets.set(new Map([[configAsset.id, configAsset]]));++ safeSetAsset(templateAsset, "project-id");++ expect($assets.get().get(templateAsset.id)).toEqual(templateAsset);});test("requests upload tickets without client-supplied asset ids", async () => {@@ -35,6 +90,7 @@ describe("upload-assets", () => {createUploadTicket({authToken: "token",projectId: "project-id",+ folderId: "folder-id",fileOrUrl: new File(["content"], "image.png", { type: "image/png" }),assetType: "image",request,@@ -52,6 +108,7 @@ describe("upload-assets", () => {];expect(init.body.has("assetId")).toBe(false);expect(init.body.get("projectId")).toBe("project-id");+ expect(init.body.get("folderId")).toBe("folder-id");expect(init.body.get("type")).toBe("image");expect(init.body.get("filename")).toBe("image.png");expect(init.body.get("displayFilename")).toBe("image");@@ -109,6 +166,48 @@ describe("upload-assets", () => {expect(init.body.get("displayFilename")).toBe("Campaign photo");});+ test("keeps collection filenames independent across folders", async () => {+ $assets.set(+ new Map([+ [+ "other-template",+ {+ id: "other-template",+ projectId: "project-id",+ name: "template-storage.mdx",+ filename: "template",+ folderId: "other-folder",+ type: "file",+ format: "mdx",+ size: 1,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ } satisfies Asset,+ ],+ ])+ );+ request.mockResolvedValue(+ Response.json({+ assetId: "new-template",+ name: "upload-name",+ deduplicated: false,+ })+ );++ await createUploadTicket({+ authToken: "token",+ projectId: "project-id",+ folderId: "new-folder",+ fileOrUrl: new File([], "template.mdx", { type: "text/mdx" }),+ assetType: "file",+ request,+ });++ const [, init] = request.mock.calls[0] as [string, { body: FormData }];+ expect(init.body.get("filename")).toBe("template.mdx");+ });+test("imports every asset type through the production upload queue", async () => {$project.set({ id: "target-project" } as Project);$assets.set(new Map());diff --git a/apps/builder/app/builder/shared/assets/upload-assets.tsx b/apps/builder/app/builder/shared/assets/upload-assets.tsxindex a4dfed5f87..0293ddc005 100644--- a/apps/builder/app/builder/shared/assets/upload-assets.tsx+++ b/apps/builder/app/builder/shared/assets/upload-assets.tsx@@ -22,7 +22,11 @@ import { $assets } from "~/shared/sync/data-stores";import { $project } from "~/shared/sync/data-stores";import { onNextTransactionComplete } from "~/shared/sync/project-queue";import { invalidateAssets } from "~/shared/resources";-import { executeRuntimeMutation } from "~/shared/instance-utils/data";+import {+ executeRuntimeMutation,+ getWebstudioData,+} from "~/shared/instance-utils/data";+import { createTransactionFromBuilderPatchPayload } from "~/shared/sync/builder-patch";import { formatAssetName } from "@webstudio-is/project-build/runtime";import {getFileName,@@ -67,9 +71,17 @@ const safeSetAsset = (asset: Asset, projectId: string) => {return;}- executeRuntimeMutation({- id: "assets.add",- input: { asset },+ // The upload API already validated and persisted this asset. Commit its+ // canonical server record directly so collection-only creation rules do not+ // reject a valid template repair while syncing it into Builder state.+ createTransactionFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: [+ {+ namespace: "assets",+ patches: [{ op: "add", path: [asset.id], value: asset }],+ },+ ],});onNextTransactionComplete(() => {@@ -300,6 +312,7 @@ const submitAssetUpload = async ({const createUploadTicket = async ({authToken,projectId,+ folderId,fileOrUrl,contentHash,deduplicate = true,@@ -308,6 +321,7 @@ const createUploadTicket = async ({}: {authToken: undefined | string;projectId: string;+ folderId?: string;fileOrUrl: File | URL;contentHash?: string;deduplicate?: boolean;@@ -317,13 +331,18 @@ const createUploadTicket = async ({const fileName = getFileName(fileOrUrl);const metaFormData = new FormData();metaFormData.append("projectId", projectId);+ if (folderId !== undefined) {+ metaFormData.append("folderId", folderId);+ }metaFormData.append("type", assetType);if (contentHash !== undefined && deduplicate) {metaFormData.append("contentHash", contentHash);}const existingNames = new Set<string>();for (const asset of $assets.get().values()) {- existingNames.add(formatAssetName(asset));+ if (asset.folderId === folderId) {+ existingNames.add(formatAssetName(asset));+ }}const deduplicatedFilename = deduplicateAssetName(fileName, existingNames);// sanitizeS3Key here is just because of https://github.com/remix-run/remix/issues/4443@@ -524,6 +543,7 @@ export const uploadAssets = async <T extends File | URL>(const ticket = await createUploadTicket({authToken,projectId,+ folderId: fileData.folderId,fileOrUrl:fileData.source === "file" ? fileData.file : new URL(fileData.url),contentHash:@@ -664,5 +684,6 @@ export const __testing__ = {deduplicateAssetName,getFilesData,getUniqueFilesData,+ safeSetAsset,submitAssetUpload,};diff --git a/apps/builder/app/builder/shared/assets/use-collection-entry-validation.test.ts b/apps/builder/app/builder/shared/assets/use-collection-entry-validation.test.tsnew file mode 100644index 0000000000..9bf1d105d7--- /dev/null+++ b/apps/builder/app/builder/shared/assets/use-collection-entry-validation.test.ts@@ -0,0 +1,128 @@+import { expect, test, vi } from "vitest";+import {+ createDefaultCollectionConfig,+ parseCollectionConfig,+} from "@webstudio-is/content-engine";+import type { Asset } from "@webstudio-is/sdk";+import type { ContentCollection } from "./content-collections";+import { checkCollectionEntries } from "./use-collection-entry-validation";++const asset = (id: string, folderId = "posts"): Asset => ({+ id,+ projectId: "project",+ name: `${id}.mdx`,+ filename: id,+ folderId,+ type: "file",+ format: "mdx",+ size: 30,+ meta: {},+ createdAt: "2026-09-08T00:00:00Z",+});+const collection: Extract<ContentCollection, { status: "ready" }> = {+ status: "ready",+ folderId: "posts",+ configAsset: asset("collection"),+ templateAsset: asset("template"),+ templateProperties: {},+ config: parseCollectionConfig(createDefaultCollectionConfig()),+};++test("checks only direct entries, reuses revisions and clears repaired field errors", async () => {+ const assets = [+ asset("post"),+ asset("template"),+ asset("nested", "child"),+ { ...asset("image"), name: "image.png" },+ ];+ const cache = new Map();+ const readFrontmatter = vi.fn(async () => ({ title: "", slug: "post" }));+ const input = {+ collection,+ assets,+ cache,+ readFrontmatter,+ cancelled: () => false,+ };+ const issues = await checkCollectionEntries(input);+ expect([...issues.keys()]).toEqual(["post"]);+ expect(issues.get("post")?.[0].fieldKey).toBe("title");+ expect(readFrontmatter).toHaveBeenCalledTimes(1);+ await checkCollectionEntries(input);+ expect(readFrontmatter).toHaveBeenCalledTimes(1);+ readFrontmatter.mockResolvedValue({ title: "Fixed", slug: "post" });+ expect(+ (+ await checkCollectionEntries({+ ...input,+ assets: [{ ...assets[0], name: "revision.mdx" }],+ })+ ).size+ ).toBe(0);+ expect(readFrontmatter).toHaveBeenCalledTimes(2);+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.title.minLength = 20;+ const changed = {+ ...collection,+ config: parseCollectionConfig(JSON.stringify(schema)),+ };+ expect(+ (+ await checkCollectionEntries({+ ...input,+ collection: changed,+ assets: [{ ...assets[0], name: "revision.mdx" }],+ })+ ).get("post")?.[0].fieldKey+ ).toBe("title");+ expect(readFrontmatter).toHaveBeenCalledTimes(2);+});++test("keeps a read failure local to its entry and retries it", async () => {+ const readFrontmatter = vi.fn(async (file: Asset) => {+ if (file.id === "broken") {+ throw new Error("Network failed");+ }+ return { title: "Good", slug: file.id };+ });+ const input = {+ collection,+ assets: [asset("broken"), asset("good")],+ cache: new Map(),+ readFrontmatter,+ cancelled: () => false,+ };+ expect([...(await checkCollectionEntries(input)).keys()]).toEqual(["broken"]);+ readFrontmatter.mockImplementation(async (file) => ({+ title: "Fixed",+ slug: file.id,+ }));+ expect((await checkCollectionEntries(input)).size).toBe(0);+ expect(readFrontmatter).toHaveBeenCalledTimes(3);+});++test("stops scheduling after cancellation and discards late results", async () => {+ let finish: () => void = () => {};+ const pending = new Promise<void>((resolve) => {+ finish = resolve;+ });+ let cancelled = false;+ const readFrontmatter = vi.fn(async () => {+ await pending;+ return {};+ });+ const cache = new Map();+ const result = checkCollectionEntries({+ collection,+ assets: Array.from({ length: 8 }, (_, id) => asset(String(id))),+ cache,+ readFrontmatter,+ cancelled: () => cancelled,+ });+ expect(readFrontmatter).toHaveBeenCalledTimes(4);+ cancelled = true;+ finish();+ expect((await result).size).toBe(0);+ expect(cache.size).toBe(0);+ expect(readFrontmatter).toHaveBeenCalledTimes(4);+});diff --git a/apps/builder/app/builder/shared/assets/use-collection-entry-validation.ts b/apps/builder/app/builder/shared/assets/use-collection-entry-validation.tsnew file mode 100644index 0000000000..046bf015af--- /dev/null+++ b/apps/builder/app/builder/shared/assets/use-collection-entry-validation.ts@@ -0,0 +1,171 @@+import { useEffect, useRef, useState } from "react";+import { useStore } from "@nanostores/react";+import {+ contentEngineLimits,+ extractMarkdownFrontmatter,+ getCollectionEntryValidationIssues,+} from "@webstudio-is/content-engine";+import {+ formatAssetName,+ getAssetDisplayNameParts,+ type Asset,+} from "@webstudio-is/sdk";+import { $assets } from "~/shared/sync/data-stores";+import type { ContentCollection } from "./content-collections";+import { createBuilderHttpAssetContentRepository } from "./builder-mdx-content-repository.client";++export type CollectionEntryIssue = {+ fieldKey?: string;+ message: string;+};+type CachedFrontmatter = {+ name: string;+ properties: Readonly<Record<string, unknown>>;+};++export const checkCollectionEntries = async ({+ collection,+ assets,+ cache,+ readFrontmatter,+ cancelled,+}: {+ collection: Extract<ContentCollection, { status: "ready" }>;+ assets: readonly Asset[];+ cache: Map<string, CachedFrontmatter>;+ readFrontmatter: (asset: Asset) => Promise<Readonly<Record<string, unknown>>>;+ cancelled: () => boolean;+}) => {+ const issues = new Map<string, readonly CollectionEntryIssue[]>();+ const entries = assets.filter(+ (asset) =>+ asset.folderId === collection.folderId &&+ collection.config.matchesEntry(formatAssetName(asset))+ );+ const remaining = entries.values();+ const worker = async () => {+ for (const asset of remaining) {+ if (cancelled()) {+ return;+ }+ try {+ const cached = cache.get(asset.id);+ const properties =+ cached?.name === asset.name+ ? cached.properties+ : await readFrontmatter(asset);+ if (cancelled()) {+ return;+ }+ cache.set(asset.id, { name: asset.name, properties });+ const entryIssues = getCollectionEntryValidationIssues({+ config: collection.config,+ properties,+ basename: getAssetDisplayNameParts(asset).basename,+ });+ if (entryIssues.length > 0) {+ issues.set(asset.id, entryIssues);+ }+ } catch {+ if (cancelled()) {+ return;+ }+ issues.set(asset.id, [+ {+ message:+ "This entry could not be checked. Open the file to inspect it or retry the check.",+ },+ ]);+ }+ }+ };+ await Promise.all(+ Array.from({ length: Math.min(4, entries.length) }, worker)+ );+ if (cancelled()) {+ return issues;+ }+ const entryIds = new Set(entries.map((asset) => asset.id));+ for (const id of cache.keys()) {+ if (!entryIds.has(id)) {+ cache.delete(id);+ }+ }+ return issues;+};++export const useCollectionEntryValidation = (+ collection: ContentCollection | undefined+) => {+ const assets = useStore($assets);+ const folderId = collection?.folderId;+ const projectId = collection?.configAsset.projectId;+ const cacheRef = useRef({+ folderId,+ projectId,+ entries: new Map<string, CachedFrontmatter>(),+ });+ if (+ cacheRef.current.folderId !== folderId ||+ cacheRef.current.projectId !== projectId+ ) {+ cacheRef.current = { folderId, projectId, entries: new Map() };+ }+ const cache = cacheRef.current.entries;+ const [refresh, setRefresh] = useState(0);+ const [result, setResult] = useState<{+ collection: ContentCollection;+ assets: typeof assets;+ issues: Map<string, readonly CollectionEntryIssue[]>;+ }>();+ useEffect(() => {+ let cancelled = false;+ if (collection?.status !== "ready" || projectId === undefined) {+ return;+ }+ const repository = createBuilderHttpAssetContentRepository({ projectId });+ void checkCollectionEntries({+ collection,+ assets: Array.from(assets.values()),+ cache,+ cancelled: () => cancelled,+ readFrontmatter: async (asset) => {+ if (asset.size === 0) {+ return {};+ }+ const content = await repository.readContent({+ assetId: asset.id,+ range: {+ offset: 0,+ length: Math.min(+ asset.size,+ // Include delimiters, CRLF and an optional UTF-8 BOM.+ contentEngineLimits.frontmatterBytes + 16+ ),+ },+ });+ const { properties } = await extractMarkdownFrontmatter(content.data);+ if (content.asset.name !== asset.name) {+ throw new Error("Entry changed during validation");+ }+ return properties;+ },+ }).then((issues) => {+ if (!cancelled) {+ setResult({ collection, assets, issues });+ }+ });+ return () => {+ cancelled = true;+ };+ }, [assets, cache, collection, projectId, refresh]);+ return {+ issues:+ result !== undefined &&+ result.collection === collection &&+ result.assets === assets+ ? result.issues+ : undefined,+ retry: () => setRefresh((value) => value + 1),+ };+};diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsxindex 25f969457b..a994787862 100644--- a/apps/builder/app/builder/shared/binding-popover.tsx+++ b/apps/builder/app/builder/shared/binding-popover.tsx@@ -14,6 +14,7 @@ import {TrashIcon,} from "@webstudio-is/icons";import {+ PanelContent,Box,Button,cssVar,@@ -31,6 +32,7 @@ import {SmallIconButton,Text,Tooltip,+ InputErrorsTooltip,theme,} from "@webstudio-is/design-system";import { getExpressionIdentifiers } from "@webstudio-is/expression";@@ -101,7 +103,7 @@ const BindingPanel = ({}}><Box css={{ paddingBottom: theme.spacing[5] }}>- <Flex gap="1" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="1"><Text variant="labels">Variables</Text><Tooltipvariant="wrapped"@@ -109,9 +111,12 @@ const BindingPanel = ({"Click on the available variables in this scope to insert them into the Expression Editor."}>- <InfoCircleIcon tabIndex={0} />+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ /></Tooltip>- </Flex>+ </PanelContent>{scopeEntries.length === 0 && (<Flex justify="center" align="center" css={{ py: theme.spacing[5] }}><Text variant="labels" align="center">@@ -154,7 +159,7 @@ const BindingPanel = ({</CssValueListArrowFocus></ScrollAreaNative></Box>- <Flex gap="1" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="1"><Text variant="labels">Expression editor</Text><Tooltipvariant="wrapped"@@ -168,31 +173,38 @@ const BindingPanel = ({</Text>}>- <InfoCircleIcon tabIndex={0} />+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ /></Tooltip>- </Flex>- <Box css={{ padding: theme.panel.padding, pt: 0 }}>- <ExpressionEditor- editorApiRef={editorApiRef}- scope={scope}- aliases={aliases}- color={- (touched && errorsCount > 0) || valueError !== undefined- ? "error"- : undefined- }- autoFocus={true}- value={expression}- onChange={(value) => {- updateExpression(value);- setTouched(false);- }}- onChangeComplete={() => {- onSave(expression, errorsCount > 0);- setTouched(true);- }}- />- </Box>+ </PanelContent>+ <PanelContent as={Box} css={{ pt: 0 }}>+ <InputErrorsTooltip+ errors={valueError === undefined ? undefined : [valueError]}+ >+ <ExpressionEditor+ editorApiRef={editorApiRef}+ scope={scope}+ aliases={aliases}+ color={+ (touched && errorsCount > 0) || valueError !== undefined+ ? "error"+ : undefined+ }+ autoFocus={true}+ value={expression}+ onChange={(value) => {+ updateExpression(value);+ setTouched(false);+ }}+ onChangeComplete={() => {+ onSave(expression, errorsCount > 0);+ setTouched(true);+ }}+ />+ </InputErrorsTooltip>+ </PanelContent></ScrollArea>);};diff --git a/apps/builder/app/builder/shared/client-settings/settings.ts b/apps/builder/app/builder/shared/client-settings/settings.tsindex 18a7551e76..4080bbf15a 100644--- a/apps/builder/app/builder/shared/client-settings/settings.ts+++ b/apps/builder/app/builder/shared/client-settings/settings.ts@@ -14,6 +14,7 @@ const userSettings = z.object({.partialRecord(z.enum(sidebarPanelNames), z.number()).default({}),lastDashboardSearch: z.string().default(""),+ lastAssetFolderIds: z.record(z.string(), z.string()).default({}),colorScheme: z.enum(colorSchemePreferences).default("system"),});const persistedUserSettings = userSettings.omit({ colorScheme: true });diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex b80152bd9a..ec3cca0d30 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -36,8 +36,10 @@ import { $instances } from "~/shared/sync/data-stores";import {externalContentInstanceNameMessage,getExternalContentRoots,+ findExternalContentRootEntryBySelector,isExternalContentInstance,} from "~/shared/external-content-mutations";+import { traverseExternalContentHistory } from "~/shared/external-content-roots";// Declare command for type safetydeclare module "~/shared/pubsub" {@@ -176,6 +178,35 @@ const guardDesignOrContentModeCommand = ({const hasMultiInstanceSelection = () =>$allSelectedInstanceSelectors.get().length > 1;+const traverseSelectedContentHistory = (direction: "undo" | "redo") => {+ const selector = $selectedInstancePath.get()?.[0]?.instanceSelector;+ if (selector === undefined) {+ return false;+ }+ const roots = getExternalContentRoots();+ const root = findExternalContentRootEntryBySelector(roots, selector)?.[1];+ if (+ root?.projectId === undefined ||+ root.assetId === undefined ||+ ($isContentMode.get() === false &&+ isExternalContentInstance(roots, selector[0]) === false &&+ root.contentInstanceId !== selector[0])+ ) {+ return false;+ }+ void traverseExternalContentHistory({+ projectId: root.projectId,+ direction,+ }).catch((error) => {+ toast.error(+ error instanceof Error+ ? error.message+ : "Unable to restore the article edit."+ );+ });+ return true;+};+const copyPageActionTarget = () => {if ($isDesignMode.get() === false) {return false;@@ -1157,7 +1188,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({defaultHotkeys: ["meta+z", "ctrl+z"],disableOnInputLikeControls: true,handler: () => {- serverSyncStore.undo();+ if (traverseSelectedContentHistory("undo") === false) {+ serverSyncStore.undo();+ }},},{@@ -1168,7 +1201,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({defaultHotkeys: ["meta+shift+z", "ctrl+shift+z"],disableOnInputLikeControls: true,handler: () => {- serverSyncStore.redo();+ if (traverseSelectedContentHistory("redo") === false) {+ serverSyncStore.redo();+ }},},diff --git a/apps/builder/app/builder/shared/css-editor/css-editor.tsx b/apps/builder/app/builder/shared/css-editor/css-editor.tsxindex 0d55ce210c..dc6f474651 100644--- a/apps/builder/app/builder/shared/css-editor/css-editor.tsx+++ b/apps/builder/app/builder/shared/css-editor/css-editor.tsx@@ -11,6 +11,7 @@ import {} from "react";import { matchSorter } from "match-sorter";import {+ PanelContent,Box,Flex,Label,@@ -543,9 +544,9 @@ export const CssEditor = ({return (<Box css={{ isolation: "isolate" }}>{showSearch && (- <Box+ <PanelContent+ as={Box}css={{- padding: theme.panel.padding,position: "sticky",top: 0,background: cssVar("--background-primary"),@@ -557,7 +558,7 @@ export const CssEditor = ({onChange={handleSearch}onAbort={handleAbortSearch}/>- </Box>+ </PanelContent>)}<CssEditorContextMenuonPaste={handleInsertStyles}diff --git a/apps/builder/app/builder/shared/css-variable-utils.tsx b/apps/builder/app/builder/shared/css-variable-utils.tsxindex dd4d58d5d2..8824bc015f 100644--- a/apps/builder/app/builder/shared/css-variable-utils.tsx+++ b/apps/builder/app/builder/shared/css-variable-utils.tsx@@ -2,6 +2,7 @@ import { useState, useEffect } from "react";import { atom, computed } from "nanostores";import { useStore } from "@nanostores/react";import {+ PanelContent,Dialog,DialogActions,DialogContent,@@ -182,9 +183,9 @@ export const DeleteCssVariableDialog = ({}}><DialogTitle>Delete confirmation</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column"><Text>{`Delete CSS variable "${cssVariable?.property}" from the project?`}</Text>- </Flex>+ </PanelContent><DialogActions><ButtonautoFocus@@ -256,7 +257,7 @@ export const RenameCssVariableDialog = ({}}><DialogTitle>Rename CSS variable</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column"><Flex direction="column" gap="1"><InputFieldvalue={name}@@ -272,7 +273,7 @@ export const RenameCssVariableDialog = ({</Text>)}</Flex>- </Flex>+ </PanelContent><DialogActions><Button color="primary" onClick={handleConfirm}>Rename@@ -297,7 +298,7 @@ const DeleteUnusedCssVariablesDialogContent = ({return (<>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column">{unusedVariablesArray.length === 0 ? (<Text>There are no unused CSS variables to delete.</Text>) : (@@ -321,7 +322,7 @@ const DeleteUnusedCssVariablesDialogContent = ({</Text></>)}- </Flex>+ </PanelContent><DialogActions>{unusedVariablesArray.length > 0 && (<Buttondiff --git a/apps/builder/app/builder/shared/data-variable-utils.tsx b/apps/builder/app/builder/shared/data-variable-utils.tsxindex 14091594a7..4c0210e07f 100644--- a/apps/builder/app/builder/shared/data-variable-utils.tsx+++ b/apps/builder/app/builder/shared/data-variable-utils.tsx@@ -1,7 +1,7 @@import { useState, useEffect } from "react";import { atom } from "nanostores";import { useStore } from "@nanostores/react";-import { toast } from "@webstudio-is/design-system";+import { PanelContent, toast } from "@webstudio-is/design-system";import {Dialog,DialogActions,@@ -65,14 +65,14 @@ export const DeleteDataVariableDialog = ({}}><DialogTitle>Delete confirmation</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column"><Text>{variable &&(variable.usages > 0? `Delete "${variable.name}" variable from the project? It is used in ${variable.usages} ${variable.usages === 1 ? "expression" : "expressions"}.`: `Delete "${variable.name}" variable from the project?`)}</Text>- </Flex>+ </PanelContent><DialogActions><ButtonautoFocus@@ -201,7 +201,7 @@ export const RenameDataVariableDialog = ({}}><DialogTitle>Rename variable</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column"><Flex direction="column" gap="1"><InputFieldvalue={name}@@ -217,7 +217,7 @@ export const RenameDataVariableDialog = ({</Text>)}</Flex>- </Flex>+ </PanelContent><DialogActions><Button color="primary" onClick={handleConfirm}>Rename@@ -270,7 +270,7 @@ export const DeleteUnusedDataVariablesDialog = () => {}}><DialogTitle>Delete unused data variables</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column">{unusedVariables.length === 0 ? (<Text>There are no unused data variables to delete.</Text>) : (@@ -294,7 +294,7 @@ export const DeleteUnusedDataVariablesDialog = () => {</Text></>)}- </Flex>+ </PanelContent><DialogActions>{unusedVariables.length > 0 && (<Buttondiff --git a/apps/builder/app/builder/shared/instance-context-menu.test.ts b/apps/builder/app/builder/shared/instance-context-menu.test.tsindex 33f1d41f70..2809da49f7 100644--- a/apps/builder/app/builder/shared/instance-context-menu.test.ts+++ b/apps/builder/app/builder/shared/instance-context-menu.test.ts@@ -387,6 +387,7 @@ describe("getMenuPermissions", () => {});expect(permissions).toMatchObject({+ canMove: true,canCopy: true,canPaste: true,canCut: false,@@ -422,8 +423,8 @@ describe("getMenuPermissions", () => {isContentMode: true,isDesignMode: false,instances,- }).canDelete- ).toBe(false);+ })+ ).toMatchObject({ canDelete: false, canMove: false });});test("content mode keeps multi-copy available but disables single-instance and mutation actions", () => {diff --git a/apps/builder/app/builder/shared/instance-context-menu.tsx b/apps/builder/app/builder/shared/instance-context-menu.tsxindex 077ce26e74..2eef2caa0e 100644--- a/apps/builder/app/builder/shared/instance-context-menu.tsx+++ b/apps/builder/app/builder/shared/instance-context-menu.tsx@@ -30,6 +30,7 @@ import {} from "~/shared/nano-states";import {getInstancePath,+ canMoveInstanceInContentMode,type InstancePath,} from "@webstudio-is/project-build/runtime";import { canDeleteInstanceInContentMode } from "@webstudio-is/project-build/runtime";@@ -94,12 +95,22 @@ const getMenuPermissions = ({});if (isContentMode) {+ const instanceSelector = instancePath?.[0]?.instanceSelector;+ const parentSelector = instancePath?.[1]?.instanceSelector;return {canCopy: hasActionableSelection,canPaste: hasActionableSelection,canCut: false,canDuplicate: false,- canMove: false,+ canMove:+ canUseSingleSelectionActions &&+ instanceSelector !== undefined &&+ parentSelector !== undefined &&+ canMoveInstanceInContentMode({+ instanceSelector,+ parentSelector,+ instances,+ }),canHide: false,canRename: false,canWrap: false,diff --git a/apps/builder/app/builder/shared/query-builder.test.tsx b/apps/builder/app/builder/shared/query-builder.test.tsxindex 51787d3d78..10887b045a 100644--- a/apps/builder/app/builder/shared/query-builder.test.tsx+++ b/apps/builder/app/builder/shared/query-builder.test.tsx@@ -1,6 +1,11 @@import { act } from "react-dom/test-utils";import { createRoot, type Root } from "react-dom/client";-import { afterEach, expect, test } from "vitest";+import { afterEach, expect, test, vi } from "vitest";+import { userEvent } from "@vitest/browser/context";+import {+ $commandMetas,+ createCommandsEmitter,+} from "~/shared/commands-emitter";import type { QueryDefinition } from "@webstudio-is/query-builder";import { encodeDataSourceVariable, type DataSource } from "@webstudio-is/sdk";import { $dataSources } from "~/shared/sync/data-stores";@@ -53,58 +58,86 @@ const renderQueryBuilder = <Query extends Record<string, unknown>>({return container;};-test("shows public variable names without changing the stored expression", () => {- const value = {- where: {- all: [+test.each(["Backspace", "Delete"])(+ "protects a bound filter from the %s instance shortcut",+ async (key) => {+ const value = {+ where: {+ all: [+ {+ field: ["path"],+ operator: "eq",+ value: "$ws$system.pathname",+ },+ ],+ },+ };+ const capabilities = {+ version: 1,+ fields: [{ path: ["path"], label: "Path", types: ["string"] }],+ operators: [{- field: ["path"],- operator: "eq",- value: "$ws$system.pathname",+ value: "eq",+ label: "Equals",+ types: ["string"],+ input: { control: "expression", defaultValue: '""' },},],- },- };- const capabilities = {- version: 1,- fields: [{ path: ["path"], label: "Path", types: ["string"] }],- operators: [- {- value: "eq",- label: "Equals",- types: ["string"],- input: { control: "expression", defaultValue: '""' },- },- ],- source: {- fieldPathSchema: {- type: "array",- items: { type: "string" },- minItems: 1,+ source: {+ fieldPathSchema: {+ type: "array",+ items: { type: "string" },+ minItems: 1,+ },+ controls: [+ {+ type: "filter",+ key: "where",+ label: "Filters",+ defaultValue: { all: [] },+ combinators: ["all"],+ limits: { conditions: 8, depth: 3 },+ defaultCondition: { field: ["path"], operator: "eq" },+ },+ ],},- controls: [+ } as const satisfies QueryDefinition<string, string>;++ const container = renderQueryBuilder({ value, capabilities });+ const editor = container.querySelector(".cm-content");+ const source = Array.from(container.querySelectorAll(".cm-content")).at(-1);++ expect(editor?.textContent).toBe('"/blog/article"');+ expect(source?.textContent).toContain("system.pathname");+ expect(source?.textContent).not.toContain("$ws$system.pathname");+ expect(value.where.all[0].value).toBe("$ws$system.pathname");+ const handler = vi.fn();+ const previousCommands = $commandMetas.get();+ const { subscribeCommands } = createCommandsEmitter({+ source: "builder",+ commands: [{- type: "filter",- key: "where",- label: "Filters",- defaultValue: { all: [] },- combinators: ["all"],- limits: { conditions: 8, depth: 3 },- defaultCondition: { field: ["path"], operator: "eq" },+ name: "deleteTestInstance",+ defaultHotkeys: [key],+ disableOnInputLikeControls: true,+ handler,},],- },- } as const satisfies QueryDefinition<string, string>;-- const container = renderQueryBuilder({ value, capabilities });- const editor = container.querySelector(".cm-content");- const source = Array.from(container.querySelectorAll(".cm-content")).at(-1);-- expect(editor?.textContent).toBe('"/blog/article"');- expect(source?.textContent).toContain("system.pathname");- expect(source?.textContent).not.toContain("$ws$system.pathname");- expect(value.where.all[0].value).toBe("$ws$system.pathname");-});+ });+ const unsubscribe = subscribeCommands();+ try {+ await userEvent.click(editor as HTMLElement);+ await userEvent.keyboard(`{${key}}`);+ expect(handler).not.toHaveBeenCalled();+ (editor as HTMLElement).blur();+ await userEvent.keyboard(`{${key}}`);+ expect(handler).toHaveBeenCalledOnce();+ } finally {+ unsubscribe();+ $commandMetas.set(previousCommands);+ }+ }+);test("shows an evaluated value for a bound number input", () => {const capabilities = {diff --git a/apps/builder/app/builder/shared/style-source-actions.tsx b/apps/builder/app/builder/shared/style-source-actions.tsxindex 734c8f9218..0d1ae3a66c 100644--- a/apps/builder/app/builder/shared/style-source-actions.tsx+++ b/apps/builder/app/builder/shared/style-source-actions.tsx@@ -2,6 +2,7 @@ import { useState, useEffect } from "react";import { atom, computed } from "nanostores";import { useStore } from "@nanostores/react";import {+ PanelContent,Dialog,DialogActions,DialogContent,@@ -148,9 +149,9 @@ export const DeleteStyleSourceDialog = ({}}><DialogTitle>Delete confirmation</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column"><Text>{`Delete "${styleSource?.name}" token from the project including all of its styles?`}</Text>- </Flex>+ </PanelContent><DialogActions><ButtonautoFocus@@ -226,7 +227,7 @@ export const RenameStyleSourceDialog = ({}}><DialogTitle>Rename token</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column"><Flex direction="column" gap="1"><InputFieldvalue={name}@@ -242,7 +243,7 @@ export const RenameStyleSourceDialog = ({</Text>)}</Flex>- </Flex>+ </PanelContent><DialogActions><Button color="primary" onClick={handleConfirm}>Rename@@ -290,7 +291,7 @@ export const DeleteUnusedTokensDialog = () => {}}><DialogTitle>Delete unused tokens</DialogTitle>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column">{unusedTokens.length === 0 ? (<Text>There are no unused tokens to delete.</Text>) : (@@ -314,7 +315,7 @@ export const DeleteUnusedTokensDialog = () => {</Text></>)}- </Flex>+ </PanelContent><DialogActions>{unusedTokens.length > 0 && (<Buttondiff --git a/apps/builder/app/canvas/features/text-editor/interop.test.tsx b/apps/builder/app/canvas/features/text-editor/interop.test.tsxindex a9ba5e3520..03cd1cb6f5 100644--- a/apps/builder/app/canvas/features/text-editor/interop.test.tsx+++ b/apps/builder/app/canvas/features/text-editor/interop.test.tsx@@ -270,3 +270,134 @@ test("convert lexical formatting to plain text content", async () => {},]);});++test.each([+ ["strong", "bold"],+ ["em", "italic"],+ ["del", "strikethrough"],+ ["code", "code"],+] as const)(+ "keeps MDX %s text and formatting when editing",+ async (tag, format) => {+ const { instances } = renderData(+ <ws.element ws:tag="p" ws:id="paragraph">+ Before{" "}+ <ws.element ws:tag={tag} ws:id="inline">+ original+ </ws.element>{" "}+ after+ </ws.element>+ );+ const refs: Refs = new Map();+ const editor = createHeadlessEditor({ nodes: [LinkNode] });+ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ $convertToLexical(instances, "paragraph", refs);+ },+ { onUpdate: resolve }+ );+ });+ editor.getEditorState().read(() => {+ expect($getRoot().getTextContent()).toBe("Before original after");+ const text = $getRoot()+ .getAllTextNodes()+ .find((node) => node.getTextContent() === "original")!;+ expect(text.hasFormat(format)).toBe(true);+ });+ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ $getRoot()+ .getAllTextNodes()+ .find((node) => node.getTextContent() === "original")!+ .setTextContent("edited");+ },+ { onUpdate: resolve }+ );+ });+ expect(+ editor+ .getEditorState()+ .read(() =>+ $convertToUpdates(+ instances.get("paragraph")!,+ refs,+ new Map(),+ () => "new"+ )+ )+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="p" ws:id="paragraph">+ {"Before "}+ <ws.element ws:tag={tag} ws:id="inline">+ edited+ </ws.element>+ {" after"}+ </ws.element>+ ).instances+ );+ }+);++test.each(["em", "strong", "span"])(+ "preserves text and a nested link inside %s across edits",+ async (tag) => {+ const { instances } = renderData(+ <ws.element ws:tag="p" ws:id="paragraph">+ <ws.element ws:tag={tag} ws:id="wrapper">+ {"Before "}+ <ws.element ws:tag="a" ws:id="link">+ linked text+ </ws.element>+ {" after."}+ </ws.element>+ </ws.element>+ );+ const refs: Refs = new Map();+ const editor = createHeadlessEditor({ nodes: [LinkNode] });+ await new Promise<void>((resolve) => {+ editor.update(() => $convertToLexical(instances, "paragraph", refs), {+ onUpdate: resolve,+ });+ });+ expect(+ editor.getEditorState().read(() => $getRoot().getTextContent())+ ).toBe("Before linked text after.");+ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ $getRoot()+ .getAllTextNodes()+ .find((node) => node.getTextContent() === "linked text")!+ .setTextContent("edited link");+ },+ { onUpdate: resolve }+ );+ });+ let id = 0;+ const updates = editor+ .getEditorState()+ .read(() =>+ $convertToUpdates(+ instances.get("paragraph")!,+ refs,+ new Map(),+ () => `new-${++id}`+ )+ );+ const expected = renderTemplate(+ <ws.element ws:tag="p" ws:id="paragraph">+ <ws.element ws:tag={tag} ws:id="wrapper">+ {"Before "}+ <ws.element ws:tag="a" ws:id="link">+ edited link+ </ws.element>+ {" after."}+ </ws.element>+ </ws.element>+ ).instances;+ expect(updates).toEqual(expected);+ }+);diff --git a/apps/builder/app/canvas/features/text-editor/interop.ts b/apps/builder/app/canvas/features/text-editor/interop.tsindex 214036d9d2..b0735f6ac1 100644--- a/apps/builder/app/canvas/features/text-editor/interop.ts+++ b/apps/builder/app/canvas/features/text-editor/interop.ts@@ -1,12 +1,12 @@import {type TextNode,type ElementNode,+ type TextFormatType,$getRoot,$createTextNode,$createParagraphNode,$createLineBreakNode,$isTextNode,- $isElementNode,$isParagraphNode,$isLineBreakNode,} from "lexical";@@ -30,10 +30,12 @@ const legacyLexicalFormats = [] as const;const elementLexicalFormats = [- ["bold", "b"],- ["italic", "i"],+ ["bold", "b", "strong"],+ ["italic", "i", "em"],["superscript", "sup"],["subscript", "sub"],+ ["strikethrough", "del"],+ ["code", "code"],] as const;const $writeUpdates = (@@ -43,8 +45,60 @@ const $writeUpdates = (refs: Refs,newLinkKeyToInstanceId: Refs,createId: CreateId,- transientTextNodeKeys: ReadonlySet<string>+ transientTextNodeKeys: ReadonlySet<string>,+ inheritedFormats: ReadonlySet<string> = new Set()) => {+ const wrapFormats = (child: TextNode | ElementNode) => {+ let parentUpdates = instanceChildren;+ const formats = new Set(inheritedFormats);+ const textNodes = $isTextNode(child) ? [child] : child.getAllTextNodes();+ const candidates = [["span", "span"], ...elementLexicalFormats] as const;+ for (const [format, defaultTag, ...aliases] of candidates) {+ if (formats.has(format)) {+ continue;+ }+ const alias = aliases.find((tag) => refs.has(`${child.getKey()}:${tag}`));+ const key = `${child.getKey()}:${alias ?? format}`;+ if (!$isTextNode(child) && !refs.has(key)) {+ continue;+ }+ if (+ textNodes.length === 0 ||+ !textNodes.every((text) =>+ format === "span" ? $isSpanNode(text) : text.hasFormat(format)+ )+ ) {+ continue;+ }+ let id = refs.get(key) ?? createId();+ const previous = parentUpdates.at(-1);+ const existing = instancesList.find((instance) => instance.id === id);+ if (+ previous?.type === "id" &&+ previous.value === id &&+ existing !== undefined+ ) {+ parentUpdates = existing.children;+ } else {+ if (existing !== undefined) {+ id = createId();+ }+ const instance: Instance = {+ type: "instance",+ id,+ component: elementComponent,+ tag: alias ?? defaultTag,+ children: [],+ };+ refs.set(key, id);+ instancesList.push(instance);+ parentUpdates.push({ type: "id", value: id });+ parentUpdates = instance.children;+ }+ formats.add(format);+ }+ return { parentUpdates, formats };+ };const children = node.getChildren();for (const child of children) {if ($isParagraphNode(child)) {@@ -62,10 +116,11 @@ const $writeUpdates = (instanceChildren.push({ type: "text", value: "\n" });}if ($isLinkNode(child)) {+ const { parentUpdates, formats } = wrapFormats(child);const key = child.getKey();const id = refs.get(key) ?? newLinkKeyToInstanceId.get(key) ?? createId();refs.set(key, id);- instanceChildren.push({+ parentUpdates.push({type: "id",value: id,});@@ -77,7 +132,8 @@ const $writeUpdates = (refs,newLinkKeyToInstanceId,createId,- transientTextNodeKeys+ transientTextNodeKeys,+ formats);instancesList.push({type: "instance",@@ -95,41 +151,7 @@ const $writeUpdates = (// considering lexical represents both as single node// and add ref suffix to distinct styling on one node keyconst text = child.getTextContent();- let parentUpdates = instanceChildren;- if ($isSpanNode(child)) {- // prematurely generate span id to select it right after applying- const key = `${child.getKey()}:span`;- const id = refs.get(key) ?? createId();- refs.set(key, id);- const childChildren: Instance["children"] = [];- instancesList.push({- type: "instance",- id,- component: elementComponent,- tag: "span",- children: childChildren,- });- parentUpdates.push({ type: "id", value: id });- parentUpdates = childChildren;- }- // convert all lexical formats- for (const [format, tag] of elementLexicalFormats) {- if (child.hasFormat(format)) {- const key = `${child.getKey()}:${format}`;- const id = refs.get(key) ?? createId();- refs.set(key, id);- const childInstance: Instance = {- type: "instance",- id,- component: elementComponent,- tag,- children: [],- };- instancesList.push(childInstance);- parentUpdates.push({ type: "id", value: id });- parentUpdates = childInstance.children;- }- }+ const { parentUpdates } = wrapFormats(child);parentUpdates.push({ type: "text", value: text });}}@@ -169,26 +191,37 @@ export const $convertToPlainTextUpdate = (treeRootInstance: Instance) => [},];+type InlineFormat = {+ format: TextFormatType | "span";+ suffix: string;+ id: string;+};+const $writeLexical = (- parent: ElementNode | TextNode,+ parent: ElementNode,children: Instance["children"],instances: Instances,- refs: Refs+ refs: Refs,+ formats: InlineFormat[] = []) => {for (const child of children) {if (child.type === "text") {// convert text- if (child.value === "\n" && $isElementNode(parent)) {+ if (child.value === "\n") {const lineBreakNode = $createLineBreakNode();parent.append(lineBreakNode);continue;}- if ($isTextNode(parent)) {- parent.setTextContent(child.value);- } else {- const textNode = $createTextNode(child.value);- parent.append(textNode);+ const textNode = $createTextNode(child.value);+ for (const { format, suffix, id } of formats) {+ if (format === "span") {+ $setNodeSpan(textNode);+ } else if (!textNode.hasFormat(format)) {+ textNode.toggleFormat(format);+ }+ refs.set(`${textNode.getKey()}:${suffix}`, id);}+ parent.append(textNode);continue;}@@ -201,55 +234,46 @@ const $writeLexical = (const isLinkInstance =instance.component === "RichTextLink" ||(instance.component === elementComponent && instance.tag === "a");- if (isLinkInstance && $isElementNode(parent)) {+ if (isLinkInstance) {const linkNode = $createLinkNode("");refs.set(linkNode.getKey(), instance.id);+ for (const { suffix, id } of formats) {+ refs.set(`${linkNode.getKey()}:${suffix}`, id);+ }parent.append(linkNode);- $writeLexical(linkNode, instance.children, instances, refs);+ $writeLexical(linkNode, instance.children, instances, refs, formats);+ continue;}if (instance.component === "Span" ||(instance.component === elementComponent && instance.tag === "span")) {- let textNode;- if ($isTextNode(parent)) {- textNode = parent;- } else {- textNode = $createTextNode("");- parent.append(textNode);- }- $setNodeSpan(textNode);- refs.set(`${textNode.getKey()}:span`, instance.id);- $writeLexical(textNode, instance.children, instances, refs);+ $writeLexical(parent, instance.children, instances, refs, [+ ...formats,+ { format: "span", suffix: "span", id: instance.id },+ ]);+ continue;}// convert all lexical formatsfor (const [format, component] of legacyLexicalFormats) {if (instance.component === component) {- let textNode;- if ($isTextNode(parent)) {- textNode = parent;- } else {- textNode = $createTextNode("");- parent.append(textNode);- }- textNode.toggleFormat(format);- refs.set(`${textNode.getKey()}:${format}`, instance.id);- $writeLexical(textNode, instance.children, instances, refs);+ $writeLexical(parent, instance.children, instances, refs, [+ ...formats,+ { format, suffix: format, id: instance.id },+ ]);}}// convert all lexical formats- for (const [format, tag] of elementLexicalFormats) {- if (instance.component === elementComponent && instance.tag === tag) {- let textNode;- if ($isTextNode(parent)) {- textNode = parent;- } else {- textNode = $createTextNode("");- parent.append(textNode);- }- textNode.toggleFormat(format);- refs.set(`${textNode.getKey()}:${format}`, instance.id);- $writeLexical(textNode, instance.children, instances, refs);+ for (const [format, tag, ...aliases] of elementLexicalFormats) {+ const alias = aliases.find((tag) => instance.tag === tag);+ if (+ instance.component === elementComponent &&+ (instance.tag === tag || alias !== undefined)+ ) {+ $writeLexical(parent, instance.children, instances, refs, [+ ...formats,+ { format, suffix: alias ?? format, id: instance.id },+ ]);}}}diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.test.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.test.tsxindex 4fa631817a..3b5add8376 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.test.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.test.tsx@@ -2,6 +2,8 @@ import { act } from "react-dom/test-utils";import { createRoot, type Root } from "react-dom/client";import { afterEach, describe, expect, test, vi } from "vitest";import { ContentEditable } from "@lexical/react/LexicalContentEditable";+import { userEvent } from "@vitest/browser/context";+import { renderData, renderTemplate, ws } from "@webstudio-is/template";import {blockComponent,blockTemplateComponent,@@ -83,6 +85,68 @@ afterEach(() => {});describe("TextEditor", () => {+ test("saves edits to text containing a formatted link on blur", async () => {+ const { instances } = renderData(+ <ws.element ws:id="paragraph" ws:tag="p">+ <ws.element ws:id="emphasis" ws:tag="em">+ {"Before "}+ <ws.element ws:id="link" ws:tag="a" ws:label="Link">+ linked text+ </ws.element>+ {" after."}+ </ws.element>+ </ws.element>+ );+ $instances.set(instances);+ selectInstance(["paragraph"]);+ $textEditingInstanceSelector.set({+ selector: ["paragraph"],+ reason: "left",+ });+ const onChange = vi.fn();+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () => {+ root?.render(+ <TextEditor+ rootInstanceSelector={["paragraph"]}+ instances={instances}+ props={new Map()}+ contentEditable={<ContentEditable />}+ onChange={onChange}+ onSelectInstance={() => {}}+ />+ );+ });+ const editable = container.querySelector<HTMLElement>(+ "[data-lexical-editor]"+ )!;+ expect(editable.textContent).toBe("Before linked text after.");+ expect(editable.querySelector("a")?.getAttribute("data-ws-id")).toBe(+ "link"+ );+ await act(async () => {+ await userEvent.type(editable, " edited");+ editable.blur();+ });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange.mock.calls[0]?.[0]).toEqual(+ renderTemplate(+ <ws.element ws:id="paragraph" ws:tag="p">+ <ws.element ws:id="emphasis" ws:tag="em">+ {"Before "}+ <ws.element ws:id="link" ws:tag="a" ws:label="Link">+ linked text+ </ws.element>+ {" after."}+ </ws.element>+ {" edited"}+ </ws.element>+ ).instances+ );+ });+test("focuses the editable element when initializing a new empty instance", async () => {const instance: Instance = {type: "instance",@@ -122,57 +186,70 @@ describe("TextEditor", () => {);});- test("does not save the active slash-menu trigger on blur", async () => {- const instances = createContentBlockInstances();- $instances.set(instances);- selectInstance(["current", "block"]);- $textEditingInstanceSelector.set({- selector: ["current", "block"],- reason: "left",- });- const onChange = vi.fn();- const container = document.createElement("div");- document.body.appendChild(container);- root = createRoot(container);+ test.each(["element", "window"])(+ "saves text without the slash trigger on %s blur",+ async (target) => {+ const instances = createContentBlockInstances();+ $instances.set(instances);+ selectInstance(["current", "block"]);+ $textEditingInstanceSelector.set({+ selector: ["current", "block"],+ reason: "left",+ });+ const onChange = vi.fn();+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);- await act(async () => {- root?.render(- <TextEditor- rootInstanceSelector={["current", "block"]}- instances={instances}- props={new Map()}- contentEditable={<ContentEditable />}- onChange={onChange}- onSelectInstance={() => {}}- />- );- });+ await act(async () => {+ root?.render(+ <TextEditor+ rootInstanceSelector={["current", "block"]}+ instances={instances}+ props={new Map()}+ contentEditable={<ContentEditable />}+ onChange={onChange}+ onSelectInstance={() => {}}+ />+ );+ });- const editable = container.querySelector<HTMLElement>(- "[data-lexical-editor]"- );- await act(async () => {- editable?.dispatchEvent(- new KeyboardEvent("keydown", { key: "/", bubbles: true })+ const editable = container.querySelector<HTMLElement>(+ "[data-lexical-editor]"+ );+ await act(async () => {+ if (target === "window") {+ await userEvent.type(editable!, " edited");+ } else {+ editable?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "/", bubbles: true })+ );+ }+ });+ expect(editable?.textContent).toBe(+ target === "window" ? "Before edited" : "Before/");- });- expect(editable?.textContent).toBe("Before/");- expect($textEditorContextMenu.get()).toMatchObject({- replaceAnchor: false,- });- await act(async () => {- editable?.dispatchEvent(new FocusEvent("blur"));- });+ await act(async () => {+ (target === "window" ? window : editable)?.dispatchEvent(+ new FocusEvent("blur")+ );+ });- expect(onChange).toHaveBeenCalledTimes(1);- expect(onChange.mock.calls[0]?.[0]).toContainEqual(- expect.objectContaining({- id: "current",- children: [{ type: "text", value: "Before" }],- })- );- });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange.mock.calls[0]?.[0]).toContainEqual(+ expect.objectContaining({+ id: "current",+ children: [+ {+ type: "text",+ value: target === "window" ? "Before edited" : "Before",+ },+ ],+ })+ );+ }+ );test("does not save an editor after its instance was replaced", async () => {const instances = createContentBlockInstances();diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsxindex f7fb147f5a..960e5a470c 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx@@ -135,6 +135,9 @@ const BindInstanceToNodePlugin = ({for (const [nodeKey, instanceId] of refs) {// extract key from stored key:style formatconst [key] = nodeKey.split(":");+ if (nodeKey !== key && refs.has(key)) {+ continue;+ }const element = editor.getElementByKey(key);if (element) {element.setAttribute(idAttribute, instanceId);@@ -217,7 +220,10 @@ const isChrome = () =>const OnChangeOnBlurPlugin = ({onChange,}: {- onChange: (editorState: EditorState, reason: "blur" | "unmount") => void;+ onChange: (+ editorState: EditorState,+ reason: "blur" | "window-blur" | "unmount"+ ) => void;}) => {const [editor] = useLexicalComposerContext();const handleChange = useEffectEvent(onChange);@@ -255,6 +261,21 @@ const OnChangeOnBlurPlugin = ({[editor]);+ useEffect(() => {+ // Leaving the canvas iframe does not blur its active editable element.+ // Save without ending editing so toolbar actions can keep the selection.+ const handleWindowBlur = () => {+ if ($textEditorContextMenu.get() !== undefined) {+ return;+ }+ editor.read(() => {+ handleChange(editor.getEditorState(), "window-blur");+ });+ };+ window.addEventListener("blur", handleWindowBlur);+ return () => window.removeEventListener("blur", handleWindowBlur);+ }, [editor]);+useEffect(() => {const handleBlur = () => {// force read to get the latest state@@ -1626,7 +1647,10 @@ export const TextEditor = ({const [newLinkKeyToInstanceId] = useState(() => new Map());const handleChange = useEffectEvent(- (editorState: EditorState, reason: "blur" | "unmount" | "next") => {+ (+ editorState: EditorState,+ reason: "blur" | "window-blur" | "unmount" | "next"+ ) => {const currentInstances = $instances.get();const treeRootInstance = currentInstances.get(rootInstanceSelector[0]);// Replacing a content block child unmounts its editor after the instance@@ -1652,7 +1676,12 @@ export const TextEditor = ({builderRuntimeContext.createId,transientTextNodeKeys);- const idMap = onChange(updates);+ const idMap = onChange(+ updates.map((instance) => ({+ ...currentInstances.get(instance.id),+ ...instance,+ }))+ );if (idMap !== undefined) {for (const [key, instanceId] of refs) {refs.set(key, idMap[instanceId] ?? instanceId);diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex 7281b9b9e1..fadb8d1c44 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -1,3 +1,4 @@+import { parseError } from "~/shared/error/error-parse";import {useEffect,forwardRef,@@ -98,7 +99,7 @@ import {} from "~/shared/external-content-mutations";import {getSelectedContentBlockDocumentBindingPath,- isObjectPathWritable,+ getFrontmatterWriteTarget,} from "~/shared/content-block-document";import {formatContentBlockDiagnostic,@@ -877,10 +878,12 @@ const WebstudioComponentCanvasInner = forwardRef<return;}if (- isObjectPathWritable({+ getFrontmatterWriteTarget({+ assetId: externalRoot.assetId ?? "",+ sources: externalRoot.frontmatterSources,value: externalRoot.document.frontmatter.properties,path: frontmatterPath,- }) === false+ }) === undefined) {toast.error("Open the referenced file to edit this value.");return;@@ -894,11 +897,7 @@ const WebstudioComponentCanvasInner = forwardRef<path: frontmatterPath,value,}).catch((error) => {- toast.error(- error instanceof Error- ? error.message- : "Unable to update MDX frontmatter"- );+ toast.error(parseError(error).message);});return;}diff --git a/apps/builder/app/dashboard/dashboard.tsx b/apps/builder/app/dashboard/dashboard.tsxindex f4c98b7cea..24b1defb42 100644--- a/apps/builder/app/dashboard/dashboard.tsx+++ b/apps/builder/app/dashboard/dashboard.tsx@@ -7,7 +7,6 @@ import {Text,TooltipProvider,Toaster,- css,theme,PanelBanner,Link,@@ -16,7 +15,8 @@ import {Grid,IconButton,cssVar,- selectedItemBackground,+ InsetList,+ InsetListItem,} from "@webstudio-is/design-system";import { BodyIcon } from "@webstudio-is/icons";import {@@ -90,24 +90,6 @@ const CloneProject = ({}};-const sidebarLinkStyle = css({- all: "unset",- cursor: "pointer",- display: "flex",- alignItems: "center",- gap: theme.spacing[5],- height: theme.spacing[13],- paddingInline: theme.panel.paddingInline,- outline: "none",- "&:focus-visible, &:hover": {- background: cssVar("--overlay-interaction-hover"),- },- "&[aria-current=page]": {- background: selectedItemBackground,- color: cssVar("--foreground-primary"),- },-});-const NavigationItems = ({items,}: {@@ -124,7 +106,7 @@ const NavigationItems = ({return (<List asChild>- <Box>+ <InsetList>{items.map((item, index) => {const to =workspaceId && item.target === undefined@@ -133,21 +115,18 @@ const NavigationItems = ({return (<ListItem asChild index={index} key={index}>- <NavLink- to={to}- end- target={item.target}- className={sidebarLinkStyle()}- >- {item.prefix}- <Text variant="labels" color="main">- {item.children}- </Text>- </NavLink>+ <InsetListItem asChild>+ <NavLink to={to} end target={item.target}>+ {item.prefix}+ <Text variant="labels" color="main">+ {item.children}+ </Text>+ </NavLink>+ </InsetListItem></ListItem>);})}- </Box>+ </InsetList></List>);};diff --git a/apps/builder/app/dashboard/projects/project-card.tsx b/apps/builder/app/dashboard/projects/project-card.tsxindex dc8cde9a76..3dd7e27c90 100644--- a/apps/builder/app/dashboard/projects/project-card.tsx+++ b/apps/builder/app/dashboard/projects/project-card.tsx@@ -1,5 +1,6 @@import { useEffect, useState } from "react";import {+ PanelContent,css,Flex,Text,@@ -26,7 +27,10 @@ import type { User } from "~/shared/db/user.server";import { ProjectMenu } from "./project-menu";import { formatDate } from "./utils";-const infoIconStyle = css({ flexShrink: 0, opacity: 0.8 });+const infoIconStyle = css({+ flexShrink: 0,+ color: cssVar("--foreground-secondary"),+});const prefetchImageBackground = declareCssVar("--project-card-prefetch-image-background");@@ -140,12 +144,12 @@ export const ProjectCard = ({opacity: 0,}}/>- <Flex+ <PanelContent+ as={Flex}wrap="wrap"gap={1}css={{position: "absolute",- padding: theme.panel.padding,bottom: 0,zIndex: 1,}}@@ -166,7 +170,7 @@ export const ProjectCard = ({);}})}- </Flex>+ </PanelContent>{previewImageAsset ? (<ThumbnailLinkWithImage to={linkPath} name={previewImageAsset.name} />) : (diff --git a/apps/builder/app/dashboard/projects/projects-list.tsx b/apps/builder/app/dashboard/projects/projects-list.tsxindex b078fa2eda..0c99ec603d 100644--- a/apps/builder/app/dashboard/projects/projects-list.tsx+++ b/apps/builder/app/dashboard/projects/projects-list.tsx@@ -7,6 +7,8 @@ import {css,List,ListItem,+ InsetList,+ InsetListItem,IconButton,cssVar,} from "@webstudio-is/design-system";@@ -19,61 +21,54 @@ import { ProjectMenu } from "./project-menu";import { formatDate } from "./utils";import type { SortField, SortOrder } from "./sort";+const projectColumns =+ "minmax(0, 35fr) repeat(3, minmax(0, 20fr)) minmax(0, 5fr)";+const tableStyles = css({- display: "table",+ display: "grid",+ alignContent: "start",width: "100%",- tableLayout: "fixed",- borderCollapse: "collapse",marginBottom: theme.spacing[13],minWidth: 550,flexGrow: 1,'& [role="rowgroup"]': {- display: "table-row-group",+ display: "grid",},'& [role="row"]': {- display: "table-row",+ display: "grid",+ gridTemplateColumns: projectColumns,+ alignItems: "center",position: "relative",- "&:focus-visible": {- outline: `1px solid ${cssVar("--border-focus")}`,- },- '&:has([role="cell"]):hover': {- background: cssVar("--overlay-interaction-hover"),- },+ },++ "& [data-projects-header]": {+ marginInline: theme.spacing[3],},'& [role="columnheader"]': {- display: "table-cell",padding: theme.spacing[5],paddingBottom: theme.spacing[3],textAlign: "left",borderBottom: `1px solid ${cssVar("--border-default")}`,- "&:first-child": {- width: "35%",- },- "&:nth-child(2), &:nth-child(3), &:nth-child(4)": {- width: "20%",- },- "&:last-child": {- width: "5%",- },},'& [role="cell"]': {- display: "table-cell",padding: theme.spacing[5],- verticalAlign: "middle",+ minWidth: 0,},});type ProjectsListItemProps = {+ index: number;project: DashboardProject;publisherHost: string;projectsTags: User["projectsTags"];};export const ProjectsListItem = ({+ index,project: {id,title,@@ -103,60 +98,62 @@ export const ProjectsListItem = ({return (<>- <ListItem index={0} asChild>- <div role="row">- <div role="cell">- <Flex direction="column" gap="1">- <Link- href={linkPath}- color="inherit"- underline="none"- tabIndex={-1}- stretched- >- {title}- </Link>- {isPublished && (+ <ListItem index={index} asChild>+ <InsetListItem asChild css={{ padding: 0 }}>+ <div role="row">+ <div role="cell">+ <Flex direction="column" gap="1"><Link- href={`https://${displayDomain}`}- target="_blank"- rel="noreferrer"- color="subtle"- underline="hover"+ href={linkPath}+ color="inherit"+ underline="none"tabIndex={-1}- aria-label={`Visit ${title} website at ${displayDomain}`}- css={{ zIndex: 1 }}+ stretched>- {displayDomain}+ {title}</Link>- )}- </Flex>- </div>+ {isPublished && (+ <Link+ href={`https://${displayDomain}`}+ target="_blank"+ rel="noreferrer"+ color="subtle"+ underline="hover"+ tabIndex={-1}+ aria-label={`Visit ${title} website at ${displayDomain}`}+ css={{ zIndex: 1 }}+ >+ {displayDomain}+ </Link>+ )}+ </Flex>+ </div>- <div role="cell">- <Text color="subtle">- {latestBuildVirtual?.updatedAt- ? formatDate(latestBuildVirtual.updatedAt)- : formatDate(createdAt)}- </Text>- </div>+ <div role="cell">+ <Text color="subtle">+ {latestBuildVirtual?.updatedAt+ ? formatDate(latestBuildVirtual.updatedAt)+ : formatDate(createdAt)}+ </Text>+ </div>- <div role="cell">- <Text color="subtle">- {isPublished && latestBuildVirtual- ? formatDate(latestBuildVirtual.createdAt)- : "Not published"}- </Text>- </div>+ <div role="cell">+ <Text color="subtle">+ {isPublished && latestBuildVirtual+ ? formatDate(latestBuildVirtual.createdAt)+ : "Not published"}+ </Text>+ </div>- <div role="cell">- <Text color="subtle">{formatDate(createdAt)}</Text>- </div>+ <div role="cell">+ <Text color="subtle">{formatDate(createdAt)}</Text>+ </div>- <div role="cell">- <ProjectMenu projectId={id} onOpenChange={setOpenDialog} />+ <div role="cell">+ <ProjectMenu projectId={id} onOpenChange={setOpenDialog} />+ </div></div>- </div>+ </InsetListItem></ListItem><ProjectDialogs@@ -202,7 +199,7 @@ export const ProjectsList = ({<List asChild><div role="rowgroup"><ListItem index={0} asChild>- <div role="row">+ <div role="row" data-projects-header>{columns.map((column, index) => (<div role="columnheader" key={index}>{column ? (@@ -242,16 +239,17 @@ export const ProjectsList = ({</List><List asChild>- <div role="rowgroup">- {projects.map((project) => (+ <InsetList role="rowgroup">+ {projects.map((project, index) => (<ProjectsListItemkey={project.id}+ index={index}project={project}publisherHost={publisherHost}projectsTags={projectsTags}/>))}- </div>+ </InsetList></List></div>);diff --git a/apps/builder/app/dashboard/projects/tags.tsx b/apps/builder/app/dashboard/projects/tags.tsxindex 1ef7ddbaee..014503d71e 100644--- a/apps/builder/app/dashboard/projects/tags.tsx+++ b/apps/builder/app/dashboard/projects/tags.tsx@@ -2,6 +2,7 @@ import { useRevalidator, useSearchParams } from "react-router-dom";import { useState, type ComponentProps } from "react";import { createId } from "@webstudio-is/sdk";import {+ PanelContent,Text,theme,Dialog,@@ -59,9 +60,9 @@ const DeleteConfirmationDialog = ({}}><DialogContent>- <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} gap="3" direction="column"><Text>{question}</Text>- </Flex>+ </PanelContent><DialogActions><DialogClose><Button@@ -252,7 +253,7 @@ const TagEdit = ({onComplete();}}>- <Grid css={{ padding: theme.panel.padding }}>+ <PanelContent as={Grid}><InputFieldautoFocusdefaultValue={tag.label}@@ -260,7 +261,7 @@ const TagEdit = ({placeholder="My tag"minLength={1}/>- </Grid>+ </PanelContent><DialogActions><Button color="primary" type="submit">{isExisting ? "Update tag" : "Create tag"}diff --git a/apps/builder/app/dashboard/workspace/transfer-project-dialog.tsx b/apps/builder/app/dashboard/workspace/transfer-project-dialog.tsxindex 63a938bf94..36d9d4dcac 100644--- a/apps/builder/app/dashboard/workspace/transfer-project-dialog.tsx+++ b/apps/builder/app/dashboard/workspace/transfer-project-dialog.tsx@@ -1,6 +1,7 @@import { useEffect, useRef, useState } from "react";import { useRevalidator, useSearchParams } from "@remix-run/react";import {+ PanelContent,Button,Flex,Label,@@ -230,11 +231,7 @@ export const TransferProjectDialog = ({<Dialog open={isOpen} onOpenChange={onOpenChange}><DialogContent><Flex direction="column" css={{ width: theme.spacing[32] }}>- <Flex- direction="column"- gap="3"- css={{ padding: theme.panel.padding }}- >+ <PanelContent as={Flex} direction="column" gap="3"><DialogDescription asChild><Text as="p">Move “{title}” to another workspace, or transfer it@@ -263,7 +260,7 @@ export const TransferProjectDialog = ({</Text>) : undefined}</Flex>- </Flex>+ </PanelContent><div className={orSeparatorStyle()}><Text color="subtle" variant="tiny">@@ -271,11 +268,7 @@ export const TransferProjectDialog = ({</Text></div>- <Flex- direction="column"- gap="3"- css={{ padding: theme.panel.padding }}- >+ <PanelContent as={Flex} direction="column" gap="3"><Flex direction="column" gap="1"><Label htmlFor="transfer-email">Recipient</Label><SearchField@@ -303,7 +296,7 @@ export const TransferProjectDialog = ({selector above to move it.</Text>)}- </Flex>+ </PanelContent></Flex><DialogTitle>Transfer project</DialogTitle>diff --git a/apps/builder/app/routes/rest.assets.collection-folders.tsx b/apps/builder/app/routes/rest.assets.collection-folders.tsxnew file mode 100644index 0000000000..f1276fd789--- /dev/null+++ b/apps/builder/app/routes/rest.assets.collection-folders.tsx@@ -0,0 +1,42 @@+import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";+import { z } from "zod";+import { assetFolderId, assetFolderName } from "@webstudio-is/sdk/schema";+import { ensureApiCsrf } from "~/services/api-auth.server";+import {+ assetRestErrorResponse,+ assetRestMethodNotAllowed,+ createAssetRestRepository,+ readAssetRestJson,+} from "~/services/asset-rest.server";+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";++const collectionFolderCreateRequest = z.strictObject({+ id: assetFolderId,+ name: assetFolderName,+ parentId: assetFolderId.optional(),+});++export const loader = async () =>+ assetRestMethodNotAllowed([{ method: "post" }]);++export const action = async ({ request }: ActionFunctionArgs) => {+ preventCrossOriginCookie(request);+ if (request.method.toLowerCase() !== "post") {+ return assetRestMethodNotAllowed([{ method: "post" }]);+ }+ await ensureApiCsrf(request);+ try {+ const result = await (+ await createAssetRestRepository(request, "build")+ ).createCollectionFolder(+ collectionFolderCreateRequest.parse(await readAssetRestJson(request))+ );+ return json(result, {+ status: 201,+ headers: privateNoStoreResponseHeaders,+ });+ } catch (error) {+ return assetRestErrorResponse(error);+ }+};diff --git a/apps/builder/app/routes/rest.assets.folders.$folderId.collection-settings.tsx b/apps/builder/app/routes/rest.assets.folders.$folderId.collection-settings.tsxnew file mode 100644index 0000000000..7365744058--- /dev/null+++ b/apps/builder/app/routes/rest.assets.folders.$folderId.collection-settings.tsx@@ -0,0 +1,59 @@+import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";+import isValidFilename from "valid-filename";+import { z } from "zod";+import { contentEngineLimits } from "@webstudio-is/content-engine";+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";+import { ensureApiCsrf } from "~/services/api-auth.server";+import {+ assetRestErrorResponse,+ assetRestMethodNotAllowed,+ createAssetRestRepository,+ parseAssetRestIdentifier,+ readAssetRestJson,+} from "~/services/asset-rest.server";+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";++const requestSchema = z.object({+ configAssetId: z.string().min(1),+ expectedConfigName: z.string().min(1),+ templateAssetId: z.string().min(1),+ expectedTemplateFilename: z.string().nullable(),+ templateFilename: z+ .string()+ .min(1)+ .max(assetResourceLimits.assetFilenameCharacters)+ .refine((value) => isValidFilename(`${value}.mdx`)),+ configSource: z.string().min(1),+});++const collectionSettingsRequestBytes =+ contentEngineLimits.jsonBytes * 2 ++ assetResourceLimits.restMutationRequestBytes;++export const loader = async () =>+ assetRestMethodNotAllowed([{ method: "post" }]);++export const action = async ({ request, params }: ActionFunctionArgs) => {+ preventCrossOriginCookie(request);+ if (request.method.toLowerCase() !== "post") {+ return assetRestMethodNotAllowed([{ method: "post" }]);+ }+ await ensureApiCsrf(request);+ try {+ const folderId = parseAssetRestIdentifier(params.folderId);+ const { expectedTemplateFilename, ...input } = requestSchema.parse(+ await readAssetRestJson(request, collectionSettingsRequestBytes)+ );+ const assets = await (+ await createAssetRestRepository(request, "build")+ ).updateCollectionConfigAndTemplateName({+ folderId,+ ...input,+ expectedTemplateFilename: expectedTemplateFilename ?? undefined,+ });+ return json(assets, { headers: privateNoStoreResponseHeaders });+ } catch (error) {+ return assetRestErrorResponse(error);+ }+};diff --git a/apps/builder/app/routes/rest.assets.folders.$folderId.entries.tsx b/apps/builder/app/routes/rest.assets.folders.$folderId.entries.tsxnew file mode 100644index 0000000000..49e8d94a94--- /dev/null+++ b/apps/builder/app/routes/rest.assets.folders.$folderId.entries.tsx@@ -0,0 +1,43 @@+import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";+import { z } from "zod";+import { ensureApiCsrf } from "~/services/api-auth.server";+import {+ assetRestErrorResponse,+ assetRestMethodNotAllowed,+ createAssetRestRepository,+ parseAssetRestIdentifier,+ readAssetRestJson,+} from "~/services/asset-rest.server";+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";++const requestSchema = z.object({+ values: z.record(z.string(), z.json()),+ requestId: z.uuid().optional(),+});++export const loader = async () =>+ assetRestMethodNotAllowed([{ method: "post" }]);++export const action = async ({ request, params }: ActionFunctionArgs) => {+ preventCrossOriginCookie(request);+ if (request.method.toLowerCase() !== "post") {+ return assetRestMethodNotAllowed([{ method: "post" }]);+ }+ await ensureApiCsrf(request);+ try {+ const folderId = parseAssetRestIdentifier(params.folderId);+ const { values, requestId } = requestSchema.parse(+ await readAssetRestJson(request)+ );+ const asset = await (+ await createAssetRestRepository(request, "edit")+ ).createCollectionEntry({ folderId, values, requestId });+ return json(+ { asset },+ { status: 201, headers: privateNoStoreResponseHeaders }+ );+ } catch (error) {+ return assetRestErrorResponse(error);+ }+};diff --git a/apps/builder/app/services/api-build.server.test.ts b/apps/builder/app/services/api-build.server.test.tsindex 16f0ba78af..948579a172 100644--- a/apps/builder/app/services/api-build.server.test.ts+++ b/apps/builder/app/services/api-build.server.test.ts@@ -242,6 +242,10 @@ describe("api build patch commits", () => {expect(patchBuild).toHaveBeenNthCalledWith(1,{+ assetStore: expect.objectContaining({+ readFile: expect.any(Function),+ uploadFile: expect.any(Function),+ }),buildId: "build",projectId: "project",clientVersion: 1,@@ -252,6 +256,10 @@ describe("api build patch commits", () => {expect(patchBuild).toHaveBeenNthCalledWith(2,{+ assetStore: expect.objectContaining({+ readFile: expect.any(Function),+ uploadFile: expect.any(Function),+ }),buildId: "build",projectId: "project",clientVersion: 1,diff --git a/apps/builder/app/services/api-build.server.ts b/apps/builder/app/services/api-build.server.tsindex d2096160c7..db1d63ed0e 100644--- a/apps/builder/app/services/api-build.server.ts+++ b/apps/builder/app/services/api-build.server.ts@@ -15,6 +15,7 @@ import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import { serializePages } from "@webstudio-is/project-migrations/pages";import { assertApiProjectPermit } from "./api-permits.server";import { throwApiError } from "./api-errors.server";+import { createAssetClient } from "~/shared/asset-client";export const loadBuildByProjectVersion = async (ctx: AppContext,@@ -162,6 +163,7 @@ export const commitBuildTransactions = async ({projectId,clientVersion,transactions,+ assetStore: createAssetClient(),},ctx);diff --git a/apps/builder/app/services/asset-rest.server.test.ts b/apps/builder/app/services/asset-rest.server.test.tsindex e199c341c5..9a7709b859 100644--- a/apps/builder/app/services/asset-rest.server.test.ts+++ b/apps/builder/app/services/asset-rest.server.test.ts@@ -9,6 +9,8 @@ import { assetFolders } from "@webstudio-is/sdk";import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";import { assetResourceApiOperations } from "@webstudio-is/protocol/asset-resource-api";import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";+import { MarkdownMetadataError } from "@webstudio-is/content-engine";+import { ByteLimitExceededError } from "@webstudio-is/content-engine/compiler";import {AssetRestRangeError,AssetRestPayloadTooLargeError,@@ -31,9 +33,14 @@ describe("Assets REST responses", () => {[new TRPCError({ code: "FORBIDDEN" }), 403],[new AssetRepositoryNotFoundError("missing"), 404],[new AssetRepositoryConflictError("conflict"), 409],+ [+ new MarkdownMetadataError("FRONTMATTER_INVALID", "invalid frontmatter"),+ 409,+ ],[new AssetUploadCountLimitError(50), 409],[new AssetRestRangeError("bad range"), 416],[new AssetRestPayloadTooLargeError("too large"), 413],+ [new ByteLimitExceededError(), 413],[new AssetUploadSizeLimitError("post.md", 10), 413],])("maps domain errors to HTTP status", async (error, status) => {const response = assetRestErrorResponse(error);@@ -120,6 +127,25 @@ describe("Assets REST responses", () => {).rejects.toBeInstanceOf(AssetRestPayloadTooLargeError);});+ test("accepts a larger explicit JSON limit for internal asset operations", async () => {+ const body = JSON.stringify({+ configSource: "x".repeat(assetResourceLimits.restMutationRequestBytes),+ });++ await expect(+ readAssetRestJson(+ new Request("https://example.com/rest/assets", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body,+ }),+ new TextEncoder().encode(body).byteLength+ )+ ).resolves.toEqual({+ configSource: "x".repeat(assetResourceLimits.restMutationRequestBytes),+ });+ });+test("rejects malformed UTF-8 in JSON bodies", async () => {const prefix = new TextEncoder().encode('{"description":"');const suffix = new TextEncoder().encode('"}');diff --git a/apps/builder/app/services/asset-rest.server.ts b/apps/builder/app/services/asset-rest.server.tsindex 1dc42a72f8..298bd5b7fa 100644--- a/apps/builder/app/services/asset-rest.server.ts+++ b/apps/builder/app/services/asset-rest.server.ts@@ -1,9 +1,14 @@import { json } from "@remix-run/server-runtime";import {+ ContentCollectionError,+ MarkdownMetadataError,readBoundedRequestBytes,RequestByteLimitError,} from "@webstudio-is/content-engine";-import { decodeUtf8 } from "@webstudio-is/content-engine/compiler";+import {+ ByteLimitExceededError,+ decodeUtf8,+} from "@webstudio-is/content-engine/compiler";import {AssetRepositoryConflictError,AssetRepositoryNotFoundError,@@ -36,12 +41,12 @@ export const requireAssetRestBody = (request: Request) => {return request.body;};-const readAssetRestBody = async (request: Request) => {+const readAssetRestBody = async (+ request: Request,+ maximumBytes = assetResourceLimits.restMutationRequestBytes+) => {try {- return await readBoundedRequestBytes(- request,- assetResourceLimits.restMutationRequestBytes- );+ return await readBoundedRequestBytes(request, maximumBytes);} catch (error) {if (error instanceof RequestByteLimitError) {throw new AssetRestPayloadTooLargeError(@@ -53,8 +58,11 @@ const readAssetRestBody = async (request: Request) => {}};-export const readAssetRestJson = async (request: Request) => {- const bytes = await readAssetRestBody(request);+export const readAssetRestJson = async (+ request: Request,+ maximumBytes = assetResourceLimits.restMutationRequestBytes+) => {+ const bytes = await readAssetRestBody(request, maximumBytes);try {return JSON.parse(decodeUtf8(bytes)) as unknown;} catch (error) {@@ -185,6 +193,8 @@ const getAssetRestErrorStatus = (error: unknown) => {}if (error instanceof AssetRepositoryConflictError ||+ error instanceof ContentCollectionError ||+ error instanceof MarkdownMetadataError ||error instanceof AssetRevisionConflictError ||error instanceof AssetUploadCountLimitError) {@@ -203,6 +213,7 @@ const getAssetRestErrorStatus = (error: unknown) => {}if (error instanceof AssetRestPayloadTooLargeError ||+ error instanceof ByteLimitExceededError ||error instanceof AssetUploadSizeLimitError) {return 413;diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.tsindex c687e6e78d..a8cedc85b7 100644--- a/apps/builder/app/services/build-router.server.ts+++ b/apps/builder/app/services/build-router.server.ts@@ -50,7 +50,10 @@ import {commitBuildTransactions,} from "./api-build.server";import { assertApiProjectPermit } from "./api-permits.server";-import { getContentDatabasePublishDiagnostics } from "./content-database.server";+import {+ getContentDatabasePublishDiagnostics,+ getMdxTemplatePublishDiagnostics,+} from "./content-database.server";const projectBundleInput = z.object({projectId: z.string(),@@ -302,9 +305,11 @@ export const buildRouter = router({"You don't have permission to edit this project.");}- return getContentDatabasePublishDiagnostics(- await loadProjectBundleByProjectId(input.projectId, ctx)- );+ const bundle = await loadProjectBundleByProjectId(input.projectId, ctx);+ return {+ ...getContentDatabasePublishDiagnostics(bundle),+ mdxOmissions: await getMdxTemplatePublishDiagnostics(bundle),+ };}),checkProjectBuildPermission: procedurediff --git a/apps/builder/app/services/content-database.server.test.ts b/apps/builder/app/services/content-database.server.test.tsindex a4466a1a89..c73c119a9a 100644--- a/apps/builder/app/services/content-database.server.test.ts+++ b/apps/builder/app/services/content-database.server.test.ts@@ -6,9 +6,106 @@ import {createAssetIndex,createCanonicalAssetFileEntry,} from "@webstudio-is/content-engine/compiler";-import { getContentDatabasePublishDiagnostics } from "./content-database.server";+import {+ getContentDatabasePublishDiagnostics,+ getMdxTemplatePublishDiagnostics,+} from "./content-database.server";describe("content database publish diagnostics", () => {+ test("reports the file and template omitted from a published page", async () => {+ const bundle = createPublishedProjectBundleFixture();+ const rootId = bundle.build.pages.pages[0].rootInstanceId;+ bundle.build.instances = [+ [+ rootId,+ {+ id: rootId,+ type: "instance",+ component: "ws:block",+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ id: "templates",+ type: "instance",+ component: "ws:block-template",+ children: [],+ },+ ],+ ];+ bundle.build.props = [+ [+ "source",+ {+ id: "source",+ instanceId: rootId,+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ ];+ bundle.assets = [+ {+ id: "article",+ projectId: bundle.build.projectId,+ name: "revision.mdx",+ filename: "post",+ type: "file",+ format: "mdx",+ size: 11,+ meta: {},+ createdAt: "2026-09-08T00:00:00Z",+ },+ ];+ bundle.assetIndex = {+ ...(await createAssetIndex({+ projectId: bundle.build.projectId,+ entries: [+ createCanonicalAssetFileEntry({+ projectId: bundle.build.projectId,+ document: {+ _id: "article",+ _type: "asset.file",+ name: "post.mdx",+ path: "post.mdx",+ key: "post",+ extension: "mdx",+ mimeType: "text/mdx",+ size: 11,+ revision: "revision",+ contentRef: "article.mdx",+ properties: {},+ },+ }),+ ],+ maxBytes: 5000,+ })),+ contents: { "article.mdx": "<Missing />" },+ };+ expect(await getMdxTemplatePublishDiagnostics(bundle)).toEqual([+ {+ assetId: "article",+ filename: "post.mdx",+ blockInstanceId: rootId,+ templateName: "Missing",+ },+ ]);+ bundle.build.instances.push([+ "missing",+ {+ id: "missing",+ type: "instance",+ name: "Missing",+ component: "Box",+ children: [],+ },+ ]);+ bundle.build.instances[1][1].children = [{ type: "id", value: "missing" }];+ expect(await getMdxTemplatePublishDiagnostics(bundle)).toEqual([]);+ });test("classifies affected dynamic and static resources individually", async () => {const resourceId = "blog-posts";const overviewResourceId = "blog-overview";diff --git a/apps/builder/app/services/content-database.server.ts b/apps/builder/app/services/content-database.server.tsindex 4fa1246959..cc098bcf40 100644--- a/apps/builder/app/services/content-database.server.ts+++ b/apps/builder/app/services/content-database.server.ts@@ -1,6 +1,39 @@import { parseContentDatabaseMaxBytes } from "@webstudio-is/content-engine";import { getContentDatabasePublishDiagnostics as analyzeContentDatabasePublish } from "@webstudio-is/project-build";import type { PublishedProjectBundle } from "@webstudio-is/protocol";+import { resolvePublishedMdxDependencyClosure } from "@webstudio-is/project-build";+import { formatAssetName } from "@webstudio-is/sdk";+import { migratePages } from "@webstudio-is/project-migrations/pages";++export const getMdxTemplatePublishDiagnostics = async (+ bundle: PublishedProjectBundle+) => {+ const omissions = new Map<+ string,+ {+ assetId: string;+ filename: string;+ templateName: string;+ blockInstanceId: string;+ }+ >();+ if (bundle.assetIndex === undefined) {+ return [];+ }+ const assets = new Map(bundle.assets.map((asset) => [asset.id, asset]));+ await resolvePublishedMdxDependencyClosure({+ build: { ...bundle.build, pages: migratePages(bundle.build.pages) },+ artifact: bundle.assetIndex,+ onTemplateOmission: (issue) => {+ const asset = assets.get(issue.assetId);+ omissions.set(JSON.stringify(issue), {+ ...issue,+ filename: asset === undefined ? issue.assetId : formatAssetName(asset),+ });+ },+ });+ return [...omissions.values()];+};export const getContentDatabaseMaxBytes = () =>parseContentDatabaseMaxBytes(process.env.CONTENT_DATABASE_MAX_BYTES);diff --git a/apps/builder/app/services/project-import.server.test.ts b/apps/builder/app/services/project-import.server.test.tsindex eb72ebdc9f..a036183324 100644--- a/apps/builder/app/services/project-import.server.test.ts+++ b/apps/builder/app/services/project-import.server.test.ts@@ -6,6 +6,10 @@ import {} from "@webstudio-is/protocol/fixtures";import { type PublishedProjectBundle } from "@webstudio-is/protocol";import { createAssetRows } from "@webstudio-is/asset-uploader/server";+import {+ ContentCollectionError,+ createDefaultCollectionConfig,+} from "@webstudio-is/content-engine";import {__testing__,importPublishedProjectBundle,@@ -13,14 +17,34 @@ import {const {assertBundleVersion,- assertImportedAssetFilesUploaded,normalizeImportedAssetFolderData,assertImportedAssetNames,assertProjectBuildPermit,createBuildImportUpdate,getImportedPreviewImageAssetId,+ loadImportedAssetFiles,} = __testing__;+const createFileRow = ({+ name,+ format,+ size,+ meta = {},+}: {+ name: string;+ format: string;+ size: number;+ meta?: Record<string, unknown>;+}) => ({+ name,+ format,+ description: null,+ size,+ createdAt: "2026-09-03T00:00:00.000Z",+ updatedAt: "2026-09-03T00:00:00.000Z",+ meta: JSON.stringify(meta),+});+const createData = (overrides: Partial<PublishedProjectBundle> = {}): PublishedProjectBundle => {@@ -85,8 +109,11 @@ const createPostgrestClient = (calls: string[],options: {existingFileNames?: string[];+ existingFiles?: ReturnType<typeof createFileRow>[];fileFilters?: [string, string][];+ restoredFileFilters?: [string, string][];insertedFolders?: Array<{ id: string; projectId: string }>;+ buildUpdateCount?: number;} = {}) => ({from: (table: string) => {@@ -99,21 +126,35 @@ const createPostgrestClient = (in: async () => {calls.push("files-select");return {- data: (options.existingFileNames ?? []).map((name) => ({- name,- })),+ data:+ options.existingFiles ??+ (options.existingFileNames ?? []).map((name) =>+ createFileRow({+ name,+ format: name.split(".").at(-1) ?? "",+ size: 1,+ meta: name.endsWith(".png") ? { width: 1, height: 1 } : {},+ })+ ),error: undefined,};},};return {select: () => selectFiles,- update: () => ({- in: async () => {- calls.push("files-restore");- return { error: undefined };- },- }),+ update: () => {+ const restoreFiles = {+ eq: (column: string, value: string) => {+ options.restoredFileFilters?.push([column, value]);+ return restoreFiles;+ },+ in: async () => {+ calls.push("files-restore");+ return { error: undefined };+ },+ };+ return restoreFiles;+ },insert: async () => {calls.push("files-insert");return { error: undefined };@@ -126,7 +167,10 @@ const createPostgrestClient = (update: () => ({match: async () => {calls.push("build-update");- return { count: 1, error: undefined };+ return {+ count: options.buildUpdateCount ?? 1,+ error: undefined,+ };},}),};@@ -361,16 +405,182 @@ describe("build import helpers", () => {expect(calls).toEqual(["files-select",- "files-restore","build-update","project-preview-reset","assets-delete","asset-folders-delete","assets-insert",+ "files-restore","project-preview-update",]);});+ test("does not restore imported files when the build version changed", async () => {+ const calls: string[] = [];++ await expect(+ importPublishedProjectBundle(+ {+ ctx: {+ postgrest: {+ client: createPostgrestClient(calls, {+ existingFileNames: ["image.png"],+ buildUpdateCount: 0,+ }),+ },+ } as never,+ data: createData(),+ projectId: "target-project",+ },+ { hasProjectPermit, loadDevBuildByProjectId }+ )+ ).rejects.toThrow("build changed");++ expect(calls).toEqual(["files-select", "build-update"]);+ });++ test("rejects an invalid imported collection before changing the project", async () => {+ const calls: string[] = [];+ const configSource = createDefaultCollectionConfig();+ const configAsset = {+ id: "config",+ projectId: "source-project",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file" as const,+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ };++ await expect(+ importPublishedProjectBundle(+ {+ ctx: {+ postgrest: {+ client: createPostgrestClient(calls, {+ existingFiles: [+ createFileRow({+ name: configAsset.name,+ format: "json",+ size: configSource.length,+ }),+ ],+ }),+ },+ } as never,+ data: createData({+ assets: [configAsset],+ assetFolders: [+ {+ id: "posts",+ projectId: "source-project",+ name: "Posts",+ createdAt: "2026-09-03T00:00:00.000Z",+ },+ ],+ }),+ projectId: "target-project",+ },+ {+ hasProjectPermit,+ loadDevBuildByProjectId,+ assetStore: {+ readFile: async () => ({+ data: new Blob([configSource]).stream(),+ contentLength: configSource.length,+ }),+ },+ }+ )+ ).rejects.toThrow('Collection template "template.mdx" not found');++ expect(calls).toEqual(["files-select"]);+ });++ test("validates imported collections against destination file metadata", async () => {+ const calls: string[] = [];+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset = {+ id: "config",+ projectId: "source-project",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file" as const,+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ };+ const templateAsset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };++ await expect(+ importPublishedProjectBundle(+ {+ ctx: {+ postgrest: {+ client: createPostgrestClient(calls, {+ existingFiles: [+ createFileRow({+ name: configAsset.name,+ format: "json",+ size: configSource.length,+ }),+ createFileRow({+ name: templateAsset.name,+ format: "txt",+ size: templateSource.length,+ }),+ ],+ }),+ },+ } as never,+ data: createData({+ assets: [configAsset, templateAsset],+ assetFolders: [+ {+ id: "posts",+ projectId: "source-project",+ name: "Posts",+ createdAt: "2026-09-03T00:00:00.000Z",+ },+ ],+ }),+ projectId: "target-project",+ },+ {+ hasProjectPermit,+ loadDevBuildByProjectId,+ assetStore: {+ readFile: async (name) => {+ const source =+ name === configAsset.name ? configSource : templateSource;+ return {+ data: new Blob([source]).stream(),+ contentLength: source.length,+ };+ },+ },+ }+ )+ ).rejects.toBeInstanceOf(ContentCollectionError);++ expect(calls).toEqual(["files-select"]);+ });+test("inserts the complete folder hierarchy in one request", async () => {const calls: string[] = [];const insertedFolders: Array<{ id: string; projectId: string }> = [];@@ -452,7 +662,7 @@ describe("build import helpers", () => {const fileFilters: [string, string][] = [];await expect(- assertImportedAssetFilesUploaded({+ loadImportedAssetFiles({assets: createData().assets,ctx: {postgrest: {@@ -464,9 +674,9 @@ describe("build import helpers", () => {} as never,projectId: "target-project",})- ).resolves.toBeUndefined();+ ).resolves.toMatchObject({ fileNames: new Set(["image.png"]) });- expect(calls).toEqual(["files-select", "files-restore"]);+ expect(calls).toEqual(["files-select"]);expect(fileFilters).toEqual([["status", "UPLOADED"],["uploaderProjectId", "target-project"],@@ -475,6 +685,7 @@ describe("build import helpers", () => {test("makes imported file rows visible", async () => {const calls: string[] = [];+ const restoredFileFilters: [string, string][] = [];await importPublishedProjectBundle({@@ -482,6 +693,7 @@ describe("build import helpers", () => {postgrest: {client: createPostgrestClient(calls, {existingFileNames: ["image.png"],+ restoredFileFilters,}),},} as never,@@ -495,6 +707,9 @@ describe("build import helpers", () => {);expect(calls).toContain("files-restore");+ expect(restoredFileFilters).toEqual([+ ["uploaderProjectId", "target-project"],+ ]);});test("rejects imported asset names with path separators", () => {@@ -505,13 +720,13 @@ describe("build import helpers", () => {).toThrow("Imported asset name is invalid: ../image.png");});- test("rejects duplicated imported asset names", () => {+ test("allows imported assets to share one storage file", () => {expect(() =>assertImportedAssetNames([createData().assets[0],{ ...createData().assets[0], id: "asset-2" },])- ).toThrow("Imported asset name is duplicated: image.png");+ ).not.toThrow();});test("rejects duplicated imported asset ids", () => {diff --git a/apps/builder/app/services/project-import.server.ts b/apps/builder/app/services/project-import.server.tsindex 8001e753fa..0b4c38822e 100644--- a/apps/builder/app/services/project-import.server.ts+++ b/apps/builder/app/services/project-import.server.ts@@ -12,6 +12,10 @@ import {import {createAssetFolderRows,createAssetRows,+ formatAsset,+ getCollectionFolderIds,+ validateCollectionFolder,+ type AssetObjectReader,} from "@webstudio-is/asset-uploader/server";import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";import {@@ -44,6 +48,7 @@ import {type Resource,type StyleSource,} from "@webstudio-is/sdk";+import { createAssetClient } from "~/shared/asset-client";const toMap = <Key extends string, Value>(entries: [Key, Value][]) =>new Map<Key, Value>(entries);@@ -131,7 +136,6 @@ const getImportedPreviewImageAssetId = (data: ProjectBundle) => {const assertImportedAssetNames = (assets: Asset[]) => {const assetIds = new Set<string>();- const assetNames = new Set<string>();for (const asset of assets) {if (asset.id === "") {@@ -143,11 +147,7 @@ const assertImportedAssetNames = (assets: Asset[]) => {if (isAssetFileName(asset.name) === false) {throw new Error(`Imported asset name is invalid: ${asset.name}`);}- if (assetNames.has(asset.name)) {- throw new Error(`Imported asset name is duplicated: ${asset.name}`);- }assetIds.add(asset.id);- assetNames.add(asset.name);}};@@ -170,7 +170,7 @@ const normalizeImportedAssetFolderData = (});};-const assertImportedAssetFilesUploaded = async ({+const loadImportedAssetFiles = async ({assets,ctx,projectId,@@ -180,12 +180,12 @@ const assertImportedAssetFilesUploaded = async ({projectId: string;}) => {if (assets.length === 0) {- return;+ return { assets, fileNames: new Set<string>() };}const files = await ctx.postgrest.client.from("File")- .select("name")+ .select("name, format, description, size, createdAt, updatedAt, meta").eq("status", "UPLOADED").eq("uploaderProjectId", projectId).in(@@ -197,11 +197,11 @@ const assertImportedAssetFilesUploaded = async ({throw files.error;}- const existingFileNames = new Set(- (files.data ?? []).map((file) => file.name)+ const filesByName = new Map(+ (files.data ?? []).map((file) => [file.name, file]));const missingAssets = assets.filter(- (asset) => existingFileNames.has(asset.name) === false+ (asset) => filesByName.has(asset.name) === false);if (missingAssets.length > 0) {throw new Error(@@ -211,14 +211,56 @@ const assertImportedAssetFilesUploaded = async ({);}- if (existingFileNames.size > 0) {- const visibleFiles = await ctx.postgrest.client- .from("File")- .update({ isDeleted: false })- .in("name", Array.from(existingFileNames));- if (visibleFiles.error) {- throw visibleFiles.error;- }+ return {+ assets: assets.map((asset) => {+ const file = filesByName.get(asset.name);+ if (file === undefined) {+ throw new Error(`Imported asset file is missing: ${asset.name}`);+ }+ return formatAsset({+ assetId: asset.id,+ projectId,+ filename: asset.filename ?? null,+ description: asset.description ?? null,+ folderId: asset.folderId,+ file,+ });+ }),+ fileNames: new Set(filesByName.keys()),+ };+};++const restoreImportedAssetFiles = async ({+ fileNames,+ ctx,+ projectId,+}: {+ fileNames: ReadonlySet<string>;+ ctx: AppContext;+ projectId: string;+}) => {+ if (fileNames.size === 0) {+ return;+ }+ const visibleFiles = await ctx.postgrest.client+ .from("File")+ .update({ isDeleted: false })+ .eq("uploaderProjectId", projectId)+ .in("name", Array.from(fileNames));+ if (visibleFiles.error) {+ throw visibleFiles.error;+ }+};++const validateImportedCollections = async ({+ assets,+ assetStore,+}: {+ assets: readonly Asset[];+ assetStore: AssetObjectReader;+}) => {+ for (const folderId of getCollectionFolderIds(assets)) {+ await validateCollectionFolder({ assets, folderId, assetStore });}};@@ -311,6 +353,7 @@ export const importPublishedProjectBundle = async (dependencies: {hasProjectPermit: typeof authorizeProject.hasProjectPermit;loadDevBuildByProjectId: typeof loadDevBuildByProjectId;+ assetStore?: AssetObjectReader;} = {hasProjectPermit: authorizeProject.hasProjectPermit,loadDevBuildByProjectId,@@ -330,15 +373,22 @@ export const importPublishedProjectBundle = async (const nextVersion = build.version + 1;assertImportedAssets(data.assets);- const { assets: importedAssets, folders: importedAssetFolders } =+ const { assets: normalizedAssets, folders: importedAssetFolders } =normalizeImportedAssetFolderData(data.assetFolders ?? [], data.assets);- await assertImportedAssetFilesUploaded({- assets: importedAssets,- ctx,- projectId,- });-+ const { assets: importedAssets, fileNames: importedFileNames } =+ await loadImportedAssetFiles({+ assets: normalizedAssets,+ ctx,+ projectId,+ });+ const collectionFolderIds = getCollectionFolderIds(importedAssets);+ if (collectionFolderIds.size > 0) {+ await validateImportedCollections({+ assets: importedAssets,+ assetStore: dependencies.assetStore ?? createAssetClient(),+ });+ }const buildUpdate = createBuildImportUpdate({data,lastTransactionId: createId(),@@ -368,6 +418,12 @@ export const importPublishedProjectBundle = async (projectId,});+ await restoreImportedAssetFiles({+ fileNames: importedFileNames,+ ctx,+ projectId,+ });+await updateProjectPreviewImage({assetId: getImportedPreviewImageAssetId(data),ctx,@@ -385,5 +441,7 @@ export const __testing__ = {assertImportedAssetNames,assertImportedAssets,normalizeImportedAssetFolderData,- assertImportedAssetFilesUploaded,+ loadImportedAssetFiles,+ restoreImportedAssetFiles,+ validateImportedCollections,};diff --git a/apps/builder/app/shared/asset-content-bridge.client.test.ts b/apps/builder/app/shared/asset-content-bridge.client.test.tsindex b738c430b7..73b851940a 100644--- a/apps/builder/app/shared/asset-content-bridge.client.test.ts+++ b/apps/builder/app/shared/asset-content-bridge.client.test.ts@@ -116,3 +116,53 @@ test("bounds Asset content writes before forwarding them", async () => {).rejects.toThrow("exceeds");expect(request).not.toHaveBeenCalled();});++test("routes frontmatter writes to the mounted document owner and cleans up safely", async () => {+ const { bridge, authorize } = createBridge();+ const update = vi.fn(async () => {});+ const registration = {+ rootKey: "root",+ projectId: "project-1",+ assetId: "asset-1",+ update,+ };+ const release = bridge.registerFrontmatterWriter(registration);+ const input = { rootKey: "root", path: ["title"], value: "Updated" };+ await bridge.updateFrontmatter(input);+ expect(update).toHaveBeenCalledWith(input);+ expect(authorize).toHaveBeenLastCalledWith({+ projectId: "project-1",+ assetId: "asset-1",+ operation: "write",+ });++ const replacement = vi.fn(async () => {});+ const releaseReplacement = bridge.registerFrontmatterWriter({+ ...registration,+ update: replacement,+ });+ release();+ await bridge.updateFrontmatter(input);+ expect(replacement).toHaveBeenCalledWith(input);+ releaseReplacement();+ await expect(bridge.updateFrontmatter(input)).rejects.toThrow("not open");+});++test("rejects unauthorized frontmatter writes before calling the document owner", async () => {+ const { bridge } = createBridge({ authorized: false });+ const update = vi.fn(async () => {});+ bridge.registerFrontmatterWriter({+ rootKey: "root",+ projectId: "project-1",+ assetId: "asset-1",+ update,+ });+ await expect(+ bridge.updateFrontmatter({+ rootKey: "root",+ path: ["title"],+ value: "Updated",+ })+ ).rejects.toThrow("not authorized");+ expect(update).not.toHaveBeenCalled();+});diff --git a/apps/builder/app/shared/asset-content-bridge.client.ts b/apps/builder/app/shared/asset-content-bridge.client.tsindex f8887d1f26..edeae9516e 100644--- a/apps/builder/app/shared/asset-content-bridge.client.ts+++ b/apps/builder/app/shared/asset-content-bridge.client.ts@@ -7,11 +7,27 @@ type AssetContentAuthorization = Readonly<{operation: "read" | "write";}>;+type FrontmatterUpdate = Readonly<{+ rootKey: string;+ path: readonly string[];+ value: unknown;+ resolvedValue?: unknown;+}>;++type FrontmatterWriter = Readonly<{+ rootKey: string;+ projectId: string;+ assetId: string;+ update: (input: FrontmatterUpdate) => Promise<void>;+}>;+export type AssetContentBridge = Readonly<{request: (input: string, init?: RequestInit) => Promise<Response>;authorize: (input: AssetContentAuthorization) => boolean;requireReload: (error: string) => void;getContentSession?: (projectId: string) => AssetContentSession;+ registerFrontmatterWriter: (writer: FrontmatterWriter) => () => void;+ updateFrontmatter: (input: FrontmatterUpdate) => Promise<void>;}>;const namespace = "__webstudio__$__assetContentBridge";@@ -28,90 +44,117 @@ export const createAssetContentBridge = ({authorize: (input: AssetContentAuthorization) => boolean;requireReload: (error: string) => void;getContentSession?: (projectId: string) => AssetContentSession;-}): AssetContentBridge => ({- authorize,- requireReload,- getContentSession,- request: async (input, init) => {- const url = new URL(input, origin);- const method = init?.method?.toUpperCase() ?? "GET";- const [, rest, assets, encodedAssetId, content, ...extraPath] =- url.pathname.split("/");- if (- url.origin !== origin ||- rest !== "rest" ||- assets !== "assets" ||- encodedAssetId === undefined ||- encodedAssetId === "" ||- content !== "content" ||- extraPath.length !== 0 ||- (method !== "GET" && method !== "PUT")- ) {- throw new Error("Only same-origin Asset content requests are allowed");- }- let assetId: string;- try {- assetId = decodeURIComponent(encodedAssetId);- } catch {- throw new Error("Asset content request has an invalid Asset id");- }- const projectIds = url.searchParams.getAll("projectId");- const expectedNames = url.searchParams.getAll("expectedName");- const allowedQueryNames =- method === "GET"- ? new Set(["projectId"])- : new Set(["projectId", "expectedName"]);- if (- projectIds.length !== 1 ||- projectIds[0] === "" ||- expectedNames.length !== (method === "PUT" ? 1 : 0) ||- (method === "PUT" && expectedNames[0] === "") ||- [...url.searchParams.keys()].some(- (name) => allowedQueryNames.has(name) === false- )- ) {- throw new Error("Asset content request has invalid parameters");- }- const operation = method === "PUT" ? "write" : "read";- if (- authorize({- projectId: projectIds[0],- assetId,- operation,- }) === false- ) {- throw new Error("Asset content request is not authorized");- }- if (method === "GET") {- if (init?.body != null) {- throw new Error("Asset content reads cannot include a body");+}): AssetContentBridge => {+ const frontmatterWriters = new Map<string, FrontmatterWriter>();+ return {+ authorize,+ requireReload,+ getContentSession,+ registerFrontmatterWriter: (writer) => {+ frontmatterWriters.set(writer.rootKey, writer);+ return () => {+ if (frontmatterWriters.get(writer.rootKey) === writer) {+ frontmatterWriters.delete(writer.rootKey);+ }+ };+ },+ updateFrontmatter: async (input) => {+ const writer = frontmatterWriters.get(input.rootKey);+ if (writer === undefined) {+ throw new Error("Connected Content Block is not open");}- return await request(url.href, init);- }- const headers = new Headers(init?.headers);- if (headers.get("content-type") !== "application/octet-stream") {- throw new Error("Asset content writes require binary content");- }- const body = init?.body;- const byteLength =- typeof body === "string"- ? new TextEncoder().encode(body).byteLength- : body instanceof Blob- ? body.size- : body instanceof ArrayBuffer- ? body.byteLength- : ArrayBuffer.isView(body)+ if (+ !authorize({+ projectId: writer.projectId,+ assetId: writer.assetId,+ operation: "write",+ })+ ) {+ throw new Error("Asset content request is not authorized");+ }+ await writer.update(input);+ },+ request: async (input, init) => {+ const url = new URL(input, origin);+ const method = init?.method?.toUpperCase() ?? "GET";+ const [, rest, assets, encodedAssetId, content, ...extraPath] =+ url.pathname.split("/");+ if (+ url.origin !== origin ||+ rest !== "rest" ||+ assets !== "assets" ||+ encodedAssetId === undefined ||+ encodedAssetId === "" ||+ content !== "content" ||+ extraPath.length !== 0 ||+ (method !== "GET" && method !== "PUT")+ ) {+ throw new Error("Only same-origin Asset content requests are allowed");+ }+ let assetId: string;+ try {+ assetId = decodeURIComponent(encodedAssetId);+ } catch {+ throw new Error("Asset content request has an invalid Asset id");+ }+ const projectIds = url.searchParams.getAll("projectId");+ const expectedNames = url.searchParams.getAll("expectedName");+ const allowedQueryNames =+ method === "GET"+ ? new Set(["projectId"])+ : new Set(["projectId", "expectedName"]);+ if (+ projectIds.length !== 1 ||+ projectIds[0] === "" ||+ expectedNames.length !== (method === "PUT" ? 1 : 0) ||+ (method === "PUT" && expectedNames[0] === "") ||+ [...url.searchParams.keys()].some(+ (name) => allowedQueryNames.has(name) === false+ )+ ) {+ throw new Error("Asset content request has invalid parameters");+ }+ const operation = method === "PUT" ? "write" : "read";+ if (+ authorize({+ projectId: projectIds[0],+ assetId,+ operation,+ }) === false+ ) {+ throw new Error("Asset content request is not authorized");+ }+ if (method === "GET") {+ if (init?.body != null) {+ throw new Error("Asset content reads cannot include a body");+ }+ return await request(url.href, init);+ }+ const headers = new Headers(init?.headers);+ if (headers.get("content-type") !== "application/octet-stream") {+ throw new Error("Asset content writes require binary content");+ }+ const body = init?.body;+ const byteLength =+ typeof body === "string"+ ? new TextEncoder().encode(body).byteLength+ : body instanceof Blob+ ? body.size+ : body instanceof ArrayBuffer? body.byteLength- : undefined;- if (byteLength === undefined) {- throw new Error("Asset content writes require a bounded body");- }- if (byteLength > contentEngineLimits.hydratedFileBytes) {- throw new Error("Asset content write exceeds the MDX editing limit");- }- return await request(url.href, init);- },-});+ : ArrayBuffer.isView(body)+ ? body.byteLength+ : undefined;+ if (byteLength === undefined) {+ throw new Error("Asset content writes require a bounded body");+ }+ if (byteLength > contentEngineLimits.hydratedFileBytes) {+ throw new Error("Asset content write exceeds the MDX editing limit");+ }+ return await request(url.href, init);+ },+ };+};declare global {interface Window {diff --git a/apps/builder/app/shared/builder-api.test.ts b/apps/builder/app/shared/builder-api.test.tsindex ef5ae1594a..2840eb9376 100644--- a/apps/builder/app/shared/builder-api.test.ts+++ b/apps/builder/app/shared/builder-api.test.ts@@ -4,11 +4,12 @@ import { __testing__ } from "./builder-api";const file = (format: string) =>({ type: "file", format }) satisfies Pick<Asset, "type" | "format">;+const { canAccessAssetContent } = __testing__;-test("allows graph documents to be read but only MDX roots to be written", () => {+test("allows Markdown frontmatter writes without allowing JSON or viewer writes", () => {for (const format of ["md", "mdx", "json"]) {expect(- __testing__.canAccessAssetContent({+ canAccessAssetContent({asset: file(format),operation: "read",canWrite: false,@@ -16,33 +17,35 @@ test("allows graph documents to be read but only MDX roots to be written", () =>).toBe(true);}expect(- __testing__.canAccessAssetContent({+ canAccessAssetContent({asset: file("png"),operation: "read",canWrite: true,})).toBe(false);- expect(- __testing__.canAccessAssetContent({- asset: file("mdx"),- operation: "write",- canWrite: true,- })- ).toBe(true);- for (const format of ["md", "json"]) {+ for (const format of ["md", "MD", "mdx", "MDX"]) {expect(- __testing__.canAccessAssetContent({+ canAccessAssetContent({+ asset: file(format),+ operation: "write",+ canWrite: true,+ })+ ).toBe(true);+ expect(+ canAccessAssetContent({+ asset: file(format),+ operation: "write",+ canWrite: false,+ })+ ).toBe(false);+ }+ for (const format of ["json", "png", "txt"]) {+ expect(+ canAccessAssetContent({asset: file(format),operation: "write",canWrite: true,})).toBe(false);}- expect(- __testing__.canAccessAssetContent({- asset: file("mdx"),- operation: "write",- canWrite: false,- })- ).toBe(false);});diff --git a/apps/builder/app/shared/builder-api.ts b/apps/builder/app/shared/builder-api.tsindex e064e3662c..87d0a4095a 100644--- a/apps/builder/app/shared/builder-api.ts+++ b/apps/builder/app/shared/builder-api.ts@@ -19,11 +19,8 @@ import { requireBuilderReload } from "./sync/reload-required";import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";import { createHttpAssetContentRepository } from "~/builder/shared/assets/mdx-content-repository";import { $authToken } from "./nano-states";-import { isMdxFileAsset, type Asset } from "@webstudio-is/sdk";-import { createTransactionFromBuilderPatchPayload } from "./sync/builder-patch";-import { getWebstudioData } from "./instance-utils/data";-import { invalidateAssets } from "./resources";-import { onNextTransactionComplete } from "./sync/project-queue";+import { asset, type Asset } from "@webstudio-is/sdk";+import { commitAssetContentUpdate } from "~/builder/shared/assets/update-asset-content";import { disposeExternalContentProject } from "./external-content-roots";const apiWindowNamespace = "__webstudio__$__builderApi";@@ -43,7 +40,9 @@ const canAccessAssetContent = ({}) =>operation === "read"? isContentDocumentAsset(asset)- : canWrite && isMdxFileAsset(asset);+ : canWrite &&+ asset.type === "file" &&+ ["md", "mdx"].includes(asset.format.toLowerCase());type ToastHandler = (message: string) => void;@@ -337,22 +336,9 @@ export const initBuilderApi = () => {) {return;}- createTransactionFromBuilderPatchPayload({- data: getWebstudioData(),- payload: [- {- namespace: "assets",- patches: [- {- op: "replace",- path: [current.id],- value: { ...current, ...state.asset },- },- ],- },- ],- });- onNextTransactionComplete(invalidateAssets);+ commitAssetContentUpdate(+ asset.parse({ ...current, ...state.asset })+ );});activeContentSession = { projectId, session, active: true };contentSessions.set(projectId, activeContentSession);diff --git a/apps/builder/app/shared/code-editor-base.tsx b/apps/builder/app/shared/code-editor-base.tsxindex b22c6d3988..4f5b1d4e97 100644--- a/apps/builder/app/shared/code-editor-base.tsx+++ b/apps/builder/app/shared/code-editor-base.tsx@@ -40,6 +40,7 @@ import {Kbd,Text,FloatingPanel,+ PanelContent,} from "@webstudio-is/design-system";import { MaximizeIcon } from "@webstudio-is/icons";import { ChevronDownIcon, ChevronRightIcon } from "@webstudio-is/icons/svg";@@ -308,6 +309,7 @@ export const getTemplateInsertion = ({type EditorContentProps = {editorApiRef?: RefObject<undefined | EditorApi>;+ ariaLabel?: string;extensions?: Extension[];readOnly?: boolean;autoFocus?: boolean;@@ -321,6 +323,7 @@ type EditorContentProps = {export const EditorContent = ({editorApiRef,+ ariaLabel,extensions = [],readOnly = false,autoFocus = false,@@ -423,6 +426,12 @@ export const EditorContent = ({},]),EditorView.lineWrapping,+ // Read-only editors must keep keyboard focus instead of leaving+ // destructive Builder shortcuts active after clicking their content.+ EditorView.contentAttributes.of({ tabindex: "0" }),+ ...(ariaLabel === undefined+ ? []+ : [EditorView.contentAttributes.of({ "aria-label": ariaLabel })]),EditorView.editable.of(readOnly === false),EditorState.readOnly.of(readOnly === true),// https://github.com/uiwjs/react-codemirror/blob/5d7a37245ce70e61f215b77dc42a7eaf295c46e7/core/src/useCodeMirror.ts#L57-L70@@ -450,7 +459,7 @@ export const EditorContent = ({}),]),});- }, [readOnly, extensions]);+ }, [ariaLabel, readOnly, extensions]);// update editor with react value// https://github.com/uiwjs/react-codemirror/blob/5d7a37245ce70e61f215b77dc42a7eaf295c46e7/core/src/useCodeMirror.ts#L158-L169@@ -587,17 +596,18 @@ export const EditorDialog = ({maximizableresize="both"content={- <Grid+ <PanelContent+ as={Grid}align="stretch"css={{- padding: contentPadding ? theme.panel.padding : 0,+ padding: contentPadding ? undefined : 0,height: "100%",overflow: "hidden",boxSizing: "content-box",}}>{content}- </Grid>+ </PanelContent>}>{children}diff --git a/apps/builder/app/shared/code-editor.tsx b/apps/builder/app/shared/code-editor.tsxindex 4be866f945..6cbbeb6162 100644--- a/apps/builder/app/shared/code-editor.tsx+++ b/apps/builder/app/shared/code-editor.tsx@@ -30,7 +30,7 @@ import { html } from "@codemirror/lang-html";import { javascript } from "@codemirror/lang-javascript";import { markdown } from "@codemirror/lang-markdown";import { cssCompletionSource, cssLanguage } from "@codemirror/lang-css";-import { css } from "@webstudio-is/design-system";+import { css, cssVar } from "@webstudio-is/design-system";import {EditorContent,EditorDialog,@@ -45,6 +45,7 @@ const wrapperStyle = css({position: "relative",variants: {+ color: { error: { outline: `1px solid ${cssVar("--border-negative")}` } },size: {default: getCodeEditorCssVars({ minHeight: "160px", maxHeight: "320px" }),small: getCodeEditorCssVars({ minHeight: "16px", maxHeight: "120px" }),@@ -167,6 +168,7 @@ export const CodeEditor = forwardRef<title?: ReactNode;size?: "default" | "small" | "full";expandable?: boolean;+ color?: "error";}>((props, ref) => {const {@@ -176,6 +178,7 @@ export const CodeEditor = forwardRef<title,size,expandable = true,+ color,...editorContentProps} = props;const builtInExtensions = useMemo(() => {@@ -245,7 +248,11 @@ export const CodeEditor = forwardRef<};}, []);return (- <div className={wrapperStyle({ size })} ref={ref}>+ <div+ className={wrapperStyle({ size, color })}+ ref={ref}+ aria-invalid={color === "error" || undefined}+ >{expandable === false ? (<EditorContent {...editorContentProps} extensions={extensions} />) : (diff --git a/apps/builder/app/shared/commands-emitter.ts b/apps/builder/app/shared/commands-emitter.tsindex fb47a2c657..f6777a9796 100644--- a/apps/builder/app/shared/commands-emitter.ts+++ b/apps/builder/app/shared/commands-emitter.ts@@ -16,8 +16,8 @@ export type CommandMeta<CommandName extends string> = {/** listen hotkeys only locally without sharing with other apps */disableHotkeyOutsideApp?: boolean;/**- * input, select and textarea, content editable and role=option used in Radix will not invoke command when hotkey is hit- * with the exception when default event behavior is prevented+ * Inputs, text editors (including read-only ones), and Radix options+ * will not invoke the command when its hotkey is pressed.**/disableOnInputLikeControls?: boolean;/**@@ -176,6 +176,7 @@ export const createCommandsEmitter = <CommandName extends string>({element.tagName.toLowerCase()) ||element.isContentEditable ||+ element.closest('[role="textbox"]') !== null ||// Detect Radix select, dropdown and co.element.getAttribute("role") === "option");diff --git a/apps/builder/app/shared/conflict-resolution-dialog.tsx b/apps/builder/app/shared/conflict-resolution-dialog.tsxindex 895be1c65f..662499845b 100644--- a/apps/builder/app/shared/conflict-resolution-dialog.tsx+++ b/apps/builder/app/shared/conflict-resolution-dialog.tsx@@ -1,5 +1,6 @@import type { ReactNode } from "react";import {+ PanelContent,Button,Dialog,DialogActions,@@ -8,7 +9,6 @@ import {DialogTitle,Flex,Text,- theme,} from "@webstudio-is/design-system";import { DialogRadioOptions } from "./dialog-radio-options";@@ -47,7 +47,7 @@ export const ConflictResolutionDialog = <Resolution extends string>({><DialogContent css={{ minWidth: "40ch" }}><DialogTitle>{title}</DialogTitle>- <Flex direction="column" gap="2" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} direction="column" gap="2"><DialogDescription asChild><Text as="p">{description}</Text></DialogDescription>@@ -62,7 +62,7 @@ export const ConflictResolutionDialog = <Resolution extends string>({{details}</Text></Flex>- </Flex>+ </PanelContent><DialogActions><Button autoFocus color="primary" onClick={onResolve}>Continuediff --git a/apps/builder/app/shared/content-block-document.test.ts b/apps/builder/app/shared/content-block-document.test.tsindex d86c11b823..c7ee5b09bb 100644--- a/apps/builder/app/shared/content-block-document.test.ts+++ b/apps/builder/app/shared/content-block-document.test.ts@@ -4,6 +4,7 @@ import {getSelectedContentBlockExpressionMode,isObjectPathWritable,setObjectPathValue,+ getFrontmatterWriteTarget,} from "./content-block-document";import {blockComponent,@@ -15,6 +16,109 @@ import {} from "@webstudio-is/sdk";describe("Content Block document bindings", () => {+ test("follows loaded Markdown frontmatter references without changing their markers", () => {+ const article = { author: { $ref: "./author.md#frontmatter" } };+ const author = {+ name: "Ada",+ editor: { $ref: "./editor.mdx#frontmatter" },+ };+ const sources = [+ {+ assetId: "article",+ documentUrl: "https://content.test/article.mdx",+ properties: article,+ },+ {+ assetId: "author",+ documentUrl: "https://content.test/author.md",+ properties: author,+ },+ {+ assetId: "editor",+ documentUrl: "https://content.test/editor.mdx",+ properties: { name: "Grace" },+ },+ ];+ const input = { assetId: "article", value: article, sources };+ expect(+ getFrontmatterWriteTarget({ ...input, path: ["author", "name"] })+ ).toEqual({+ assetId: "author",+ path: ["name"],+ via: ["article", "author"],+ });+ expect(+ getFrontmatterWriteTarget({+ ...input,+ path: ["author", "editor", "name"],+ })+ ).toEqual({+ assetId: "editor",+ path: ["name"],+ via: ["article", "author", "editor"],+ });+ expect(getFrontmatterWriteTarget({ ...input, path: ["author"] })).toEqual({+ assetId: "article",+ path: ["author"],+ via: ["article"],+ });+ expect(article).toEqual({ author: { $ref: "./author.md#frontmatter" } });+ for (const reference of [+ "./missing.md#frontmatter",+ "./article.mdx#frontmatter",+ "./author.md#body",+ "./image.png",+ "https://other.test/author.md#frontmatter",+ ]) {+ const properties = { author: { $ref: reference } };+ expect(+ getFrontmatterWriteTarget({+ assetId: "article",+ value: properties,+ path: ["author", "name"],+ sources: [+ {+ assetId: "article",+ documentUrl: "https://content.test/article.mdx",+ properties,+ },+ ],+ })+ ).toBeUndefined();+ }+ expect(+ getFrontmatterWriteTarget({+ assetId: "article",+ value: {},+ path: ["__proto__", "polluted"],+ })+ ).toBeUndefined();+ const properties = { author: { $ref: "./author.md#frontmatter" } };+ expect(+ getFrontmatterWriteTarget({+ assetId: "article",+ value: properties,+ path: ["author", "name"],+ sources: [+ {+ assetId: "article",+ documentUrl: "https://content.test/article.mdx",+ properties,+ },+ {+ assetId: "one",+ documentUrl: "https://content.test/author.md",+ properties: {},+ },+ {+ assetId: "two",+ documentUrl: "https://content.test/author.md",+ properties: {},+ },+ ],+ })+ ).toBeUndefined();+ });test("uses the selected external root instead of an enclosing Content Block", () => {const instances = new Map<string, Instance>([[@@ -219,6 +323,12 @@ describe("Content Block document bindings", () => {expression: `${document}.frontmatter.title`,})).toBe("readwrite");+ expect(+ getSelectedContentBlockExpressionMode({+ ...context,+ expression: `${document}.frontmatter.author?.name`,+ })+ ).toBe("readwrite");expect(getSelectedContentBlockExpressionMode({...context,diff --git a/apps/builder/app/shared/content-block-document.ts b/apps/builder/app/shared/content-block-document.tsindex 9aa26029ac..20e3decc69 100644--- a/apps/builder/app/shared/content-block-document.ts+++ b/apps/builder/app/shared/content-block-document.ts@@ -12,6 +12,82 @@ import {type Props,} from "@webstudio-is/sdk";import type { InstanceSelector } from "@webstudio-is/project-build/runtime";+import { parseSourceDocumentReference } from "@webstudio-is/content-engine";++export type FrontmatterSource = Readonly<{+ assetId: string;+ documentUrl: string;+ properties: Readonly<Record<string, unknown>>;+}>;++/** Resolve only loaded Markdown frontmatter references, never arbitrary URLs. */+export const getFrontmatterWriteTarget = ({+ assetId,+ value,+ path,+ sources = [],+}: {+ assetId: string;+ value: Readonly<Record<string, unknown>>;+ path: readonly string[];+ sources?: readonly FrontmatterSource[];+}):+ | { assetId: string; path: readonly string[]; via: readonly string[] }+ | undefined => {+ const via: string[] = [];+ let properties = value;+ while (via.includes(assetId) === false) {+ via.push(assetId);+ if (path.length === 0 || isSafeContentBlockDocumentPath(path) === false) {+ return;+ }+ if (isObjectPathWritable({ value: properties, path })) {+ return { assetId, path, via };+ }+ let current: unknown = properties;+ let followed = false;+ for (let index = 0; index < path.length; index += 1) {+ if (typeof current !== "object" || current === null) {+ return;+ }+ if ("$ref" in current) {+ const source = sources.find((source) => source.assetId === assetId);+ if (source === undefined || Object.keys(current).length !== 1) {+ return;+ }+ try {+ const reference = parseSourceDocumentReference({+ value: current.$ref,+ baseUrl: source.documentUrl,+ });+ if (reference.representation.type !== "markdown-frontmatter") {+ return;+ }+ const targets = sources.filter(+ (source) => source.documentUrl === reference.documentUrl+ );+ if (targets.length !== 1) {+ return;+ }+ assetId = targets[0].assetId;+ properties = targets[0].properties;+ path = path.slice(index);+ followed = true;+ break;+ } catch {+ return;+ }+ }+ if (Array.isArray(current) && getArrayIndex(path[index]) === undefined) {+ return;+ }+ current = (current as Record<string, unknown>)[path[index]];+ }+ if (followed === false) {+ return;+ }+ }+};export const getSelectedContentBlockDocumentBindingPath = ({binding,diff --git a/apps/builder/app/shared/db/canvas.server.test.ts b/apps/builder/app/shared/db/canvas.server.test.tsindex eaebd430cf..8b9d09e97a 100644--- a/apps/builder/app/shared/db/canvas.server.test.ts+++ b/apps/builder/app/shared/db/canvas.server.test.ts@@ -9,8 +9,11 @@ import {import { migratePages } from "@webstudio-is/project-migrations/pages";import { __testing__ } from "./canvas.server";-const { createLoadPublishedProjectBundleByProjectId, serializeProjectBundle } =- __testing__;+const {+ addProjectMetadata,+ createLoadPublishedProjectBundleByProjectId,+ serializeProjectBundle,+} = __testing__;type BundleBuild = Parameters<typeof serializeProjectBundle>[0]["build"];const createBundleBuild = (@@ -102,6 +105,81 @@ test("keeps font assets referenced from nested style values", () => {expect(bundle.assets).toEqual([fontAsset]);});+test("validates collections when publication does not need a content index", async () => {+ const build = createBundleBuild({+ styles: [+ {+ styleSourceId: "token",+ breakpointId: "base",+ property: "fontFamily",+ value: {+ type: "layers",+ value: [+ {+ type: "fontFamily",+ value: ["UsedFont", "sans-serif"],+ },+ ],+ } as unknown as StyleValue,+ },+ ],+ });+ const usedFont: Asset = {+ id: "used-font",+ projectId: build.projectId,+ name: "UsedFont.woff2",+ type: "font",+ createdAt: "2024-01-01T00:00:00.000Z",+ format: "woff2",+ size: 100,+ meta: { family: "UsedFont", style: "normal", weight: 400 },+ };+ const unusedFont: Asset = {+ ...usedFont,+ id: "unused-font",+ name: "UnusedFont.woff2",+ meta: { ...usedFont.meta, family: "UnusedFont" },+ };+ const imageAsset = createImageAssetFixture({ projectId: build.projectId });+ const currentAssetFolders = [{ id: "current-folder" }] as never;+ const data = serializeProjectBundle({+ build,+ assets: [usedFont],+ });+ const validatePublishedAssetCollections = vi.fn().mockResolvedValue({+ assets: [usedFont, unusedFont, imageAsset],+ assetFolders: currentAssetFolders,+ });+ const preparePublishedAssetData = vi.fn();+ const assetStore = {} as never;++ const result = await addProjectMetadata(+ data,+ {+ id: "project-id",+ userId: null,+ domain: "example.com",+ title: "Example",+ } as never,+ {} as never,+ {+ getUserById: vi.fn(),+ preparePublishedAssetData,+ validatePublishedAssetCollections,+ createAssetClient: vi.fn(() => assetStore),+ }+ );++ expect(validatePublishedAssetCollections).toHaveBeenCalledWith({+ projectId: "project-id",+ context: {},+ assetStore,+ });+ expect(preparePublishedAssetData).not.toHaveBeenCalled();+ expect(result.assets).toEqual([usedFont, imageAsset]);+ expect(result.assetFolders).toBe(currentAssetFolders);+});+test("loads project-id bundles from the published build", async () => {const data = createPublishedProjectBundleFixture();const project = {diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.tsindex 13e1ac5cdc..29af2e4002 100644--- a/apps/builder/app/shared/db/canvas.server.ts+++ b/apps/builder/app/shared/db/canvas.server.ts@@ -19,6 +19,7 @@ import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/rimport {loadAssetDataByProject,preparePublishedAssetData,+ validatePublishedAssetCollections,} from "@webstudio-is/asset-uploader/server";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import {@@ -160,15 +161,23 @@ const loadProductionCanvasDataAndProject = async (};};+const addProjectMetadataDependencies = {+ getUserById,+ preparePublishedAssetData,+ validatePublishedAssetCollections,+ createAssetClient,+};+const addProjectMetadata = async (data: ProjectBundle,project: Project,- context: AppContext+ context: AppContext,+ dependencies = addProjectMetadataDependencies): Promise<PublishedProjectBundle> => {const user =project.userId === null? undefined- : await getUserById(context, project.userId);+ : await dependencies.getUserById(context, project.userId);const publicationBuild = {...data.build,@@ -196,10 +205,10 @@ const addProjectMetadata = async (let publishedAssets = data.assets;let publishedAssetFolders = data.assetFolders;if (assetRequirements !== undefined) {- const publishedAssetData = await preparePublishedAssetData({+ const publishedAssetData = await dependencies.preparePublishedAssetData({projectId: project.id,context,- assetStore: createAssetClient(),+ assetStore: dependencies.createAssetClient(),contentDatabaseMaxBytes: getPublishedMdxContentDatabaseMaxBytes({baseBytes: getContentDatabaseMaxBytes(),assets: data.assets,@@ -225,6 +234,22 @@ const addProjectMetadata = async (assetIndex = publishedAssetData.artifact;publishedAssets = publishedAssetData.assets;publishedAssetFolders = publishedAssetData.assetFolders;+ } else {+ const publishedAssetData =+ await dependencies.validatePublishedAssetCollections({+ projectId: project.id,+ context,+ assetStore: dependencies.createAssetClient(),+ });+ const retainedFontIds = new Set(+ data.assets+ .filter((asset) => asset.type === "font")+ .map((asset) => asset.id)+ );+ publishedAssets = publishedAssetData.assets.filter(+ (asset) => asset.type !== "font" || retainedFontIds.has(asset.id)+ );+ publishedAssetFolders = publishedAssetData.assetFolders;}return {@@ -334,6 +359,7 @@ export const loadProjectBundleByProjectId = async (};export const __testing__ = {+ addProjectMetadata,createLoadPublishedProjectBundleByProjectId,serializeProjectBundle,};diff --git a/apps/builder/app/shared/design-token-import-dialog.tsx b/apps/builder/app/shared/design-token-import-dialog.tsxindex 8380743cfa..6eec7c9b71 100644--- a/apps/builder/app/shared/design-token-import-dialog.tsx+++ b/apps/builder/app/shared/design-token-import-dialog.tsx@@ -1,6 +1,7 @@import { atom } from "nanostores";import { useStore } from "@nanostores/react";import {+ PanelContent,Button,Dialog,DialogActions,@@ -8,7 +9,6 @@ import {DialogDescription,DialogTitle,Flex,- theme,} from "@webstudio-is/design-system";import { DialogRadioOptions } from "./dialog-radio-options";@@ -78,7 +78,7 @@ export const DesignTokenImportDialog = () => {><DialogContent css={{ minWidth: "40ch" }}><DialogTitle>Import tokens</DialogTitle>- <Flex direction="column" gap="2" css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex} direction="column" gap="2"><DialogDescription>Choose how these tokens should be represented in Webstudio.</DialogDescription>@@ -91,7 +91,7 @@ export const DesignTokenImportDialog = () => {}}}/>- </Flex>+ </PanelContent><DialogActions><Button autoFocus color="primary" onClick={() => finish(target)}>Importdiff --git a/apps/builder/app/shared/external-content-history.test.ts b/apps/builder/app/shared/external-content-history.test.tsnew file mode 100644index 0000000000..2fc61c106e--- /dev/null+++ b/apps/builder/app/shared/external-content-history.test.ts@@ -0,0 +1,143 @@+import { expect, test, vi } from "vitest";+import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";+import type { Asset } from "@webstudio-is/sdk";+import {+ createAssetContentBridge,+ __testing__,+} from "./asset-content-bridge.client";+import { $externalContentHistory } from "./external-content-history";+import { $externalContentRoots } from "./external-content-mutations";+import {+ disposeExternalContentProject,+ flushExternalContentAsset,+ traverseExternalContentHistory,+ updateExternalContentAssetSource,+} from "./external-content-roots";++const { initBridge, clearBridge } = __testing__;++test("undo and redo save source changes in order across article and author files", async () => {+ const projectId = "history-project";+ const stored = new Map([+ ["article", "# Original"],+ ["author", "---\nname: Original\n---"],+ ]);+ const describeAsset = (assetId: string): Asset => ({+ id: assetId,+ projectId,+ name: `${assetId}.mdx`,+ format: "mdx",+ type: "file",+ size: new TextEncoder().encode(stored.get(assetId)!).byteLength,+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ });+ const session = createAssetContentSession({+ repository: {+ readContent: async ({ assetId }) => ({+ asset: describeAsset(assetId),+ data: (async function* () {+ yield new TextEncoder().encode(stored.get(assetId)!);+ })(),+ }),+ updateContent: async ({ assetId, data }) => {+ stored.set(assetId, await new Response(data).text());+ return describeAsset(assetId);+ },+ },+ authorize: () => true,+ debounceMilliseconds: 0,+ });+ initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ try {+ await session.open("article");+ await session.open("author");+ await updateExternalContentAssetSource({+ projectId,+ assetId: "article",+ update: () => "# Changed",+ });+ $externalContentRoots.set(+ new Map([+ [+ "pending-root",+ {+ projectId,+ assetId: "author",+ blockInstanceId: "block",+ instanceIds: new Set(),+ mutationRevision: 1,+ savedMutationRevision: 0,+ },+ ],+ ])+ );+ let traversed = false;+ const pendingUndo = traverseExternalContentHistory({+ projectId,+ direction: "undo",+ }).then(() => {+ traversed = true;+ });+ // Let the queued command run while the canvas is still serializing its edit.+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(traversed).toBe(false);+ await updateExternalContentAssetSource({+ projectId,+ assetId: "author",+ update: () => "---\nname: Changed\n---",+ });+ $externalContentRoots.set(new Map());+ await pendingUndo;+ expect(session.get("author")?.source).toBe("---\nname: Original\n---");+ expect(session.get("article")?.source).toBe("# Changed");+ await traverseExternalContentHistory({ projectId, direction: "undo" });+ expect(session.get("article")?.source).toBe("# Original");+ await Promise.all([+ traverseExternalContentHistory({ projectId, direction: "redo" }),+ traverseExternalContentHistory({ projectId, direction: "redo" }),+ ]);+ expect(session.get("article")?.source).toBe("# Changed");+ expect(session.get("author")?.source).toBe("---\nname: Changed\n---");+ await flushExternalContentAsset({ projectId, assetId: "article" });+ await flushExternalContentAsset({ projectId, assetId: "author" });+ expect(stored.get("article")).toBe("# Changed");+ expect(stored.get("author")).toBe("---\nname: Changed\n---");+ await traverseExternalContentHistory({ projectId, direction: "undo" });+ await updateExternalContentAssetSource({+ projectId,+ assetId: "author",+ update: () => "---\nname: New edit\n---",+ });+ await traverseExternalContentHistory({ projectId, direction: "redo" });+ expect(session.get("author")?.source).toBe("---\nname: New edit\n---");++ // A source replaced outside this history must never be overwritten by undo.+ session.save("author", "---\nname: Concurrent edit\n---");+ await expect(+ traverseExternalContentHistory({ projectId, direction: "undo" })+ ).rejects.toThrow("changed since this edit");+ expect(session.get("author")?.source).toBe(+ "---\nname: Concurrent edit\n---"+ );+ } finally {+ $externalContentRoots.set(new Map());+ await updateExternalContentAssetSource({+ projectId,+ assetId: "author",+ update: (source) => source,+ });+ await disposeExternalContentProject({ projectId, session });+ expect($externalContentHistory.get().has(projectId)).toBe(false);+ session.dispose();+ clearBridge();+ }+});diff --git a/apps/builder/app/shared/external-content-history.ts b/apps/builder/app/shared/external-content-history.tsnew file mode 100644index 0000000000..e38d50329c--- /dev/null+++ b/apps/builder/app/shared/external-content-history.ts@@ -0,0 +1,45 @@+import { atom } from "nanostores";++type ContentHistory = {+ edits: readonly {+ id: string;+ assetId: string;+ before: string;+ after: string;+ }[];+ index: number;+};++// Source history is separate from the transient instance patches used to render+// MDX. Replaying those patches would also undo loading and rematerialization.+export const $externalContentHistory = atom<+ ReadonlyMap<string, ContentHistory>+>(new Map());++export const recordExternalContentHistory = ({+ projectId,+ assetId,+ before,+ after,+}: {+ projectId: string;+ assetId: string;+ before: string;+ after: string;+}) => {+ if (before === after) {+ return;+ }+ const current = $externalContentHistory.get();+ const history = current.get(projectId);+ const edits = [+ ...(history?.edits.slice(0, history.index) ?? []),+ { id: crypto.randomUUID(), assetId, before, after },+ ].slice(-20);+ $externalContentHistory.set(+ new Map(current).set(projectId, {+ edits,+ index: edits.length,+ })+ );+};diff --git a/apps/builder/app/shared/external-content-mutations.ts b/apps/builder/app/shared/external-content-mutations.tsindex 86d6520451..32c3f234a7 100644--- a/apps/builder/app/shared/external-content-mutations.ts+++ b/apps/builder/app/shared/external-content-mutations.ts@@ -27,6 +27,7 @@ import type {import type { MdxDocument } from "@webstudio-is/content-engine/mdx";import { atom, type ReadableAtom } from "nanostores";import type { ExternalContentOwnership } from "./external-content-persistence";+import type { FrontmatterSource } from "./content-block-document";export type ExternalContentRoot = {sourceBlockInstanceId?: Instance["id"];@@ -44,18 +45,23 @@ export type ExternalContentRoot = {/** Latest template ownership observed in the project stores. */templateOwnership?: ExternalContentOwnership;mutationRevision: number;+ /** Last mutation serialized into the shared source session. */+ savedMutationRevision?: number;/** Cross-realm signal that the mounted content must resolve templates again. */templateMutationRevision?: number;projectId?: string;assetId?: string;/** User-visible failure from the latest template rematerialization attempt. */templateMaterializationError?: string;+ /** Save preparation failure shared with controls in the Builder frame. */+ persistenceError?: string;/** Unsaved clones that retain the exact template selected by the user. */insertedTemplates?: ReadonlyMap<Instance["id"], MdxTemplateInsertion>;identity?: ContentBlockExternalContentIdentity;diagnostics?: readonly ContentBlockDiagnostic[];document?: MdxDocument;frontmatter?: Readonly<Record<string, unknown>>;+ frontmatterSources?: readonly FrontmatterSource[];transientInstanceIds?: ReadonlySet<Instance["id"]>;};@@ -254,12 +260,14 @@ export const registerExternalContentRoot = (const registeredRoot = {...root,mutationRevision: current.get(key)?.mutationRevision ?? 0,+ savedMutationRevision: current.get(key)?.savedMutationRevision ?? 0,templateMutationRevision:current.get(key)?.templateMutationRevision ??root.templateMutationRevision ??0,templateMaterializationError:current.get(key)?.templateMaterializationError,+ persistenceError: current.get(key)?.persistenceError,insertedTemplates:current.get(key)?.insertedTemplates ?? root.insertedTemplates,};diff --git a/apps/builder/app/shared/external-content-roots.test.ts b/apps/builder/app/shared/external-content-roots.test.tsindex 8d2e6797dd..0e816f2d66 100644--- a/apps/builder/app/shared/external-content-roots.test.ts+++ b/apps/builder/app/shared/external-content-roots.test.ts@@ -15,6 +15,7 @@ import {import {__testing__ as assetContentBridgeTesting,createAssetContentBridge,+ getAssetContentBridge,} from "./asset-content-bridge.client";import {acquireExternalContentRoot,@@ -67,12 +68,17 @@ import {} from "./sync/sync-stores";import { createSyncChangesFromBuilderPatchPayload } from "./sync/builder-patch";import { insertTemplateAt } from "~/builder/features/workspace/canvas-tools/outline/block-utils";+import { __testing__ as builderApiTesting } from "./builder-api";++const { canAccessAssetContent } = builderApiTesting;registerContainers();test("places unresolved-template placeholders at their authored nesting point", async () => {const source ='<ws.element ws:tag="section">Before<ws.element ws:name="Missing" />After</ws.element>';+ let storedSource = source;+ const writes: string[] = [];const sourceAsset = {...asset,size: new TextEncoder().encode(source).byteLength,@@ -82,10 +88,17 @@ test("places unresolved-template placeholders at their authored nesting point",readContent: async () => ({asset: sourceAsset,data: (async function* () {- yield new TextEncoder().encode(source);+ yield new TextEncoder().encode(storedSource);})(),}),- updateContent: async () => sourceAsset,+ updateContent: async ({ data }) => {+ storedSource = await new Response(data).text();+ writes.push(storedSource);+ return {+ ...sourceAsset,+ size: new TextEncoder().encode(storedSource).byteLength,+ };+ },},authorize: () => true,});@@ -155,6 +168,17 @@ test("places unresolved-template placeholders at their authored nesting point",renderScope: '["block"]',})).toEqual([{ type: "id", value: section.id }]);+ executeRuntimeMutation({+ id: "instances.deleteBySelector",+ input: { instanceSelector: [missing.id, section.id, "block"] },+ });+ await flushExternalContentAsset({+ projectId: "project",+ assetId: sourceAsset.id,+ });+ expect(writes).toHaveLength(1);+ expect(storedSource).toBe("<section>BeforeAfter</section>\n");+ expect($instances.get().has(missing.id)).toBe(false);});test("re-resolves existing Markdown when a matching template is added", async () => {@@ -1013,12 +1037,19 @@ test.each([{name: "keeps the selected JSX template when editing immediately after insertion",verifyFirstSaveCleanup: false,+ editAfterFirstSave: false,},{name: "clears insertion metadata after the first queued save",verifyFirstSaveCleanup: true,+ editAfterFirstSave: false,},-])("$name", async ({ verifyFirstSaveCleanup }) => {+ {+ name: "saves edits to a template after its insertion metadata is cleared",+ verifyFirstSaveCleanup: false,+ editAfterFirstSave: true,+ },+])("$name", async ({ verifyFirstSaveCleanup, editAfterFirstSave }) => {const initialSource = "# Existing\n";const sourceAsset = {...asset,@@ -1082,6 +1113,7 @@ test.each([]),tag: "p",label: "Card",+ ...(editAfterFirstSave ? { name: "Card" } : {}),},],[@@ -1154,13 +1186,23 @@ test.each([throw new Error("Expected the inserted Card");}- if (verifyFirstSaveCleanup) {+ if (verifyFirstSaveCleanup || editAfterFirstSave) {await vi.waitFor(() =>expect(getExternalContentRoots().values().next().value?.insertedTemplates).toBeUndefined());- return;+ if (verifyFirstSaveCleanup) {+ return;+ }+ await flushExternalContentAsset({+ projectId: "project",+ assetId: sourceAsset.id,+ });+ expect(+ getExternalContentRoots().values().next().value?.persistenceError+ ).toBeUndefined();+ expect(storedSource).toBe("# Existing\n\n<Card />\n");}await expect(@@ -1214,9 +1256,22 @@ test.each([expect(writes.at(-1)).toBe('# Existing\n\n<Card title="Edited">Edited text</Card>\n');- expect(- getExternalContentRoots().values().next().value?.insertedTemplates- ).toBeUndefined();+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: inserted.value,+ mode: "text",+ text: "Edited again",+ },+ });+ await flushExternalContentAsset({+ projectId: "project",+ assetId: sourceAsset.id,+ });+ expect(writes.at(-1)).toBe(+ '# Existing\n\n<Card title="Edited">Edited again</Card>\n'+ );release();releases.splice(releases.indexOf(release), 1);@@ -1405,7 +1460,7 @@ test("rebases frontmatter edits from Content Blocks sharing one Asset", async ()}await Promise.all([- updateExternalContentFrontmatter({+ getAssetContentBridge().updateFrontmatter({rootKey: firstKey,path: ["title"],value: "After",@@ -1600,6 +1655,8 @@ test("replaces a mounted root when its source Asset changes", async () => {});test("installs MDX into the Body and recovers an invalid dependency", async () => {+ const writes: Array<{ assetId: string; source: string }> = [];+ let allowReferenceWrite = true;const source = `---author:$ref: ./author.md#frontmatter@@ -1653,6 +1710,7 @@ role: editorupdateContent: async ({ assetId, data }) => {const updatedSource = await new Response(data).text();const currentAsset = assetId === authorAsset.id ? authorAsset : asset;+ writes.push({ assetId, source: updatedSource });return {...currentAsset,size: new TextEncoder().encode(updatedSource).byteLength,@@ -1666,7 +1724,12 @@ role: editorcreateAssetContentBridge({origin: window.location.origin,request: fetch,- authorize: () => true,+ authorize: ({ assetId, operation }) =>+ canAccessAssetContent({+ asset: assetId === authorAsset.id ? authorAsset : asset,+ operation,+ canWrite: assetId !== authorAsset.id || allowReferenceWrite,+ }),requireReload: vi.fn(),getContentSession: () => session,})@@ -1766,15 +1829,20 @@ role: editor}).map(({ id }) => id)).toEqual([asset.id, authorAsset.id, avatarAsset.id]);- session.save(- authorAsset.id,- `----name: Ada Lovelace-avatar:- $ref: ./avatar.jpg-----`- );+ const rootKey = Array.from(getExternalContentRoots().keys())[0];+ writes.length = 0;+ await Promise.all([+ getAssetContentBridge().updateFrontmatter({+ rootKey,+ path: ["author", "name"],+ value: "Ada Lovelace",+ }),+ updateExternalContentFrontmatter({+ rootKey,+ path: ["author", "role"],+ value: "Writer",+ }),+ ]);await flushExternalContentAsset({projectId: "project",assetId: authorAsset.id,@@ -1785,10 +1853,25 @@ avatar:).toEqual({author: {name: "Ada Lovelace",+ role: "Writer",avatar: expect.objectContaining({ id: avatarAsset.id }),},});+ expect(writes.length).toBeGreaterThan(0);+ expect(writes.every(({ assetId }) => assetId === authorAsset.id)).toBe(true);+ expect(session.get(asset.id)?.source).toBe(source);+ expect(session.get(authorAsset.id)?.source).toContain("$ref: ./avatar.jpg");+ allowReferenceWrite = false;+ await expect(+ getAssetContentBridge().updateFrontmatter({+ rootKey,+ path: ["author", "name"],+ value: "Forbidden",+ })+ ).rejects.toThrow("permission");+ expect(session.get(authorAsset.id)?.source).not.toContain("Forbidden");+release();expect($instances.get().get("body-outlet")?.children).toEqual([]);expect($instances.get().has("header")).toBe(true);@@ -2484,6 +2567,23 @@ test("materializes into normal instances and saves their synchronous mutations o})?.identity;expect(savedIdentity?.contentRef).toBe("article_v2.mdx");expect(savedIdentity?.revision).not.toBe(initialIdentity?.revision);+ // An edit can arrive as soon as its predecessor is acknowledged, while+ // asynchronous materialization of the new revision is still in flight.+ const unsubscribe = session.subscribe((assetId, state) => {+ if (assetId !== asset.id || state.status !== "saved") {+ return;+ }+ unsubscribe();+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: insertedId,+ mode: "text",+ text: "Second after acknowledged save",+ },+ });+ });executeRuntimeMutation({id: "instances.setTextContent",input: {@@ -2495,7 +2595,11 @@ test("materializes into normal instances and saves their synchronous mutations o});expect(serverSyncStore.popAll()).toEqual([]);await flushExternalContentAsset({ projectId: "project", assetId: asset.id });- expect(writes.at(-1)).toBe("# Updated\n\n## Second after save\n");+ await flushExternalContentAsset({ projectId: "project", assetId: asset.id });+ expect(requireReload).not.toHaveBeenCalled();+ expect(writes.at(-1)).toBe(+ "# Updated\n\n## Second after acknowledged save\n"+ );expect(getExternalContentRootChildren({projectId: "project",@@ -2638,6 +2742,12 @@ test("materializes into normal instances and saves their synchronous mutations o).rejects.toThrow("The MDX content source must be structurally valid before canvas edits can be saved.");+ expect(+ findExternalContentRoot(getExternalContentRoots(), "block", '["block"]')+ ?.persistenceError+ ).toBe(+ "The MDX content source must be structurally valid before canvas edits can be saved."+ );session.save(asset.id, "# Repaired");await session.flush(asset.id);diff --git a/apps/builder/app/shared/external-content-roots.ts b/apps/builder/app/shared/external-content-roots.tsindex 568771dcfe..df9b72c2ed 100644--- a/apps/builder/app/shared/external-content-roots.ts+++ b/apps/builder/app/shared/external-content-roots.ts@@ -2,6 +2,10 @@* Manages the live lifecycle between connected Asset documents and canvas* instances: materialization, persistence, template refresh, and cleanup.*/+import {+ $externalContentHistory,+ recordExternalContentHistory,+} from "./external-content-history";import {createCanonicalAssetPath,createMarkdownFrontmatterDiagnostics,@@ -12,6 +16,7 @@ import {} from "@webstudio-is/content-engine/mdx";import {compileDocumentSourceGraph,+ extractMarkdownFrontmatter,createDocumentSourceUrl,createUniqueAssetIdsByPath,discoverAssetValueReferences,@@ -83,7 +88,11 @@ import {isRepeatedContentBlockOccurrence,parseContentBlockRenderScope,} from "./content-block-source-utils";-import { setObjectPathValue } from "./content-block-document";+import {+ getFrontmatterWriteTarget,+ setObjectPathValue,+ type FrontmatterSource,+} from "./content-block-document";type RootEntry = {key: string;@@ -106,10 +115,12 @@ type RootEntry = {templateRematerialization?: Promise<void>;saveRevision: number;dependencyAssetIds: ReadonlySet<string>;+ frontmatterSources?: readonly FrontmatterSource[];};type AssetQueue = {projectId: string;+ assetId: string;pendingSnapshots: number;serialization: Promise<void>;failedUpdate?: AssetUpdate;@@ -128,7 +139,7 @@ type PreparedAssetUpdate =| string| Readonly<{source: string;- document: MdxDocument;+ document?: MdxDocument;afterSave?: () => void;}>| undefined;@@ -229,6 +240,7 @@ const getAssetQueue = (projectId: string, assetId: string) => {if (queue === undefined) {queue = {projectId,+ assetId,pendingSnapshots: 0,serialization: Promise.resolve(),listeners: new Set(),@@ -253,6 +265,23 @@ const parseAssetSource = (};const publishAssetQueueError = (queue: AssetQueue) => {+ const current = getExternalContentRoots();+ const next = new Map(current);+ const persistenceError = queue.error?.message;+ let changed = false;+ for (const [key, root] of current) {+ if (+ root.projectId === queue.projectId &&+ root.assetId === queue.assetId &&+ root.persistenceError !== persistenceError+ ) {+ next.set(key, { ...root, persistenceError });+ changed = true;+ }+ }+ if (changed) {+ $externalContentRoots.set(next);+ }for (const listener of queue.listeners) {listener(queue.error);}@@ -363,7 +392,7 @@ const registerMutationRoot = (const owned = getExternalContentFragmentOwnership(fragment);const templateSnapshot = getTemplateSnapshot(entry);const instanceSelector = parseContentBlockRenderScope(entry.renderScope);- entry.unregisterMutationRoot = registerExternalContentRoot(entry.key, {+ const unregisterRoot = registerExternalContentRoot(entry.key, {sourceBlockInstanceId: entry.sourceBlockInstanceId,sourceRenderScope: entry.renderScope,blockInstanceId: entry.blockInstanceId,@@ -389,7 +418,18 @@ const registerMutationRoot = (entry.root.resolvedFrontmatter ??entry.root.document.frontmatter.properties,transientInstanceIds: entry.transientInstanceIds,+ frontmatterSources: entry.frontmatterSources,+ });+ const unregisterWriter = getAssetContentBridge().registerFrontmatterWriter({+ rootKey: entry.key,+ projectId: entry.projectId,+ assetId: entry.assetId,+ update: updateExternalContentFrontmatter,});+ entry.unregisterMutationRoot = () => {+ unregisterRoot();+ unregisterWriter();+ };};const installRoot = ({@@ -588,6 +628,7 @@ const resolveExternalContentFrontmatter = async (entry: RootEntry,sourceState: AssetContentSessionState) => {+ entry.frontmatterSources = undefined;const data = getWebstudioData();const hierarchy = createAssetFolderHierarchy(data.assetFolders ?? new Map());const assets = Array.from(data.assets.values());@@ -623,6 +664,7 @@ const resolveExternalContentFrontmatter = async ();const session = getSession(entry.projectId);const referencesByDocumentId = new Map<string, AssetValueReference[]>();+ const frontmatterSources: FrontmatterSource[] = [];const getReferencedAssetIds = (documentIds: Iterable<string>) =>Array.from(documentIds).flatMap((id) =>(referencesByDocumentId.get(id) ?? []).map(({ assetId }) => assetId)@@ -669,6 +711,14 @@ const resolveExternalContentFrontmatter = async (onDocumentProperties: ({ id, properties }) => {const sourcePath = assetPathsById.get(id);if (sourcePath !== undefined) {+ const document = documentAssets.find(({ asset }) => asset.id === id);+ if (document?.format === "markdown" || document?.format === "mdx") {+ frontmatterSources.push({+ assetId: id,+ documentUrl: createDocumentSourceUrl(sourcePath),+ properties,+ });+ }referencesByDocumentId.set(id,discoverAssetValueReferences({@@ -732,6 +782,7 @@ const resolveExternalContentFrontmatter = async (};},});+ entry.frontmatterSources = frontmatterSources;return properties;};@@ -857,14 +908,21 @@ const rematerializeAsset = async (preservedEntry?.projectId === projectId &&preservedEntry.assetId === assetId) {+ // This is our own document's save acknowledgment. Advance its revision+ // before async parsing so the next local edit does not look like a conflict.+ const version = ++preservedEntry.openVersion;+ preservedEntry.root = {+ ...preservedEntry.root,+ identity: createExternalContentIdentity(preservedEntry, sourceState),+ };+ registerMutationRoot(preservedEntry, preservedEntry.installedFragment);const result = await materialize({ entry: preservedEntry, sourceState });- if (roots.get(preservedEntry.key) === preservedEntry) {+ if (+ roots.get(preservedEntry.key) === preservedEntry &&+ preservedEntry.openVersion === version+ ) {// Preserve the synchronously edited fragment and refresh only the// source-owned state that does not participate in the current selection.- preservedEntry.root = {- ...preservedEntry.root,- identity: createExternalContentIdentity(preservedEntry, sourceState),- };preservedEntry.diagnostics = result.diagnostics;registerMutationRoot(preservedEntry, preservedEntry.installedFragment);}@@ -927,20 +985,15 @@ const getSession = (projectId: string) => {const extractRootFragment = ({contentInstanceId,- children: rootChildren,- transientInstanceIds,+ children,}: {contentInstanceId: string;children: WebstudioFragment["children"];- transientInstanceIds: ReadonlySet<string>;}) => {const data = getWebstudioData();if (data.instances.has(contentInstanceId) === false) {throw new Error("Connected Content Block no longer exists");}- const isPersistentChild = (child: WebstudioFragment["children"][number]) =>- child.type !== "id" || transientInstanceIds.has(child.value) === false;- const children = rootChildren.filter(isPersistentChild);const rootIds = children.flatMap((child) =>child.type === "id" ? [child.value] : []);@@ -951,12 +1004,6 @@ const extractRootFragment = ({return {...fragment,children,- instances: fragment.instances- .filter(({ id }) => transientInstanceIds.has(id) === false)- .map((instance) => ({- ...instance,- children: instance.children.filter(isPersistentChild),- })),};};@@ -964,26 +1011,8 @@ const extractCurrentFragment = (entry: RootEntry) =>extractRootFragment({contentInstanceId: entry.contentInstanceId,children: getAuthoredChildren(entry),- transientInstanceIds: entry.transientInstanceIds,});-const captureInstalledFragment = (- entry: RootEntry,- fragment: WebstudioFragment-): WebstudioFragment => {- const data = getWebstudioData();- const transientInstances = Array.from(entry.transientInstanceIds).flatMap(- (id) => {- const instance = data.instances.get(id);- return instance === undefined ? [] : [instance];- }- );- return {- ...fragment,- instances: [...fragment.instances, ...transientInstances],- };-};-const getInsertedTemplates = (entry: RootEntry,fragment: WebstudioFragment@@ -1015,11 +1044,13 @@ const enqueueAssetUpdate = ({assetId,update,preservedRootKey,+ recordHistory = true,}: {projectId: string;assetId: string;update: AssetUpdate;preservedRootKey?: string;+ recordHistory?: boolean;}) => {const queue = getAssetQueue(projectId, assetId);const session = getSession(projectId);@@ -1043,10 +1074,18 @@ const enqueueAssetUpdate = ({}const source = typeof prepared === "string" ? prepared : prepared.source;queue.latestDocument =- typeof prepared === "string"+ typeof prepared === "string" || prepared.document === undefined? undefined: { source, document: prepared.document };session.save(assetId, source);+ if (recordHistory) {+ recordExternalContentHistory({+ projectId,+ assetId,+ before: state.source,+ after: source,+ });+ }if (typeof prepared !== "string") {prepared.afterSave?.();}@@ -1093,6 +1132,112 @@ const enqueueAssetUpdate = ({return tracked;};+const applyExternalContentHistory = async ({+ projectId,+ direction,+}: {+ projectId: string;+ direction: "undo" | "redo";+}) => {+ await new Promise<void>((resolve, reject) => {+ const finish = (error?: Error) => {+ clearTimeout(timeout);+ unsubscribe();+ if (error === undefined) {+ resolve();+ } else {+ reject(error);+ }+ };+ const check = () => {+ const pending = Array.from(getExternalContentRoots().values()).filter(+ (root) =>+ root.projectId === projectId &&+ root.mutationRevision > (root.savedMutationRevision ?? 0)+ );+ const failed = pending.find(+ (root) => root.persistenceError !== undefined+ );+ if (failed !== undefined) {+ finish(new Error(failed.persistenceError));+ } else if (pending.length === 0) {+ finish();+ }+ };+ const timeout = setTimeout(+ () =>+ finish(+ new Error(+ "Wait for the article changes to finish saving, then try again."+ )+ ),+ 10000+ );+ const unsubscribe = $externalContentRoots.listen(check);+ check();+ });+ const history = $externalContentHistory.get().get(projectId);+ if (history === undefined) {+ return;+ }+ const editIndex = direction === "undo" ? history.index - 1 : history.index;+ const edit = history.edits[editIndex];+ if (edit === undefined) {+ return;+ }+ const { assetId } = edit;+ await getSession(projectId).open(assetId);+ return enqueueAssetUpdate({+ projectId,+ assetId,+ recordHistory: false,+ update: (state) => {+ const current = $externalContentHistory.get().get(projectId);+ if (+ current?.index !== history.index ||+ current.edits[editIndex]?.id !== edit.id ||+ (direction === "undo" ? edit.after : edit.before) !== state.source+ ) {+ throw new MdxAuthoredContentConflictError(+ "The article changed since this edit. Reload it before continuing."+ );+ }+ return {+ source: direction === "undo" ? edit.before : edit.after,+ afterSave: () => {+ $externalContentHistory.set(+ new Map($externalContentHistory.get()).set(projectId, {+ ...history,+ index: history.index + (direction === "undo" ? -1 : 1),+ })+ );+ },+ };+ },+ });+};++const contentHistoryTraversals = new Map<string, Promise<void>>();++export const traverseExternalContentHistory = (+ input: Parameters<typeof applyExternalContentHistory>[0]+) => {+ const pending =+ contentHistoryTraversals.get(input.projectId) ?? Promise.resolve();+ const next = pending+ .catch(() => {})+ .then(() => applyExternalContentHistory(input));+ contentHistoryTraversals.set(input.projectId, next);+ void next+ .finally(() => {+ if (contentHistoryTraversals.get(input.projectId) === next) {+ contentHistoryTraversals.delete(input.projectId);+ }+ })+ .catch(() => {});+ return next;+};+subscribeExternalContentMutations((rootKeys) => {for (const key of rootKeys) {const entry = roots.get(key);@@ -1110,8 +1255,10 @@ subscribeExternalContentMutations((rootKeys) => {});const insertedTemplates = getInsertedTemplates(entry, fragment);const authoredRoot = entry.root;+ const mutationRevision =+ getExternalContentRoots().get(key)?.mutationRevision ?? 0;const saveRevision = ++entry.saveRevision;- entry.installedFragment = captureInstalledFragment(entry, fragment);+ entry.installedFragment = fragment;registerMutationRoot(entry, entry.installedFragment);void enqueueAssetUpdate({projectId: entry.projectId,@@ -1206,7 +1353,23 @@ subscribeExternalContentMutations((rootKeys) => {}),};},- }).catch(() => {});+ })+ .then(() => {+ const current = getExternalContentRoots();+ const root = current.get(key);+ if (root !== undefined && roots.get(key) === entry) {+ $externalContentRoots.set(+ new Map(current).set(key, {+ ...root,+ savedMutationRevision: Math.max(+ root.savedMutationRevision ?? 0,+ mutationRevision+ ),+ })+ );+ }+ })+ .catch(() => {});}});@@ -1378,7 +1541,127 @@ export const updateExternalContentFrontmatter = ({}) => {const entry = roots.get(rootKey);if (entry === undefined) {- return Promise.reject(new Error("Connected Content Block is not open"));+ // Settings run in the Builder frame; mounted documents and their save+ // queues belong to the canvas. Route the write to that same owner.+ return getAssetContentBridge().updateFrontmatter({+ rootKey,+ path,+ value,+ resolvedValue,+ });+ }+ const target = getFrontmatterWriteTarget({+ assetId: entry.assetId,+ value: entry.root.document.frontmatter.properties,+ path,+ sources: entry.frontmatterSources,+ });+ if (target === undefined) {+ return Promise.reject(+ new Error("This frontmatter value cannot be edited.")+ );+ }+ if (target.assetId !== entry.assetId) {+ const sources = entry.frontmatterSources ?? [];+ const session = getSession(entry.projectId);+ return enqueueAssetUpdate({+ projectId: entry.projectId,+ assetId: target.assetId,+ update: async (state, queuedDocument) => {+ if (roots.get(rootKey) !== entry) {+ throw new Error("Connected Content Block is no longer open.");+ }+ if (+ !getAssetContentBridge().authorize({+ projectId: entry.projectId,+ assetId: target.assetId,+ operation: "write",+ })+ ) {+ throw new Error(+ "You do not have permission to edit the referenced file."+ );+ }+ const data = getWebstudioData();+ const hierarchy = createAssetFolderHierarchy(+ data.assetFolders ?? new Map()+ );+ const currentSources = await Promise.all(+ sources.map(async (source) => {+ const asset = data.assets.get(source.assetId);+ const content = session.get(source.assetId);+ if (asset === undefined || content === undefined) {+ throw new Error(+ "A referenced file is no longer available. Reload before editing."+ );+ }+ return {+ ...source,+ documentUrl: createDocumentSourceUrl(+ createCanonicalAssetPath({+ name: formatAssetName(asset),+ folderNames: hierarchy+ .getPath(asset.folderId)+ .map(({ name }) => name),+ })+ ),+ properties: (+ await extractMarkdownFrontmatter(+ new TextEncoder().encode(content.source)+ )+ ).properties,+ };+ })+ );+ const rootSource = currentSources.find(+ (source) => source.assetId === entry.assetId+ );+ const currentTarget =+ rootSource === undefined+ ? undefined+ : getFrontmatterWriteTarget({+ assetId: entry.assetId,+ value: rootSource.properties,+ path,+ sources: currentSources,+ });+ if (+ currentTarget === undefined ||+ currentTarget.assetId !== target.assetId ||+ JSON.stringify(currentTarget.path) !== JSON.stringify(target.path) ||+ JSON.stringify(currentTarget.via) !== JSON.stringify(target.via)+ ) {+ throw new Error(+ "The authoring reference changed. Reload before editing."+ );+ }+ const properties =+ queuedDocument?.frontmatter.properties ??+ (+ await extractMarkdownFrontmatter(+ new TextEncoder().encode(state.source)+ )+ ).properties;+ const updatedProperties = setObjectPathValue({+ value: properties,+ path: target.path,+ nextValue: value,+ });+ // Keep a concurrently edited MDX body in the shared queue. Markdown+ // dependencies need only a frontmatter replacement, never MDX parsing.+ if (queuedDocument !== undefined) {+ const document = {+ ...queuedDocument,+ frontmatter: { properties: updatedProperties },+ };+ return { source: serializeMdxDocument(document), document };+ }+ return replaceMdxFrontmatter({+ source: state.source,+ properties: updatedProperties,+ });+ },+ });}const properties = setObjectPathValue({value: entry.root.document.frontmatter.properties,@@ -1722,8 +2005,20 @@ export const subscribeExternalContentAsset = ({const session = getSession(projectId);const queue = getAssetQueue(projectId, assetId);const publish = (state: AssetContentSessionState) => {+ const persistenceError = Array.from(+ getExternalContentRoots().values()+ ).find(+ (root) =>+ root.projectId === projectId &&+ root.assetId === assetId &&+ root.persistenceError !== undefined+ )?.persistenceError;const error =- queue.error ?? getTemplateMaterializationError(projectId, assetId);+ queue.error ??+ (persistenceError === undefined+ ? undefined+ : new Error(persistenceError)) ??+ getTemplateMaterializationError(projectId, assetId);listener(error === undefined ? state : { ...state, status: "failed", error });@@ -1793,7 +2088,6 @@ export const getExternalContentRootSnapshot = ({getWebstudioData().instances.get(root.contentInstanceId ?? root.blockInstanceId)?.children ?? [],- transientInstanceIds: root.transientInstanceIds ?? new Set(),}),identity: root.identity,};@@ -1916,6 +2210,9 @@ export const disposeExternalContentProject = async ({}}subscribedSessions.delete(session);+ const history = new Map($externalContentHistory.get());+ history.delete(projectId);+ $externalContentHistory.set(history);return true;};diff --git a/apps/builder/app/shared/instance-utils/data.test.tsx b/apps/builder/app/shared/instance-utils/data.test.tsxindex 4dd43eda4a..0d3022635e 100644--- a/apps/builder/app/shared/instance-utils/data.test.tsx+++ b/apps/builder/app/shared/instance-utils/data.test.tsx@@ -8,7 +8,10 @@ import {type PageTemplate,} from "@webstudio-is/sdk";import { createDefaultPages } from "@webstudio-is/project-build";-import { findCycles } from "@webstudio-is/project-build/runtime";+import {+ findCycles,+ extractWebstudioFragment,+} from "@webstudio-is/project-build/runtime";import type { BuilderRuntimeOperationInput } from "@webstudio-is/project-build/runtime";import {executeRuntimeMutation,@@ -108,6 +111,130 @@ const createImageAsset = (id: string): Asset => ({});describe("data store helpers", () => {+ test.each([+ "move",+ "reparent",+ "paste",+ "nested paste",+ "aliased template paste",+ "duplicate",+ "sequence",+ ])(+ "rejects %s of an unsupported component into MDX before committing",+ (operation) => {+ setBaseStores();+ const accordion = "@webstudio-is/sdk-components-react-radix:Accordion";+ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", "Body", [+ { type: "id", value: "block" },+ { type: "id", value: "accordion" },+ ]),+ ],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, []),+ ],+ ["accordion", createInstance("accordion", accordion, [])],+ ])+ );+ $externalContentRoots.set(+ new Map([+ [+ "root",+ {+ blockInstanceId: "block",+ instanceIds: new Set(),+ mutationRevision: 0,+ },+ ],+ ])+ );+ if (operation === "aliased template paste") {+ $instances.get().set("accordion-template", {+ ...createInstance("accordion-template", accordion, []),+ name: "FAQ",+ });+ $instances.get().get("templates")!.children = [+ { type: "id", value: "accordion-template" },+ ];+ }+ if (operation === "duplicate") {+ $instances.get().get("body")!.children = [+ { type: "id", value: "block" },+ ];+ $instances+ .get()+ .get("block")!+ .children.push({ type: "id", value: "accordion" });+ $externalContentRoots.get().get("root")!.instanceIds = new Set([+ "accordion",+ ]);+ }+ const before = structuredClone(getWebstudioData());+ const move = {+ id: "instances.move",+ input: {+ moves: [{ instanceId: "accordion", parentInstanceId: "block" }],+ },+ } satisfies RuntimeMutationOperation;+ expect(() => {+ if (operation === "move") {+ executeRuntimeMutation(move);+ } else if (operation === "reparent") {+ executeRuntimeMutation({+ id: "instances.reparent",+ input: {+ sourceInstanceSelector: ["accordion", "body"],+ dropTarget: {+ parentSelector: ["block", "body"],+ position: "end",+ },+ },+ });+ } else if (+ operation === "paste" ||+ operation === "nested paste" ||+ operation === "aliased template paste"+ ) {+ const fragment = extractWebstudioFragment(before, "accordion");+ if (operation === "nested paste") {+ fragment.instances.push({+ ...createInstance("wrapper", elementComponent, fragment.children),+ tag: "div",+ });+ fragment.children = [{ type: "id", value: "wrapper" }];+ }+ executeRuntimeMutation({+ id: "instances.insertFragment",+ input: {+ parentInstanceId: "block",+ fragment,+ },+ });+ } else if (operation === "duplicate") {+ executeRuntimeMutation({+ id: "instances.duplicateAfterItself",+ input: { sourceInstanceId: "accordion", parentInstanceId: "block" },+ });+ } else {+ executeRuntimeMutationSequence([move]);+ }+ }).toThrow("MDX");+ expect(getWebstudioData()).toEqual(before);+ expect(serverSyncStore.popAll()).toEqual([]);+ expect(externalContentSyncStore.popAll()).toEqual([]);+ expect($externalContentRoots.get().get("root")?.mutationRevision).toBe(0);+ }+ );test("publishes external children only after their instances exist", () => {setBaseStores();$instances.set(diff --git a/apps/builder/app/shared/instance-utils/data.ts b/apps/builder/app/shared/instance-utils/data.tsindex 7209da10a6..ceb65efe88 100644--- a/apps/builder/app/shared/instance-utils/data.ts+++ b/apps/builder/app/shared/instance-utils/data.ts@@ -2,13 +2,22 @@// transaction boundaries. Put generic store reads/writes and content-mode data// guards here, not tree-shape mutations.import { toast } from "@webstudio-is/design-system";-import { type WebstudioData, isPageTemplate } from "@webstudio-is/sdk";+import {+ type WebstudioData,+ isPageTemplate,+ blockTemplateComponent,+ contentBlockMdxTemplateDescriptors,+ elementComponent,+ findTreeInstanceIds,+ getContentBlockTemplateName,+} from "@webstudio-is/sdk";import {BuilderRuntimeError,blockTemplateNameConfirmationInput,builderRuntimeContext,executeBuilderRuntimeOperation,createRuntimeMutationAccumulator,+ findBlockTemplates,type BuilderRuntimeContext,type BuilderRuntimeMutation,type BuilderRuntimeOperationInput,@@ -186,6 +195,83 @@ const commitRuntimeMutation = <Mutation extends BuilderRuntimeMutation>(const afterData = applyBuilderPatchTransactions(data, [{ id: "external-content-persistence-plan", payload },]).state as ReturnType<typeof getWebstudioData>;+ for (const key of affectedRootKeys) {+ const root = roots.get(key);+ if (root === undefined) {+ continue;+ }+ const templates =+ findBlockTemplates({+ anchor: [root.sourceBlockInstanceId ?? root.blockInstanceId],+ instances: afterData.instances,+ }) ?? [];+ const templateInstanceIds = new Set<string>();+ const matchTemplate = (instanceId: string, templateId: string) => {+ const instance = afterData.instances.get(instanceId);+ const template = afterData.instances.get(templateId);+ if (+ instance === undefined ||+ template === undefined ||+ instance.component !== template.component ||+ instance.tag !== template.tag ||+ templateInstanceIds.has(instanceId)+ ) {+ return;+ }+ templateInstanceIds.add(instanceId);+ instance.children.forEach((child, index) => {+ const templateChild = template.children[index];+ if (child.type === "id" && templateChild?.type === "id") {+ matchTemplate(child.value, templateChild.value);+ }+ });+ };+ const content = afterData.instances.get(+ root.contentInstanceId ?? root.blockInstanceId+ );+ for (const child of content?.children ?? []) {+ if (+ child.type !== "id" ||+ afterData.instances.get(child.value)?.component ===+ blockTemplateComponent+ ) {+ continue;+ }+ for (const id of findTreeInstanceIds(afterData.instances, child.value)) {+ const instance = afterData.instances.get(id);+ if (instance !== undefined) {+ const matching = templates.filter(+ ([template]) =>+ getContentBlockTemplateName(template) ===+ getContentBlockTemplateName(instance)+ );+ if (matching.length === 1) {+ matchTemplate(id, matching[0][0].id);+ }+ }+ if (+ instance === undefined ||+ (root.instanceIds.has(id) &&+ data.instances.get(id)?.component === instance.component) ||+ instance.component === elementComponent ||+ contentBlockMdxTemplateDescriptors.some(+ (descriptor) =>+ descriptor.kind === "component" &&+ descriptor.component === instance.component+ ) ||+ templateInstanceIds.has(id)+ ) {+ continue;+ }+ const error = new BuilderRuntimeError(+ "BAD_REQUEST",+ "This component is not in this Content Block’s Templates and cannot be added to MDX content. Add it to Templates first, or keep it outside MDX content."+ );+ toast.error(error.message);+ throw error;+ }+ }+ }const afterOwnership = getExternalContentOwnershipFromState({state: afterData,roots,diff --git a/apps/builder/app/shared/instance-utils/insert.test.tsx b/apps/builder/app/shared/instance-utils/insert.test.tsxindex 62b7bae07c..12a5a65577 100644--- a/apps/builder/app/shared/instance-utils/insert.test.tsx+++ b/apps/builder/app/shared/instance-utils/insert.test.tsx@@ -22,7 +22,12 @@ import {} from "@webstudio-is/template";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";import type { WebstudioData, WebstudioFragment } from "@webstudio-is/sdk";-import { coreMetas, elementComponent } from "@webstudio-is/sdk";+import {+ blockBodyComponent,+ blockComponent,+ coreMetas,+ elementComponent,+} from "@webstudio-is/sdk";import {$registeredComponentMetas,$registeredTemplates,@@ -803,6 +808,51 @@ describe("insert webstudio component at", () => {children: expect.any(Array),});});++ test("reports rejected MDX insertion without changing instances", async () => {+ const instances = $instances.get();+ instances.get("bodyId")!.children = [{ type: "id", value: "block" }];+ instances.set("block", {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "mdx" }],+ });+ instances.set("mdx", {+ type: "instance",+ id: "mdx",+ component: blockBodyComponent,+ children: [],+ });+ $props.set(+ new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ ])+ );+ const original = structuredClone(instances);+ const notify = vi.spyOn(toast, "error");+ try {+ expect(+ await insertWebstudioComponentAt("Form", {+ parentSelector: ["mdx", "block", "bodyId"],+ position: "end",+ })+ ).toBe(false);+ expect(notify).toHaveBeenCalledOnce();+ expect($instances.get()).toEqual(original);+ } finally {+ notify.mockRestore();+ }+ });});describe("find closest insertable", () => {diff --git a/apps/builder/app/shared/instance-utils/insert.ts b/apps/builder/app/shared/instance-utils/insert.tsindex 067440eb8b..ae1883e581 100644--- a/apps/builder/app/shared/instance-utils/insert.ts+++ b/apps/builder/app/shared/instance-utils/insert.ts@@ -11,6 +11,7 @@ import {} from "@webstudio-is/sdk";import {builderRuntimeContext,+ BuilderRuntimeError,createComponentTemplateFragment,getFragmentContentModelWarnings,type FragmentContentModelWarning,@@ -137,15 +138,26 @@ export const insertWebstudioComponentAt = (if (target === undefined) {return false;}- const result = executeRuntimeMutation({- id: "instances.insertComponent",- input: {- parentInstanceId: target.parentInstanceId,- component,- tag: target.tag,- insertIndex: target.insertIndex,- },- });+ let result: ReturnType<+ typeof executeRuntimeMutation<"instances.insertComponent">+ >;+ try {+ result = executeRuntimeMutation({+ id: "instances.insertComponent",+ input: {+ parentInstanceId: target.parentInstanceId,+ component,+ tag: target.tag,+ insertIndex: target.insertIndex,+ },+ });+ } catch (error) {+ if (error instanceof BuilderRuntimeError) {+ toast.error(error.message);+ return false;+ }+ throw error;+ }const newInstanceId = result?.result.rootInstanceIds[0];if (result !== undefined && newInstanceId !== undefined) {const parentSelector =diff --git a/apps/builder/app/shared/project-settings/import-redirects-dialog.tsx b/apps/builder/app/shared/project-settings/import-redirects-dialog.tsxindex a80c72d47b..3ae6c79f4d 100644--- a/apps/builder/app/shared/project-settings/import-redirects-dialog.tsx+++ b/apps/builder/app/shared/project-settings/import-redirects-dialog.tsx@@ -1,5 +1,6 @@import { useRef, useState, type DragEvent, type ChangeEvent } from "react";import {+ PanelContent,Box,Button,Dialog,@@ -250,13 +251,7 @@ export const ImportRedirectsDialog = ({<Dialog open={isOpen} onOpenChange={handleOpenChange}><DialogContent css={{ width: 520, maxHeight: "80vh" }}><ScrollArea>- <Flex- direction="column"- css={{- padding: theme.panel.padding,- }}- gap="3"- >+ <PanelContent as={Flex} direction="column" gap="3">{step === "input" && (<InputSteptextContent={textContent}@@ -284,7 +279,7 @@ export const ImportRedirectsDialog = ({onMergeModeChange={setMergeMode}/>)}- </Flex>+ </PanelContent></ScrollArea><DialogActions>diff --git a/apps/builder/app/shared/project-settings/project-settings.tsx b/apps/builder/app/shared/project-settings/project-settings.tsxindex 87b439c258..1e552e1732 100644--- a/apps/builder/app/shared/project-settings/project-settings.tsx+++ b/apps/builder/app/shared/project-settings/project-settings.tsx@@ -13,7 +13,8 @@ import {Text,rawTheme,cssVar,- selectedItemBackground,+ InsetList,+ InsetListItem,} from "@webstudio-is/design-system";import { SpinnerIcon } from "@webstudio-is/icons";import {@@ -83,9 +84,7 @@ export const ProjectSettingsDialog = ({<fieldset style={{ display: "contents" }} disabled={!isDesignMode}><Flex grow><List asChild>- <Flex- direction="column"- shrink={false}+ <InsetListcss={{width: leftPanelWidth,borderRight: `1px solid ${cssVar("--border-default")}`,@@ -102,30 +101,15 @@ export const ProjectSettingsDialog = ({onSectionChange?.(name);}}>- <Flex- css={{- position: "relative",- height: theme.spacing[13],- paddingInline: theme.panel.paddingInline,- outline: "none",- "&:focus-visible, &:hover": {- background: cssVar("--overlay-interaction-hover"),- },- "&[aria-current=true]": {- background: selectedItemBackground,- color: cssVar("--foreground-primary"),- },- }}- align="center"- >+ <InsetListItem><Text variant="labels" truncate>{sectionLabels.get(name) ?? titleCase(name)}</Text>- </Flex>+ </InsetListItem></ListItem>);})}- </Flex>+ </InsetList></List><ScrollAreaNative css={{ width: "100%" }}>{status === "loading" ? (diff --git a/apps/builder/app/shared/project-settings/section-agents.tsx b/apps/builder/app/shared/project-settings/section-agents.tsxindex 0f96cd871a..ee9c083321 100644--- a/apps/builder/app/shared/project-settings/section-agents.tsx+++ b/apps/builder/app/shared/project-settings/section-agents.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from "react";import { useStore } from "@nanostores/react";-import { Flex, Grid, Text, Tooltip } from "@webstudio-is/design-system";+import { Flex, Grid, Text, Tooltip, cssVar } from "@webstudio-is/design-system";import { InfoCircleIcon } from "@webstudio-is/icons";import { CodeEditor } from "~/shared/code-editor";import { $projectSettings } from "~/shared/sync/data-stores";@@ -25,7 +25,10 @@ export const SectionAgents = () => {variant="wrapped"content="Give AI coding agents project-specific guidance. When you sync the project locally, Webstudio writes these instructions to a managed AGENTS.md in the project root. An existing user-owned AGENTS.md is never overwritten.">- <InfoCircleIcon tabIndex={0} />+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ /></Tooltip></Flex><Grid gap={1} css={{ ...sectionSpacing, minHeight: 0 }}>diff --git a/apps/builder/app/shared/project-settings/section-backups.tsx b/apps/builder/app/shared/project-settings/section-backups.tsxindex 67a87781d5..594e608b22 100644--- a/apps/builder/app/shared/project-settings/section-backups.tsx+++ b/apps/builder/app/shared/project-settings/section-backups.tsx@@ -1,6 +1,7 @@import { useStore } from "@nanostores/react";import { useEffect, useState } from "react";import {+ PanelContent,Grid,Text,Button,@@ -11,7 +12,6 @@ import {DialogContent,DialogClose,Flex,- theme,toast,PanelBanner,Link,@@ -100,11 +100,7 @@ export const SectionBackups = ({</DialogTrigger><DialogContent width={320}><DialogTitle>Restore published version</DialogTitle>- <Flex- direction="column"- css={{ padding: theme.panel.padding }}- gap={2}- >+ <PanelContent as={Flex} direction="column" gap={2}><Text>Are you sure you want to restore the project to its publishedversion?@@ -125,7 +121,7 @@ export const SectionBackups = ({</Button></DialogClose></Flex>- </Flex>+ </PanelContent></DialogContent></Dialog>{canRestoreBackups === false && (diff --git a/apps/builder/app/shared/project-settings/section-general.tsx b/apps/builder/app/shared/project-settings/section-general.tsxindex 17aa94ebe4..2529e3b065 100644--- a/apps/builder/app/shared/project-settings/section-general.tsx+++ b/apps/builder/app/shared/project-settings/section-general.tsx@@ -120,7 +120,10 @@ export const SectionGeneral = ({ projectId }: { projectId?: string }) => {variant="wrapped"content="Used in search results and social previews.">- <InfoCircleIcon tabIndex={0} />+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ /></Tooltip></Flex><InputField@@ -141,7 +144,10 @@ export const SectionGeneral = ({ projectId }: { projectId?: string }) => {variant="wrapped"content="Used as the email recipient when submitting a webhook form without an action.">- <InfoCircleIcon tabIndex={0} />+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ /></Tooltip>{allowContactEmail === false && <ProChip>Pro</ProChip>}</Flex>diff --git a/apps/builder/app/shared/project-settings/section-redirects.tsx b/apps/builder/app/shared/project-settings/section-redirects.tsxindex d0d0f3d4a7..bcaec59dfb 100644--- a/apps/builder/app/shared/project-settings/section-redirects.tsx+++ b/apps/builder/app/shared/project-settings/section-redirects.tsx@@ -1,5 +1,6 @@import { useStore } from "@nanostores/react";import {+ PanelContent,Box,Button,Combobox,@@ -271,13 +272,13 @@ export const SectionRedirects = () => {><DialogContent><DialogTitle>Delete all redirects</DialogTitle>- <Flex css={{ padding: theme.panel.padding }}>+ <PanelContent as={Flex}><Text>Are you sure you want to delete all {redirects.length} redirect{redirects.length !== 1 ? "s" : ""}? This action cannot beundone.</Text>- </Flex>+ </PanelContent><DialogActions><Button color="destructive" onClick={handleDeleteAll}>Delete alldiff --git a/apps/builder/app/shared/resources.test.ts b/apps/builder/app/shared/resources.test.tsindex 2abffddc89..ab4734def9 100644--- a/apps/builder/app/shared/resources.test.ts+++ b/apps/builder/app/shared/resources.test.ts@@ -9,6 +9,7 @@ import {$resourcePerformanceCache,$resourcesCache,getResourceKey,+ invalidateAssets,loadResourceDiagnostics,preloadResources,} from "./resources";@@ -143,6 +144,57 @@ test("reloads an invalidated cached request", async () => {expect($resourcesCache.get().get(key)).toEqual({ data: "second" });});+test.each(["updated", "empty", "failed"])(+ "keeps Assets visible during refresh until the %s response settles",+ async (outcome) => {+ const request: ResourceRequest = {+ name: "assets",+ method: "post",+ url: "/$resources/assets",+ searchParams: [],+ headers: [],+ body: { query: {} },+ };+ const key = getResourceKey(request);+ const original = { data: [{ _id: "article", title: "Before" }] };+ queueResources([request]);+ await loadResources(async () => Response.json([[key, original]]));+ const values: unknown[] = [];+ const unsubscribe = $resourcesCache.listen((cache) =>+ values.push(cache.get(key))+ );+ let respond: (response: Response) => void = () => {};+ const requestFetch = vi.fn<typeof globalThis.fetch>(+ () =>+ new Promise((resolve) => {+ respond = resolve;+ })+ );+ try {+ invalidateAssets(requestFetch);+ expect(requestFetch).toHaveBeenCalledOnce();+ expect($pendingResourceKeys.get().has(key)).toBe(true);+ expect($resourcesCache.get().get(key)).toEqual(original);+ const updated = {+ data: outcome === "empty" ? [] : [{ _id: "article", title: "After" }],+ };+ respond(+ outcome === "failed"+ ? new Response(null, { status: 503 })+ : Response.json([[key, updated]])+ );+ await vi.waitFor(() => expect($hasPendingResources.get()).toBe(false));+ expect($resourcesCache.get().get(key)).toEqual(+ outcome === "failed" ? original : updated+ );+ expect(values).not.toContain(undefined);+ } finally {+ unsubscribe();+ respond(Response.json([]));+ }+ }+);+test("replaces an invalidated in-flight request without caching stale data", async () => {vi.useFakeTimers();const request: ResourceRequest = {diff --git a/apps/builder/app/shared/resources.ts b/apps/builder/app/shared/resources.tsindex 6148c1ff9d..10d2eefc18 100644--- a/apps/builder/app/shared/resources.ts+++ b/apps/builder/app/shared/resources.ts@@ -239,7 +239,11 @@ export const preloadResources = (resources: readonly ResourceRequest[]) => {const invalidateAndQueueResource = (resource: ResourceRequest) => {const key = getResourceKey(resource);- cache.delete(key);+ // Asset saves refresh collection bindings without unmounting their content.+ // Keep the last result until the replacement arrives, including an empty result.+ if (isAssetsResourceRequest(resource) === false) {+ cache.delete(key);+ }invalidateRequestState(key);pending.delete(key);knownRequests.set(key, resource);@@ -397,7 +401,7 @@ export const loadResourceDiagnostics = (* Invalidate the assets system resource.* Call this when assets are uploaded, deleted, or modified to refresh expressions using assets.*/-export const invalidateAssets = () => {+export const invalidateAssets = (requestFetch: typeof fetch = fetch) => {for (const request of knownRequests.values()) {if (isAssetsResourceRequest(request) === false) {continue;@@ -407,7 +411,7 @@ export const invalidateAssets = () => {abortObsoleteBatches();updateCache();updatePending();- startLoading();+ startLoading(requestFetch);};export const computeResourceRequest = (diff --git a/apps/builder/app/shared/share-project/share-project.tsx b/apps/builder/app/shared/share-project/share-project.tsxindex 6037bc71f0..121770bdbc 100644--- a/apps/builder/app/shared/share-project/share-project.tsx+++ b/apps/builder/app/shared/share-project/share-project.tsx@@ -11,6 +11,7 @@ import { shallowEqual } from "shallow-equal";import { type Role, roleLabels } from "@webstudio-is/project";import { roleDescriptions } from "~/shared/permissions";import {+ PanelContent,Box,Button,css,@@ -47,12 +48,7 @@ import { useIds } from "../form-utils";import type { BuilderMode } from "../nano-states";const Item = (props: ComponentProps<typeof Flex>) => (- <Flex- direction="column"- css={{ padding: theme.panel.padding }}- gap="1"- {...props}- />+ <PanelContent as={Flex} direction="column" gap="1" {...props} />);const UpgradeLink = () => (@@ -471,7 +467,6 @@ const itemStyle = css({display: "flex",alignItems: "center",gap: theme.spacing[3],- padding: theme.panel.padding,backgroundColor: cssVar("--background-primary"),});@@ -531,7 +526,8 @@ const SharedLinkItem = ({};return (- <Box+ <PanelContent+ as={Box}className={itemStyle()}role="group"aria-label={`Share link ${currentLink.name}`}@@ -555,7 +551,7 @@ const SharedLinkItem = ({onDelete={onDelete}allowAdditionalPermissions={allowAdditionalPermissions}/>- </Box>+ </PanelContent>);};@@ -619,7 +615,7 @@ export const ShareProject = ({));const create = (- <Box className={itemStyle({ css: { py: theme.spacing["7"] } })}>+ <PanelContent as={Box} className={itemStyle()}><Buttonstate={isPending ? "pending" : undefined}prefix={@@ -631,7 +627,7 @@ export const ShareProject = ({>{links.length === 0 ? "Share a custom link" : "Add another link"}</Button>- </Box>+ </PanelContent>);return (diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.ts b/apps/builder/app/shared/sync/patch/patch-service.server.tsindex d554ce4805..5153e18db2 100644--- a/apps/builder/app/shared/sync/patch/patch-service.server.ts+++ b/apps/builder/app/shared/sync/patch/patch-service.server.ts@@ -4,6 +4,8 @@ import {} from "@webstudio-is/trpc-interface/index.server";import { patchLoadedBuild } from "@webstudio-is/project/index.server";import type { Database } from "@webstudio-is/postgrest/index.server";+import type { AssetObjectReader } from "@webstudio-is/asset-uploader/server";+import { createAssetClient } from "~/shared/asset-client";import {assertProjectPermit,authorizePatchEntries,@@ -232,11 +234,13 @@ const applyAuthorizedEntries = async ({build,patch,version,+ assetStore,}: {authorized: AuthorizedPatchEntry[];build?: BuildRow;patch: NormalizedPatchRequest;version: number;+ assetStore: AssetObjectReader;}) => {if (authorized.length === 0) {return {@@ -263,6 +267,7 @@ const applyAuthorizedEntries = async ({projectId: patch.projectId,clientVersion: version,transactions: authorized.map(({ entry }) => entry.transaction),+ assetStore,},applyContext);@@ -291,6 +296,7 @@ const applyAuthorizedEntries = async ({projectId: patch.projectId,clientVersion: currentVersion,transactions: [entry.transaction],+ assetStore,},entryContext);@@ -349,6 +355,7 @@ export const applyPatchRequest = async (build,patch,version: authorized.length === 0 ? state.version : patch.clientVersion,+ assetStore: createAssetClient(),});if (applied.status === "version_mismatched") {diff --git a/apps/builder/app/shared/sync/project-queue.test.ts b/apps/builder/app/shared/sync/project-queue.test.tsindex 6203331acb..baf44f209b 100644--- a/apps/builder/app/shared/sync/project-queue.test.ts+++ b/apps/builder/app/shared/sync/project-queue.test.ts@@ -614,6 +614,8 @@ describe("project-queue", () => {status: "version_mismatched",errors: "Version mismatch",});+ const completion = vi.fn();+ onTransactionComplete("tx-1", completion);enqueueProjectDetails({projectId: "p1",@@ -632,6 +634,7 @@ describe("project-queue", () => {await flush();expect($syncStatus.get().status).toBe("fatal");+ expect(completion).toHaveBeenCalledWith(false);vi.unstubAllGlobals();});@@ -674,13 +677,22 @@ describe("project-queue", () => {vi.fn(() => false));+ const acceptedCompletion = vi.fn();+ const failedCompletion = vi.fn();+ onTransactionComplete("tx-accepted", acceptedCompletion);+ onTransactionComplete("tx-failed", failedCompletion);mockBuildPatch.mockResolvedValue({status: "partial",version: 1,entries: [{seq: 0,- transactionId: "tx-1",+ transactionId: "tx-accepted",+ status: "accepted",+ },+ {+ seq: 1,+ transactionId: "tx-failed",status: "failed",errors: "Patch failed",},@@ -697,7 +709,7 @@ describe("project-queue", () => {commandQueue.enqueue({type: "transactions",projectId: "p1",- transactions: [makeTx("tx-1")],+ transactions: [makeTx("tx-accepted"), makeTx("tx-failed")],});await vi.advanceTimersByTimeAsync(NEW_ENTRIES_INTERVAL * 3);@@ -707,6 +719,8 @@ describe("project-queue", () => {status: "fatal",error: "Patch failed",});+ expect(acceptedCompletion).toHaveBeenCalledWith(true);+ expect(failedCompletion).toHaveBeenCalledWith(false);vi.unstubAllGlobals();});diff --git a/apps/builder/app/shared/sync/project-queue.ts b/apps/builder/app/shared/sync/project-queue.tsindex b6887a4636..d1d16f88c9 100644--- a/apps/builder/app/shared/sync/project-queue.ts+++ b/apps/builder/app/shared/sync/project-queue.ts@@ -208,6 +208,11 @@ const pollQueue = async (signal: AbortSignal) => {}const { projectId, transactions } = command;+ const completeTransactions = (success: boolean) => {+ for (const transaction of transactions) {+ transactionCompletion.completeTransaction(transaction.id, success);+ }+ };const details = detailsMap.get(projectId);if (details === undefined) {@@ -220,6 +225,7 @@ const pollQueue = async (signal: AbortSignal) => {});$syncStatus.set({ status: "fatal", error });+ completeTransactions(false);return;}@@ -256,9 +262,7 @@ const pollQueue = async (signal: AbortSignal) => {details.version = result.version ?? details.version + 1;$committedVersion.set(details.version);- for (const transaction of transactions) {- transactionCompletion.completeTransaction(transaction.id, true);- }+ completeTransactions(true);// stop retrying and wait next transactionscontinue polling;@@ -286,6 +290,20 @@ const pollQueue = async (signal: AbortSignal) => {}$syncStatus.set({ status: "fatal", error });+ if (result.status === "partial") {+ for (const transaction of transactions) {+ const matchingEntries = result.entries.filter(+ ({ transactionId }) => transactionId === transaction.id+ );+ transactionCompletion.completeTransaction(+ transaction.id,+ matchingEntries.length > 0 &&+ matchingEntries.every(({ status }) => status === "accepted")+ );+ }+ } else {+ completeTransactions(false);+ }if (shouldReload === false) {toast.error(@@ -305,6 +323,7 @@ const pollQueue = async (signal: AbortSignal) => {// Api error we don't know how to handle, as retries will not help probably// We should show error and break synchronization$syncStatus.set({ status: "fatal", error });+ completeTransactions(false);toast.error(error, {id: "fatal-error",diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex b874c2d7eb..2bd750b57c 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -87,6 +87,7 @@ import {type InstanceSelector,} from "@webstudio-is/project-build/runtime";import { $externalContentRoots } from "../external-content-mutations";+import { $externalContentHistory } from "../external-content-history";enableMapSet();// safari structuredClone fix@@ -407,6 +408,7 @@ export const createObjectPool = () => {new NanostoresSyncObject("canvasScrollbarWidth", $canvasScrollbarSize),new NanostoresSyncObject("systemDataByPage", $systemDataByPage),new NanostoresSyncObject("externalContentRoots", $externalContentRoots),+ new NanostoresSyncObject("externalContentHistory", $externalContentHistory),]);};diff --git a/apps/builder/e2e/flows/assets-panel.ts b/apps/builder/e2e/flows/assets-panel.tsindex 68bd5bf1fa..5461e1a587 100644--- a/apps/builder/e2e/flows/assets-panel.ts+++ b/apps/builder/e2e/flows/assets-panel.ts@@ -40,18 +40,29 @@ export const openAssetsPanel = async ({export const createAssetFolder = async ({page,name,+ useAsContentCollection = false,}: {page: Page;name: string;+ useAsContentCollection?: boolean;}) => {await openAddAssetMenu(page);await page.getByRole("menuitem", { name: "Create folder" }).click();const dialog = page.getByRole("dialog", { name: "New folder" });await dialog.getByLabel("Name", { exact: true }).fill(name);+ if (useAsContentCollection) {+ await dialog.getByLabel("Use as content collection").check();+ }await Promise.all([waitForChangeToBeSaved({ page }),dialog.getByRole("button", { name: "Create folder" }).click(),]);+ if (useAsContentCollection) {+ const collectionCreatedDialog = page.getByRole("dialog", {+ name: "Collection created",+ });+ await collectionCreatedDialog.getByRole("button", { name: "Done" }).click();+ }return page.getByRole("button", { name: `Folder ${name}`, exact: true });};diff --git a/apps/builder/e2e/run.node.test.ts b/apps/builder/e2e/run.node.test.tsnew file mode 100644index 0000000000..293ed74824--- /dev/null+++ b/apps/builder/e2e/run.node.test.ts@@ -0,0 +1,45 @@+import { spawnSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { expect, test } from "vitest";++test.each([[], ["--reporter=line"]])(+ "validates E2E selection before starting services with arguments %j",+ (...args) => {+ const directory = mkdtempSync(join(tmpdir(), "e2e-selection-"));+ const capture = join(directory, "arguments.json");+ try {+ // Stop at the package-manager boundary: no Docker or database work runs.+ writeFileSync(+ join(directory, "pnpm"),+ `#!${process.execPath}\nrequire("node:fs").writeFileSync(process.env.ARGUMENT_CAPTURE, JSON.stringify(process.argv.slice(2))); process.exit(73);\n`,+ { mode: 0o755 }+ );+ const result = spawnSync(+ "/bin/bash",+ [join(import.meta.dirname, "run.sh"), "run", ...args],+ {+ encoding: "utf8",+ env: {+ ...process.env,+ PATH: `${directory}:${process.env.PATH}`,+ ARGUMENT_CAPTURE: capture,+ E2E_SKIP_CLEANUP: "true",+ E2E_RUN_TESTS: "true",+ SCHEMA_SNAPSHOT: join(directory, "unused.sql"),+ },+ timeout: 10_000,+ }+ );+ expect(result.status, result.stderr).toBe(73);+ expect(JSON.parse(readFileSync(capture, "utf8"))).toEqual([+ "e2e:ci",+ "--list",+ ...args,+ ]);+ } finally {+ rmSync(directory, { recursive: true, force: true });+ }+ }+);diff --git a/apps/builder/e2e/run.sh b/apps/builder/e2e/run.shindex cfa1977df6..cfd02d7112 100644--- a/apps/builder/e2e/run.sh+++ b/apps/builder/e2e/run.sh@@ -164,8 +164,12 @@ run_builder_e2e_tests() {validate_builder_e2e_selection() {(cd "$ROOT_DIR/apps/builder"- E2E_BUILDER_URL="${E2E_BUILDER_URL:-https://127.0.0.1:3000}" \+ export E2E_BUILDER_URL="${E2E_BUILDER_URL:-https://127.0.0.1:3000}"+ if [ "${#PLAYWRIGHT_ARGS[@]}" -eq 0 ]; then+ pnpm e2e:ci --list+ elsepnpm e2e:ci --list "${PLAYWRIGHT_ARGS[@]}"+ fi)}diff --git a/apps/builder/e2e/tests/asset-folders.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/asset-folders.[shard-2].[shard-5].[shard-6].e2e.tsindex 445b74752d..e25e1a9694 100644--- a/apps/builder/e2e/tests/asset-folders.[shard-2].[shard-5].[shard-6].e2e.ts+++ b/apps/builder/e2e/tests/asset-folders.[shard-2].[shard-5].[shard-6].e2e.ts@@ -105,9 +105,8 @@ test("Asset can be dragged into a folder", async ({ page, context }) => {authToken: fixture.builderToken,});await openAssetsPanel({ page });- await page- .getByRole("button", { name: `Folder ${folderName}`, exact: true })- .dblclick();+ // Reopening Assets restores Images rather than returning to the root.+ await page.getByRole("button", { name: "Back", exact: true }).waitFor();await page.getByTitle(assetTitle).waitFor();await waitForSyncStatus({ page, status: "idle" });});diff --git a/apps/builder/e2e/tests/content-mode-assets.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/content-mode-assets.[shard-2].[shard-5].[shard-6].e2e.tsindex c92fc7dded..7eecd53559 100644--- a/apps/builder/e2e/tests/content-mode-assets.[shard-2].[shard-5].[shard-6].e2e.ts+++ b/apps/builder/e2e/tests/content-mode-assets.[shard-2].[shard-5].[shard-6].e2e.ts@@ -1,9 +1,11 @@import {+ createAssetFolder,deleteSelectedAsset,openAssetSettings,openAssetsPanel,replaceSelectedAsset,uploadAsset,+ waitForAsset,} from "../flows/assets-panel";import { openProjectBuilder, waitForCanvasText } from "../flows/builder";import {@@ -224,6 +226,62 @@ test("Editor can upload, replace, and delete asset in content mode", async ({await waitForSyncStatus({ page, status: "idle" });});+test("Editor can create and reload a content collection entry", async ({+ page,+}) => {+ const folderName = "Content collection entries";+ const entryTitle = "Content collection entry";+ const entryFilename = "content-collection-entry.mdx";++ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForSyncStatus({ page, status: "idle" });+ await openAssetsPanel({ page });+ const folder = await createAssetFolder({+ page,+ name: folderName,+ useAsContentCollection: true,+ });+ await folder.dblclick();+ await page.getByRole("button", { name: "Collection settings" }).waitFor();++ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ await waitForSyncStatus({ page, status: "idle" });+ await openAssetsPanel({ page });+ // The last folder is remembered for this project, including across modes.+ await page.getByTitle("collection.json").waitFor({ state: "visible" });+ await page.getByRole("button", { name: "Add asset" }).click();+ await page.getByRole("menuitem", { name: "New entry" }).click();+ const dialog = page.getByRole("dialog", { name: "New entry" });+ await dialog.getByLabel("Title *").fill(entryTitle);+ await Promise.all([+ waitForChangeToBeSaved({ page }),+ dialog.getByRole("button", { name: "Create entry" }).click(),+ ]);+ await waitForAsset({ page, filename: entryFilename });+ await page.getByTitle("collection.json").waitFor({ state: "visible" });+ await page.getByTitle("template.mdx").waitFor({ state: "visible" });++ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ await openAssetsPanel({ page });+ await waitForAsset({ page, filename: entryFilename });+ await page.getByTitle("collection.json").waitFor({ state: "visible" });+ await page.getByTitle("template.mdx").waitFor({ state: "visible" });+});+test("Editor can replace image source with asset in content mode", async ({page,}) => {diff --git a/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts b/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.tsindex 50b2b45760..0a8b102c76 100644--- a/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts+++ b/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts@@ -183,6 +183,9 @@ test("Content Block MDX source lifecycle persists edits and resets to empty", aspage,context,}) => {+ // This full lifecycle repeatedly reloads Builder across two roles. CI can+ // exhaust the default two-minute budget at the final reload assertion.+ test.setTimeout(180_000);const fixture = await createContentModeProject({context: context,email: "[email protected]",@@ -563,7 +566,6 @@ test("Empty MDX content supports slash menu keyboard and mouse insertion", asyncconst paragraphWrite = waitForAssetWrite(page, (source) =>source.includes("Focused paragraph"));- const paragraphMetadataWrite = waitForChangeToBeSaved({ page });await page.keyboard.press("ControlOrMeta+A");await page.keyboard.type("Focused paragraph");await page.keyboard.press("Enter");@@ -572,7 +574,6 @@ test("Empty MDX content supports slash menu keyboard and mouse insertion", async);await nextEmptyParagraphEditor.waitFor({ state: "visible" });await paragraphWrite;- await paragraphMetadataWrite;const emptyParagraphId =await nextEmptyParagraphEditor.getAttribute("data-ws-id");if (emptyParagraphId === null) {@@ -773,7 +774,7 @@ test("Unresolved MDX templates are selectable only in the Builder canvas", asyncconst openButton = page.getByRole("button", { name: "Open", exact: true });await openButton.click();await page- .locator(".cm-lintRange-warning")+ .locator(".cm-lintRange-error").filter({ hasText: "MissingE2ETemplate" }).waitFor();await page.keyboard.press("Escape");diff --git a/docs/university/cli.md b/docs/university/cli.mdindex 674bf9cace..e01b7f6a98 100644--- a/docs/university/cli.md+++ b/docs/university/cli.md@@ -96,7 +96,7 @@ Or link a Project non-interactively:npx webstudio link --link "<share-link-with-build-access>"```-Publish the Project in Webstudio Cloud before syncing when you need recent Builder changes in the local export.+Sync exports the current saved Builder project and its asset files. Publishing is not required.## Install Node.js only when needed@@ -166,12 +166,22 @@ The share link should include Build access when you need to sync, build, import,## Export and build a Project-After linking, publish the Project in Webstudio Cloud, then sync it locally:+After linking, sync the current saved Project locally:```bashnpx webstudio sync```+Sync refreshes the project from the server, downloads its asset files, and prepares the local content index. It does not combine an older published build with current assets.++To replace another Project with the synced Project:++```bash+npx webstudio import --to "<target-share-link-with-build-access>"+```++Import replaces the target's pages, assets, and asset folders. It preserves file formats and folder assignments; it does not convert Markdown files to MDX.+Build a dynamic app with a deployment template:```bashdiff --git a/docs/university/core-components/content-block.md b/docs/university/core-components/content-block.mdindex ff4eeb9a20..0128f3773d 100644--- a/docs/university/core-components/content-block.md+++ b/docs/university/core-components/content-block.md@@ -20,6 +20,10 @@ Next is a breakdown of Content Block by mode:## Content Block in Design mode+Without an MDX source, add content directly inside the Content Block, alongside **Templates**. No Body wrapper is needed. **Templates** defines the reusable designs that editors can insert in Content mode. Adding a one-off content instance does not add it to the editor's insertion menu. Add a design to Templates only when editors should be able to insert more instances of it.++Templates are not required for ordinary Markdown content. Custom components referenced by JSX in MDX must match a template in that Content Block; being registered in the Builder is not enough.+Sometimes providing team members or clients the ability to edit existing content doesn’t help them accomplish everything they need.Instead, they may want to add new content without asking you.@@ -53,32 +57,38 @@ Reusable top-level templates appear in Content mode like this. Structural and in<div><figure><img src="../../.gitbook/assets/templates-design-mode.png" alt="Templates in Design mode"><figcaption><p>Templates in Design mode</p></figcaption></figure> <figure><img src="../../.gitbook/assets/templates-content-mode.png" alt="Template in Content mode"><figcaption><p>Template in Content mode</p></figcaption></figure></div>-Each time they insert a template, its copy appears inside the Content Block's Body outlet, alongside any initial body content. The Templates container remains protected source material.+Each time they insert a template, its copy appears alongside the existing content: directly inside an unconnected Content Block, or inside **MDX content** when a file is connected. The Templates container remains protected source material.### Step 3: Add an initial setup (optional)-Optionally, you can add instances inside the Content Block's Body outlet.+Optionally, add instances directly inside the Content Block. If the block is connected to MDX, its file content appears inside **MDX content** instead.<figure><img src="../../.gitbook/assets/startingpoint-content-block.png" alt="Initial Feature instances inside a Content Block Body outlet" width="357"><figcaption><p>The Feature instances are provided as a starting point</p></figcaption></figure>Doing so will provide an initial setup for editors.-Editors can delete children of the Body outlet. They cannot delete the designed shell, Templates container, templates, or nested instances independently.+Editors can delete top-level content instances. In MDX-connected blocks, these are the children of **MDX content**, not the surrounding designed shell. They cannot delete the Templates container, templates, or nested instances independently.### Store content in an MDX fileConnect a `.mdx` file when the Content Block's body should live in Assets instead of the project's regular instance data. The designed shell and Templates list remain in the project. Markdown `.md` files cannot be connected to a Content Block.+To insert a custom component such as Accordion into **MDX content**, first add its design to **Templates**, then insert it from the template picker. Inserting custom components directly from the Add panel into MDX content is blocked. Basic Markdown elements, images, and code blocks can still be inserted directly. Place designer-owned, one-off components outside **MDX content**; they remain in the project and are not saved to the file.++Moving, pasting, or duplicating content into an MDX region also checks the destination's Templates. Unsupported components are rejected before the tree changes, including components nested inside a pasted container.+#### Prepare the Content Block1. Add the Content Block and design its shell in Design mode.-2. Place the **Body** outlet where the article body should render.+2. After connecting a file, place the **MDX content** outlet where the article body should render.3. Keep exactly one direct **Templates** container. Style the standard document elements already provided inside it.4. Add any reusable custom content to **Templates**.5. Give every custom top-level template a unique instance name. Use a JSX-compatible name such as `PromotionCard` when you want component-style JSX.-New Content Blocks already include a Body outlet and direct templates for every supported Markdown element, including headings, paragraphs, marks, links, images, quotes, lists, task controls, code, separators, and tables. When you connect an older Content Block without a Body outlet, Webstudio adds it automatically.+New Content Blocks include direct templates for every supported Markdown element, including headings, paragraphs, marks, links, images, quotes, lists, task controls, code, separators, and tables. They do not include a Body outlet. Connecting an MDX file adds the outlet automatically. Existing blocks with a Body outlet remain supported without changing their saved structure.++When a file is connected, the Navigator labels its Body outlet **MDX content** and shows an MDX icon, even when the region is empty. Content inside that region is saved to the file; instances outside it remain in the project. Use the region's **MDX content settings** menu and choose **Open MDX file** to edit the connected file directly.#### Create and connect the file@@ -110,6 +120,8 @@ Select the connected filename to choose another file. Select **Open** to edit thEdit the connected body with the usual Content mode controls. You can change text and supported properties, insert templates, reorder content, and delete content. Canvas changes appear immediately and then save to the MDX file.+While editing connected content, **Undo** and **Redo** restore source edits, including edits to referenced author files, without undoing the loading of the Content Block. This history keeps the last 20 source edits in the current project session. Reloading clears the history. If the file has changed outside that history, Webstudio does not overwrite it.+Component properties in Content mode are limited to authored content, such as links, media sources and alternative text, form labels and placeholders, code, and date values. Layout, dimensions, visual themes, form wiring, and interaction settings remain available only in Design mode.If the file changes after a canvas edit starts but before it is saved, reload the Content Block before continuing. Webstudio keeps the local canvas state until reload and does not silently merge or overwrite either version.@@ -148,9 +160,15 @@ Regular document content stays Markdown and uses the matching standard templates</PromotionCard>```-The JSX name first matches the stable **Name** of a unique top-level template in the Content Block's Templates list. **Name** is a JavaScript identifier and is separate from the optional **Label** shown in the canvas. If no template has that name, Webstudio uses the exact registered component with that exported name. A new template gets its default name from its root component or HTML tag, and duplicate defaults get deterministic numeric suffixes.+The JSX name matches the stable **Name** of a unique top-level template in the Content Block's Templates list. **Name** is a JavaScript identifier and is separate from the optional **Label** shown in the canvas. If no template has that name, the custom component is unresolved and is not rendered. Its JSX remains in the file so adding the matching template can resolve it later. A new template gets its default name from its root component or HTML tag, and duplicate defaults get deterministic numeric suffixes.++In the MDX editor, type `<` to autocomplete templates connected to the file and built-in Image and CodeText components. Inside a JSX tag, autocomplete suggests its supported properties and available property values.++Missing template references are marked as errors at their JSX source range. Hover the underline to read the explanation. For dynamic sources, the editor also uses currently rendered Content Blocks to find the file's templates.-In the MDX editor, type `<` to autocomplete registered components and templates connected to the file. Inside a JSX tag, autocomplete suggests its supported properties and available property values.+Malformed MDX stays as an unsaved draft in the file editor. Fix the reported error before closing, or choose **Discard changes** to keep the last saved version. The saved article remains available while you repair the draft.++The Navigator shows an unresolved reference as **Missing template: Name**. Delete that item to remove its JSX, including its children, from the MDX file. Leaving the item in place preserves its source until the template is available.When two component libraries export the same name, the core component keeps the plain identifier and the namespaced component gets a stable library prefix, such as `Checkbox` and `RadixCheckbox`. Component discovery reports the exact JSX identifier to use.@@ -164,6 +182,14 @@ If a Content Block that already renders connected MDX temporarily has zero or muMissing or duplicate custom templates show a source-ranged warning and a selectable placeholder in Builder. Published pages omit only the unresolved custom subtree. Invalid or unsupported MDX remains editable; Builder reports the source location and renders the valid content it can recover.+Before publishing, the Publish panel warns when a missing or ambiguous custom+template would omit content. It lists the affected files and template names.+The server checks the prepared publication content, including discovered dynamic+article sources and nested Content Blocks; it is not limited to the open page.+This reuses the publication bundle loading and content scan, then resolves its+template dependencies again to collect warnings. The warning does not block+publishing. Repair the listed templates to include that content.+Legacy files that already contain internal `ws.element` or `ws:name` syntax remain readable during migration, but Webstudio does not emit or recommend those forms. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.Keep custom template names stable after connecting MDX files. Webstudio prevents duplicate top-level template names. Renaming or deleting a referenced template warns that connected files will not be rewritten. If you continue, update the affected JSX references in the MDX files. An MCP-connected agent can preview and confirm that update across a selected group of files. A confirmed rename changes the reference name. A confirmed removal unwraps and preserves explicit authored children; a self-closing reference disappears because it has no authored children.@@ -179,7 +205,43 @@ featureImage:$ref: ./images/feature.png```-To use frontmatter in the designed part of a Content Block, [bind](../foundations/variables.md) a property or text value to the Content Block's **document** variable. For example, bind a heading to `document.frontmatter.title`, an Image source to `document.frontmatter.featureImage.src`, and its alternative text to `document.frontmatter.featureImage.description`. This uses the image's Asset description instead of duplicating alternative text in frontmatter. Direct frontmatter bindings remain part of the same MDX file and can be edited on the canvas in Content mode. Computed expressions and values supplied through another document's `$ref` remain read-only on the canvas; open the referenced file to edit referenced values.+To use frontmatter in the designed part of a Content Block, [bind](../foundations/variables.md) a property or text value to the Content Block's **document** variable. For example, bind a heading to `document.frontmatter.title`, an Image source to `document.frontmatter.featureImage.src`, and its alternative text to `document.frontmatter.featureImage.description`. This uses the image's Asset description instead of duplicating alternative text in frontmatter. Fields authored directly in the connected MDX file can be edited on the canvas and through supported Settings controls in Content mode; edits save back to that file. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.++**Check every article field**++An editable MDX body does not make the whole article editable. Check the title,+excerpt, author details, dates, reading time, hero and inline images,+alternative text, captions, links, and custom-component content in **Content+mode**. Include header fields outside **MDX content**. Change each value through+its UI control, check the saved file, reload, and restore the original value.+Do not treat editing the raw MDX file as a substitute for an editor-facing control.++Replacing an article's image changes its frontmatter image `$ref`, not the+shared Asset's resolved `.src`. With a writable direct Image source binding to+`document.frontmatter.featureImage.src`, use **Choose source** in Content mode.+The resolved URL itself remains read-only.++To edit shared alternative text, open **Choose source**, open the image's+actions menu, then choose **Settings** and edit **Description**. A binding to+`document.frontmatter.featureImage.description` uses that description.+Changing it affects every use of the Asset; replacing an article's image does+not change the original Asset's description.++**Keep formatted values editable**++Keep an editable value separate from its surrounding wording. For example, to+display **— 5 min read**, place three inline text elements next to each other:++- Fixed text: `— `.+- A value element with its entire **Text Content** bound to `document.frontmatter.readingTime`.+- Fixed text: ` min read`.++Keep the spaces in the fixed text. Do not combine the value and wording into one+expression: concatenation, template literals, fallbacks, and formatting calls+produce read-only values. Keep the bound value as the only text content of its+element. The editor can then change the reading time without changing the fixed+wording. For dates, bind a Date Time component's date property directly and use+its formatting settings instead of formatting the binding expression.#### Use one file in repeated or shared content@@ -189,7 +251,7 @@ You can also connect multiple Content Blocks to the same MDX file. Editing the fWhen you copy a connected Content Block, page, template, or folder to another project, Webstudio copies the MDX file and the local files it references. The pasted Content Block points to those imported copies. If Webstudio cannot parse the MDX, it preserves the source file and reports that its dependencies could not be collected.-To create another post with the same structure, duplicate the existing MDX Asset, edit the duplicate, and connect or bind the appropriate Content Block occurrence to it.+To create another post in a collection folder, use **New entry**. For an ordinary MDX Asset outside a collection, duplicate the file and edit the duplicate. Connect or bind the appropriate Content Block occurrence to the new file.#### Disconnect the file@@ -197,6 +259,27 @@ In Design mode, select the **Source** property label and choose **Reset value**.## Content Block in Content mode+### Verify the editor experience before handoff++Use this checklist when creating, migrating, or changing any Content Block,+with or without an MDX source:++1. List every value the editor must change, its UI control, and where it saves.+ Include headers, dates, reading time, images, alternative text, links, and+ custom-component content—not just body text.+2. Use the appropriate control: a calendar for dates and an image picker for+ image replacement. Keep fixed punctuation outside directly bound values.+ Preserve existing field types and wording; a stored `4 min read` string+ can stay one directly bound value.+3. Edit every listed value in **Content mode**. Check its saved project data,+ MDX, or referenced file, reload, then restore and verify the original value.+4. Record each field as passed, failed, or not tested. A correct preview,+ successful API edit, or one editable heading does not verify other fields.+ Missing controls and read-only required fields mean the setup is unfinished.++Templates and designer-owned layout stay protected. This protection must not+be used to exclude content the editor was promised they could change.+In [Content mode](../foundations/modes.md#content), you can edit existing content inside Content Blocks. But what if you want to add _new_ content?You can within Content Block — region(s) on the page the designer designates as a place you can add new content from building blocks to entire sections.diff --git a/docs/university/core-components/time.md b/docs/university/core-components/time.mdindex e7321bb504..2a17124ee6 100644--- a/docs/university/core-components/time.md+++ b/docs/university/core-components/time.md@@ -27,6 +27,20 @@ Use Time for:## Properties+### Edit the date in Settings++The **Date Time** control uses a calendar input for date-only values and a+date/time input for timestamps. Timestamps with a time-zone offset are edited+in UTC; the tooltip identifies this separately from the display time zone.+Opening or focusing the control does not rewrite the stored value. Existing+values that cannot be represented by the date input remain available as text+so they can be repaired.++For an editable article, bind **Date Time** directly to the Content Block's+document frontmatter field. Content-mode changes then save back to that file.+Configure date formatting separately; formatting the binding expression makes+it read-only.+Some commonly used properties (see the Settings panel for all available options):### Core Propertiesdiff --git a/docs/university/foundations/assets.md b/docs/university/foundations/assets.mdindex 8e7e0347e6..155ae9ecbf 100644--- a/docs/university/foundations/assets.md+++ b/docs/university/foundations/assets.md@@ -93,6 +93,10 @@ can contain both assets and other folders. Open a folder to view its contents,and use the breadcrumbs above the asset grid to move back through the folderhierarchy.+Assets remembers the last open folder for each project in your browser. Reopen+the panel or reload the Builder to return to that folder. If the folder was+deleted, the panel opens at the root instead.+You can:- Drag assets and folders into another folder.@@ -100,6 +104,10 @@ You can:- Cut, copy, paste, and duplicate assets or complete folder trees.- Rename or delete folders.+Open **Folder settings** to change a folder's name or parent folder. Valid+changes save automatically; there is no Save button. Blank names and names+already used in the selected parent folder are not saved.+Duplicating a folder copies its nested folders and assets. Deleting a folderdeletes everything inside it, so review the confirmation before continuing.diff --git a/docs/university/foundations/content-engine.md b/docs/university/foundations/content-engine.mdindex 70106cea1f..ea6e47494d 100644--- a/docs/university/foundations/content-engine.md+++ b/docs/university/foundations/content-engine.md@@ -77,14 +77,194 @@ blog/assets/```-Keeping all articles in one folder makes them easy to query. Images can live-next to the articles or in a nested folder.+Keeping all articles in one folder makes them easy to query. Put images and+other supporting files in a nested folder.Open the settings for the `posts` folder and copy its ID. Both Assets resourcesin this guide use that ID to query only files in this folder.+### Make the folder a content collection++Turn on **Use as content collection** when you create the `posts` folder if+editors should be able to add articles without writing MDX frontmatter. For an+existing folder, choose **Use as content collection** from its context menu,+actions menu, or **Folder settings**, then confirm setup. This creates two files+in the same folder without changing its ID or existing content:++- `collection.json` defines the entry fields and their rules with JSON Schema.+- `template.mdx` supplies the starting frontmatter and body for each entry.++Existing selected entries must be MDX files. Setup leaves their content unchanged,+even when fields are missing or not yet configured. The collection shows field+errors for repair after setup. Other files stay visible and are ignored by+collection validation. Setup stops if a selected file has an incompatible type+or conflicts with the generated configuration or template. Choose **Configure+collection** after setup to define the fields used by your existing entries.++### Select collection entries++The generated `collection.json` includes filename patterns in `x-webstudio.entries`:++```json+{+ "x-webstudio": {+ "template": "template.mdx",+ "entries": ["*.mdx"]+ }+}+```++These use [URLPattern syntax](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API),+not filesystem globs. Patterns match direct filenames in the current folder,+case-insensitively; subfolders are independent. For example, use+`["post-*.mdx", "!post-private-*.mdx"]` to select public post files. A leading+`!` excludes a pattern; exclusions take priority over inclusions. At least one+inclusion is required. Slashes are not allowed. The configuration and configured+template are always excluded from entries, regardless of patterns.++Omitting `entries` preserves the default `["*.mdx"]`. The setting accepts up to+64 patterns of 256 characters each. New entry filenames must match the patterns.+Only MDX entries are currently supported; a pattern selecting another format+reports an error rather than treating that file as editable MDX. Files not+selected remain visible and can still appear in ordinary Assets query results.++### Configure fields and the template++The folder remains a normal Assets folder. The direct `collection.json` file is+what makes Webstudio treat it as a collection and show the collection badge.+The configuration and referenced template files also show this badge. You can+open them or download them when permitted, but cannot cut, copy, duplicate,+move, or delete them individually. Manage them through **Collection settings**.+Their asset **Settings** remain available to collection designers: Name is+read-only and Folder is disabled, while Description remains editable.++Open **Collection settings → Fields** and select a field from the list.+Edit **Label** and **Field key** together, then choose the field's **Type**.+Set required fields and length or number limits under **Validation**.+Choose **Add field** to add another entry field. The configurator writes the+schema; designers do not need to edit JSON.++Use the **Entry template** tab to rename the entry template and edit its default+frontmatter and starter content with the built-in Markdown editor. Creating+an entry keeps you on the current page.++The collection format uses a supported subset of JSON Schema draft 2020-12.+The configurator exposes string, number, integer, boolean, and slug fields,+along with required fields and length or value limits. Set starting values in+the entry template frontmatter. Collection fields are flat; arrays and nested+objects are not supported. Slug fields reference Webstudio's bundled schema:++```json+{+ "$ref": "https://webstudio.is/schemas/slug",+ "title": "URL slug",+ "maxLength": 120,+ "x-webstudio": { "control": "slug" }+}+```++Webstudio resolves this reference from its bundled rules, without a network+request. Length limits alongside the reference still apply. The configurator+writes the reference automatically; designers do not need to write a regex.+Other references, composition keywords, enums, formats, and custom+regular-expression patterns are not supported. Webstudio+reports unsupported rules with their location instead of silently ignoring+them.++Editors choose **New entry**, complete the generated form, and select **Create+entry**. Webstudio creates a lowercase, dash-separated slug from the configured+source field, which is **Title** by default.+Slugs preserve letters and numbers from any language, including accents:+`Привет мир` becomes `привет-мир`, and `你好世界` stays `你好世界`.+Spaces and punctuation become separators. If the title contains only emoji or+symbols, enter a slug manually. Existing filenames are never renamed.++Webstudio recognizes its previously generated slug patterns and uses the bundled+Unicode rule for those collections too. Saving collection settings replaces the+old pattern with the reference. Existing entry content and filenames remain+unchanged. Future rule updates do not require editing each collection's regex.++Editors can change the slug before creating the entry. New entries must satisfy+the schema. Existing entries report field errors without blocking incremental+edits or publication. The slug becomes+the MDX filename and cannot be changed after creation.++Slug fields are optional. Change the Slug field to another type+if the collection does not need one. New entries then receive unique generated+MDX filenames, without adding a filename field to their frontmatter. Existing+filenames stay unchanged. For a manual slug, set **Generate from** to+**None (manual entry)**.++For optional fields, click the field label and choose **Reset value**, or+Alt-click the label, to omit the value, including a value supplied by the+template. An empty text+value is different from an omitted value. Optional boolean fields offer+**Yes**, **No**, and **Not set**. Validation errors appear beside their fields.++Collection settings save automatically when valid. Webstudio checks the entry+template against the new rules. Existing entries remain editable if a rule changes.+The open collection folder checks entry frontmatter in the background and shows+a warning when an entry needs attention. Select an entry's error indicator or+choose **Entry settings** from its menu to edit its fields using the same controls+as **New entry**. Edits save automatically, including partial repairs. Unknown+frontmatter properties and the MDX body are preserved. Slugs remain fixed to the+filename; an existing mismatch has a repair action.++Use **Open MDX file** to edit the body or inspect unconfigured fields. Invalid field+values are underlined in the source editor; hover them for details. Content-mode+text and number controls bound to these fields also show their collection errors.+Fixing the values clears the errors. A field error does not hide the entry,+stop the collection rendering, or block publication of unrelated changes.++These checks read bounded file prefixes for direct entries in the open folder,+with at most four reads at once. Frontmatter is cached by file revision while+that folder remains open. Changing the schema rechecks cached values without+downloading unchanged entries again. A failed read is reported separately from+field errors and can be retried with **Check again**.++The configurator rejects Integer limits that leave no possible whole number.+Slug limits must allow at least one character, even when minimum length is unset.+Without a Slug field, use a single `*.mdx` or `entry-*.mdx` entry pattern when+saving collection settings. These match automatically generated filenames.+Custom filename patterns require a Slug field. Existing configurations remain+readable so their content can still be repaired and published.++Builder shares collection configuration loading across Assets, file editors, and+bound property controls. It groups the already-synchronized asset metadata once+per update and downloads the active collection's configuration and template once+for all consumers. Editing an entry does not download those unchanged files again.+Changing the configuration or template, retrying a failed read, or changing project+or access token refreshes this state. Entry validation still reads frontmatter as+described above; sharing configuration does not remove those reads.++A collection folder accepts entries, supporting assets, and subfolders. Use+**New entry** for filenames selected by the entry patterns. Files excluded by+the patterns behave like ordinary assets: upload, create, paste, move, rename,+and duplicate them normally. The collection configuration and template remain+protected and do not appear in Content+Engine query results. Keep `collection.json` valid and its referenced template+available. Broken collection configuration can still block collection queries+and publishing when Webstudio cannot safely identify the reserved files.+An invalid template still blocks entry creation and publication. Malformed YAML+and unreadable files are not ordinary field-validation errors; those existing+parsing and access checks still apply.++**Delete unused assets** does not list the files directly inside a collection+folder. Collection entries are loaded dynamically and may not have a direct+page or component reference.++Choose **Convert to regular folder** in **Collection settings**, the folder's+context or actions menu, or the empty-space context menu inside the folder.+Confirm the conversion. This deletes only+`collection.json`. The folder becomes a normal folder again, while its entries+and template remain. The former template is then a regular MDX file and can+appear in Assets query results.+## 2. Create an article+If `posts` is a content collection, choose **New entry** and fill in its form.+Otherwise, create the file and frontmatter manually:+1. Open `blog/posts` in the Assets panel.2. Open the add menu and choose **Create text file**.3. Name the file `hello-world.md`.@@ -110,7 +290,6 @@ Write the article here.<figure><img src="../../.gitbook/assets/content-engine-markdown-editor.png" alt="Markdown editor showing article frontmatter and body"><figcaption><p>An article's metadata and body in the Markdown editor</p></figcaption></figure>-### FrontmatterThe opening YAML block is called **frontmatter**. It must be the first block in@@ -147,8 +326,8 @@ Select only the referenced fields the page uses, such asvalue becomes structured data:```js-post.properties.featureImage.src-post.properties.featureImage.description+post.properties.featureImage.src;+post.properties.featureImage.description;```Bind the Image source to `post.properties.featureImage.src`. Bind its@@ -210,7 +389,8 @@ page-level **Dynamic data**:5. Under **Content**, choose **Metadata only**. The overview does not rendercomplete article bodies.6. Add these filters:- - `extension` **equals** `"md"`+ - `extension` **equals** `"mdx"` for collection entries, or `"md"` for the+ manually created Markdown files in this guide- `folder id` **equals** the quoted `posts` folder ID- `properties.draft` **does not equal** `true`7. Sort `properties.publishedAt` in descending order. Add `id` in ascending@@ -219,7 +399,6 @@ page-level **Dynamic data**:<figure><img src="../../.gitbook/assets/content-engine-overview-query.png" alt="Assets overview query filtering Markdown files and drafts, then sorting by publication date and ID"><figcaption><p>An overview query for the Webstudio Updates project</p></figcaption></figure>-Choosing only the fields the page renders keeps the published content datasmall. Leaving article bodies out of the overview also avoids loading everyarticle just to display a list.@@ -259,14 +438,14 @@ Add another Assets resource to the page-level **Dynamic data**:4. Under **Result**, choose **Exactly one**.5. Under **Content**, choose **Markdown body reference**.6. Add these filters:- - `extension` **equals** `"md"`+ - `extension` **equals** `"mdx"` for collection entries, or `"md"` for the+ manually created Markdown files in this guide- `folder id` **equals** the quoted `posts` folder ID- `properties.slug` **equals** `system.params.slug`- `properties.draft` **does not equal** `true`<figure><img src="../../.gitbook/assets/content-engine-article-query.png" alt="Assets resource filtering one Markdown article by folder and the dynamic page slug"><figcaption><p>The article Resource uses the dynamic slug from the page URL</p></figcaption></figure>-**Exactly one** returns the matching article directly at `post.data`. It alsoreports an error if two articles use the same slug. You do not need aCollection on the article page.@@ -338,9 +517,10 @@ give its Assets resource the same `properties.draft does not equal true`filter. The metadata field does not automatically remove an article from acustom sitemap.-To publish another article, duplicate the Markdown file and change its title,-slug, publication date, image, and body. The existing overview and dynamic page-will render it without another page design.+To publish another collection article, choose **New entry**. For the manual+workflow, duplicate the Markdown file and change its title, slug, publication+date, image, and body. The existing overview and dynamic page will render it+without another page design.## Connect content with document references@@ -352,10 +532,10 @@ for values inside JSON files, but it does not implement JSON Schema resolution.All supported source formats can reference the other content formats:-| Source | Where references can appear | JSON target | Markdown or MDX target |-| --- | --- | --- | --- |-| Markdown or MDX | YAML frontmatter | Yes | Yes |-| JSON | Anywhere in the document | Yes | Yes |+| Source | Where references can appear | JSON target | Markdown or MDX target |+| --------------- | --------------------------- | ----------- | ---------------------- |+| Markdown or MDX | YAML frontmatter | Yes | Yes |+| JSON | Anywhere in the document | Yes | Yes |References do not work inside a Markdown or MDX body. A `$ref` object can benested in an object or array, including inside a file reached through another@@ -375,13 +555,13 @@ relative to the file containing the reference, not the project root.The optional fragment selects which value to insert:-| Reference | Value inserted at `$ref` |-| --- | --- |-| `../authors/ada.json` | The complete JSON value |-| `../authors/ada.json#/profile/name` | The value at JSON Pointer `/profile/name` |-| `../authors/ada.md` | The complete Markdown source, including frontmatter |-| `../authors/ada.md#frontmatter` | The Markdown frontmatter as an object |-| `../authors/ada.md#body` | The Markdown body without frontmatter |+| Reference | Value inserted at `$ref` |+| ----------------------------------- | --------------------------------------------------- |+| `../authors/ada.json` | The complete JSON value |+| `../authors/ada.json#/profile/name` | The value at JSON Pointer `/profile/name` |+| `../authors/ada.md` | The complete Markdown source, including frontmatter |+| `../authors/ada.md#frontmatter` | The Markdown frontmatter as an object |+| `../authors/ada.md#body` | The Markdown body without frontmatter |JSON Pointer fragments apply only to JSON files. Use `~1` for `/` and `~0` for`~` inside a property name. For example, `#/social~1links/0` selects the firstdiff --git a/docs/university/mcp.md b/docs/university/mcp.mdindex aaaa7bdec4..f0da47acf6 100644--- a/docs/university/mcp.md+++ b/docs/university/mcp.md@@ -179,7 +179,7 @@ webstudio migrate-content-block-template-references '{"assetIds":["<mdxAssetId>"Prefer Markdown for standard document content. Markdown nodes automatically use a unique matching semantic template when one exists and keep their normal semantic fallback otherwise. Use lowercase JSX such as `<section>` or `<svg>` for a standard HTML or SVG element with authored properties Markdown cannot express.-Reference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template's stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins; otherwise the exact registered component export is used. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.+Reference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template's stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block's Templates. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants so template styles stay intact. A mismatched child structure replaces the root defaults, and each authored child still resolves through a matching template when possible. An explicit empty pair such as `<PromotionCard></PromotionCard>` clears the defaults. A self-closing reference such as `<PromotionCard />` keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live: adding a missing semantic or named template later also updates existing MDX without rewriting it. Preserve unresolved template names and report their diagnostics.@@ -189,7 +189,28 @@ Use the dedicated connect, switch, inspect, edit, update-frontmatter, reload, an`renderScope` is any non-empty stable identity for one rendered occurrence, such as `page:/articles/example`. It does not load that page, its route parameters, or its resource results. To connect a result-one Assets resource, run `preview-asset-query` with concrete values, keep the saved source expression such as `post.data.id`, and supply the previewed item for this occurrence with `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`. The operation validates that concrete Asset while persisting the dynamic expression.-A source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects, bind Image sources to their resolved `.src`, and bind alt properties to their Asset `.description`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document's frontmatter. Computed expressions and `$ref` values remain read-only.+A source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document's frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.++For an editable MDX article, use the resource to select the Content Block's source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.++### Content Block completion checklist++For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.++### Complete article editability is required++When the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.++Before handoff:++1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block's document bindings.+2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.+3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.+4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.++**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.++Keep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.If an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.diff --git a/fixtures/react-router-cloudflare/package.json b/fixtures/react-router-cloudflare/package.jsonindex 9880ec1181..1c7ad42c22 100644--- a/fixtures/react-router-cloudflare/package.json+++ b/fixtures/react-router-cloudflare/package.json@@ -7,12 +7,12 @@"fixtures:link": "pnpm cli:local link --link https://p-d845c167-ea07-4875-b08d-83e97c09dcce-dot-${BUILDER_HOST:-main.development.webstudio.is}'?authToken=e9d1343f-9298-4fd3-a66e-f89a5af2dd93'","fixtures:sync": "pnpm cli:local sync --buildId f565d527-32e7-4731-bc71-aca9e9574587 && oxfmt ./.webstudio/","fixtures:build": "pnpm cli:local build --template cloudflare-new --template .template && oxfmt ./app/ ./package.json ./tsconfig.json",- "build": "react-router build",- "dev": "react-router dev",+ "build": "node ./node_modules/@react-router/dev/bin.js build",+ "dev": "node ./node_modules/@react-router/dev/bin.js dev","typegen": "wrangler types","preview": "react-router build && vite preview","deploy": "react-router build && wrangler deploy",- "start": "react-router-serve ./build/server/index.js"+ "start": "node ./node_modules/@react-router/serve/bin.js ./build/server/index.js"},"dependencies": {"@cloudflare/vite-plugin": "^1.1.0",diff --git a/fixtures/react-router-docker/package.json b/fixtures/react-router-docker/package.jsonindex 4da3da5dc9..4a5b442625 100644--- a/fixtures/react-router-docker/package.json+++ b/fixtures/react-router-docker/package.json@@ -1,7 +1,7 @@{"scripts": {- "build": "react-router build",- "dev": "react-router dev",+ "build": "node ./node_modules/@react-router/dev/bin.js build",+ "dev": "node ./node_modules/@react-router/dev/bin.js dev","start": "react-router-serve ./build/server/index.js","typecheck": "tsc --noEmit","cli": "NODE_OPTIONS='--conditions=webstudio --import=tsx' webstudio",diff --git a/fixtures/react-router-docker/vite.config.ts b/fixtures/react-router-docker/vite.config.tsindex f843eb1b94..32e453175c 100644--- a/fixtures/react-router-docker/vite.config.ts+++ b/fixtures/react-router-docker/vite.config.ts@@ -5,6 +5,8 @@ const sourceConditions =process.env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED === "1" ? ["webstudio"] : [];export default defineConfig({+ // Local previews share node_modules, but must not share optimizer state.+ cacheDir: ".react-router/vite",plugins: [reactRouter()],server: {hmr: process.env.WEBSTUDIO_PREVIEW_HMR === "disabled" ? false : undefined,diff --git a/fixtures/react-router-netlify/package.json b/fixtures/react-router-netlify/package.jsonindex 571fec2b9e..74955258d0 100644--- a/fixtures/react-router-netlify/package.json+++ b/fixtures/react-router-netlify/package.json@@ -7,8 +7,8 @@"fixtures:link": "pnpm cli:local link --link https://p-d845c167-ea07-4875-b08d-83e97c09dcce-dot-${BUILDER_HOST:-main.development.webstudio.is}'?authToken=e9d1343f-9298-4fd3-a66e-f89a5af2dd93'","fixtures:sync": "pnpm cli:local sync --buildId f565d527-32e7-4731-bc71-aca9e9574587 && oxfmt ./.webstudio/","fixtures:build": "pnpm cli:local build --template netlify --template .template && oxfmt ./app/ ./package.json ./tsconfig.json",- "build": "react-router build",- "dev": "react-router dev",+ "build": "node ./node_modules/@react-router/dev/bin.js build",+ "dev": "node ./node_modules/@react-router/dev/bin.js dev","start": "npx netlify-cli serve","deploy": "npx netlify-cli deploy --build --prod"},diff --git a/fixtures/react-router-vercel/package.json b/fixtures/react-router-vercel/package.jsonindex 5aefc94099..68ea6cac37 100644--- a/fixtures/react-router-vercel/package.json+++ b/fixtures/react-router-vercel/package.json@@ -7,10 +7,10 @@"fixtures:link": "pnpm cli:local link --link https://p-d845c167-ea07-4875-b08d-83e97c09dcce-dot-${BUILDER_HOST:-main.development.webstudio.is}'?authToken=e9d1343f-9298-4fd3-a66e-f89a5af2dd93'","fixtures:sync": "pnpm cli:local sync --buildId f565d527-32e7-4731-bc71-aca9e9574587 && oxfmt ./.webstudio/","fixtures:build": "pnpm cli:local build --template vercel --template .template && oxfmt ./app/ ./package.json ./tsconfig.json",- "build": "react-router build",- "dev": "react-router dev",+ "build": "node ./node_modules/@react-router/dev/bin.js build",+ "dev": "node ./node_modules/@react-router/dev/bin.js dev","deploy": "npx vercel deploy",- "start": "react-router-serve ./build/server/index.js"+ "start": "node ./node_modules/@react-router/serve/bin.js ./build/server/index.js"},"dependencies": {"@react-router/dev": "^7.5.3",diff --git a/fixtures/react-router-vercel/vite.config.ts b/fixtures/react-router-vercel/vite.config.tsindex f843eb1b94..32e453175c 100644--- a/fixtures/react-router-vercel/vite.config.ts+++ b/fixtures/react-router-vercel/vite.config.ts@@ -5,6 +5,8 @@ const sourceConditions =process.env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED === "1" ? ["webstudio"] : [];export default defineConfig({+ // Local previews share node_modules, but must not share optimizer state.+ cacheDir: ".react-router/vite",plugins: [reactRouter()],server: {hmr: process.env.WEBSTUDIO_PREVIEW_HMR === "disabled" ? false : undefined,diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.jsonindex 7a291f30a9..4805319a68 100644--- a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json@@ -1,11 +1,11 @@{"bundleVersion": "bundle-1x6rafk","build": {- "id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c",+ "id": "823cc69d-b2ed-418b-823c-2efc717319cd","projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e","version": 7,- "createdAt": "2026-01-04T10:46:48.415+00:00",- "updatedAt": "2026-01-04T10:46:48.415+00:00",+ "createdAt": "2024-09-03T04:31:42.776+00:00",+ "updatedAt": "2026-01-04T10:46:33.246+00:00","pages": {"homePageId": "Y60VJnVZMU_ifI0GnAR1N","rootFolderId": "root",@@ -147,12 +147,6 @@"projectSettings": {"meta": {},"compiler": {}- },- "deployment": {- "destination": "saas",- "domains": ["fixture-client-do-not-touch-wsmel"],- "assetsDomain": "fixture-client-do-not-touch-wsmel",- "excludeWstdDomainFromSearch": false}},"page": {@@ -202,9 +196,6 @@],"assets": [],"assetFolders": [],- "user": {- "email": "[email protected]"- },"projectDomain": "fixture-client-do-not-touch-wsmel","projectTitle": "FIXTURE-CLIENT-DO-NOT-TOUCH","origin": "https://main.development.webstudio.is"diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.asset-query-manifest.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.asset-query-manifest.tsindex b68197d7f6..e37659a7b9 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.asset-query-manifest.ts+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.asset-query-manifest.ts@@ -1,2 +1,2 @@-export const assetQueryDeploymentId = "8f0fdff2-e76b-4f86-9203-ea7df5f1143c";+export const assetQueryDeploymentId = "823cc69d-b2ed-418b-823c-2efc717319cd";export const assetQueryDatabase = undefined;diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsxindex 49b47c91c4..0e16cc445e 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx@@ -43,5 +43,5 @@ export const getRemixParams = ({ ...params }: Params): Params => {}- export const contactEmail = "[email protected]";+ export const contactEmail = undefined;\ No newline at end of filediff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsxindex badabac03c..fc07ae7561 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsx@@ -12,7 +12,7 @@export const projectDomain = "fixture-client-do-not-touch-wsmel";- export const lastPublished = "2026-01-04T10:46:48.415Z";+ export const lastPublished = "2024-09-03T04:31:42.776Z";export const siteName = undefined;diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsxindex 55164bf9dd..821087eabb 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx@@ -43,5 +43,5 @@ export const getRemixParams = ({ ...params }: Params): Params => {}- export const contactEmail = "[email protected]";+ export const contactEmail = undefined;\ No newline at end of filediff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsxindex 6697abdec4..130a8e6dd8 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx@@ -13,7 +13,7 @@export const projectDomain = "fixture-client-do-not-touch-wsmel";- export const lastPublished = "2026-01-04T10:46:48.415Z";+ export const lastPublished = "2024-09-03T04:31:42.776Z";export const siteName = undefined;diff --git a/fixtures/webstudio-features/package.json b/fixtures/webstudio-features/package.jsonindex e0b347d7d2..c57fbfea5a 100644--- a/fixtures/webstudio-features/package.json+++ b/fixtures/webstudio-features/package.json@@ -2,14 +2,14 @@"type": "module","scripts": {"typecheck": "tsc --noEmit",- "build": "react-router build",- "dev": "react-router dev",+ "build": "node ./node_modules/@react-router/dev/bin.js build",+ "dev": "node ./node_modules/@react-router/dev/bin.js dev","cli": "NODE_OPTIONS='--conditions=webstudio --import=tsx' webstudio","cli:local": "node ../../packages/cli/local.js","fixtures:link": "pnpm cli:local link --link https://p-cddc1d44-af37-4cb6-a430-d300cf6f932d-dot-${BUILDER_HOST:-main.development.webstudio.is}'?authToken=1cdc6026-dd5b-4624-b89b-9bd45e9bcc3d'","fixtures:sync": "pnpm cli:local sync --buildId 1b66ee06-8ea5-4420-9a0e-e0d3a67aca32 && oxfmt ./.webstudio/","fixtures:build": "pnpm cli:local build --template react-router --template ./.template && oxfmt ./app/ ./package.json ./tsconfig.json",- "start": "react-router-serve ./build/server/index.js"+ "start": "node ./node_modules/@react-router/serve/bin.js ./build/server/index.js"},"private": true,"sideEffects": false,diff --git a/packages/asset-uploader/src/asset-patch-core.ts b/packages/asset-uploader/src/asset-patch-core.tsindex 0178bb12ce..b6578280a2 100644--- a/packages/asset-uploader/src/asset-patch-core.ts+++ b/packages/asset-uploader/src/asset-patch-core.ts@@ -1,6 +1,6 @@-import { type Asset, assets } from "@webstudio-is/sdk";+import { asset as assetSchema, type Asset, assets } from "@webstudio-is/sdk";import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";-import type { Client } from "@webstudio-is/postgrest/index.server";+import type { Client, Database } from "@webstudio-is/postgrest/index.server";import { mapBounded } from "@webstudio-is/content-engine/compiler";import { formatAsset } from "./utils/format-asset";import {@@ -9,12 +9,82 @@ import {diffMaps,type Patch,} from "./patch-utils";-import { swapAssetFileWithClient } from "./revision";+import {+ AssetRevisionConflictError,+ swapAssetFileWithClient,+} from "./revision";import type { AssetMetadataUpdate } from "./asset-mutation-types";import { AssetRepositoryNotFoundError } from "./asset-repository-errors";const serializeAssetMeta = (meta: Asset["meta"]) => JSON.stringify(meta);+type FileRow = Database["public"]["Tables"]["File"]["Row"];++const getCanonicalAssetsForValidation = async ({+ current,+ next,+ client,+}: {+ current: ReadonlyMap<Asset["id"], Asset>;+ next: ReadonlyMap<Asset["id"], Asset>;+ client: Client;+}) => {+ const canonical = new Map<Asset["id"], Asset>();+ const filesByName = new Map<string, FileRow>();+ const assetsWithChangedFiles: Asset[] = [];+ for (const [assetId, asset] of next) {+ const previous = current.get(assetId);+ if (previous?.name === asset.name) {+ canonical.set(+ assetId,+ assetSchema.parse({+ ...previous,+ filename: asset.filename,+ description: asset.description,+ folderId: asset.folderId,+ meta: asset.meta,+ })+ );+ continue;+ }+ assetsWithChangedFiles.push(asset);+ }+ if (assetsWithChangedFiles.length === 0) {+ return { assets: canonical, filesByName };+ }++ const files = await loadUploadedFilesByNames({+ names: assetsWithChangedFiles.map((asset) => asset.name),+ client,+ });+ for (const file of files) {+ filesByName.set(file.name, file);+ }+ for (const asset of assetsWithChangedFiles) {+ const file = filesByName.get(asset.name);+ if (file === undefined) {+ throw new AssetRepositoryNotFoundError(+ `Asset file not found for ${asset.id}`+ );+ }+ canonical.set(+ asset.id,+ assetSchema.parse({+ ...formatAsset({+ assetId: asset.id,+ projectId: asset.projectId,+ filename: asset.filename ?? null,+ description: asset.description ?? null,+ folderId: asset.folderId,+ file,+ }),+ meta: asset.meta,+ })+ );+ }+ return { assets: canonical, filesByName };+};+// Supabase documents that REST requests most often hit Cloudflare 520 errors// at 16+ KiB across the URL and headers, especially with long `in` filters:// https://supabase.com/docs/guides/troubleshooting/fixing-520-errors-in-the-database-rest-api-Ur5-B2@@ -30,6 +100,132 @@ const maxConcurrentAssetMetadataPostgrestRequests = Math.ceil(assetResourceLimits.concurrentContentReads / 2);+// Keep encoded `in` filters around 4 KiB. File storage names can be much+// longer than Asset ids, so a fixed item count cannot provide the same bound.+const maxPostgrestInFilterCharacters = 4 * 1024;++const chunkPostgrestInValues = (values: Iterable<string>) => {+ const chunks: string[][] = [];+ let chunk: string[] = [];+ for (const value of new Set(values)) {+ const candidate = [...chunk, value];+ const encodedFilter = new URLSearchParams({+ name: `in.(${candidate.join(",")})`,+ }).toString();+ if (+ chunk.length > 0 &&+ encodedFilter.length > maxPostgrestInFilterCharacters+ ) {+ chunks.push(chunk);+ chunk = [value];+ continue;+ }+ chunk = candidate;+ }+ if (chunk.length > 0) {+ chunks.push(chunk);+ }+ return chunks;+};++// File.uploaderProjectId records physical-file provenance, not every project+// allowed to reference it. clone_project intentionally shares File rows while+// copying their logical Asset rows, so filtering these lookups by that field+// would prevent cloned projects from restoring their shared files during Undo.+const loadUploadedFilesByNames = async ({+ names,+ client,+}: {+ names: Iterable<string>;+ client: Client;+}) => {+ const chunks = chunkPostgrestInValues(names);+ return (+ await mapBounded(+ chunks,+ maxConcurrentAssetMetadataPostgrestRequests,+ async (chunk) => {+ const files = await client+ .from("File")+ .select()+ .in("name", chunk)+ .eq("status", "UPLOADED");+ assertPostgrestSuccess(files);+ return (files.data ?? []).filter((file) => file.status === "UPLOADED");+ }+ )+ ).flat();+};++const restoreUploadedFilesByNames = async ({+ names,+ client,+}: {+ names: Iterable<string>;+ client: Client;+}) => {+ await mapBounded(+ chunkPostgrestInValues(names),+ maxConcurrentAssetMetadataPostgrestRequests,+ async (chunk) => {+ const restoredFiles = await client+ .from("File")+ .update({ isDeleted: false })+ .in("name", chunk)+ .eq("status", "UPLOADED");+ assertPostgrestSuccess(restoredFiles);+ }+ );+};++const restoreSharedAssetFileWithClient = async (+ {+ projectId,+ assetId,+ expectedName,+ replacementName,+ }: {+ projectId: string;+ assetId: string;+ expectedName: string;+ replacementName: string;+ },+ client: Client+) => {+ // clone_project shares existing File revision rows with the source project.+ // Restore the shared target before the compare-and-set so an Asset never+ // points at a deleted file if either request fails.+ const restoredFile = await client+ .from("File")+ .update({ isDeleted: false })+ .eq("name", replacementName)+ .eq("status", "UPLOADED")+ .select("name")+ .maybeSingle();+ assertPostgrestSuccess(restoredFile);+ if (restoredFile.data?.name !== replacementName) {+ throw new AssetRepositoryNotFoundError("Asset revision is not available");+ }++ const updatedAsset = await client+ .from("Asset")+ .update({ name: replacementName })+ .eq("id", assetId)+ .eq("projectId", projectId)+ .eq("name", expectedName)+ .select("id")+ .maybeSingle();+ assertPostgrestSuccess(updatedAsset);+ if (updatedAsset.data?.id !== assetId) {+ throw new AssetRevisionConflictError(+ "This file changed since it was opened. Reload it before saving again."+ );+ }+ // Retain the prior File revision here. A separate read-then-delete cleanup+ // could mark it deleted after another project or Undo restores a reference.+ // Owned revisions use swap_asset_file's transactional cleanup instead.+};+export const createAssetRows = (assets: Iterable<Asset>, projectId: string) =>Array.from(assets, (asset) => ({id: asset.id,@@ -40,6 +236,80 @@ export const createAssetRows = (assets: Iterable<Asset>, projectId: string) =>folderId: asset.folderId ?? null,}));+export type AssetUploadReservation = Pick<+ Asset,+ "id" | "name" | "filename" | "folderId" | "createdAt"+> & {+ status?: "UPLOADING" | "UPLOADED";+};++const uploadReservationFreshnessMs = 30 * 60 * 1000;++export const loadAssetUploadReservationsByProjectWithClient = async (+ projectId: string,+ client: Client,+ now = new Date()+): Promise<AssetUploadReservation[]> => {+ const response = await client+ .from("Asset")+ .select(+ "id, filename, folderId, file:File!inner(name, status, isDeleted, createdAt, updatedAt)"+ )+ .eq("projectId", projectId)+ .order("id");+ assertPostgrestSuccess(response);+ const activeAfter = now.getTime() - uploadReservationFreshnessMs;+ return (response.data ?? []).flatMap(({ id, filename, folderId, file }) => {+ if (+ file.status !== "UPLOADED" &&+ (file.status !== "UPLOADING" ||+ file.isDeleted ||+ new Date(file.updatedAt).getTime() <= activeAfter)+ ) {+ return [];+ }+ return [+ {+ id,+ name: file.name,+ filename: filename ?? undefined,+ folderId: folderId ?? undefined,+ createdAt: file.createdAt,+ status: file.status,+ },+ ];+ });+};++export const deleteAssetUploadReservationWithClient = async (+ {+ projectId,+ assetId,+ name,+ }: { projectId: string; assetId: string; name: string },+ client: Client+) => {+ const deletedAsset = await client+ .from("Asset")+ .delete()+ .eq("id", assetId)+ .eq("projectId", projectId)+ .eq("name", name)+ .select("id")+ .maybeSingle();+ assertPostgrestSuccess(deletedAsset);+ if (deletedAsset.data?.id !== assetId) {+ return;+ }+ const deletedFile = await client+ .from("File")+ .delete()+ .eq("name", name)+ .eq("uploaderProjectId", projectId)+ .eq("status", "UPLOADING");+ assertPostgrestSuccess(deletedFile);+};+export const loadAssetsByProjectWithClient = async (projectId: string,client: Client,@@ -205,6 +475,45 @@ export const updateAssetMetadataWithClient = async (return asset;};+export const updateAssetFilenameIfCurrentWithClient = async (+ {+ projectId,+ assetId,+ expectedFilename,+ filename,+ }: {+ projectId: string;+ assetId: Asset["id"];+ expectedFilename: string | undefined;+ filename: string | undefined;+ },+ client: Client+): Promise<Asset | undefined> => {+ const query = client+ .from("Asset")+ .update({ filename: filename ?? null })+ .eq("id", assetId)+ .eq("projectId", projectId);+ const result = await (+ expectedFilename === undefined+ ? query.is("filename", null)+ : query.eq("filename", expectedFilename)+ )+ .select("id")+ .maybeSingle();+ assertPostgrestSuccess(result);+ if (result.data?.id !== assetId) {+ return;+ }+ const [asset] = await loadAssetsByProjectWithClient(projectId, client, [+ assetId,+ ]);+ if (asset === undefined) {+ throw new AssetRepositoryNotFoundError("Asset not found");+ }+ return asset;+};+const persistAssetMetadataWithClient = async ({projectId,@@ -255,7 +564,21 @@ export const patchAssetsWithClient = async (projectId: string;client: Client;},- patches: Array<Patch>+ patches: Array<Patch>,+ {+ validate,+ allowSharedFileRestore = false,+ }: {+ validate?: (input: {+ current: ReadonlyMap<Asset["id"], Asset>;+ next: ReadonlyMap<Asset["id"], Asset>;+ }) => Promise<void>;+ /**+ * Allows the authorized sync endpoint to restore File rows shared by a+ * cloned project. Direct revision writes remain restricted to owned rows.+ */+ allowSharedFileRestore?: boolean;+ } = {}): Promise<void> => {const assetsList = await loadAssetsByProjectWithClient(projectId, client);const assetsMap = new Map<Asset["id"], Asset>();@@ -265,11 +588,26 @@ export const patchAssetsWithClient = async (const patchedAssets = applyValidatedMapPatches(assetsMap, patches, (value) =>assets.parse(value));- for (const asset of patchedAssets.values()) {+ for (const [assetId, asset] of patchedAssets) {+ if (asset.id !== assetId) {+ throw new Error(+ `Asset ${asset.id} does not match its map key ${assetId}`+ );+ }if (asset.projectId !== projectId) {throw new Error(`Asset ${asset.id} belongs to another project`);}}+ let replacementFilesByName = new Map<string, FileRow>();+ if (validate !== undefined || allowSharedFileRestore) {+ const canonical = await getCanonicalAssetsForValidation({+ current: assetsMap,+ next: patchedAssets,+ client,+ });+ replacementFilesByName = canonical.filesByName;+ await validate?.({ current: assetsMap, next: canonical.assets });+ }const {added,updated,@@ -284,6 +622,56 @@ export const patchAssetsWithClient = async (previous.folderId === asset.folderId &&serializeAssetMeta(previous.meta) === serializeAssetMeta(asset.meta));+ const sharedMetadataAssetIds = new Set<Asset["id"]>();+ if (allowSharedFileRestore) {+ const assetsWithMetadataChanges = updated.filter((asset) => {+ const previous = assetsMap.get(asset.id);+ return (+ previous !== undefined &&+ serializeAssetMeta(previous.meta) !== serializeAssetMeta(asset.meta)+ );+ });+ const missingFileNames = assetsWithMetadataChanges.flatMap((asset) =>+ replacementFilesByName.has(asset.name) ? [] : [asset.name]+ );+ for (const file of await loadUploadedFilesByNames({+ names: missingFileNames,+ client,+ })) {+ replacementFilesByName.set(file.name, file);+ }+ for (const asset of assetsWithMetadataChanges) {+ const file = replacementFilesByName.get(asset.name);+ if (file === undefined) {+ throw new AssetRepositoryNotFoundError(+ `Asset file not found for ${asset.id}`+ );+ }+ // Files uploaded before provenance tracking have a null project id.+ // Preserve their existing metadata edits, but validate replacement files.+ if (+ file.uploaderProjectId === projectId ||+ (file.uploaderProjectId === null &&+ assetsMap.get(asset.id)?.name === asset.name)+ ) {+ continue;+ }+ sharedMetadataAssetIds.add(asset.id);+ const authoritativeMeta = formatAsset({+ assetId: asset.id,+ projectId,+ filename: asset.filename ?? null,+ description: asset.description ?? null,+ folderId: asset.folderId,+ file,+ }).meta;+ if (+ serializeAssetMeta(asset.meta) !== serializeAssetMeta(authoritativeMeta)+ ) {+ throw new Error("Shared asset metadata does not match its file");+ }+ }+ }if (deletedAssetIds.length !== 0) {await deleteAssetsWithClient({ projectId, ids: deletedAssetIds }, client);}@@ -294,15 +682,37 @@ export const patchAssetsWithClient = async (throw new Error(`Asset ${asset.id} was not loaded`);}if (previous.name !== asset.name) {- await swapAssetFileWithClient(- {- projectId,- assetId: asset.id,- expectedName: previous.name,- replacementName: asset.name,- },- client- );+ const replacementFile = replacementFilesByName.get(asset.name);+ if (allowSharedFileRestore && replacementFile === undefined) {+ throw new AssetRepositoryNotFoundError(+ `Asset file not found for ${asset.id}`+ );+ }+ if (+ allowSharedFileRestore &&+ replacementFile !== undefined &&+ replacementFile.uploaderProjectId !== projectId+ ) {+ await restoreSharedAssetFileWithClient(+ {+ projectId,+ assetId: asset.id,+ expectedName: previous.name,+ replacementName: asset.name,+ },+ client+ );+ } else {+ await swapAssetFileWithClient(+ {+ projectId,+ assetId: asset.id,+ expectedName: previous.name,+ replacementName: asset.name,+ },+ client+ );+ }}if (previous.filename !== asset.filename ||@@ -319,7 +729,10 @@ export const patchAssetsWithClient = async (client);}- if (serializeAssetMeta(previous.meta) !== serializeAssetMeta(asset.meta)) {+ if (+ sharedMetadataAssetIds.has(asset.id) === false &&+ serializeAssetMeta(previous.meta) !== serializeAssetMeta(asset.meta)+ ) {const meta = serializeAssetMeta(asset.meta);const updatedFile = await client.from("File")@@ -337,16 +750,11 @@ export const patchAssetsWithClient = async (}const addedAssets: Asset[] = added;if (addedAssets.length !== 0) {- const files = await client- .from("File")- .select()- .in(- "name",- addedAssets.map((asset) => asset.name)- );- assertPostgrestSuccess(files);-- const fileNames = new Set(files.data?.map((file) => file.name));+ const files = await loadUploadedFilesByNames({+ names: addedAssets.map((asset) => asset.name),+ client,+ });+ const fileNames = new Set(files.map((file) => file.name));const missingFile = addedAssets.find((asset) => fileNames.has(asset.name) === false);@@ -357,11 +765,7 @@ export const patchAssetsWithClient = async (}// restore file when undo is triggered- const restoredFiles = await client- .from("File")- .update({ isDeleted: false })- .in("name", Array.from(fileNames));- assertPostgrestSuccess(restoredFiles);+ await restoreUploadedFilesByNames({ names: fileNames, client });const insertedAssets = await client.from("Asset")diff --git a/packages/asset-uploader/src/asset-repository.test.ts b/packages/asset-uploader/src/asset-repository.test.tsindex ab55aebbd1..ee62d9453f 100644--- a/packages/asset-uploader/src/asset-repository.test.ts+++ b/packages/asset-uploader/src/asset-repository.test.ts@@ -1,5 +1,7 @@import { beforeEach, describe, expect, test, vi } from "vitest";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";+import type { Asset } from "@webstudio-is/sdk";+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";import type { AssetObjectStore } from "./client";import { createUploadTicket, uploadFile } from "./upload";import {@@ -15,6 +17,9 @@ import {createContentRuntimeArtifact,createLiteralContentCompilationQuery,assetQuery,+ createDefaultCollectionConfig,+ createCollectionEntry as createContentCollectionEntry,+ parseCollectionConfig,serializeContentArtifact,type AssetQueryInput,type AssetFileDocument,@@ -30,8 +35,11 @@ import {} from "./asset-repository";import { createContentCompilationCache } from "./content-compilation-cache";import {+ deleteAssetUploadReservationWithClient,deleteAssetsWithClient,+ loadAssetUploadReservationsByProjectWithClient,loadAssetsByProjectWithClient,+ updateAssetFilenameIfCurrentWithClient,updateAssetMetadataWithClient,} from "./asset-patch-core";import { updateAssetContent } from "./revision";@@ -49,6 +57,27 @@ const assetClient: AssetObjectStore = {uploadFile: vi.fn(),};+const createSourceAssetClient = (+ sources: Readonly<Record<string, string>>+): AssetObjectStore => ({+ readFile: vi.fn(async (name, range) => {+ const source = sources[name];+ if (source === undefined) {+ throw new Error(`Unexpected asset read: ${name}`);+ }+ const offset = range?.offset ?? 0;+ const data =+ range?.length === undefined+ ? source.slice(offset)+ : source.slice(offset, offset + range.length);+ return {+ data: new Blob([data]).stream() as unknown as AsyncIterable<Uint8Array>,+ contentLength: data.length,+ };+ }),+ uploadFile: vi.fn(),+});+beforeEach(() => {vi.mocked(assetClient.readFile).mockReset()@@ -79,54 +108,2286 @@ const createCompilationPlan = (query: AssetQueryInput) => {return plan;};-const createDependencies = () => {- const loadFileEntries = vi- .fn<typeof loadCanonicalAssetFileEntries>()- .mockResolvedValue([]);- return {- hasProjectPermit: vi.fn().mockResolvedValue(true),- createUploadTicket: vi.fn<typeof createUploadTicket>(),- uploadFile: vi.fn<typeof uploadFile>(),- updateAssetContent: vi.fn<typeof updateAssetContent>(),- deleteAssetsWithClient: vi.fn<typeof deleteAssetsWithClient>(),- synchronizeCanonicalAssets: vi- .fn<typeof synchronizeCanonicalAssets>()- .mockResolvedValue({- scanned: 0,- indexed: 0,- metadataUpdated: 0,- unchanged: 0,- removed: 0,- skipped: 0,- inconsistent: 0,- issues: [],+const createDependencies = () => {+ const loadFileEntries = vi+ .fn<typeof loadCanonicalAssetFileEntries>()+ .mockResolvedValue([]);+ return {+ hasProjectPermit: vi.fn().mockResolvedValue(true),+ createUploadTicket: vi.fn<typeof createUploadTicket>(),+ uploadFile: vi.fn<typeof uploadFile>(),+ updateAssetContent: vi.fn<typeof updateAssetContent>(),+ deleteAssetsWithClient: vi.fn<typeof deleteAssetsWithClient>(),+ deleteAssetUploadReservationWithClient:+ vi.fn<typeof deleteAssetUploadReservationWithClient>(),+ synchronizeCanonicalAssets: vi+ .fn<typeof synchronizeCanonicalAssets>()+ .mockResolvedValue({+ scanned: 0,+ indexed: 0,+ metadataUpdated: 0,+ unchanged: 0,+ removed: 0,+ skipped: 0,+ inconsistent: 0,+ issues: [],+ }),+ loadCanonicalAssetBaseEntries: vi+ .fn<typeof loadCanonicalAssetBaseEntries>()+ .mockResolvedValue([]),+ loadCanonicalAssetFileEntries: loadFileEntries,+ loadCanonicalAssetFileEntriesForRecovery: vi+ .fn<typeof loadCanonicalAssetFileEntriesForRecovery>()+ .mockImplementation(async (input) => ({+ entries: await loadFileEntries(input),+ inconsistentRows: [],+ })),+ createAssetIndex: vi.fn<typeof createAssetIndex>(),+ updateAssetMetadataWithClient:+ vi.fn<typeof updateAssetMetadataWithClient>(),+ updateAssetFilenameIfCurrentWithClient:+ vi.fn<typeof updateAssetFilenameIfCurrentWithClient>(),+ loadAssetsByProjectWithClient: vi+ .fn<typeof loadAssetsByProjectWithClient>()+ .mockResolvedValue([]),+ loadAssetUploadReservationsByProjectWithClient: vi+ .fn<typeof loadAssetUploadReservationsByProjectWithClient>()+ .mockResolvedValue([]),+ loadAssetFoldersByProjectWithClient:+ vi.fn<typeof loadAssetFoldersByProjectWithClient>(),+ upsertAssetFolderWithClient: vi.fn<typeof upsertAssetFolderWithClient>(),+ deleteAssetFoldersWithClient: vi.fn<typeof deleteAssetFoldersWithClient>(),+ createId: vi.fn(() => "folder-1"),+ now: vi.fn(() => new Date("2026-07-25T00:00:00.000Z")),+ };+};++const prepareAssetContentUpdate = (+ dependencies: ReturnType<typeof createDependencies>,+ asset: Asset+) =>+ dependencies.updateAssetContent.mockImplementation(async (input) => {+ await input.prepareData?.({ asset, data: input.data });+ return asset;+ });++describe("PostgresAssetRepository", () => {+ test("publication keeps entries with invalid fields but rejects broken configuration", async () => {+ const sources = {+ "collection.json": createDefaultCollectionConfig(),+ "template.mdx": "---\ndraft: true\n---\n",+ "post.mdx": "---\ntitle: ''\nslug: post\n---\nVisible article.\n",+ };+ const assets: Asset[] = Object.entries(sources).map(([name, source]) => ({+ id: name,+ projectId: "project-1",+ folderId: "posts",+ name,+ type: "file",+ format: name.endsWith(".json") ? "json" : "mdx",+ size: source.length,+ createdAt: "2026-09-08T00:00:00.000Z",+ meta: {},+ }));+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient(sources),+ dependencies: createDependencies(),+ });+ await expect(+ repository.validateCollections(assets)+ ).resolves.toBeUndefined();+ sources["collection.json"] = "!".repeat(sources["collection.json"].length);+ await expect(repository.validateCollections(assets)).rejects.toThrow(+ "invalid JSON"+ );+ });++ test.each([+ { name: "notes.txt", extension: "mdx", collection: true },+ { name: "template.txt", extension: "mdx", collection: true },+ { name: "collection.txt", extension: "json", collection: false },+ { name: "collection.mdx", extension: "json", collection: false },+ ])(+ "blocks extension changes that bypass collection creation: $name",+ async ({ name, extension, collection }) => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const config: Asset = {+ id: "config",+ projectId: "project-1",+ folderId: "posts",+ name: "collection.json",+ type: "file",+ format: "json",+ size: configSource.length,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const ignored: Asset = {+ ...config,+ id: "ignored",+ name,+ format: name.split(".").at(-1)!,+ size: 5,+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue(+ collection ? [config, ignored] : [ignored]+ );+ prepareAssetContentUpdate(dependencies, ignored);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ dependencies,+ assetStore: createSourceAssetClient({ [config.name]: configSource }),+ });+ await expect(+ repository.updateContent({+ assetId: ignored.id,+ expectedName: ignored.name,+ extension,+ data: new Blob(["notes"]).stream(),+ })+ ).rejects.toThrow();+ // Unselected extensions remain ordinary supporting-file edits.+ await expect(+ repository.updateContent({+ assetId: ignored.id,+ expectedName: ignored.name,+ extension: "md",+ data: new Blob(["notes"]).stream(),+ })+ ).resolves.toBe(ignored);+ }+ );+ test.each(["notes.txt", "notes.md", "draft-idea.mdx"])(+ "allows ordinary asset operations for ignored %s",+ async (filename) => {+ const dependencies = createDependencies();+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = ["*.mdx", "!draft-*.mdx"];+ const configSource = JSON.stringify(schema);+ const templateSource = "---\ndraft: true\n---\n";+ const config: Asset = {+ id: "config",+ projectId: "project-1",+ folderId: "posts",+ name: "collection.json",+ type: "file",+ format: "json",+ size: configSource.length,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const template: Asset = {+ ...config,+ id: "template",+ name: "template.mdx",+ format: "mdx",+ size: templateSource.length,+ };+ const ignored: Asset = {+ ...config,+ id: "ignored",+ name: filename,+ format: filename.split(".").at(-1)!,+ size: 5,+ };+ const invalidEntry: Asset = {+ ...ignored,+ id: "invalid-entry",+ name: "invalid.mdx",+ format: "mdx",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ config,+ template,+ ignored,+ invalidEntry,+ ]);+ const ticket = {+ assetId: ignored.id,+ name: ignored.name,+ deduplicated: false as const,+ };+ dependencies.createUploadTicket.mockResolvedValue(ticket);+ dependencies.uploadFile.mockResolvedValue(ignored);+ dependencies.updateAssetMetadataWithClient.mockResolvedValue(ignored);+ prepareAssetContentUpdate(dependencies, ignored);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ dependencies,+ assetStore: createSourceAssetClient({+ [config.name]: configSource,+ [template.name]: templateSource,+ [ignored.name]: "notes",+ [invalidEntry.name]: "notes",+ }),+ });+ await expect(+ repository.createUploadTicket({+ type: "file",+ filename,+ folderId: "posts",+ })+ ).resolves.toEqual(ticket);+ await expect(+ repository.completeUpload({+ name: ignored.name,+ assetId: ignored.id,+ data: new Blob(["notes"]).stream(),+ assetInfoFallback: undefined,+ })+ ).resolves.toBe(ignored);+ await expect(+ repository.updateContent({+ assetId: ignored.id,+ expectedName: ignored.name,+ data: new Blob(["---\ntitle: ignored\n---\n"]).stream(),+ })+ ).resolves.toBe(ignored);+ await expect(+ repository.updateMetadata(ignored.id, { filename: "draft-renamed" })+ ).resolves.toBe(ignored);+ if (ignored.format === "mdx") {+ await expect(+ repository.updateMetadata(ignored.id, { filename: "post" })+ ).rejects.toThrow("Use New entry");+ }+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ config,+ template,+ invalidEntry,+ { ...ignored, folderId: undefined },+ ]);+ await expect(+ repository.updateMetadata(ignored.id, { folderId: "posts" })+ ).resolves.toBe(ignored);+ expect(dependencies.deleteAssetsWithClient).not.toHaveBeenCalled();+ }+ );+ test("treats a root-level collection.json as an ordinary asset", async () => {+ const dependencies = createDependencies();+ const rootAsset: Asset = {+ id: "root-config",+ projectId: "project-1",+ name: "collection.json",+ filename: "collection",+ type: "file",+ format: "json",+ size: 2,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ dependencies.hasProjectPermit.mockImplementation(+ async ({ permit }) => permit === "edit"+ );+ dependencies.createUploadTicket.mockResolvedValue({+ assetId: rootAsset.id,+ name: rootAsset.name,+ deduplicated: false,+ });+ dependencies.uploadFile.mockResolvedValue(rootAsset);+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([rootAsset]);+ dependencies.updateAssetMetadataWithClient.mockResolvedValue(rootAsset);+ dependencies.updateAssetContent.mockResolvedValue(rootAsset);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: assetClient,+ dependencies,+ });++ await expect(+ repository.createUploadTicket({+ type: "file",+ filename: "collection.json",+ })+ ).resolves.toMatchObject({ assetId: rootAsset.id });+ await expect(+ repository.completeUpload({+ name: rootAsset.name,+ data: new Blob(["{}"]).stream(),+ assetInfoFallback: undefined,+ assetId: rootAsset.id,+ })+ ).resolves.toBe(rootAsset);+ await expect(+ repository.updateContent({+ assetId: rootAsset.id,+ expectedName: rootAsset.name,+ data: new Blob(["{}"]).stream(),+ })+ ).resolves.toBe(rootAsset);+ await expect(+ repository.updateMetadata(rootAsset.id, { description: "ordinary" })+ ).resolves.toBe(rootAsset);+ await expect(repository.delete([rootAsset.id])).resolves.toBeUndefined();+ expect(+ dependencies.hasProjectPermit.mock.calls.some(+ ([{ permit }]) => permit === "build"+ )+ ).toBe(false);+ });++ test("blocks generic uploads matching collection entry patterns", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ {+ id: "config",+ projectId: "project-1",+ name: "collection.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ },+ ]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ ...assetClient,+ readFile: vi.fn(async () => ({+ data: new Blob([+ createDefaultCollectionConfig(),+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ })),+ },+ dependencies,+ });++ await expect(+ repository.createUploadTicket({+ type: "file",+ filename: "notes.mdx",+ folderId: "posts",+ })+ ).rejects.toThrow("Use New entry");+ await expect(+ repository.createUploadTicket({+ type: "file",+ filename: "collection.json",+ folderId: "posts",+ })+ ).rejects.toThrow("Collection configuration already exists");+ expect(dependencies.createUploadTicket).not.toHaveBeenCalled();+ });++ test("rejects an upload completed after its folder becomes a collection", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "collection.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const uploadedAsset: Asset = {+ ...configAsset,+ id: "notes",+ name: "notes.mdx",+ filename: "notes",+ format: "mdx",+ };+ dependencies.uploadFile.mockResolvedValue(uploadedAsset);+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ uploadedAsset,+ ]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({ [configAsset.name]: configSource }),+ dependencies,+ });++ await expect(+ repository.completeUpload({+ name: uploadedAsset.name,+ data: new Blob(["notes"]).stream(),+ assetInfoFallback: undefined,+ assetId: uploadedAsset.id,+ })+ ).rejects.toThrow("Use New entry");+ expect(dependencies.deleteAssetsWithClient).toHaveBeenCalledWith(+ { projectId: "project-1", ids: [uploadedAsset.id] },+ context.postgrest.client+ );+ });++ test("preserves a collection upload error when cleanup also fails", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "collection.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const uploadedAsset: Asset = {+ ...configAsset,+ id: "notes",+ name: "notes.mdx",+ filename: "notes",+ format: "mdx",+ };+ dependencies.uploadFile.mockResolvedValue(uploadedAsset);+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ uploadedAsset,+ ]);+ dependencies.deleteAssetsWithClient.mockRejectedValue(+ new Error("cleanup failed")+ );+ const report = vi.spyOn(console, "error").mockImplementation(() => {});+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({ [configAsset.name]: configSource }),+ dependencies,+ });++ await expect(+ repository.completeUpload({+ name: uploadedAsset.name,+ data: new Blob(["notes"]).stream(),+ assetInfoFallback: undefined,+ assetId: uploadedAsset.id,+ })+ ).rejects.toThrow("Use New entry");+ expect(report).toHaveBeenCalledWith(+ "Failed to clean up an invalid uploaded asset"+ );+ report.mockRestore();+ });++ test("preserves a reserved-upload error when reservation cleanup fails", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const reservation = {+ id: "notes",+ name: "notes-storage.mdx",+ filename: "notes",+ folderId: "posts",+ createdAt: "2026-09-03T00:00:00.000Z",+ };+ dependencies.loadAssetUploadReservationsByProjectWithClient.mockResolvedValue(+ [reservation]+ );+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([configAsset]);+ dependencies.deleteAssetUploadReservationWithClient.mockRejectedValue(+ new Error("cleanup failed")+ );+ const report = vi.spyOn(console, "error").mockImplementation(() => {});+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ }),+ dependencies,+ });++ await expect(+ repository.completeUpload({+ name: reservation.name,+ data: new Blob(["notes"]).stream(),+ assetInfoFallback: undefined,+ assetId: reservation.id,+ })+ ).rejects.toThrow("Use New entry");+ expect(report).toHaveBeenCalledWith(+ "Failed to clean up an asset upload reservation"+ );+ expect(dependencies.uploadFile).not.toHaveBeenCalled();+ report.mockRestore();+ });++ test("does not delete a completed asset when upload completion is retried", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const completedAsset = {+ id: "notes",+ name: "notes-storage.mdx",+ filename: "notes",+ folderId: "posts",+ createdAt: "2026-09-03T00:00:00.000Z",+ status: "UPLOADED" as const,+ };+ dependencies.loadAssetUploadReservationsByProjectWithClient.mockResolvedValue(+ [completedAsset]+ );+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([configAsset]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ }),+ dependencies,+ });++ await expect(+ repository.completeUpload({+ name: completedAsset.name,+ data: new Blob(["notes"]).stream(),+ assetInfoFallback: undefined,+ assetId: completedAsset.id,+ })+ ).rejects.toThrow("Use New entry");+ expect(+ dependencies.deleteAssetUploadReservationWithClient+ ).not.toHaveBeenCalled();+ expect(dependencies.uploadFile).not.toHaveBeenCalled();+ });++ test("rejects collection creation completed after a generic upload", async () => {+ const dependencies = createDependencies();+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = ["*"];+ const configSource = JSON.stringify(schema);+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "collection.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const uploadedAsset: Asset = {+ ...configAsset,+ id: "notes",+ name: "notes.txt",+ filename: "notes",+ format: "txt",+ };+ dependencies.uploadFile.mockResolvedValue(configAsset);+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ uploadedAsset,+ configAsset,+ ]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ ...assetClient,+ readFile: vi.fn(async () => ({+ data: new Blob([+ configSource,+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ })),+ },+ dependencies,+ });++ await expect(+ repository.completeUpload({+ name: configAsset.name,+ data: new Blob([createDefaultCollectionConfig()]).stream(),+ assetInfoFallback: undefined,+ assetId: configAsset.id,+ })+ ).rejects.toThrow('Collection entry "notes.txt" must be an MDX file');+ expect(dependencies.deleteAssetsWithClient).toHaveBeenCalledWith(+ { projectId: "project-1", ids: [configAsset.id] },+ context.postgrest.client+ );+ });++ test("removes invalid collection configuration restored by upload deduplication", async () => {+ const dependencies = createDependencies();+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = ["*"];+ const configSource = JSON.stringify(schema);+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ const notesAsset: Asset = {+ ...configAsset,+ id: "notes",+ name: "notes-storage.txt",+ filename: "notes",+ format: "txt",+ size: 5,+ };+ dependencies.loadAssetsByProjectWithClient+ .mockResolvedValueOnce([templateAsset, notesAsset])+ .mockResolvedValueOnce([configAsset, templateAsset, notesAsset]);+ dependencies.createUploadTicket.mockResolvedValue({+ assetId: configAsset.id,+ name: configAsset.name,+ deduplicated: true,+ asset: configAsset,+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: templateSource,+ [notesAsset.name]: "notes",+ }),+ dependencies,+ });++ await expect(+ repository.createUploadTicket({+ type: "file",+ filename: "collection.json",+ folderId: "posts",+ contentHash: "hash",+ })+ ).rejects.toThrow('Collection entry "notes.txt" must be an MDX file');+ expect(dependencies.deleteAssetsWithClient).toHaveBeenCalledWith(+ { projectId: "project-1", ids: [configAsset.id] },+ context.postgrest.client+ );+ });++ test.each([+ ["Hello world", "hello-world", false],+ ["Привет мир", "привет-мир", false],+ ["你好世界", "你好世界", false],+ ["Café", "café", false],+ ["Slugless entry", "entry-91f1de15-e03b-40ae-9b2f-6c19a8bbf1fa", true],+ ] as const)(+ "creates and retries a validated collection entry: %s",+ async (title, slug, slugless) => {+ const dependencies = createDependencies();+ const schema = JSON.parse(createDefaultCollectionConfig());+ if (slugless) {+ delete schema.properties.slug;+ schema.required = ["title"];+ delete schema["x-webstudio"].slugField;+ delete schema["x-webstudio"].generateSlugFrom;+ }+ const configSource = JSON.stringify(schema);+ const templateSource = "---\ndraft: true\n---\n\nStarter body.\n";+ const folder = {+ id: "posts",+ projectId: "project-1",+ name: "Posts",+ createdAt: "2026-09-02T00:00:00.000Z",+ };+ const configAsset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: folder.id,+ type: "file" as const,+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ const createdAsset = {+ ...templateAsset,+ id: "created",+ name: "created-storage.mdx",+ filename: slug,+ size: 0,+ };+ // A schema change may leave older entries invalid. New valid entries+ // must still be creatable, including an upload-ticket retry.+ const outdatedSource = "---\nslug: outdated\n---\nOld body.\n";+ const outdatedAsset = {+ ...templateAsset,+ id: "outdated",+ name: "outdated-storage.mdx",+ filename: "outdated",+ size: outdatedSource.length,+ };+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([+ folder,+ ]);+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ outdatedAsset,+ ]);+ dependencies.createUploadTicket.mockResolvedValue({+ assetId: createdAsset.id,+ name: createdAsset.name,+ deduplicated: false,+ });+ let uploadedSource = "";+ let uploadedAsset: Asset | undefined;+ dependencies.uploadFile.mockImplementation(async (_name, data) => {+ uploadedSource = await new Response(data).text();+ uploadedAsset = {+ ...createdAsset,+ size: new TextEncoder().encode(uploadedSource).length,+ };+ return uploadedAsset;+ });+ const readFile = vi.fn(async (name: string, range) => {+ const source =+ name === configAsset.name+ ? configSource+ : name === templateAsset.name+ ? templateSource+ : name === outdatedAsset.name+ ? outdatedSource+ : uploadedSource;+ const bytes = new TextEncoder().encode(source);+ const offset = range?.offset ?? 0;+ const content =+ range?.length === undefined+ ? bytes.slice(offset)+ : bytes.slice(offset, offset + range.length);+ return {+ data: new Blob([+ content,+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ contentLength: content.length,+ };+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { ...assetClient, readFile },+ dependencies,+ });++ const result = await repository.createCollectionEntry({+ folderId: folder.id,+ values: { title },+ requestId: "91f1de15-e03b-40ae-9b2f-6c19a8bbf1fa",+ });+ expect(result).toBe(uploadedAsset);+ expect(dependencies.createUploadTicket).toHaveBeenCalledWith(+ expect.objectContaining({+ filename: `${slug}.mdx`,+ displayFilename: slug,+ folderId: folder.id,+ contentHash: expect.stringMatching(/^[0-9a-f]{64}$/),+ }),+ context+ );+ expect(uploadedSource).toContain("Starter body.");++ dependencies.createUploadTicket.mockResolvedValue({+ assetId: uploadedAsset!.id,+ name: uploadedAsset!.name,+ deduplicated: true,+ asset: uploadedAsset!,+ });+ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title },+ requestId: "91f1de15-e03b-40ae-9b2f-6c19a8bbf1fa",+ })+ ).resolves.toBe(uploadedAsset);+ expect(dependencies.uploadFile).toHaveBeenCalledOnce();++ const existingAsset = {+ ...uploadedAsset!,+ filename: slug.normalize("NFD"),+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ existingAsset,+ ]);+ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title },+ requestId: "91f1de15-e03b-40ae-9b2f-6c19a8bbf1fa",+ })+ ).resolves.toBe(existingAsset);++ const duplicateTemplate = {+ ...templateAsset,+ id: "duplicate-template",+ name: "duplicate-template-storage.mdx",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ duplicateTemplate,+ ]);+ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title: "Another post" },+ })+ ).rejects.toThrow('Collection template "template.mdx" is ambiguous');++ const duplicateConfig = {+ ...configAsset,+ id: "duplicate-config",+ name: "duplicate-config-storage.json",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ duplicateConfig,+ templateAsset,+ ]);+ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title: "Another post" },+ })+ ).rejects.toThrow(+ "A collection folder must contain exactly one collection.json"+ );+ }+ );++ test.each([false, true])(+ "cleans up only new uploads when the collection changes (deduplicated: %s)",+ async (deduplicated) => {+ const dependencies = createDependencies();+ const folder = {+ id: "posts",+ projectId: "project-1",+ name: "Posts",+ createdAt: "2026-09-02T00:00:00.000Z",+ };+ const configSource = createDefaultCollectionConfig();+ const nextConfigValue = JSON.parse(configSource);+ nextConfigValue["x-webstudio"].template = "replacement.mdx";+ const nextConfigSource = JSON.stringify(nextConfigValue);+ const templateSource = "---\ndraft: true\n---\n\nStarter body.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: folder.id,+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const nextConfigAsset: Asset = {+ ...configAsset,+ name: "next-config-storage.json",+ size: nextConfigSource.length,+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ const createdAsset: Asset = {+ ...templateAsset,+ id: "created",+ name: "created-storage.mdx",+ filename: "hello-world",+ };+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([+ folder,+ ]);+ dependencies.loadAssetsByProjectWithClient+ .mockResolvedValueOnce([configAsset, templateAsset])+ .mockResolvedValueOnce([nextConfigAsset, templateAsset, createdAsset]);+ dependencies.createUploadTicket.mockResolvedValue({+ assetId: createdAsset.id,+ name: createdAsset.name,+ ...(deduplicated+ ? { deduplicated: true, asset: createdAsset }+ : { deduplicated: false }),+ });+ dependencies.uploadFile.mockResolvedValue(createdAsset);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [nextConfigAsset.name]: nextConfigSource,+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title: "Hello world" },+ })+ ).rejects.toThrow('Collection template "replacement.mdx" not found');+ if (deduplicated) {+ expect(dependencies.deleteAssetsWithClient).not.toHaveBeenCalled();+ } else {+ expect(dependencies.deleteAssetsWithClient).toHaveBeenCalledWith(+ { projectId: "project-1", ids: [createdAsset.id] },+ context.postgrest.client+ );+ }+ }+ );++ test("returns the existing entry when an identical creation request is retried", async () => {+ const dependencies = createDependencies();+ const folder = {+ id: "posts",+ projectId: "project-1",+ name: "Posts",+ createdAt: "2026-09-02T00:00:00.000Z",+ };+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStarter body.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: folder.id,+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ const entry = await createContentCollectionEntry({+ config: parseCollectionConfig(configSource),+ templateSource,+ values: { title: "Hello world" },+ existingFilenames: [],+ });+ const existingAsset: Asset = {+ ...templateAsset,+ id: "existing-entry",+ name: "existing-entry-storage.mdx",+ filename: "hello-world",+ size: entry.source.length,+ };+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([+ folder,+ ]);+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ existingAsset,+ ]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: templateSource,+ [existingAsset.name]: entry.source,+ }),+ dependencies,+ });++ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title: "Hello world" },+ })+ ).resolves.toBe(existingAsset);+ expect(dependencies.createUploadTicket).not.toHaveBeenCalled();+ });++ test("does not treat the collection template as an idempotent entry retry", async () => {+ const dependencies = createDependencies();+ const folder = {+ id: "posts",+ projectId: "project-1",+ name: "Posts",+ createdAt: "2026-09-02T00:00:00.000Z",+ };+ const configSource = createDefaultCollectionConfig();+ const generatedTemplate = {+ source:+ "---\ntitle: Template\nslug: template\ndraft: true\n---\n\nStarter body.\n",+ };+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: folder.id,+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: generatedTemplate.source.length,+ };+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([+ folder,+ ]);+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ ]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: generatedTemplate.source,+ }),+ dependencies,+ });++ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title: "Template" },+ })+ ).rejects.toThrow(+ 'The filename "template.mdx" does not match the collection entry patterns'+ );+ expect(dependencies.createUploadTicket).not.toHaveBeenCalled();+ });++ test("allows only builders to repair a missing collection template", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([configAsset]);+ dependencies.hasProjectPermit.mockImplementation(+ async ({ permit }) => permit !== "build"+ );+ dependencies.createUploadTicket.mockResolvedValue({+ assetId: "template",+ name: "template-storage.mdx",+ deduplicated: false,+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ }),+ dependencies,+ });+ const input = {+ type: "file",+ filename: "template.mdx",+ folderId: "posts",+ };++ await expect(repository.createUploadTicket(input)).rejects.toThrow(+ "configure this project collections"+ );+ dependencies.hasProjectPermit.mockResolvedValue(true);+ await expect(repository.createUploadTicket(input)).resolves.toMatchObject({+ assetId: "template",+ });+ expect(dependencies.createUploadTicket).toHaveBeenCalledOnce();+ });++ test("reconciles lost responses when collection seed files are retried", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ ]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ dependencies.createUploadTicket.mockResolvedValue({+ assetId: templateAsset.id,+ name: templateAsset.name,+ deduplicated: true,+ asset: templateAsset,+ });+ await expect(+ repository.createUploadTicket({+ type: "file",+ filename: "template.mdx",+ folderId: "posts",+ contentHash: "template-hash",+ })+ ).resolves.toMatchObject({ assetId: templateAsset.id });++ dependencies.createUploadTicket.mockResolvedValue({+ assetId: configAsset.id,+ name: configAsset.name,+ deduplicated: true,+ asset: configAsset,+ });+ await expect(+ repository.createUploadTicket({+ type: "file",+ filename: "collection.json",+ folderId: "posts",+ contentHash: "config-hash",+ })+ ).resolves.toMatchObject({ assetId: configAsset.id });+ expect(dependencies.deleteAssetsWithClient).not.toHaveBeenCalled();+ });++ test("reconciles a lost missing-template repair response before the template is fixed", async () => {+ const dependencies = createDependencies();+ const configValue = JSON.parse(createDefaultCollectionConfig());+ configValue.required.push("summary");+ configValue.properties.summary = { type: "string", minLength: 1 };+ const configSource = `${JSON.stringify(configValue)}\n`;+ const templateSource = "---\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ ]);+ dependencies.createUploadTicket.mockResolvedValue({+ assetId: templateAsset.id,+ name: templateAsset.name,+ deduplicated: true,+ asset: templateAsset,+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ await expect(+ repository.createUploadTicket({+ type: "file",+ filename: "template.mdx",+ folderId: "posts",+ contentHash: "template-hash",+ })+ ).resolves.toMatchObject({ assetId: templateAsset.id });+ expect(dependencies.deleteAssetsWithClient).not.toHaveBeenCalled();+ });++ test("retains a missing template upload so a builder can repair invalid template defaults", async () => {+ const dependencies = createDependencies();+ const configValue = JSON.parse(createDefaultCollectionConfig());+ configValue.required.push("summary");+ configValue.properties.summary = { type: "string", minLength: 1 };+ const configSource = `${JSON.stringify(configValue)}\n`;+ const templateSource = "---\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ const reservation = {+ id: templateAsset.id,+ name: templateAsset.name,+ filename: templateAsset.filename,+ folderId: templateAsset.folderId,+ createdAt: templateAsset.createdAt,+ };+ dependencies.loadAssetUploadReservationsByProjectWithClient.mockResolvedValue(+ [reservation]+ );+ dependencies.loadAssetsByProjectWithClient+ .mockResolvedValueOnce([configAsset])+ .mockResolvedValueOnce([configAsset, templateAsset]);+ dependencies.uploadFile.mockResolvedValue(templateAsset);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ await expect(+ repository.completeUpload({+ name: templateAsset.name,+ data: new Blob([templateSource]).stream(),+ assetInfoFallback: undefined,+ assetId: templateAsset.id,+ })+ ).resolves.toBe(templateAsset);+ expect(dependencies.deleteAssetsWithClient).not.toHaveBeenCalled();+ });++ test("rejects a missing template upload with non-MDX metadata", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "txt",+ size: templateSource.length,+ };+ dependencies.loadAssetUploadReservationsByProjectWithClient.mockResolvedValue(+ [+ {+ id: templateAsset.id,+ name: templateAsset.name,+ filename: templateAsset.filename,+ folderId: templateAsset.folderId,+ createdAt: templateAsset.createdAt,+ },+ ]+ );+ dependencies.loadAssetsByProjectWithClient+ .mockResolvedValueOnce([configAsset])+ .mockResolvedValueOnce([configAsset, templateAsset]);+ dependencies.uploadFile.mockResolvedValue(templateAsset);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ await expect(+ repository.completeUpload({+ name: templateAsset.name,+ data: new Blob([templateSource]).stream(),+ assetInfoFallback: undefined,+ assetId: templateAsset.id,+ })+ ).rejects.toThrow("Collection templates must be MDX files");+ expect(dependencies.deleteAssetsWithClient).toHaveBeenCalledWith(+ { projectId: "project-1", ids: [templateAsset.id] },+ context.postgrest.client+ );+ });++ test("requires build permission to mutate collection configuration files", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ ]);+ dependencies.hasProjectPermit.mockImplementation(+ async ({ permit }) => permit === "edit"+ );+ prepareAssetContentUpdate(dependencies, templateAsset);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ await expect(+ repository.updateContent({+ assetId: templateAsset.id,+ expectedName: templateAsset.name,+ data: new Blob([templateSource]).stream(),+ })+ ).rejects.toThrow("configure this project collections");+ await expect(+ repository.updateMetadata(configAsset.id, { description: "reserved" })+ ).rejects.toThrow("configure this project collections");+ await expect(repository.delete([templateAsset.id])).rejects.toThrow(+ "configure this project collections"+ );+ expect(dependencies.updateAssetMetadataWithClient).not.toHaveBeenCalled();+ expect(dependencies.deleteAssetsWithClient).not.toHaveBeenCalled();+ });++ test("does not delete or move a configured collection template", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ ]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ await expect(repository.delete([templateAsset.id])).rejects.toThrow(+ 'Collection template "template.mdx" not found'+ );+ await expect(+ repository.updateMetadata(templateAsset.id, { folderId: null })+ ).rejects.toThrow('Collection template "template.mdx" not found');+ expect(dependencies.deleteAssetsWithClient).not.toHaveBeenCalled();+ expect(dependencies.updateAssetMetadataWithClient).not.toHaveBeenCalled();+ });++ test("rejects a slug reserved by a concurrent entry request", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStarter body.\n";+ const folder = {+ id: "posts",+ projectId: "project-1",+ name: "Posts",+ createdAt: "2026-09-02T00:00:00.000Z",+ };+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: folder.id,+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ const createdAsset: Asset = {+ ...templateAsset,+ id: "created",+ name: "created-storage.mdx",+ filename: "hello-world",+ createdAt: "2026-09-02T00:00:01.000Z",+ };+ const competingAsset: Asset = {+ ...createdAsset,+ id: "competing",+ name: "competing-storage.mdx",+ createdAt: "2026-09-02T00:00:00.500Z",+ };+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([+ folder,+ ]);+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ ]);+ dependencies.loadAssetUploadReservationsByProjectWithClient.mockResolvedValue(+ [createdAsset, competingAsset]+ );+ dependencies.createUploadTicket.mockResolvedValue({+ assetId: createdAsset.id,+ name: createdAsset.name,+ deduplicated: false,+ });+ dependencies.uploadFile.mockResolvedValue(createdAsset);+ const readFile = vi.fn(async (name: string) => {+ const source = name === configAsset.name ? configSource : templateSource;+ return {+ data: new Blob([+ source,+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ contentLength: source.length,+ };+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { ...assetClient, readFile },+ dependencies,+ });++ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title: "Hello world" },+ })+ ).rejects.toThrow('An entry named "hello-world.mdx" already exists');+ expect(+ dependencies.deleteAssetUploadReservationWithClient+ ).toHaveBeenCalledWith(+ {+ projectId: "project-1",+ assetId: createdAsset.id,+ name: createdAsset.name,+ },+ context.postgrest.client+ );+ expect(dependencies.uploadFile).not.toHaveBeenCalled();++ dependencies.deleteAssetUploadReservationWithClient.mockClear();+ dependencies.loadAssetUploadReservationsByProjectWithClient.mockRejectedValueOnce(+ new Error("Reservation lookup failed")+ );+ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title: "Hello world" },+ })+ ).rejects.toThrow("Reservation lookup failed");+ expect(+ dependencies.deleteAssetUploadReservationWithClient+ ).toHaveBeenCalledWith(+ {+ projectId: "project-1",+ assetId: createdAsset.id,+ name: createdAsset.name,+ },+ context.postgrest.client+ );+ });++ test("rejects collection entry filenames beyond the Assets limit", async () => {+ const dependencies = createDependencies();+ const configValue = JSON.parse(createDefaultCollectionConfig());+ delete configValue.properties.title.maxLength;+ delete configValue.properties.slug.maxLength;+ const configSource = JSON.stringify(configValue);+ const templateSource = "---\ndraft: true\n---\n";+ const folder = {+ id: "posts",+ projectId: "project-1",+ name: "Posts",+ createdAt: "2026-09-02T00:00:00.000Z",+ };+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: folder.id,+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([+ folder,+ ]);+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ ]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ ...assetClient,+ readFile: vi.fn(async (name: string) => {+ const source =+ name === configAsset.name ? configSource : templateSource;+ return {+ data: new Blob([+ source,+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ contentLength: source.length,+ };+ }),+ },+ dependencies,+ });++ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title: "a".repeat(600) },+ })+ ).rejects.toThrow("The generated entry filename is too long");+ expect(dependencies.createUploadTicket).not.toHaveBeenCalled();+ });++ test("saves invalid entry fields without allowing slug or format changes", async () => {+ const dependencies = createDependencies();+ const configAsset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file" as const,+ format: "json",+ size: createDefaultCollectionConfig().length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const entryAsset = {+ ...configAsset,+ id: "entry",+ name: "hello-world.mdx",+ filename: "hello-world",+ format: "mdx",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ entryAsset,+ ]);+ prepareAssetContentUpdate(dependencies, entryAsset);+ const readFile = vi.fn(async (name: string) => {+ const source =+ name === configAsset.name+ ? createDefaultCollectionConfig()+ : "---\ntitle: Hello world\nslug: hello-world\ndraft: true\n---\n\nBody.\n";+ return {+ data: new Blob([+ source,+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ contentLength: source.length,+ };+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { ...assetClient, readFile },+ dependencies,+ });++ await expect(+ repository.updateContent({+ assetId: entryAsset.id,+ expectedName: entryAsset.name,+ data: new Blob([+ "---\ntitle: ''\nslug: hello-world\ndraft: true\n---\n\nBody.\n",+ ]).stream(),+ })+ ).resolves.toEqual(entryAsset);+ await expect(+ repository.updateContent({+ assetId: entryAsset.id,+ expectedName: entryAsset.name,+ data: new Blob([+ "---\ntitle: Updated\nslug: another-slug\ndraft: true\n---\n\nBody.\n",+ ]).stream(),+ })+ ).rejects.toThrow("slug must match the entry filename");+ await expect(+ repository.updateContent({+ assetId: entryAsset.id,+ expectedName: entryAsset.name,+ extension: "txt",+ data: new Blob([+ "---\ntitle: Hello world\nslug: hello-world\ndraft: true\n---\n\nBody.\n",+ ]).stream(),+ })+ ).rejects.toThrow("must remain MDX files");+ expect(dependencies.updateAssetContent).toHaveBeenCalledTimes(3);+ });++ test("updates collection entries without requiring a filename slug field", async () => {+ const dependencies = createDependencies();+ const schema = JSON.parse(createDefaultCollectionConfig());+ delete schema["x-webstudio"].slugField;+ delete schema["x-webstudio"].generateSlugFrom;+ delete schema.properties.slug;+ schema.required = schema.required.filter((key: string) => key !== "slug");+ const configSource = JSON.stringify(schema);+ const configAsset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file" as const,+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const entryAsset = {+ ...configAsset,+ id: "entry",+ name: "entry-id.mdx",+ filename: "entry-id",+ format: "mdx",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ entryAsset,+ ]);+ prepareAssetContentUpdate(dependencies, entryAsset);+ const readFile = vi.fn(async (name: string) => {+ const source =+ name === configAsset.name+ ? configSource+ : "---\ntitle: Original\n---\nBody";+ return {+ data: new Blob([+ source,+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ contentLength: source.length,+ };+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { ...assetClient, readFile },+ dependencies,+ });+ await expect(+ repository.updateContent({+ assetId: entryAsset.id,+ expectedName: entryAsset.name,+ data: new Blob(["---\ntitle: Updated\n---\nBody"]).stream(),+ })+ ).resolves.toBeDefined();+ });++ test("allows collection schema changes while existing entries are repaired", async () => {+ const dependencies = createDependencies();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file" as const,+ format: "json",+ size: 1,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ const entryAsset = {+ ...templateAsset,+ id: "entry",+ name: "entry-storage.mdx",+ filename: "hello-world",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ entryAsset,+ ]);+ prepareAssetContentUpdate(dependencies, configAsset);+ const entrySource =+ "---\ntitle: Hello world\nslug: hello-world\ndraft: true\n---\n\nBody.\n";+ const readFile = vi.fn(async (name: string) => {+ const source = name === templateAsset.name ? templateSource : entrySource;+ return {+ data: new Blob([+ source,+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ contentLength: source.length,+ };+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { ...assetClient, readFile },+ dependencies,+ });+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.title.minLength = 20;++ await expect(+ repository.updateContent({+ assetId: configAsset.id,+ expectedName: configAsset.name,+ data: new Blob([JSON.stringify(schema)]).stream(),+ })+ ).resolves.toBe(configAsset);+ });++ test("rejects collection patterns that select unsupported entry formats", async () => {+ const dependencies = createDependencies();+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = ["*"];+ const configSource = JSON.stringify(schema);+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ const notesAsset: Asset = {+ ...configAsset,+ id: "notes",+ name: "notes-storage.txt",+ filename: "notes",+ format: "txt",+ size: 5,+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ notesAsset,+ ]);+ prepareAssetContentUpdate(dependencies, configAsset);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ await expect(+ repository.updateContent({+ assetId: configAsset.id,+ expectedName: configAsset.name,+ data: new Blob([configSource]).stream(),+ })+ ).rejects.toThrow('Collection entry "notes.txt" must be an MDX file');+ });++ test("allows collection template defaults to be repaired separately", async () => {+ const dependencies = createDependencies();+ const configAsset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file" as const,+ format: "json",+ size: createDefaultCollectionConfig().length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ ]);+ prepareAssetContentUpdate(dependencies, templateAsset);+ const configSource = createDefaultCollectionConfig();+ const readFile = vi.fn(async () => ({+ data: new Blob([+ configSource,+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ contentLength: configSource.length,+ }));+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { ...assetClient, readFile },+ dependencies,+ });++ await expect(+ repository.updateContent({+ assetId: templateAsset.id,+ expectedName: templateAsset.name,+ data: new Blob([+ "---\ndraft: not-a-boolean\n---\n\nStart writing.\n",+ ]).stream(),+ })+ ).resolves.toBe(templateAsset);+ });++ test("rejects an invalid MDX collection template", async () => {+ const dependencies = createDependencies();+ const configAsset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file" as const,+ format: "json",+ size: createDefaultCollectionConfig().length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ ]);+ prepareAssetContentUpdate(dependencies, templateAsset);+ const configSource = createDefaultCollectionConfig();+ const readFile = vi.fn(async () => ({+ data: new Blob([+ configSource,+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ contentLength: configSource.length,+ }));+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { ...assetClient, readFile },+ dependencies,+ });++ await expect(+ repository.updateContent({+ assetId: templateAsset.id,+ expectedName: templateAsset.name,+ data: new Blob(["---\ndraft: false\n---\n\n<Broken"]).stream(),+ })+ ).rejects.toThrow("Collection template is invalid");+ });++ test("keeps existing entry content editable when collection.json is broken", async () => {+ const dependencies = createDependencies();+ const configAsset = {+ id: "config",+ projectId: "project-1",+ name: "collection.json",+ folderId: "posts",+ type: "file" as const,+ format: "json",+ size: 8,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const entryAsset = {+ ...configAsset,+ id: "entry",+ name: "hello-world.mdx",+ format: "mdx",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ entryAsset,+ ]);+ prepareAssetContentUpdate(dependencies, entryAsset);+ const readFile = vi.fn(async () => ({+ data: new Blob([+ "not json",+ ]).stream() as unknown as AsyncIterable<Uint8Array>,+ contentLength: 8,+ }));+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { ...assetClient, readFile },+ dependencies,+ });++ await expect(+ repository.updateContent({+ assetId: entryAsset.id,+ expectedName: entryAsset.name,+ data: new Blob(["---\ntitle: Updated\n---\n\nBody.\n"]).stream(),+ })+ ).resolves.toBe(entryAsset);+ expect(dependencies.updateAssetContent).toHaveBeenCalledOnce();+ });++ test("rejects metadata moves into a collection folder", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const sourceAsset = {+ id: "source",+ projectId: "project-1",+ name: "source.mdx",+ type: "file" as const,+ format: "mdx",+ size: 10,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const configAsset = {+ ...sourceAsset,+ id: "config",+ name: "collection.json",+ size: configSource.length,+ folderId: "posts",+ format: "json",+ };+ const entryAsset = {+ ...sourceAsset,+ id: "entry",+ name: "entry.mdx",+ folderId: "posts",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ sourceAsset,+ configAsset,+ entryAsset,+ ]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({ [configAsset.name]: configSource }),+ dependencies,+ });++ await expect(+ repository.updateMetadata(sourceAsset.id, { folderId: "posts" })+ ).rejects.toThrow("Use New entry");+ await expect(+ repository.updateMetadata(entryAsset.id, {+ filename: "entry",+ description: "Updated",+ })+ ).resolves.toBeUndefined();+ await expect(+ repository.updateMetadata(entryAsset.id, { filename: "renamed" })+ ).rejects.toThrow("Collection MDX filenames cannot be changed");+ expect(dependencies.updateAssetMetadataWithClient).toHaveBeenCalledOnce();+ });++ test("rejects renaming an asset into an incomplete collection", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const candidate: Asset = {+ id: "candidate",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "manifest",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([candidate]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [candidate.name]: configSource,+ }),+ dependencies,+ });++ await expect(+ repository.updateMetadata(candidate.id, { filename: "collection" })+ ).rejects.toThrow('Collection template "template.mdx" not found');+ expect(dependencies.updateAssetMetadataWithClient).not.toHaveBeenCalled();+ });++ test("requires build permission when clearing a filename activates a collection", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const candidate: Asset = {+ id: "candidate",+ projectId: "project-1",+ name: "collection.json",+ filename: "manifest",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const template: Asset = {+ ...candidate,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ candidate,+ template,+ ]);+ dependencies.hasProjectPermit.mockImplementation(+ async ({ permit }) => permit === "edit"+ );+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [candidate.name]: configSource,+ [template.name]: templateSource,}),- loadCanonicalAssetBaseEntries: vi- .fn<typeof loadCanonicalAssetBaseEntries>()- .mockResolvedValue([]),- loadCanonicalAssetFileEntries: loadFileEntries,- loadCanonicalAssetFileEntriesForRecovery: vi- .fn<typeof loadCanonicalAssetFileEntriesForRecovery>()- .mockImplementation(async (input) => ({- entries: await loadFileEntries(input),- inconsistentRows: [],- })),- createAssetIndex: vi.fn<typeof createAssetIndex>(),- updateAssetMetadataWithClient:- vi.fn<typeof updateAssetMetadataWithClient>(),- loadAssetsByProjectWithClient: vi- .fn<typeof loadAssetsByProjectWithClient>()- .mockResolvedValue([]),- loadAssetFoldersByProjectWithClient:- vi.fn<typeof loadAssetFoldersByProjectWithClient>(),- upsertAssetFolderWithClient: vi.fn<typeof upsertAssetFolderWithClient>(),- deleteAssetFoldersWithClient: vi.fn<typeof deleteAssetFoldersWithClient>(),- createId: vi.fn(() => "folder-1"),- now: vi.fn(() => new Date("2026-07-25T00:00:00.000Z")),- };-};+ dependencies,+ });++ await expect(+ repository.updateMetadata(candidate.id, { filename: null })+ ).rejects.toThrow("configure this project collections");+ expect(dependencies.updateAssetMetadataWithClient).not.toHaveBeenCalled();+ });-describe("PostgresAssetRepository", () => {test("lists, gets, and range-reads assets through the authorized object store", async () => {const dependencies = createDependencies();const asset = {@@ -229,6 +2490,150 @@ describe("PostgresAssetRepository", () => {);});+ test("creates and retries a collection without changing existing invalid entries", async () => {+ const dependencies = createDependencies();+ const folder = {+ id: "posts",+ projectId: "project-1",+ name: "Posts",+ createdAt: "2026-07-25T00:00:00.000Z",+ };+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configSource = createDefaultCollectionConfig();+ const templateAsset: Asset = {+ id: "template",+ projectId: "project-1",+ name: "template-storage.mdx",+ filename: "template",+ folderId: folder.id,+ type: "file",+ format: "mdx",+ size: new TextEncoder().encode(templateSource).byteLength,+ description: null,+ createdAt: folder.createdAt,+ meta: {},+ };+ const configAsset: Asset = {+ ...templateAsset,+ id: "config",+ name: "config-storage.json",+ filename: "collection",+ format: "json",+ size: new TextEncoder().encode(configSource).byteLength,+ };+ const ignoredAsset: Asset = {+ ...templateAsset,+ id: "notes",+ name: "notes.txt",+ filename: "notes",+ format: "txt",+ };+ const entrySource = "---\nexcerpt: Existing content\n---\nBody\n";+ const entryAsset: Asset = {+ ...templateAsset,+ id: "existing-post",+ name: "existing-post.mdx",+ filename: "existing-post",+ size: entrySource.length,+ };+ const uploadedAssets: Asset[] = [ignoredAsset, entryAsset];+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([]);+ dependencies.upsertAssetFolderWithClient.mockResolvedValue(folder);+ dependencies.loadAssetsByProjectWithClient.mockImplementation(+ async () => uploadedAssets+ );+ dependencies.createUploadTicket.mockImplementation(async ({ filename }) =>+ filename === "template.mdx"+ ? {+ assetId: templateAsset.id,+ name: templateAsset.name,+ deduplicated: false,+ }+ : {+ assetId: configAsset.id,+ name: configAsset.name,+ deduplicated: false,+ }+ );+ dependencies.uploadFile.mockImplementation(async (name) => {+ const asset = name === templateAsset.name ? templateAsset : configAsset;+ uploadedAssets.push(asset);+ return asset;+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [templateAsset.name]: templateSource,+ [configAsset.name]: configSource,+ [entryAsset.name]: entrySource,+ }),+ dependencies,+ });++ await expect(+ repository.createCollectionFolder({ id: folder.id, name: folder.name })+ ).resolves.toEqual({+ folder,+ assets: [templateAsset, configAsset],+ });+ expect(dependencies.upsertAssetFolderWithClient).toHaveBeenCalledWith(+ { projectId: "project-1", folder },+ context.postgrest.client+ );+ expect(dependencies.uploadFile).toHaveBeenCalledTimes(2);+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([+ folder,+ ]);+ dependencies.upsertAssetFolderWithClient.mockClear();+ dependencies.uploadFile.mockClear();+ await expect(+ repository.createCollectionFolder({ id: folder.id, name: folder.name })+ ).resolves.toEqual({ folder, assets: [templateAsset, configAsset] });+ expect(dependencies.upsertAssetFolderWithClient).not.toHaveBeenCalled();+ expect(dependencies.uploadFile).not.toHaveBeenCalled();+ expect(uploadedAssets).toContainEqual(ignoredAsset);+ expect(uploadedAssets).toContainEqual(entryAsset);+ });++ test("rejects selected files with incompatible types before writing collection seeds", async () => {+ const dependencies = createDependencies();+ const folder = {+ id: "posts",+ projectId: "project-1",+ name: "Posts",+ createdAt: "2026-07-25T00:00:00.000Z",+ };+ const source = "Supporting notes";+ const file: Asset = {+ id: "notes",+ projectId: folder.projectId,+ folderId: folder.id,+ name: "notes.mdx",+ filename: "notes",+ type: "file",+ format: "txt",+ size: source.length,+ meta: {},+ createdAt: folder.createdAt,+ };+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([+ folder,+ ]);+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([file]);+ const repository = new PostgresAssetRepository({+ projectId: folder.projectId,+ context,+ assetStore: createSourceAssetClient({ [file.name]: source }),+ dependencies,+ });+ await expect(+ repository.createCollectionFolder({ id: folder.id, name: folder.name })+ ).rejects.toThrow();+ expect(dependencies.createUploadTicket).not.toHaveBeenCalled();+ expect(dependencies.upsertAssetFolderWithClient).not.toHaveBeenCalled();+ });+test("lists and gets folders with view authorization", async () => {const dependencies = createDependencies();const folder = {@@ -259,6 +2664,98 @@ describe("PostgresAssetRepository", () => {);});+ test("preserves a deduplicated entry when a competing filename is detected", async () => {+ const dependencies = createDependencies();+ const folder = {+ id: "posts",+ projectId: "project-1",+ name: "Posts",+ createdAt: "2026-09-02T00:00:00.000Z",+ };+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStarter body.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: folder.id,+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ const createdSource = (+ await createContentCollectionEntry({+ config: parseCollectionConfig(configSource),+ templateSource,+ values: { title: "Hello world" },+ existingFilenames: [],+ })+ ).source;+ const createdAsset: Asset = {+ ...templateAsset,+ id: "created",+ name: "created-storage.mdx",+ filename: "hello-world",+ size: createdSource.length,+ };+ const competingSource =+ "---\ntitle: A competing post\nslug: hello-world\ndraft: false\n---\n";+ const competingAsset: Asset = {+ ...createdAsset,+ id: "competing",+ name: "competing-storage.mdx",+ size: competingSource.length,+ };+ dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([+ folder,+ ]);+ dependencies.loadAssetsByProjectWithClient+ .mockResolvedValueOnce([configAsset, templateAsset])+ .mockResolvedValueOnce([+ configAsset,+ templateAsset,+ competingAsset,+ createdAsset,+ ]);+ dependencies.createUploadTicket.mockResolvedValue({+ assetId: createdAsset.id,+ name: createdAsset.name,+ deduplicated: true,+ asset: createdAsset,+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: templateSource,+ [createdAsset.name]: createdSource,+ [competingAsset.name]: competingSource,+ }),+ dependencies,+ });++ await expect(+ repository.createCollectionEntry({+ folderId: folder.id,+ values: { title: "Hello world" },+ })+ ).rejects.toThrow("duplicate filename");+ expect(dependencies.deleteAssetsWithClient).not.toHaveBeenCalled();+ });+test("rejects deleting a non-empty folder", async () => {const dependencies = createDependencies();dependencies.loadAssetFoldersByProjectWithClient.mockResolvedValue([@@ -690,42 +3187,283 @@ describe("PostgresAssetRepository", () => {},});- expect(result.data.items).toEqual([]);- expect(result.__diagnostics__.issues).toBeUndefined();- expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledOnce();+ expect(result.data.items).toEqual([]);+ expect(result.__diagnostics__.issues).toBeUndefined();+ expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledOnce();+ });++ test("creates a base-only index without synchronizing or reading content", async () => {+ const dependencies = createDependencies();+ const entries = [+ {+ projectId: "project-1",+ assetId: "asset-1",+ revision: "revision-1",+ document: {+ _id: "asset-1",+ _type: "asset.file" as const,+ name: "post.md",+ path: "post.md",+ key: "post",+ extension: "md",+ mimeType: "text/markdown",+ size: 10,+ revision: "revision-1",+ contentRef: "post.md",+ properties: {},+ },+ },+ ];+ const index = { integrity: { checksum: `sha256:${"b".repeat(64)}` } };+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);+ dependencies.createAssetIndex.mockResolvedValue(index as never);+ const readFile = vi.fn();+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { readFile, uploadFile: vi.fn() },+ dependencies,+ });++ await expect(+ repository.prepareIndex(+ createCompilationPlan({+ where: { all: [] },+ output: { mode: "base", includeMetadata: true },+ })+ )+ ).resolves.toBe(index);++ expect(dependencies.synchronizeCanonicalAssets).not.toHaveBeenCalled();+ expect(dependencies.loadCanonicalAssetFileEntries).not.toHaveBeenCalled();+ expect(dependencies.loadCanonicalAssetBaseEntries).toHaveBeenCalledWith({+ client: context.postgrest.client,+ projectId: "project-1",+ });+ expect(readFile).not.toHaveBeenCalled();+ });++ test("keeps collection configuration and templates out of query indexes", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const createEntry = ({+ id,+ name,+ mimeType,+ size = 10,+ folderId = "posts",+ }: {+ id: string;+ name: string;+ mimeType: string;+ size?: number;+ folderId?: string;+ }): CanonicalAssetFileEntry => ({+ projectId: "project-1",+ assetId: id,+ revision: `revision-${id}`,+ document: {+ _id: id,+ _type: "asset.file",+ name,+ path: `posts/${name}`,+ key: name.slice(0, name.lastIndexOf(".")),+ extension: name.slice(name.lastIndexOf(".") + 1),+ ...(folderId === "" ? {} : { folderId }),+ mimeType,+ size,+ revision: `revision-${id}`,+ contentRef: name,+ properties: {},+ },+ });+ const config = createEntry({+ id: "config",+ name: "collection.json",+ mimeType: "application/json",+ size: new TextEncoder().encode(configSource).byteLength,+ });+ const templateSource = "---\ndraft: true\n---\nTemplate\n";+ const postSource =+ "---\ntitle: Hello world\nslug: hello-world\ndraft: false\n---\n";+ const template = createEntry({+ id: "template",+ name: "template.mdx",+ mimeType: "text/mdx",+ size: new TextEncoder().encode(templateSource).byteLength,+ });+ const post = createEntry({+ id: "post",+ name: "hello-world.mdx",+ mimeType: "text/mdx",+ size: new TextEncoder().encode(postSource).byteLength,+ });+ const rootConfig = createEntry({+ id: "root-config",+ name: "collection.json",+ mimeType: "application/json",+ folderId: "",+ });+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([+ config,+ template,+ post,+ rootConfig,+ ]);+ dependencies.createAssetIndex.mockResolvedValue({} as never);+ const sources = new Map([+ ["collection.json", configSource],+ ["template.mdx", templateSource],+ ["hello-world.mdx", postSource],+ ]);+ const readFile = vi.fn(async (name: string) => {+ const source = sources.get(name) ?? "";+ return {+ data: new Blob([source]).stream(),+ contentLength: new TextEncoder().encode(source).byteLength,+ };+ });+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: { readFile },+ dependencies,+ });++ await repository.prepareIndex(+ createCompilationPlan({+ where: { all: [] },+ output: { mode: "base", includeMetadata: true },+ })+ );++ expect(dependencies.createAssetIndex).toHaveBeenCalledWith(+ expect.objectContaining({+ entries: [+ expect.objectContaining({ assetId: "post" }),+ expect.objectContaining({ assetId: "root-config" }),+ ],+ })+ );++ template.document.size += 1;+ await expect(+ repository.prepareIndex(+ createCompilationPlan({+ where: { all: [] },+ output: { mode: "base", includeMetadata: true },+ })+ )+ ).resolves.toBeDefined();+ template.document.size -= 1;++ const duplicatePost = {+ ...post,+ assetId: "duplicate-post",+ revision: "revision-duplicate-post",+ document: {+ ...post.document,+ _id: "duplicate-post",+ name: "HELLO-WORLD.mdx",+ path: "posts/HELLO-WORLD.mdx",+ key: "HELLO-WORLD",+ revision: "revision-duplicate-post",+ },+ };+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([+ config,+ template,+ post,+ duplicatePost,+ ]);+ await expect(+ repository.prepareIndex(+ createCompilationPlan({+ where: { all: [] },+ output: { mode: "base", includeMetadata: true },+ })+ )+ ).rejects.toThrow('duplicate filename "HELLO-WORLD.mdx"');++ const duplicateTemplate = createEntry({+ id: "duplicate-template",+ name: "template.mdx",+ mimeType: "text/mdx",+ });+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([+ config,+ template,+ duplicateTemplate,+ post,+ ]);+ await expect(+ repository.prepareIndex(+ createCompilationPlan({+ where: { all: [] },+ output: { mode: "base", includeMetadata: true },+ })+ )+ ).rejects.toThrow('Collection template "template.mdx" is ambiguous');++ const duplicateConfig = createEntry({+ id: "duplicate-config",+ name: "collection.json",+ mimeType: "application/json",+ size: new TextEncoder().encode(configSource).byteLength,+ });+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([+ config,+ duplicateConfig,+ template,+ post,+ ]);+ await expect(+ repository.prepareIndex(+ createCompilationPlan({+ where: { all: [] },+ output: { mode: "base", includeMetadata: true },+ })+ )+ ).rejects.toThrow(+ "A collection folder must contain exactly one collection.json"+ );});- test("creates a base-only index without synchronizing or reading content", async () => {+ test("rejects a truncated collection config while preparing an index", async () => {const dependencies = createDependencies();- const entries = [+ const configSource = createDefaultCollectionConfig();+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([{projectId: "project-1",- assetId: "asset-1",- revision: "revision-1",+ assetId: "config",+ revision: "revision-config",document: {- _id: "asset-1",- _type: "asset.file" as const,- name: "post.md",- path: "post.md",- key: "post",- extension: "md",- mimeType: "text/markdown",- size: 10,- revision: "revision-1",- contentRef: "post.md",+ _id: "config",+ _type: "asset.file",+ name: "collection.json",+ path: "posts/collection.json",+ key: "collection",+ extension: "json",+ folderId: "posts",+ mimeType: "application/json",+ size: configSource.length,+ revision: "revision-config",+ contentRef: "collection.json",properties: {},},},- ];- const index = { integrity: { checksum: `sha256:${"b".repeat(64)}` } };- dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);- dependencies.createAssetIndex.mockResolvedValue(index as never);- const readFile = vi.fn();+ ]);const repository = new PostgresAssetRepository({projectId: "project-1",context,- assetStore: { readFile, uploadFile: vi.fn() },+ assetStore: {+ readFile: async () => ({+ data: new Blob([configSource.slice(0, -1)]).stream(),+ contentLength: configSource.length - 1,+ }),+ },dependencies,+ compilationCache: false,});await expect(@@ -735,15 +3473,76 @@ describe("PostgresAssetRepository", () => {output: { mode: "base", includeMetadata: true },}))- ).resolves.toBe(index);+ ).rejects.toThrow("content length does not match its metadata");+ });- expect(dependencies.synchronizeCanonicalAssets).not.toHaveBeenCalled();- expect(dependencies.loadCanonicalAssetFileEntries).not.toHaveBeenCalled();- expect(dependencies.loadCanonicalAssetBaseEntries).toHaveBeenCalledWith({- client: context.postgrest.client,+ test("rejects content snapshots when a collection cannot identify its template", async () => {+ const dependencies = createDependencies();+ const config = {projectId: "project-1",+ assetId: "config",+ revision: "revision-config",+ document: {+ _id: "config",+ _type: "asset.file" as const,+ name: "collection.json",+ path: "posts/collection.json",+ key: "collection",+ extension: "json",+ folderId: "posts",+ mimeType: "application/json",+ size: 8,+ revision: "revision-config",+ contentRef: "collection.json",+ properties: {},+ },+ };+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([config]);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ readFile: vi.fn(async () => ({+ data: new Blob(["not json"]).stream(),+ contentLength: 8,+ })),+ },+ dependencies,});- expect(readFile).not.toHaveBeenCalled();++ await expect(+ repository.prepareIndex(+ createCompilationPlan({+ where: { all: [] },+ output: { mode: "base", includeMetadata: true },+ })+ )+ ).rejects.toThrow("collection.json contains invalid JSON");+ expect(dependencies.createAssetIndex).not.toHaveBeenCalled();++ const validConfigSource = createDefaultCollectionConfig();+ config.document.size = new TextEncoder().encode(+ validConfigSource+ ).byteLength;+ const repositoryWithoutTemplate = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: {+ readFile: vi.fn(async () => ({+ data: new Blob([validConfigSource]).stream(),+ contentLength: new TextEncoder().encode(validConfigSource).byteLength,+ })),+ },+ dependencies,+ });+ await expect(+ repositoryWithoutTemplate.prepareIndex(+ createCompilationPlan({+ where: { all: [] },+ output: { mode: "base", includeMetadata: true },+ })+ )+ ).rejects.toThrow('Collection template "template.mdx" not found');});test("compiles concrete databases across dynamic query values", async () => {@@ -3574,4 +6373,471 @@ describe("PostgresAssetRepository", () => {]));});++ test("updates a collection config and template name as one repository operation", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: new TextEncoder().encode(configSource).byteLength,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: new TextEncoder().encode(templateSource).byteLength,+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ templateAsset,+ ]);+ const renamedTemplate = { ...templateAsset, filename: "post-template" };+ dependencies.updateAssetFilenameIfCurrentWithClient+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce(renamedTemplate);+ const nextConfigValue = JSON.parse(configSource);+ nextConfigValue["x-webstudio"].template = "post-template.mdx";+ const nextConfigSource = `${JSON.stringify(+ nextConfigValue,+ undefined,+ 2+ )}\n`;+ const updatedConfig = {+ ...configAsset,+ name: "config-revision.json",+ size: new TextEncoder().encode(nextConfigSource).byteLength,+ };+ dependencies.updateAssetContent.mockResolvedValue(updatedConfig);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [updatedConfig.name]: nextConfigSource,+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ await expect(+ repository.updateCollectionConfigAndTemplateName({+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: configAsset.name,+ templateAssetId: templateAsset.id,+ expectedTemplateFilename: templateAsset.filename,+ templateFilename: "t".repeat(+ assetResourceLimits.assetFilenameCharacters + 1+ ),+ configSource: nextConfigSource,+ })+ ).rejects.toThrow("Collection template name is invalid");+ await expect(+ repository.updateCollectionConfigAndTemplateName({+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: configAsset.name,+ templateAssetId: configAsset.id,+ expectedTemplateFilename: templateAsset.filename,+ templateFilename: "post-template",+ configSource: nextConfigSource,+ })+ ).rejects.toThrow("Collection template not found");+ expect(+ dependencies.updateAssetFilenameIfCurrentWithClient+ ).not.toHaveBeenCalled();++ await expect(+ repository.updateCollectionConfigAndTemplateName({+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: "stale-config.json",+ templateAssetId: templateAsset.id,+ expectedTemplateFilename: templateAsset.filename,+ templateFilename: "post-template",+ configSource: nextConfigSource,+ })+ ).rejects.toThrow(+ "Collection configuration changed while settings were being saved"+ );+ await expect(+ repository.updateCollectionConfigAndTemplateName({+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: configAsset.name,+ templateAssetId: templateAsset.id,+ expectedTemplateFilename: "stale-template",+ templateFilename: "post-template",+ configSource: nextConfigSource,+ })+ ).rejects.toThrow(+ "Collection template changed while settings were being saved"+ );+ expect(+ dependencies.updateAssetFilenameIfCurrentWithClient+ ).not.toHaveBeenCalled();++ await expect(+ repository.updateCollectionConfigAndTemplateName({+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: configAsset.name,+ templateAssetId: templateAsset.id,+ expectedTemplateFilename: templateAsset.filename,+ templateFilename: "post-template",+ configSource: nextConfigSource,+ })+ ).rejects.toThrow(+ "Collection template changed while settings were being saved"+ );+ expect(dependencies.updateAssetContent).not.toHaveBeenCalled();++ await expect(+ repository.updateCollectionConfigAndTemplateName({+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: configAsset.name,+ templateAssetId: templateAsset.id,+ expectedTemplateFilename: templateAsset.filename,+ templateFilename: "post-template",+ configSource: nextConfigSource,+ })+ ).resolves.toEqual({+ configAsset: updatedConfig,+ templateAsset: renamedTemplate,+ });+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ updatedConfig,+ renamedTemplate,+ ]);+ await expect(+ repository.updateCollectionConfigAndTemplateName({+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: configAsset.name,+ templateAssetId: templateAsset.id,+ expectedTemplateFilename: templateAsset.filename,+ templateFilename: "post-template",+ configSource: nextConfigSource,+ })+ ).resolves.toEqual({+ configAsset: updatedConfig,+ templateAsset: renamedTemplate,+ });+ expect(+ dependencies.updateAssetFilenameIfCurrentWithClient+ ).toHaveBeenCalledTimes(2);+ expect(dependencies.updateAssetContent).toHaveBeenCalledOnce();+ });++ test("resumes saving collection settings after the template rename succeeded", async () => {+ const dependencies = createDependencies();+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = ["*"];+ const configSource = JSON.stringify(schema);+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: new TextEncoder().encode(configSource).byteLength,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const renamedTemplate: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "post-template",+ format: "mdx",+ size: new TextEncoder().encode(templateSource).byteLength,+ };+ const nonEntryAsset: Asset = {+ ...renamedTemplate,+ id: "notes",+ name: "notes-storage.txt",+ filename: "notes",+ format: "txt",+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ renamedTemplate,+ nonEntryAsset,+ ]);+ const nextConfigValue = JSON.parse(configSource);+ nextConfigValue["x-webstudio"].template = "post-template.mdx";+ const nextConfigSource = `${JSON.stringify(nextConfigValue)}\n`;+ const updatedConfig = {+ ...configAsset,+ name: "config-revision.json",+ size: new TextEncoder().encode(nextConfigSource).byteLength,+ };+ dependencies.updateAssetContent.mockResolvedValue(updatedConfig);+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [renamedTemplate.name]: templateSource,+ }),+ dependencies,+ });+ const input = {+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: configAsset.name,+ templateAssetId: renamedTemplate.id,+ expectedTemplateFilename: "template",+ templateFilename: "post-template",+ configSource: nextConfigSource,+ };++ await expect(+ repository.updateCollectionConfigAndTemplateName(input)+ ).rejects.toThrow('Collection entry "notes.txt" must be an MDX file');+ expect(dependencies.updateAssetContent).not.toHaveBeenCalled();+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ renamedTemplate,+ ]);++ await expect(+ repository.updateCollectionConfigAndTemplateName(input)+ ).resolves.toEqual({+ configAsset: updatedConfig,+ templateAsset: renamedTemplate,+ });+ expect(+ dependencies.updateAssetFilenameIfCurrentWithClient+ ).not.toHaveBeenCalled();+ expect(dependencies.updateAssetContent).toHaveBeenCalledOnce();+ });++ test("does not roll back a template rename resumed by this request", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: new TextEncoder().encode(configSource).byteLength,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const renamedTemplate: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "post-template",+ format: "mdx",+ size: new TextEncoder().encode(templateSource).byteLength,+ };+ dependencies.loadAssetsByProjectWithClient.mockResolvedValue([+ configAsset,+ renamedTemplate,+ ]);+ dependencies.updateAssetContent.mockRejectedValue(+ new Error("write failed")+ );+ const nextConfigValue = JSON.parse(configSource);+ nextConfigValue["x-webstudio"].template = "post-template.mdx";+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [renamedTemplate.name]: templateSource,+ }),+ dependencies,+ });++ await expect(+ repository.updateCollectionConfigAndTemplateName({+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: configAsset.name,+ templateAssetId: renamedTemplate.id,+ expectedTemplateFilename: "template",+ templateFilename: "post-template",+ configSource: `${JSON.stringify(nextConfigValue)}\n`,+ })+ ).rejects.toThrow("write failed");+ expect(dependencies.updateAssetContent).toHaveBeenCalledOnce();+ expect(+ dependencies.updateAssetFilenameIfCurrentWithClient+ ).not.toHaveBeenCalled();+ });++ test("restores the template name when the collection config update fails", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: new TextEncoder().encode(configSource).byteLength,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: new TextEncoder().encode(templateSource).byteLength,+ };+ const renamedTemplate = { ...templateAsset, filename: "post-template" };+ dependencies.loadAssetsByProjectWithClient+ .mockResolvedValueOnce([configAsset, templateAsset])+ .mockResolvedValueOnce([configAsset, renamedTemplate]);+ dependencies.updateAssetFilenameIfCurrentWithClient+ .mockResolvedValueOnce(renamedTemplate)+ .mockResolvedValueOnce(templateAsset);+ dependencies.updateAssetContent.mockRejectedValue(+ new Error("write failed")+ );+ const nextConfigValue = JSON.parse(configSource);+ nextConfigValue["x-webstudio"].template = "post-template.mdx";+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ await expect(+ repository.updateCollectionConfigAndTemplateName({+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: configAsset.name,+ templateAssetId: templateAsset.id,+ expectedTemplateFilename: templateAsset.filename,+ templateFilename: "post-template",+ configSource: `${JSON.stringify(nextConfigValue)}\n`,+ })+ ).rejects.toThrow("write failed");+ expect(+ dependencies.updateAssetFilenameIfCurrentWithClient+ ).toHaveBeenCalledTimes(2);+ expect(+ dependencies.updateAssetFilenameIfCurrentWithClient.mock.calls[1]?.[0]+ ).toMatchObject({+ assetId: templateAsset.id,+ expectedFilename: "post-template",+ filename: "template",+ });+ });++ test("does not roll back collection settings that another save replaced", async () => {+ const dependencies = createDependencies();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: new TextEncoder().encode(configSource).byteLength,+ description: null,+ createdAt: "2026-09-02T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: new TextEncoder().encode(templateSource).byteLength,+ };+ const renamedTemplate = { ...templateAsset, filename: "post-template" };+ const concurrentTemplate = {+ ...templateAsset,+ filename: "article-template",+ };+ const concurrentConfigValue = JSON.parse(configSource);+ concurrentConfigValue["x-webstudio"].template = "article-template.mdx";+ const concurrentConfigSource = `${JSON.stringify(+ concurrentConfigValue,+ undefined,+ 2+ )}\n`;+ const concurrentConfigAsset = {+ ...configAsset,+ name: "concurrent-config.json",+ size: new TextEncoder().encode(concurrentConfigSource).byteLength,+ };+ dependencies.loadAssetsByProjectWithClient+ .mockResolvedValueOnce([configAsset, templateAsset])+ .mockResolvedValueOnce([concurrentConfigAsset, concurrentTemplate]);+ dependencies.updateAssetFilenameIfCurrentWithClient.mockResolvedValueOnce(+ renamedTemplate+ );+ dependencies.updateAssetContent.mockRejectedValue(+ new Error("write failed")+ );+ const nextConfigValue = JSON.parse(configSource);+ nextConfigValue["x-webstudio"].template = "post-template.mdx";+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context,+ assetStore: createSourceAssetClient({+ [configAsset.name]: configSource,+ [concurrentConfigAsset.name]: concurrentConfigSource,+ [templateAsset.name]: templateSource,+ }),+ dependencies,+ });++ await expect(+ repository.updateCollectionConfigAndTemplateName({+ folderId: "posts",+ configAssetId: configAsset.id,+ expectedConfigName: configAsset.name,+ templateAssetId: templateAsset.id,+ expectedTemplateFilename: templateAsset.filename,+ templateFilename: "post-template",+ configSource: `${JSON.stringify(nextConfigValue)}\n`,+ })+ ).rejects.toThrow("write failed");+ expect(+ dependencies.updateAssetFilenameIfCurrentWithClient+ ).toHaveBeenCalledOnce();+ });});diff --git a/packages/asset-uploader/src/asset-repository.ts b/packages/asset-uploader/src/asset-repository.tsindex f4b2fe63e1..007b9c407a 100644--- a/packages/asset-uploader/src/asset-repository.ts+++ b/packages/asset-uploader/src/asset-repository.ts@@ -5,6 +5,11 @@ import {createContentCompilationPlan,createContentFieldCatalogCompilationPlan,createDocumentResolutionSession,+ createCollectionEntry,+ createDefaultCollectionConfig,+ createDefaultCollectionTemplate,+ defaultCollectionTemplateFilename,+ extractMarkdownFrontmatter,createLiteralContentCompilationQuery,getContentArtifactRuntimeAssetIds,getAssetQueryErrorDiagnosticIssue,@@ -12,10 +17,14 @@ import {DocumentSourceCompilationAggregateError,isAssetQueryCoveredByCompilationPlan,isContentDocumentCandidate,+ inspectContentCollection,prepareContentCompilerEntries,requiresRuntimeDocumentData,requiresStructuredProperties,validateAssetQueryAgainstCatalog,+ collectionConfigFilename,+ ContentCollectionError,+ parseCollectionConfig,type AssetQueryRequestInput,type AssetQueryPreviewResult,type AssetQueryExecutionPreviewResult,@@ -30,6 +39,8 @@ import {type DocumentSourceLoader,observeDocumentSourceLoader,} from "@webstudio-is/content-engine";+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import { createHash } from "node:crypto";import {createAssetIndex,createAssetFieldCatalog,@@ -48,10 +59,14 @@ import {} from "@webstudio-is/content-engine/compiler";import {createId,+ formatAssetName,+ getAssetDisplayNameParts,+ isMdxFileAsset,toAssetReferenceRuntimeData,type Asset,type AssetFolder,} from "@webstudio-is/sdk";+import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";import type {AssetFolderUpdate,AssetMetadataUpdate,@@ -77,6 +92,9 @@ import {import { updateAssetContent } from "./revision";import {deleteAssetsWithClient,+ deleteAssetUploadReservationWithClient,+ loadAssetUploadReservationsByProjectWithClient,+ updateAssetFilenameIfCurrentWithClient,updateAssetMetadataWithClient,loadAssetsByProjectWithClient,} from "./asset-patch-core";@@ -114,6 +132,12 @@ import {import type { AssetContentRead as SharedAssetContentRead } from "@webstudio-is/content-engine/asset-content-repository";import { validateTextAssetSourceBytes } from "@webstudio-is/content-engine/mdx";import { removeMetadataIssuesDuplicatedBySource } from "./diagnostic-utils";+import {+ getCollectionFolderIds,+ getCollectionReservedAssetIds,+ validateCollectionFolder,+ type CollectionFolderDefinition,+} from "./collection-persistence";type CreateId = () => Asset["id"];type RepositoryObjectStore = AssetObjectReader & Partial<AssetObjectWriter>;@@ -236,6 +260,18 @@ const getPreparedDiagnosticIssues = ({];};+const parseCollectionTemplate = async (source: string) => {+ try {+ return await parseMdxDocument({ source });+ } catch (error) {+ const details = error instanceof Error ? `: ${error.message}` : "";+ throw new AssetRepositoryConflictError(+ `Collection template is invalid${details}`,+ { cause: error }+ );+ }+};+class RequestContentBytesCache {private values = new Map<string, Uint8Array>();private byteLength = 0;@@ -271,6 +307,9 @@ const defaultDependencies = {uploadFile,updateAssetContent,deleteAssetsWithClient,+ deleteAssetUploadReservationWithClient,+ loadAssetUploadReservationsByProjectWithClient,+ updateAssetFilenameIfCurrentWithClient,updateAssetMetadataWithClient,loadAssetsByProjectWithClient,loadAssetFoldersByProjectWithClient,@@ -412,11 +451,31 @@ export interface AssetRepository {name: string;parentId?: string;}): Promise<AssetFolder>;+ createCollectionFolder(input: {+ id: string;+ name: string;+ parentId?: string;+ }): Promise<{ folder: AssetFolder; assets: Asset[] }>;+ createCollectionEntry(input: {+ folderId: string;+ values: Readonly<Record<string, unknown>>;+ requestId?: string;+ }): Promise<Asset>;+ updateCollectionConfigAndTemplateName(input: {+ folderId: string;+ configAssetId: Asset["id"];+ expectedConfigName: Asset["name"];+ templateAssetId: Asset["id"];+ expectedTemplateFilename: Asset["filename"];+ templateFilename: string;+ configSource: string;+ }): Promise<{ configAsset: Asset; templateAsset: Asset }>;updateFolder(folderId: string,values: AssetFolderUpdate): Promise<AssetFolder>;deleteFolder(folderId: string): Promise<void>;+ validateCollections(assets: readonly Asset[]): Promise<void>;readFieldCatalog(): Promise<BuilderAssetFieldCatalog>;query(request: AssetQueryRequestInput,@@ -538,6 +597,10 @@ export class PostgresAssetRepository implements AssetRepository {await this.assertPermit("edit", "edit this project assets");}+ private async assertCanConfigureCollections() {+ await this.assertPermit("build", "configure this project collections");+ }+private async assertCanView() {await this.assertPermit("view", "view this project assets");}@@ -570,20 +633,15 @@ export class PostgresAssetRepository implements AssetRepository {return;}return async (name: string) => {- const deletedAsset = await this.context.postgrest.client- .from("Asset")- .delete()- .eq("id", assetId)- .eq("projectId", this.projectId);- if (deletedAsset.error) {- throw deletedAsset.error;- }- const deletedFile = await this.context.postgrest.client- .from("File")- .delete()- .eq("name", name);- if (deletedFile.error) {- throw deletedFile.error;+ try {+ await this.dependencies.deleteAssetUploadReservationWithClient(+ { projectId: this.projectId, assetId, name },+ this.context.postgrest.client+ );+ } catch {+ // Cleanup is best effort. Keep the original upload/validation error so+ // callers can repair the actual problem; stale reservations expire.+ console.error("Failed to clean up an asset upload reservation");}};}@@ -625,29 +683,246 @@ export class PostgresAssetRepository implements AssetRepository {return { asset, ...content };}+ private async readCollectionAssetBytes(asset: Asset) {+ if (asset.size > contentEngineLimits.hydratedFileBytes) {+ throw new ContentCollectionError(+ `Collection file "${formatAssetName(+ asset+ )}" exceeds the content size limit`+ );+ }+ const content = await this.readContent({ assetId: asset.id, asset });+ const bytes = await readBoundedBytes(+ content.data,+ contentEngineLimits.hydratedFileBytes+ );+ if (bytes.byteLength !== asset.size) {+ throw new ContentCollectionError(+ `Collection file "${formatAssetName(+ asset+ )}" content length does not match its metadata`+ );+ }+ return bytes;+ }+async createUploadTicket(input: Omit<CreateUploadTicketInput, "projectId">,createId?: CreateId) {await this.assertCanEdit();+ let existingReservedAsset: Asset | undefined;+ let isExistingTemplateRetry = false;+ const displayName = formatAssetName({+ name: input.filename,+ filename: input.displayFilename,+ });+ if (+ input.folderId !== undefined &&+ displayName === collectionConfigFilename+ ) {+ await this.assertCanConfigureCollections();+ }+ if (input.folderId !== undefined) {+ const assets = await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ const configAsset = assets.find(+ (asset) =>+ asset.folderId === input.folderId &&+ formatAssetName(asset) === collectionConfigFilename+ );+ if (configAsset !== undefined) {+ if (displayName === collectionConfigFilename) {+ if (input.contentHash === undefined) {+ throw new AssetRepositoryConflictError(+ "Collection configuration already exists"+ );+ }+ existingReservedAsset = configAsset;+ } else {+ const config = parseCollectionConfig(+ decodeUtf8(await this.readCollectionAssetBytes(configAsset))+ );+ const templateAsset = assets.find(+ (asset) =>+ asset.folderId === input.folderId &&+ formatAssetName(asset) === config.template+ );+ if (displayName === config.template && templateAsset === undefined) {+ await this.assertCanConfigureCollections();+ } else if (+ displayName === config.template &&+ templateAsset !== undefined &&+ input.contentHash !== undefined+ ) {+ await this.assertCanConfigureCollections();+ existingReservedAsset = templateAsset;+ isExistingTemplateRetry = true;+ } else if (+ displayName === config.template ||+ config.matchesEntry(displayName)+ ) {+ throw new AssetRepositoryConflictError(+ "Use New entry to add files to a collection folder"+ );+ }+ }+ }+ }const ticket = await this.dependencies.createUploadTicket({ ...input, projectId: this.projectId },this.context,createId);+ if (existingReservedAsset !== undefined && ticket.deduplicated === false) {+ await this.getUploadErrorCleanup(ticket.assetId)?.(ticket.name);+ throw new AssetRepositoryConflictError(+ `Collection file "${displayName}" already exists with different content`+ );+ }+ if (ticket.deduplicated) {+ await this.validateCompletedCollectionUpload({+ asset: ticket.asset,+ allowCollectionFolder: false,+ allowInvalidTemplateRepair:+ existingReservedAsset === undefined || isExistingTemplateRetry,+ cleanupOnError: ticket.asset.id !== existingReservedAsset?.id,+ });+ }return ticket;}- async completeUpload({+ private async validateCompletedCollectionUpload({+ asset,+ assets,+ allowCollectionFolder,+ allowInvalidTemplateRepair = true,+ cleanupOnError = true,+ }: {+ asset: Asset;+ assets?: readonly Asset[];+ allowCollectionFolder: boolean;+ allowInvalidTemplateRepair?: boolean;+ cleanupOnError?: boolean;+ }): Promise<CollectionFolderDefinition | undefined> {+ if (asset.folderId === undefined) {+ return;+ }+ const projectAssets =+ assets ??+ (await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ ));+ const currentAssets = projectAssets.some(+ (candidate) => candidate.id === asset.id+ )+ ? projectAssets+ : [...projectAssets, asset];+ try {+ const uploadKind = await this.assertUploadAllowed({+ asset,+ assets: currentAssets,+ allowCollectionFolder,+ });+ if (uploadKind === "ordinary") {+ return;+ }+ if (uploadKind === "template-repair" && isMdxFileAsset(asset) === false) {+ throw new ContentCollectionError(+ "Collection templates must be MDX files"+ );+ }+ if (formatAssetName(asset) === collectionConfigFilename) {+ parseCollectionConfig(+ decodeUtf8(await this.readCollectionAssetBytes(asset))+ );+ }+ const isCollectionFolder = currentAssets.some(+ (candidate) =>+ candidate.folderId === asset.folderId &&+ formatAssetName(candidate) === collectionConfigFilename+ );+ if (allowCollectionFolder && isCollectionFolder === false) {+ throw new ContentCollectionError(+ "Collection configuration not found after entry upload"+ );+ }+ if (+ isCollectionFolder &&+ (uploadKind !== "template-repair" ||+ allowInvalidTemplateRepair === false)+ ) {+ return await validateCollectionFolder({+ assets: currentAssets,+ folderId: asset.folderId,+ assetStore: this.assetStore,+ // Entry creation validates the uploaded entry, not older entries+ // made invalid by an earlier schema edit. Manifest uploads still+ // validate the complete folder before establishing a collection.+ entryIdsToValidate: allowCollectionFolder+ ? new Set([asset.id])+ : undefined,+ });+ }+ } catch (error) {+ if (cleanupOnError) {+ try {+ await this.dependencies.deleteAssetsWithClient(+ { projectId: this.projectId, ids: [asset.id] },+ this.context.postgrest.client+ );+ } catch {+ console.error("Failed to clean up an invalid uploaded asset");+ }+ }+ throw error;+ }+ }++ private async completeReservedUpload({name,data,assetInfoFallback,assetDataOverride,assetId,- }: Parameters<AssetRepository["completeUpload"]>[0]) {+ allowCollectionFolder,+ validateCollectionState = true,+ }: Parameters<AssetRepository["completeUpload"]>[0] & {+ allowCollectionFolder: boolean;+ validateCollectionState?: boolean;+ }) {// Reserved upload names are not authorization credentials. Recheck the// derived owning project when the second upload step writes file content.await this.assertCanEdit();+ const reservations =+ await this.dependencies.loadAssetUploadReservationsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ const reservation = reservations.find(+ (candidate) =>+ (assetId === undefined && candidate.name === name) ||+ (assetId !== undefined &&+ candidate.id === assetId &&+ candidate.name === name)+ );+ if (reservation !== undefined) {+ try {+ await this.assertUploadAllowed({+ asset: reservation,+ allowCollectionFolder,+ });+ } catch (error) {+ if (reservation.status !== "UPLOADED") {+ const cleanup = this.getUploadErrorCleanup(reservation.id);+ await cleanup?.(reservation.name);+ }+ throw error;+ }+ }const asset = await this.dependencies.uploadFile(name,data,@@ -657,9 +932,274 @@ export class PostgresAssetRepository implements AssetRepository {assetDataOverride,this.getUploadErrorCleanup(assetId));+ if (asset.folderId === undefined || validateCollectionState === false) {+ return asset;+ }+ const assets = await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ await this.validateCompletedCollectionUpload({+ asset,+ assets,+ allowCollectionFolder,+ });return asset;}+ private async assertUploadAllowed({+ asset,+ assets,+ allowCollectionFolder,+ }: {+ asset: Pick<Asset, "id" | "name" | "filename" | "folderId">;+ assets?: readonly Asset[];+ allowCollectionFolder: boolean;+ }) {+ const displayName = formatAssetName(asset);+ if (+ asset.folderId !== undefined &&+ displayName === collectionConfigFilename+ ) {+ await this.assertCanConfigureCollections();+ return "collection" as const;+ }+ if (allowCollectionFolder) {+ return "collection" as const;+ }+ if (asset.folderId === undefined) {+ return "ordinary" as const;+ }+ const projectAssets =+ assets ??+ (await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ ));+ const configAsset = projectAssets.find(+ (candidate) =>+ candidate.folderId === asset.folderId &&+ formatAssetName(candidate) === collectionConfigFilename+ );+ if (configAsset === undefined) {+ return "ordinary" as const;+ }+ const config = parseCollectionConfig(+ decodeUtf8(await this.readCollectionAssetBytes(configAsset))+ );+ if (+ displayName !== config.template &&+ config.matchesEntry(displayName) === false+ ) {+ return "ordinary" as const;+ }+ const templateExists = projectAssets.some(+ (candidate) =>+ candidate.id !== asset.id &&+ candidate.folderId === asset.folderId &&+ formatAssetName(candidate) === config.template+ );+ if (displayName === config.template && templateExists === false) {+ await this.assertCanConfigureCollections();+ return "template-repair" as const;+ }+ throw new AssetRepositoryConflictError(+ "Use New entry to add files to a collection folder"+ );+ }++ async completeUpload(+ input: Parameters<AssetRepository["completeUpload"]>[0]+ ) {+ return await this.completeReservedUpload({+ ...input,+ allowCollectionFolder: false,+ });+ }++ private async prepareCollectionAssetContent({+ currentAsset,+ extension,+ data,+ }: {+ currentAsset: Asset;+ extension?: string;+ data: ReadableStream<Uint8Array>;+ }) {+ if (currentAsset.folderId === undefined) {+ return data;+ }+ const currentFilename = formatAssetName(currentAsset);+ const nextFilename =+ extension === undefined+ ? currentFilename+ : `${getAssetDisplayNameParts(currentAsset).basename}.${extension.toLowerCase()}`;+ // A revision can change the logical extension as well as its content.+ // It must not create a manifest or bypass the New entry workflow.+ if (+ nextFilename !== currentFilename &&+ nextFilename === collectionConfigFilename+ ) {+ throw new AssetRepositoryConflictError(+ "Use collection setup to add collection.json"+ );+ }+ const isCollectionConfig = currentFilename === collectionConfigFilename;+ if (isCollectionConfig) {+ await this.assertCanConfigureCollections();+ }+ if (+ isCollectionConfig === false &&+ isMdxFileAsset(currentAsset) === false &&+ nextFilename === currentFilename+ ) {+ return data;+ }+ const assets = await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ const siblings = assets.filter(+ (asset) => asset.folderId === currentAsset.folderId+ );+ const configAsset = siblings.find(+ (asset) => formatAssetName(asset) === collectionConfigFilename+ );+ if (configAsset === undefined) {+ if (isCollectionConfig) {+ await this.assertCanConfigureCollections();+ }+ return data;+ }+ const reservedAssetIds = await getCollectionReservedAssetIds({+ assets,+ assetStore: this.assetStore,+ folderIds: new Set([currentAsset.folderId]),+ });+ if (isCollectionConfig === false && reservedAssetIds.has(currentAsset.id)) {+ await this.assertCanConfigureCollections();+ }+ let config;+ if (isCollectionConfig === false) {+ try {+ config = parseCollectionConfig(+ decodeUtf8(await this.readCollectionAssetBytes(configAsset))+ );+ } catch (error) {+ if (error instanceof ContentCollectionError === false) {+ throw error;+ }+ return data;+ }+ const filename = formatAssetName(currentAsset);+ if (+ nextFilename !== filename &&+ (nextFilename === config.template || config.matchesEntry(nextFilename))+ ) {+ throw new AssetRepositoryConflictError(+ "Use New entry to add files to a collection folder"+ );+ }+ if (filename !== config.template && !config.matchesEntry(filename)) {+ return data;+ }+ }+ const bytes = await readBoundedBytes(+ data,+ contentEngineLimits.hydratedFileBytes+ );+ const nextData = new ReadableStream({+ start(controller) {+ controller.enqueue(bytes);+ controller.close();+ },+ });+ if (isCollectionConfig) {+ if (extension !== undefined && extension.toLowerCase() !== "json") {+ throw new AssetRepositoryConflictError(+ "collection.json must remain a JSON file"+ );+ }+ const projectedAssets = assets.map((asset) =>+ asset.id === currentAsset.id+ ? { ...asset, size: bytes.byteLength }+ : asset+ );+ const projectedAssetStore: AssetObjectReader = {+ readFile: async (name, range) => {+ if (name !== currentAsset.name) {+ return await this.assetStore.readFile(name, range);+ }+ const projectedBytes =+ range === undefined+ ? bytes+ : bytes.subarray(range.offset, range.offset + range.length);+ return {+ data: {+ [Symbol.asyncIterator]: async function* () {+ yield projectedBytes;+ },+ },+ contentLength: projectedBytes.byteLength,+ };+ },+ };+ await validateCollectionFolder({+ assets: projectedAssets,+ folderId: currentAsset.folderId,+ assetStore: projectedAssetStore,+ validateTemplate: false,+ validateEntries: false,+ });+ return nextData;+ }+ if (+ isMdxFileAsset(currentAsset) &&+ extension !== undefined &&+ extension.toLowerCase() !== "mdx"+ ) {+ throw new AssetRepositoryConflictError(+ "Collection MDX files must remain MDX files"+ );+ }+ if (config === undefined) {+ return nextData;+ }+ if (formatAssetName(currentAsset) === config.template) {+ await parseCollectionTemplate(decodeUtf8(bytes));+ return nextData;+ }+ if (isMdxFileAsset(currentAsset) === false) {+ return nextData;+ }+ const nextFrontmatter = await extractMarkdownFrontmatter(bytes);+ const currentContent = await this.readContent({+ assetId: currentAsset.id,+ asset: currentAsset,+ });+ const currentFrontmatter = await extractMarkdownFrontmatter(+ currentContent.data+ );+ const frontmatterChanged =+ serializeJsonDeterministically(nextFrontmatter.properties) !==+ serializeJsonDeterministically(currentFrontmatter.properties);+ // Existing entries can be repaired incrementally. Field validation is+ // diagnostic; only creation requires every field to satisfy the schema.+ if (frontmatterChanged && config.slugField !== undefined) {+ const slug = nextFrontmatter.properties[config.slugField];+ const filenameSlug = getAssetDisplayNameParts(currentAsset).basename;+ if (+ slug !== currentFrontmatter.properties[config.slugField] &&+ slug !== filenameSlug+ ) {+ throw new AssetRepositoryConflictError(+ "The slug must match the entry filename"+ );+ }+ }+ return nextData;+ }+async updateContent({assetId,expectedName,@@ -674,6 +1214,12 @@ export class PostgresAssetRepository implements AssetRepository {expectedName,extension,data,+ prepareData: ({ asset, data }) =>+ this.prepareCollectionAssetContent({+ currentAsset: asset,+ extension,+ data,+ }),},this.getWritableStore(),this.context@@ -683,6 +1229,145 @@ export class PostgresAssetRepository implements AssetRepository {async updateMetadata(assetId: Asset["id"], values: AssetMetadataUpdate) {await this.assertCanEdit();+ const assets = await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ const currentAsset = assets.find((asset) => asset.id === assetId);+ const reservedAssetIds = await getCollectionReservedAssetIds({+ assets,+ assetStore: this.assetStore,+ folderIds: new Set(+ [currentAsset?.folderId, values.folderId].filter(+ (folderId): folderId is string => typeof folderId === "string"+ )+ ),+ });+ const nextFilename =+ values.filename === undefined+ ? currentAsset?.filename+ : (values.filename ?? undefined);+ const nextDisplayName =+ currentAsset === undefined+ ? undefined+ : formatAssetName({+ name: currentAsset.name,+ filename: nextFilename,+ });+ const nextFolderId =+ values.folderId === null+ ? undefined+ : (values.folderId ?? currentAsset?.folderId);+ if (+ reservedAssetIds.has(assetId) ||+ (nextFolderId !== undefined &&+ nextDisplayName === collectionConfigFilename)+ ) {+ await this.assertCanConfigureCollections();+ }+ if (typeof values.folderId === "string" || values.filename !== undefined) {+ if (+ values.filename !== undefined &&+ currentAsset?.folderId !== undefined &&+ values.filename !== getAssetDisplayNameParts(currentAsset).basename &&+ isMdxFileAsset(currentAsset)+ ) {+ const configAsset = assets.find(+ (asset) =>+ asset.folderId === currentAsset.folderId &&+ formatAssetName(asset) === collectionConfigFilename+ );+ if (configAsset !== undefined) {+ const config = parseCollectionConfig(+ decodeUtf8(await this.readCollectionAssetBytes(configAsset))+ );+ if (config.matchesEntry(formatAssetName(currentAsset))) {+ throw new AssetRepositoryConflictError(+ "Collection MDX filenames cannot be changed"+ );+ }+ }+ }+ if (+ nextFolderId !== undefined &&+ (currentAsset?.folderId !== nextFolderId ||+ (nextDisplayName !== undefined &&+ currentAsset !== undefined &&+ formatAssetName(currentAsset) !== nextDisplayName))+ ) {+ const configAsset = assets.find(+ (asset) =>+ asset.folderId === nextFolderId &&+ formatAssetName(asset) === collectionConfigFilename+ );+ if (configAsset !== undefined && nextDisplayName !== undefined) {+ const config = parseCollectionConfig(+ decodeUtf8(await this.readCollectionAssetBytes(configAsset))+ );+ if (+ nextDisplayName === config.template ||+ config.matchesEntry(nextDisplayName)+ ) {+ throw new AssetRepositoryConflictError(+ "Use New entry to add files to a collection folder"+ );+ }+ }+ }+ }+ if (currentAsset !== undefined) {+ const nextAsset: Asset = {+ ...currentAsset,+ ...(values.filename === undefined+ ? {}+ : values.filename === null+ ? { filename: undefined }+ : { filename: values.filename }),+ ...(values.folderId === undefined+ ? {}+ : values.folderId === null+ ? { folderId: undefined }+ : { folderId: values.folderId }),+ };+ const projectedAssets = assets.map((asset) =>+ asset.id === currentAsset.id ? nextAsset : asset+ );+ if (+ nextAsset.folderId !== undefined &&+ projectedAssets.some(+ (asset) =>+ asset.folderId === nextAsset.folderId &&+ formatAssetName(asset) === collectionConfigFilename+ ) &&+ (currentAsset.folderId !== nextAsset.folderId ||+ formatAssetName(currentAsset) !== formatAssetName(nextAsset))+ ) {+ await validateCollectionFolder({+ assets: projectedAssets,+ folderId: nextAsset.folderId,+ assetStore: this.assetStore,+ validateEntries:+ reservedAssetIds.has(assetId) ||+ nextDisplayName === collectionConfigFilename,+ });+ }+ if (+ reservedAssetIds.has(currentAsset.id) &&+ currentAsset.folderId !== undefined &&+ currentAsset.folderId !== nextAsset.folderId &&+ projectedAssets.some(+ (asset) =>+ asset.folderId === currentAsset.folderId &&+ formatAssetName(asset) === collectionConfigFilename+ )+ ) {+ await validateCollectionFolder({+ assets: projectedAssets,+ folderId: currentAsset.folderId,+ assetStore: this.assetStore,+ });+ }+ }const asset = await this.dependencies.updateAssetMetadataWithClient({ projectId: this.projectId, assetId, values },this.context.postgrest.client@@ -693,6 +1378,51 @@ export class PostgresAssetRepository implements AssetRepository {async delete(ids: Asset["id"][]) {await this.assertCanEdit();+ const assets = await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ const reservedAssetIds = await getCollectionReservedAssetIds({+ assets,+ assetStore: this.assetStore,+ folderIds: new Set(+ assets.flatMap((asset) =>+ ids.includes(asset.id) && asset.folderId !== undefined+ ? [asset.folderId]+ : []+ )+ ),+ });+ if (ids.some((id) => reservedAssetIds.has(id))) {+ await this.assertCanConfigureCollections();+ }+ const nextAssets = assets.filter(+ (asset) => ids.includes(asset.id) === false+ );+ const affectedFolderIds = new Set(+ assets.flatMap((asset) =>+ ids.includes(asset.id) &&+ reservedAssetIds.has(asset.id) &&+ asset.folderId !== undefined+ ? [asset.folderId]+ : []+ )+ );+ for (const folderId of affectedFolderIds) {+ if (+ nextAssets.some(+ (asset) =>+ asset.folderId === folderId &&+ formatAssetName(asset) === collectionConfigFilename+ )+ ) {+ await validateCollectionFolder({+ assets: nextAssets,+ folderId,+ assetStore: this.assetStore,+ });+ }+ }await this.dependencies.deleteAssetsWithClient({ projectId: this.projectId, ids },this.context.postgrest.client@@ -738,6 +1468,581 @@ export class PostgresAssetRepository implements AssetRepository {);}+ async createCollectionFolder({+ id,+ name,+ parentId,+ }: {+ id: string;+ name: string;+ parentId?: string;+ }) {+ await this.assertCanConfigureCollections();+ const [existingFolder] =+ await this.dependencies.loadAssetFoldersByProjectWithClient(+ this.projectId,+ this.context.postgrest.client,+ [id]+ );+ let folder = existingFolder;+ if (folder === undefined) {+ folder = await this.dependencies.upsertAssetFolderWithClient(+ {+ projectId: this.projectId,+ folder: {+ id,+ projectId: this.projectId,+ name,+ parentId,+ createdAt: this.dependencies.now().toISOString(),+ },+ },+ this.context.postgrest.client+ );+ } else if (folder.name !== name || folder.parentId !== parentId) {+ throw new AssetRepositoryConflictError(+ "A different asset folder already uses this identifier"+ );+ }++ // Validate the proposed collection before creating either control file.+ // Exact seed files can be reused after an interrupted setup; never replace+ // an existing template or configuration with generated defaults.+ const seedSources = new Map([+ [defaultCollectionTemplateFilename, createDefaultCollectionTemplate()],+ [collectionConfigFilename, createDefaultCollectionConfig()],+ ]);+ const existingAssets =+ await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ const siblings = existingAssets.filter((asset) => asset.folderId === id);+ const reusableSeeds = new Map<string, Asset>();+ for (const asset of siblings) {+ const filename = formatAssetName(asset);+ const seed = seedSources.get(filename);+ if (seed === undefined) {+ continue;+ }+ if (+ reusableSeeds.has(filename) ||+ decodeUtf8(await this.readCollectionAssetBytes(asset)) !== seed+ ) {+ throw new AssetRepositoryConflictError(+ `Collection setup would conflict with "${filename}". Rename or move it first.`+ );+ }+ reusableSeeds.set(filename, asset);+ }+ await inspectContentCollection({+ validateEntries: false,+ files: [+ ...siblings+ .filter((asset) => !reusableSeeds.has(formatAssetName(asset)))+ .map((asset) => ({+ id: asset.id,+ filename: formatAssetName(asset),+ basename: getAssetDisplayNameParts(asset).basename,+ isMdx: isMdxFileAsset(asset),+ file: asset as Asset | undefined,+ })),+ ...Array.from(seedSources.keys(), (filename) => ({+ id: filename,+ filename,+ basename:+ filename === collectionConfigFilename ? "collection" : "template",+ isMdx: filename === defaultCollectionTemplateFilename,+ file: undefined as Asset | undefined,+ })),+ ],+ readSource: async ({ file: asset, filename }) =>+ asset === undefined+ ? seedSources.get(filename)!+ : decodeUtf8(await this.readCollectionAssetBytes(asset)),+ });++ const createSeedAsset = async (filename: string, source: string) => {+ const existing = reusableSeeds.get(filename);+ if (existing !== undefined) {+ return existing;+ }+ const bytes = new TextEncoder().encode(source);+ const ticket = await this.createUploadTicket({+ type: "file",+ filename,+ displayFilename: filename.slice(0, filename.lastIndexOf(".")),+ folderId: id,+ contentHash: createHash("sha256").update(bytes).digest("hex"),+ });+ if (ticket.deduplicated) {+ if (+ ticket.asset.folderId === id &&+ formatAssetName(ticket.asset) === filename+ ) {+ return ticket.asset;+ }+ throw new AssetRepositoryConflictError(+ `Collection file "${filename}" could not be created`+ );+ }+ return await this.completeReservedUpload({+ name: ticket.name,+ data: new ReadableStream({+ start(controller) {+ controller.enqueue(bytes);+ controller.close();+ },+ }),+ assetInfoFallback: undefined,+ assetId: ticket.assetId,+ allowCollectionFolder: true,+ validateCollectionState: false,+ });+ };++ const templateAsset = await createSeedAsset(+ defaultCollectionTemplateFilename,+ createDefaultCollectionTemplate()+ );+ const configAsset = await createSeedAsset(+ collectionConfigFilename,+ createDefaultCollectionConfig()+ );+ const assets = await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ await validateCollectionFolder({+ assets,+ folderId: id,+ assetStore: this.assetStore,+ validateEntries: false,+ });+ return { folder, assets: [templateAsset, configAsset] };+ }++ async createCollectionEntry({+ folderId,+ values,+ requestId,+ }: {+ folderId: string;+ values: Readonly<Record<string, unknown>>;+ requestId?: string;+ }) {+ await this.assertCanEdit();+ const [folders, assets] = await Promise.all([+ this.dependencies.loadAssetFoldersByProjectWithClient(+ this.projectId,+ this.context.postgrest.client,+ [folderId]+ ),+ this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ ),+ ]);+ if (folders.length === 0) {+ throw new AssetRepositoryNotFoundError("Asset folder not found");+ }+ const siblings = assets.filter((asset) => asset.folderId === folderId);+ const configAssets = siblings.filter(+ (asset) => formatAssetName(asset) === collectionConfigFilename+ );+ const configAsset = configAssets[0];+ if (configAsset === undefined) {+ throw new AssetRepositoryNotFoundError(+ "Collection configuration not found"+ );+ }+ const inspected = await inspectContentCollection({+ files: siblings.map((asset) => ({+ file: asset,+ id: asset.id,+ filename: formatAssetName(asset),+ basename: getAssetDisplayNameParts(asset).basename,+ isMdx: isMdxFileAsset(asset),+ })),+ readSource: async ({ file }) =>+ decodeUtf8(await this.readCollectionAssetBytes(file)),+ validateTemplate: false,+ validateEntries: false,+ });+ const { config } = inspected;+ const templateAsset = inspected.templateFile.file;+ const entry = await createCollectionEntry({+ config,+ requestId,+ templateSource: decodeUtf8(+ await this.readCollectionAssetBytes(templateAsset)+ ),+ values,+ // Persistence performs the collision check so an exact retry can return+ // the entry created by the first request instead of reporting a false+ // conflict after the response was lost.+ existingFilenames: [],+ });+ if (entry.filename.length > assetResourceLimits.assetFilenameCharacters) {+ throw new AssetRepositoryConflictError(+ "The generated entry filename is too long"+ );+ }+ const existingAsset = siblings.find(+ (asset) =>+ formatAssetName(asset).normalize("NFC").toLowerCase() ===+ entry.filename.toLowerCase()+ );+ if (existingAsset !== undefined) {+ if (+ existingAsset.id === configAsset.id ||+ existingAsset.id === templateAsset.id+ ) {+ throw new AssetRepositoryConflictError(+ `An entry named "${entry.filename}" already exists`+ );+ }+ const existingSource = decodeUtf8(+ await this.readCollectionAssetBytes(existingAsset)+ );+ if (existingSource === entry.source) {+ return existingAsset;+ }+ throw new AssetRepositoryConflictError(+ `An entry named "${entry.filename}" already exists`+ );+ }+ const bytes = new TextEncoder().encode(entry.source);+ const contentHash = createHash("sha256").update(bytes).digest("hex");+ const ticket = await this.dependencies.createUploadTicket(+ {+ projectId: this.projectId,+ type: "file",+ filename: entry.filename,+ displayFilename: entry.filename.slice(0, -".mdx".length),+ folderId,+ contentHash,+ },+ this.context+ );+ if (ticket.deduplicated) {+ if (+ ticket.asset.id !== configAsset.id &&+ ticket.asset.id !== templateAsset.id &&+ ticket.asset.folderId === folderId &&+ formatAssetName(ticket.asset).toLowerCase() ===+ entry.filename.toLowerCase()+ ) {+ const definition = await this.validateCompletedCollectionUpload({+ asset: ticket.asset,+ allowCollectionFolder: true,+ // Deduplication returns an existing asset owned by another request.+ // A failed retry must never delete it.+ cleanupOnError: false,+ });+ if (+ definition !== undefined &&+ (ticket.asset.id === definition.configAsset.id ||+ ticket.asset.id === definition.templateAsset.id)+ ) {+ throw new AssetRepositoryConflictError(+ `An entry named "${entry.filename}" already exists`+ );+ }+ return ticket.asset;+ }+ throw new AssetRepositoryConflictError(+ "Entry upload was deduplicated incorrectly"+ );+ }+ let reservations: Awaited<+ ReturnType<typeof loadAssetUploadReservationsByProjectWithClient>+ >;+ try {+ reservations =+ await this.dependencies.loadAssetUploadReservationsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ } catch (error) {+ await this.getUploadErrorCleanup(ticket.assetId)?.(ticket.name);+ throw error;+ }+ const matchingReservations = reservations+ .filter(+ (candidate) =>+ candidate.folderId === folderId &&+ candidate.filename?.normalize("NFC").toLowerCase() ===+ entry.filename.slice(0, -".mdx".length).toLowerCase()+ )+ .sort(+ (left, right) =>+ left.createdAt.localeCompare(right.createdAt) ||+ left.id.localeCompare(right.id)+ );+ const duplicateReservation =+ matchingReservations[0] !== undefined &&+ matchingReservations[0].id !== ticket.assetId;+ if (duplicateReservation) {+ await this.getUploadErrorCleanup(ticket.assetId)?.(ticket.name);+ throw new AssetRepositoryConflictError(+ `An entry named "${entry.filename}" already exists`+ );+ }+ return await this.completeReservedUpload({+ name: ticket.name,+ data: new ReadableStream({+ start(controller) {+ controller.enqueue(bytes);+ controller.close();+ },+ }),+ assetInfoFallback: undefined,+ assetId: ticket.assetId,+ allowCollectionFolder: true,+ });+ }++ async updateCollectionConfigAndTemplateName({+ folderId,+ configAssetId,+ expectedConfigName,+ templateAssetId,+ expectedTemplateFilename,+ templateFilename,+ configSource,+ }: {+ folderId: string;+ configAssetId: Asset["id"];+ expectedConfigName: Asset["name"];+ templateAssetId: Asset["id"];+ expectedTemplateFilename: Asset["filename"];+ templateFilename: string;+ configSource: string;+ }) {+ await this.assertCanConfigureCollections();+ if (+ templateFilename.length === 0 ||+ templateFilename.length > assetResourceLimits.assetFilenameCharacters+ ) {+ throw new AssetRepositoryConflictError(+ "Collection template name is invalid"+ );+ }+ const assets = await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ const configAsset = assets.find(+ (asset) =>+ asset.id === configAssetId &&+ asset.folderId === folderId &&+ formatAssetName(asset) === collectionConfigFilename+ );+ if (configAsset === undefined) {+ throw new AssetRepositoryNotFoundError(+ "Collection configuration not found"+ );+ }+ const currentConfigSource = decodeUtf8(+ await this.readCollectionAssetBytes(configAsset)+ );+ const currentConfig = parseCollectionConfig(currentConfigSource);+ const nextConfig = parseCollectionConfig(configSource);+ const requestedTemplateAsset = assets.find(+ (asset) =>+ asset.id === templateAssetId &&+ asset.folderId === folderId &&+ asset.filename === templateFilename &&+ formatAssetName(asset) === nextConfig.template &&+ isMdxFileAsset(asset)+ );+ if (+ currentConfigSource === configSource &&+ requestedTemplateAsset !== undefined+ ) {+ await validateCollectionFolder({+ assets,+ folderId,+ assetStore: this.assetStore,+ validateEntries: false,+ });+ return {+ configAsset,+ templateAsset: requestedTemplateAsset,+ };+ }+ if (configAsset.name !== expectedConfigName) {+ throw new AssetRepositoryConflictError(+ "Collection configuration changed while settings were being saved"+ );+ }+ const templateAsset = assets.find(+ (asset) =>+ asset.id === templateAssetId &&+ asset.folderId === folderId &&+ isMdxFileAsset(asset)+ );+ if (templateAsset === undefined) {+ throw new AssetRepositoryNotFoundError("Collection template not found");+ }+ const expectedTemplateAsset = {+ ...templateAsset,+ filename: expectedTemplateFilename,+ };+ if (+ currentConfig.template !== formatAssetName(expectedTemplateAsset) ||+ (templateAsset.filename !== expectedTemplateFilename &&+ templateAsset.filename !== templateFilename)+ ) {+ throw new AssetRepositoryConflictError(+ "Collection template changed while settings were being saved"+ );+ }+ const nextTemplateAsset = { ...templateAsset, filename: templateFilename };+ if (nextConfig.template !== formatAssetName(nextTemplateAsset)) {+ throw new AssetRepositoryConflictError(+ "Collection configuration does not reference the renamed template"+ );+ }+ const configBytes = new TextEncoder().encode(configSource);+ const projectedAssets = assets.map((asset) => {+ if (asset.id === configAsset.id) {+ return { ...asset, size: configBytes.byteLength };+ }+ return asset.id === templateAsset.id ? nextTemplateAsset : asset;+ });+ const projectedAssetStore: AssetObjectReader = {+ readFile: async (name, range) => {+ if (name !== configAsset.name) {+ return await this.assetStore.readFile(name, range);+ }+ const bytes =+ range === undefined+ ? configBytes+ : configBytes.subarray(range.offset, range.offset + range.length);+ return {+ data: {+ [Symbol.asyncIterator]: async function* () {+ yield bytes;+ },+ },+ contentLength: bytes.byteLength,+ };+ },+ };+ await validateCollectionFolder({+ assets: projectedAssets,+ folderId,+ assetStore: projectedAssetStore,+ validateEntries: false,+ });++ let renamedTemplate = templateAsset;+ let renamedTemplateByThisRequest = false;+ if (templateAsset.filename !== templateFilename) {+ const updatedTemplate =+ await this.dependencies.updateAssetFilenameIfCurrentWithClient(+ {+ projectId: this.projectId,+ assetId: templateAsset.id,+ expectedFilename: expectedTemplateFilename,+ filename: templateFilename,+ },+ this.context.postgrest.client+ );+ if (updatedTemplate === undefined) {+ throw new AssetRepositoryConflictError(+ "Collection template changed while settings were being saved"+ );+ }+ renamedTemplate = updatedTemplate;+ renamedTemplateByThisRequest = true;+ }+ try {+ const updatedConfig = await this.updateContent({+ assetId: configAsset.id,+ expectedName: configAsset.name,+ data: new ReadableStream({+ start(controller) {+ controller.enqueue(configBytes);+ controller.close();+ },+ }),+ });+ return { configAsset: updatedConfig, templateAsset: renamedTemplate };+ } catch (error) {+ const currentAssets =+ await this.dependencies.loadAssetsByProjectWithClient(+ this.projectId,+ this.context.postgrest.client+ );+ const currentConfigAsset = currentAssets.find(+ (asset) => asset.id === configAsset.id && asset.folderId === folderId+ );+ const currentTemplateAsset = currentAssets.find(+ (asset) => asset.id === templateAsset.id && asset.folderId === folderId+ );+ if (+ currentConfigAsset === undefined ||+ currentTemplateAsset === undefined+ ) {+ throw new Error(+ "Collection settings failed and the current collection state could not be verified",+ { cause: error }+ );+ }+ const currentConfigSource = decodeUtf8(+ await this.readCollectionAssetBytes(currentConfigAsset)+ );+ const currentTemplateName = formatAssetName(currentTemplateAsset);+ if (+ currentConfigSource === configSource &&+ currentTemplateName === formatAssetName(nextTemplateAsset)+ ) {+ return {+ configAsset: currentConfigAsset,+ templateAsset: currentTemplateAsset,+ };+ }+ if (renamedTemplateByThisRequest === false) {+ throw error;+ }+ let currentConfig;+ try {+ currentConfig = parseCollectionConfig(currentConfigSource);+ } catch {+ throw new Error(+ "Collection settings failed and the current collection state could not be verified",+ { cause: error }+ );+ }+ if (+ currentConfig.template !== formatAssetName(templateAsset) ||+ currentTemplateAsset.filename !== templateFilename+ ) {+ throw error;+ }+ const restoredTemplate =+ await this.dependencies.updateAssetFilenameIfCurrentWithClient(+ {+ projectId: this.projectId,+ assetId: templateAsset.id,+ expectedFilename: templateFilename,+ filename: templateAsset.filename,+ },+ this.context.postgrest.client+ );+ if (restoredTemplate === undefined) {+ throw new Error(+ "Collection settings failed and the template name could not be restored",+ { cause: error }+ );+ }+ throw error;+ }+ }+async updateFolder(folderId: string, values: AssetFolderUpdate) {await this.assertCanEdit();const folder = (@@ -800,6 +2105,18 @@ export class PostgresAssetRepository implements AssetRepository {return await this.synchronizeTrusted();}+ async validateCollections(assets: readonly Asset[]) {+ await this.assertCanBuild();+ for (const folderId of getCollectionFolderIds(assets)) {+ await validateCollectionFolder({+ assets,+ folderId,+ assetStore: this.assetStore,+ validateEntries: false,+ });+ }+ }+private async synchronizeTrusted(requirements?: ContentCompilationPlan,assetIds?: string[]@@ -1032,13 +2349,75 @@ export class PostgresAssetRepository implements AssetRepository {client: this.context.postgrest.client,projectId: this.projectId,});+ const excludeCollectionFiles = async (+ entries: Awaited<ReturnType<typeof loadCanonicalAssetBaseEntries>>+ ) => {+ const reservedAssetIds = new Set<string>();+ const folderIds = new Set(+ entries.flatMap((entry) =>+ entry.document.name === collectionConfigFilename &&+ entry.document.folderId !== undefined+ ? [entry.document.folderId]+ : []+ )+ );+ for (const folderId of folderIds) {+ const siblings = entries.filter(+ (candidate) => candidate.document.folderId === folderId+ );+ try {+ const inspected = await inspectContentCollection({+ files: siblings.map((entry) => ({+ file: entry,+ id: entry.assetId,+ filename: entry.document.name,+ basename: entry.document.key,+ isMdx: entry.document.extension.toLowerCase() === "mdx",+ })),+ readSource: async ({ file: entry }) => {+ if (entry.document.size > contentEngineLimits.hydratedFileBytes) {+ throw new ContentCollectionError(+ `Collection file "${entry.document.name}" exceeds the content size limit`+ );+ }+ const response = await readFile(entry.document.contentRef);+ const bytes = await readBoundedBytes(+ response.data,+ contentEngineLimits.hydratedFileBytes+ );+ if (bytes.byteLength !== entry.document.size) {+ throw new ContentCollectionError(+ `Collection file "${entry.document.name}" content length does not match its metadata`+ );+ }+ return decodeUtf8(bytes);+ },+ validateTemplate: false,+ validateEntries: false,+ });+ reservedAssetIds.add(inspected.configFile.id);+ reservedAssetIds.add(inspected.templateFile.id);+ } catch (error) {+ if (error instanceof ContentCollectionError) {+ throw error;+ }+ throw new ContentCollectionError(+ "Collection configuration could not be read"+ );+ }+ }+ return entries.filter(+ (entry) => reservedAssetIds.has(entry.assetId) === false+ );+ };return {openSnapshot: async () => {// Each snapshot must report only issues observed during its own// preparation, including when uncached materialization retries.preparationIssues.length = 0;- const baseEntries = await loadBaseEntries();- const revision = await computeCanonicalAssetRevision(baseEntries);+ const allBaseEntries = await loadBaseEntries();+ const revision = await computeCanonicalAssetRevision(allBaseEntries);+ const baseEntries = await excludeCollectionFiles(allBaseEntries);return {revision,files: baseEntries.map(createContentSourceFile),diff --git a/packages/asset-uploader/src/collection-persistence.test.ts b/packages/asset-uploader/src/collection-persistence.test.tsnew file mode 100644index 0000000000..57644e96a0--- /dev/null+++ b/packages/asset-uploader/src/collection-persistence.test.ts@@ -0,0 +1,147 @@+import { describe, expect, test } from "vitest";+import { createDefaultCollectionConfig } from "@webstudio-is/content-engine";+import type { Asset } from "@webstudio-is/sdk";+import { validateCollectionFolder } from "./collection-persistence";++describe("collection persistence", () => {+ test("rejects a truncated collection config read", async () => {+ const source = createDefaultCollectionConfig();+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: source.length,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ };++ await expect(+ validateCollectionFolder({+ assets: [configAsset],+ folderId: "posts",+ assetStore: {+ readFile: async () => ({+ data: new Blob([source.slice(0, -1)]).stream(),+ contentLength: source.length - 1,+ }),+ },+ })+ ).rejects.toThrow("content length does not match its metadata");+ });++ test("rejects a truncated collection template read", async () => {+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };++ await expect(+ validateCollectionFolder({+ assets: [configAsset, templateAsset],+ folderId: "posts",+ assetStore: {+ readFile: async (name) => {+ const source =+ name === configAsset.name+ ? configSource+ : templateSource.slice(0, -1);+ return {+ data: new Blob([source]).stream(),+ contentLength: source.length,+ };+ },+ },+ })+ ).rejects.toThrow("content length does not match its metadata");+ });++ test("rejects case-insensitive duplicate entry filenames", async () => {+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const entrySource =+ "---\ntitle: Hello world\nslug: hello-world\ndraft: true\n---\n\nBody.\n";+ const configAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ };+ const templateAsset: Asset = {+ ...configAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ size: templateSource.length,+ };+ const firstEntry: Asset = {+ ...templateAsset,+ id: "first-entry",+ name: "first-entry-storage.mdx",+ filename: "hello-world",+ size: entrySource.length,+ };+ const secondEntry: Asset = {+ ...firstEntry,+ id: "second-entry",+ name: "second-entry-storage.mdx",+ filename: "HELLO-WORLD",+ };+ const sources = new Map([+ [configAsset.name, configSource],+ [templateAsset.name, templateSource],+ [firstEntry.name, entrySource],+ [secondEntry.name, entrySource],+ ]);++ await expect(+ validateCollectionFolder({+ assets: [configAsset, templateAsset, firstEntry, secondEntry],+ folderId: "posts",+ assetStore: {+ readFile: async (name) => {+ const source = sources.get(name);+ if (source === undefined) {+ throw new Error(`Unexpected read: ${name}`);+ }+ return {+ data: new Blob([source]).stream(),+ contentLength: source.length,+ };+ },+ },+ })+ ).rejects.toThrow('duplicate filename "HELLO-WORLD.mdx"');+ });+});diff --git a/packages/asset-uploader/src/collection-persistence.ts b/packages/asset-uploader/src/collection-persistence.tsnew file mode 100644index 0000000000..01b99c7da0--- /dev/null+++ b/packages/asset-uploader/src/collection-persistence.ts@@ -0,0 +1,180 @@+import {+ collectionConfigFilename,+ ContentCollectionError,+ contentEngineLimits,+ extractMarkdownFrontmatter,+ inspectContentCollection,+ parseCollectionConfig,+} from "@webstudio-is/content-engine";+import {+ decodeUtf8,+ readBoundedBytes,+} from "@webstudio-is/content-engine/compiler";+import {+ formatAssetName,+ getAssetDisplayNameParts,+ isMdxFileAsset,+ type Asset,+} from "@webstudio-is/sdk";+import type { AssetObjectReader } from "./client";++export type CollectionFolderDefinition = Readonly<{+ configAsset: Asset;+ templateAsset: Asset;+}>;++const getFolderAssets = (assets: readonly Asset[], folderId: string) =>+ assets.filter((asset) => asset.folderId === folderId);++const readAssetBytes = async (asset: Asset, assetStore: AssetObjectReader) => {+ if (asset.size > contentEngineLimits.hydratedFileBytes) {+ throw new ContentCollectionError(+ `Collection file "${formatAssetName(asset)}" exceeds the content size limit`+ );+ }+ const response = await assetStore.readFile(asset.name);+ const bytes = await readBoundedBytes(+ response.data,+ contentEngineLimits.hydratedFileBytes+ );+ if (bytes.byteLength !== asset.size) {+ throw new ContentCollectionError(+ `Collection file "${formatAssetName(asset)}" content length does not match its metadata`+ );+ }+ return bytes;+};++export const getCollectionFolderIds = (assets: readonly Asset[]) =>+ new Set(+ assets.flatMap((asset) =>+ asset.folderId !== undefined &&+ formatAssetName(asset) === collectionConfigFilename+ ? [asset.folderId]+ : []+ )+ );++export const validateCollectionFolder = async ({+ assets,+ folderId,+ assetStore,+ validateTemplate = true,+ validateEntries = true,+ entryIdsToValidate,+}: {+ assets: readonly Asset[];+ folderId: string;+ assetStore: AssetObjectReader;+ validateTemplate?: boolean;+ validateEntries?: boolean;+ entryIdsToValidate?: ReadonlySet<string>;+}): Promise<CollectionFolderDefinition> => {+ const siblings = getFolderAssets(assets, folderId);+ const result = await inspectContentCollection({+ files: siblings.map((asset) => ({+ file: asset,+ id: asset.id,+ filename: formatAssetName(asset),+ basename: getAssetDisplayNameParts(asset).basename,+ isMdx: isMdxFileAsset(asset),+ })),+ readSource: async ({ file }) =>+ decodeUtf8(await readAssetBytes(file, assetStore)),+ readFrontmatter: async ({ file }) =>+ (+ await extractMarkdownFrontmatter(+ (+ await assetStore.readFile(file.name)+ ).data+ )+ ).properties,+ validateTemplate,+ validateEntries,+ entryIdsToValidate,+ });+ return {+ configAsset: result.configFile.file,+ templateAsset: result.templateFile.file,+ };+};++const readConfiguredTemplateName = async (+ configAsset: Asset,+ assetStore: AssetObjectReader+) => {+ try {+ const source = decodeUtf8(await readAssetBytes(configAsset, assetStore));+ try {+ return parseCollectionConfig(source).template;+ } catch {+ const value = JSON.parse(source) as unknown;+ if (+ typeof value === "object" &&+ value !== null &&+ typeof (value as Record<string, unknown>)["x-webstudio"] === "object" &&+ (value as Record<string, unknown>)["x-webstudio"] !== null+ ) {+ const template = (+ (value as Record<string, unknown>)["x-webstudio"] as Record<+ string,+ unknown+ >+ ).template;+ if (typeof template === "string") {+ return template;+ }+ }+ }+ } catch {+ // The caller conservatively reserves every MDX sibling when the configured+ // template cannot be identified from a broken manifest.+ }+ return;+};++export const getCollectionReservedAssetIds = async ({+ assets,+ assetStore,+ folderIds,+}: {+ assets: readonly Asset[];+ assetStore: AssetObjectReader;+ folderIds?: ReadonlySet<string>;+}) => {+ const reservedIds = new Set<string>();+ for (const folderId of getCollectionFolderIds(assets)) {+ if (folderIds !== undefined && folderIds.has(folderId) === false) {+ continue;+ }+ const siblings = getFolderAssets(assets, folderId);+ const configAssets = siblings.filter(+ (asset) => formatAssetName(asset) === collectionConfigFilename+ );+ for (const configAsset of configAssets) {+ reservedIds.add(configAsset.id);+ }+ if (configAssets.length !== 1) {+ for (const asset of siblings.filter(isMdxFileAsset)) {+ reservedIds.add(asset.id);+ }+ continue;+ }+ const templateName = await readConfiguredTemplateName(+ configAssets[0],+ assetStore+ );+ if (templateName === undefined) {+ for (const asset of siblings.filter(isMdxFileAsset)) {+ reservedIds.add(asset.id);+ }+ continue;+ }+ for (const asset of siblings) {+ if (formatAssetName(asset) === templateName && isMdxFileAsset(asset)) {+ reservedIds.add(asset.id);+ }+ }+ }+ return reservedIds;+};diff --git a/packages/asset-uploader/src/patch.test.ts b/packages/asset-uploader/src/patch.test.tsindex d57867c07f..d067cb8b59 100644--- a/packages/asset-uploader/src/patch.test.ts+++ b/packages/asset-uploader/src/patch.test.ts@@ -8,10 +8,14 @@ import {testContext,} from "@webstudio-is/postgrest/testing";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";+import { createDefaultCollectionConfig } from "@webstudio-is/content-engine";import {+ deleteAssetUploadReservationWithClient,deleteAssetsWithClient,+ loadAssetUploadReservationsByProjectWithClient,loadAssetsByProjectWithClient,patchAssetsWithClient,+ updateAssetFilenameIfCurrentWithClient,updateAssetMetadataWithClient,} from "./asset-patch-core";import { AssetRepositoryNotFoundError } from "./asset-repository-errors";@@ -22,6 +26,7 @@ import {upsertAssetFolderWithClient,} from "./folder-persistence";import { patchAssets } from "./patch";+import type { AssetObjectReader } from "./client";import type { Patch } from "immer";const server = createTestServer();@@ -35,6 +40,32 @@ const createContext = (): AppContext =>getOwnerPlanFeatures: async () => ({}),}) as unknown as AppContext;+const unusedAssetStore: AssetObjectReader = {+ readFile: async () => {+ throw new Error("Unexpected asset content read");+ },+};++const createSourceAssetStore = (+ sources: Readonly<Record<string, string>>+): AssetObjectReader => ({+ readFile: async (name, range) => {+ const source = sources[name];+ if (source === undefined) {+ throw new Error(`Unexpected asset content read: ${name}`);+ }+ const offset = range?.offset ?? 0;+ const data =+ range?.length === undefined+ ? source.slice(offset)+ : source.slice(offset, offset + range.length);+ return {+ data: new Blob([data]).stream(),+ contentLength: data.length,+ };+ },+});+/** hasProjectPermit: direct ownership check — returns a row for any project */const ownershipHandler = db.get("Project", ({ request }) => {const url = new URL(request.url);@@ -44,6 +75,18 @@ const ownershipHandler = db.get("Project", ({ request }) => {return json(null);});+const editorPermitHandlers = (projectId: string) => [+ db.get("Project", ({ request }) => {+ const url = new URL(request.url);+ return url.searchParams.has("userId")+ ? json(null)+ : json({ id: projectId, userId: "owner-1" });+ }),+ db.get("WorkspaceProjectAuthorization", () =>+ json([{ relation: "editors" }])+ ),+];+describe("asset folder persistence", () => {test("validates and upserts one REST folder mutation", async () => {const projectId = uid();@@ -504,6 +547,64 @@ const assetRow = {};describe("asset patch persistence", () => {+ test("sync saves an existing entry revision while a required field still needs repair", async () => {+ const projectId = uid();+ const sources = {+ "config.json": createDefaultCollectionConfig(),+ "template.mdx": "---\ndraft: true\n---\n",+ "old.mdx": "---\nslug: post\n---\nOld body.\n",+ "new.mdx": "---\nslug: post\n---\nRepaired body.\n",+ };+ const row = (+ assetId: string,+ filename: string,+ name: keyof typeof sources+ ) => ({+ ...assetRow,+ assetId,+ projectId,+ filename,+ folderId: "posts",+ file: {+ ...assetRow.file,+ name,+ format: name.endsWith("json") ? "json" : "mdx",+ meta: "{}",+ size: sources[name].length,+ isDeleted: false,+ },+ });+ const nextFile = row("entry", "post", "new.mdx").file;+ let swapped = false;+ server.use(+ ownershipHandler,+ db.get("Asset", () =>+ json([+ row("config", "collection", "config.json"),+ row("template", "template", "template.mdx"),+ row("entry", "post", "old.mdx"),+ ])+ ),+ db.get("File", () => json([nextFile])),+ db.patch("File", () => json({ name: nextFile.name })),+ db.patch("Asset", () => {+ swapped = true;+ return json({ id: "entry" });+ }),+ http.post("http://test-postgrest/rpc/swap_asset_file", () =>+ HttpResponse.json("invalid_revision")+ )+ );+ await expect(+ patchAssets(+ { projectId, assetStore: createSourceAssetStore(sources) },+ [{ op: "replace", path: ["entry", "name"], value: "new.mdx" }],+ createContext()+ )+ ).resolves.toBeUndefined();+ expect(swapped).toBe(true);+ });+test("loads only requested assets", async () => {const projectId = uid();let idFilter: string | null = null;@@ -538,6 +639,81 @@ describe("asset patch persistence", () => {expect(requestCount).toBe(0);});+ test("loads incomplete upload reservations for conflict checks", async () => {+ const projectId = uid();+ server.use(+ db.get("Asset", ({ request }) => {+ const url = new URL(request.url);+ expect(url.searchParams.get("projectId")).toBe(`eq.${projectId}`);+ expect(url.searchParams.has("file.status")).toBe(false);+ return json([+ {+ id: "uploading-entry",+ projectId,+ filename: "hello-world",+ folderId: "posts",+ file: {+ name: "uploading-entry.mdx",+ status: "UPLOADING",+ isDeleted: false,+ createdAt: "2026-09-03T12:00:00.000Z",+ updatedAt: "2026-09-03T12:00:00.000Z",+ },+ },+ {+ id: "stale-entry",+ projectId,+ filename: "hello-world",+ folderId: "posts",+ file: {+ name: "stale-entry.mdx",+ status: "UPLOADING",+ isDeleted: false,+ createdAt: "2026-09-03T10:00:00.000Z",+ updatedAt: "2026-09-03T10:00:00.000Z",+ },+ },+ ]);+ })+ );++ await expect(+ loadAssetUploadReservationsByProjectWithClient(+ projectId,+ testContext.postgrest.client,+ new Date("2026-09-03T12:15:00.000Z")+ )+ ).resolves.toEqual([+ {+ id: "uploading-entry",+ name: "uploading-entry.mdx",+ filename: "hello-world",+ folderId: "posts",+ createdAt: "2026-09-03T12:00:00.000Z",+ status: "UPLOADING",+ },+ ]);+ });++ test("does not delete a file when the exact upload reservation is missing", async () => {+ const projectId = uid();+ let deletedFile = false;+ server.use(+ db.delete("Asset", () => json(null)),+ db.delete("File", () => {+ deletedFile = true;+ return empty({ status: 204 });+ })+ );++ await deleteAssetUploadReservationWithClient(+ { projectId, assetId: "missing", name: "reservation.mdx" },+ testContext.postgrest.client+ );++ expect(deletedFile).toBe(false);+ });+test("chunks large requested asset id filters", async () => {const projectId = uid();const idFilters: string[] = [];@@ -593,6 +769,46 @@ describe("asset patch persistence", () => {).rejects.toThrow("belongs to another project");});+ test("preserves mutable file metadata in the validation snapshot", async () => {+ const projectId = uid();+ const fontRow = {+ ...assetRow,+ projectId,+ file: {+ ...assetRow.file,+ name: "font.woff2",+ format: "woff2",+ meta: JSON.stringify({+ family: "Inter",+ style: "normal",+ weight: 400,+ }),+ },+ };+ const nextMeta = {+ family: "Inter",+ style: "normal" as const,+ weight: 600,+ };+ let validatedMeta: unknown;+ server.use(+ db.get("Asset", () => json([fontRow])),+ db.patch("File", () => json({ meta: JSON.stringify(nextMeta) }))+ );++ await patchAssetsWithClient(+ { projectId, client: testContext.postgrest.client },+ [{ op: "replace", path: ["asset-1", "meta"], value: nextMeta }],+ {+ validate: async ({ next }) => {+ validatedMeta = next.get("asset-1")?.meta;+ },+ }+ );++ expect(validatedMeta).toEqual(nextMeta);+ });+test("updates only supplied metadata and reloads only that asset", async () => {const projectId = uid();let update: unknown;@@ -624,6 +840,70 @@ describe("asset patch persistence", () => {expect(readIdFilter).toBe("in.(asset-1)");});+ test("updates an asset filename only when the expected value is current", async () => {+ const projectId = uid();+ let updatedFilename: unknown;+ let expectedFilenameFilter: string | null = null;+ server.use(+ db.patch("Asset", async ({ request }) => {+ const url = new URL(request.url);+ expectedFilenameFilter = url.searchParams.get("filename");+ updatedFilename = ((await request.json()) as { filename?: unknown })+ .filename;+ return json({ id: "asset-1" });+ }),+ db.get("Asset", () =>+ json([{ ...assetRow, projectId, filename: "post-template" }])+ )+ );++ await expect(+ updateAssetFilenameIfCurrentWithClient(+ {+ projectId,+ assetId: "asset-1",+ expectedFilename: "template",+ filename: "post-template",+ },+ testContext.postgrest.client+ )+ ).resolves.toEqual(+ expect.objectContaining({ id: "asset-1", filename: "post-template" })+ );+ expect(expectedFilenameFilter).toBe("eq.template");+ expect(updatedFilename).toBe("post-template");+ });++ test("reports when a conditional filename update loses a race", async () => {+ const projectId = uid();+ let reloaded = false;+ server.use(+ db.patch("Asset", ({ request }) => {+ expect(new URL(request.url).searchParams.get("filename")).toBe(+ "is.null"+ );+ return json(null);+ }),+ db.get("Asset", () => {+ reloaded = true;+ return json([]);+ })+ );++ await expect(+ updateAssetFilenameIfCurrentWithClient(+ {+ projectId,+ assetId: "asset-1",+ expectedFilename: undefined,+ filename: "post-template",+ },+ testContext.postgrest.client+ )+ ).resolves.toBeUndefined();+ expect(reloaded).toBe(false);+ });+test("reports a missing metadata update as a repository not-found error", async () => {const projectId = uid();server.use(db.patch("Asset", () => json(null)));@@ -662,7 +942,11 @@ describe("patchAssets (msw)", () => {);await expect(- patchAssets({ projectId }, [], createContext())+ patchAssets(+ { projectId, assetStore: unusedAssetStore },+ [],+ createContext()+ )).rejects.toThrow("You don't have edit access");});@@ -674,7 +958,11 @@ describe("patchAssets (msw)", () => {);// Should complete without throwing- await patchAssets({ projectId }, [], createContext());+ await patchAssets(+ { projectId, assetStore: unusedAssetStore },+ [],+ createContext()+ );});test("updates asset description via patch", async () => {@@ -710,114 +998,839 @@ describe("patchAssets (msw)", () => {},];- await patchAssets({ projectId }, patches, createContext());+ await patchAssets(+ { projectId, assetStore: unusedAssetStore },+ patches,+ createContext()+ );expect(updatedDescription).toBe("New description");});- test("persists asset metadata via patch", async () => {+ test("requires build access to patch collection configuration assets", async () => {const projectId = uid();- let localAssetRow = {+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configRow = {...assetRow,+ assetId: "config",projectId,+ filename: "collection",+ folderId: "posts",file: {...assetRow.file,- name: "font.woff2",- format: "woff2",- meta: JSON.stringify({- family: "Rajdhani",- style: "normal",- weight: 400,- }),+ name: "config-storage.json",+ format: "json",+ size: configSource.length,},};- let updatedMeta: unknown;-+ const templateRow = {+ ...assetRow,+ assetId: "template",+ projectId,+ filename: "template",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "template-storage.mdx",+ format: "mdx",+ size: templateSource.length,+ },+ };+ let metadataUpdated = false;server.use(- ownershipHandler,- db.get("Asset", () => json([localAssetRow])),- db.patch("File", async ({ request }) => {- updatedMeta = ((await request.json()) as { meta: unknown }).meta;- localAssetRow = {- ...localAssetRow,- file: { ...localAssetRow.file, meta: String(updatedMeta) },- };- return json({ meta: updatedMeta });+ db.get("Project", ({ request }) => {+ const url = new URL(request.url);+ return url.searchParams.has("userId")+ ? json(null)+ : json({ id: projectId, userId: "owner-1" });+ }),+ db.get("WorkspaceProjectAuthorization", () =>+ json([{ relation: "editors" }])+ ),+ db.get("Asset", () => json([configRow, templateRow])),+ db.patch("Asset", () => {+ metadataUpdated = true;+ return json({ id: "template" });}));- await patchAssets(- { projectId },- [+ await expect(+ patchAssets({- op: "replace",- path: ["asset-1", "meta"],- value: { family: "Rajdhani", style: "normal", weight: 600 },+ projectId,+ assetStore: createSourceAssetStore({+ [configRow.file.name]: configSource,+ [templateRow.file.name]: templateSource,+ }),},- ],- createContext()- );-- expect(updatedMeta).toBe(- JSON.stringify({ family: "Rajdhani", style: "normal", weight: 600 })- );- await expect(- loadAssetsByProjectWithClient(projectId, testContext.postgrest.client)- ).resolves.toEqual([- expect.objectContaining({- id: "asset-1",- meta: { family: "Rajdhani", style: "normal", weight: 600 },- }),- ]);+ [+ {+ op: "replace",+ path: ["template", "description"],+ value: "Reserved",+ },+ ],+ createContext()+ )+ ).rejects.toThrow("permission to configure");+ expect(metadataUpdated).toBe(false);});- test("updates asset filename via patch", async () => {+ test("rejects mismatched asset map keys before collection authorization", async () => {const projectId = uid();- let localAssetRow = { ...assetRow, projectId };- let updatedFilename: string | undefined;-+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configFile = {+ ...assetRow.file,+ name: "config-storage.json",+ format: "json",+ size: configSource.length,+ meta: "{}",+ updatedAt: "2026-09-03T00:00:00.000Z",+ isDeleted: true,+ };+ const templateRow = {+ ...assetRow,+ assetId: "template",+ projectId,+ filename: "template",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "template-storage.mdx",+ format: "mdx",+ size: templateSource.length,+ meta: "{}",+ },+ };+ let inserted = false;server.use(- ownershipHandler,- db.get("Asset", () => json([localAssetRow])),- db.get("AssetFileMetadata", () => json([])),- db.patch("Asset", async ({ request }) => {- const body = (await request.json()) as { filename?: string };- updatedFilename = body.filename;- localAssetRow = {- ...localAssetRow,- filename: body.filename ?? localAssetRow.filename,- };- return json({- id: localAssetRow.assetId,- filename: localAssetRow.filename,- description: localAssetRow.description,- });+ ...editorPermitHandlers(projectId),+ db.get("Asset", () => json([templateRow])),+ db.get("File", () => json([configFile])),+ db.patch("File", () => empty({ status: 204 })),+ db.post("Asset", () => {+ inserted = true;+ return empty({ status: 201 });}));- const patches: Patch[] = [- {- op: "replace",- path: ["asset-1", "filename"],- value: "renamed-photo.jpg",- },- ];-- await patchAssets({ projectId }, patches, createContext());- expect(updatedFilename).toBe("renamed-photo.jpg");await expect(- loadAssetsByProjectWithClient(projectId, testContext.postgrest.client)- ).resolves.toEqual([- expect.objectContaining({- id: "asset-1",- filename: "renamed-photo.jpg",- }),- ]);- });-- test("atomically swaps an asset file while preserving its id", async () => {- const projectId = uid();- const localAssetRow = { ...assetRow, projectId };- let swapInput: unknown;+ patchAssets(+ {+ projectId,+ assetStore: createSourceAssetStore({+ [configFile.name]: configSource,+ [templateRow.file.name]: templateSource,+ }),+ },+ [+ {+ op: "add",+ path: ["forged-map-key"],+ value: {+ id: "config",+ projectId,+ name: configFile.name,+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: configFile.createdAt,+ meta: {},+ },+ },+ ],+ createContext()+ )+ ).rejects.toThrow("does not match its map key");+ expect(inserted).toBe(false);+ });++ test("validates collection moves with authoritative file metadata", async () => {+ const projectId = uid();+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = ["*"];+ const configSource = JSON.stringify(schema);+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const entrySource =+ "---\ntitle: Hello world\nslug: hello-world\ndraft: true\n---\n\nBody.\n";+ const configRow = {+ ...assetRow,+ assetId: "config",+ projectId,+ filename: "collection",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "config-storage.json",+ format: "json",+ size: configSource.length,+ meta: "{}",+ },+ };+ const templateRow = {+ ...assetRow,+ assetId: "template",+ projectId,+ filename: "template",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "template-storage.mdx",+ format: "mdx",+ size: templateSource.length,+ meta: "{}",+ },+ };+ const textEntryRow = {+ ...assetRow,+ assetId: "entry",+ projectId,+ filename: "hello-world",+ folderId: null,+ file: {+ ...assetRow.file,+ name: "entry-storage.txt",+ format: "txt",+ size: entrySource.length,+ meta: "{}",+ },+ };+ let metadataUpdated = false;+ server.use(+ ownershipHandler,+ db.get("Asset", () => json([configRow, templateRow, textEntryRow])),+ db.patch("Asset", () => {+ metadataUpdated = true;+ return json({ id: "entry" });+ })+ );++ await expect(+ patchAssets(+ {+ projectId,+ assetStore: createSourceAssetStore({+ [configRow.file.name]: configSource,+ [templateRow.file.name]: templateSource,+ [textEntryRow.file.name]: entrySource,+ }),+ },+ [+ { op: "replace", path: ["entry", "format"], value: "mdx" },+ { op: "add", path: ["entry", "folderId"], value: "posts" },+ ],+ createContext()+ )+ ).rejects.toThrow('Collection entry "hello-world.txt" must be an MDX file');+ expect(metadataUpdated).toBe(false);+ });++ test("restores a valid collection entry through a sync patch", async () => {+ const projectId = uid();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const entrySource =+ "---\ntitle: Hello world\nslug: hello-world\ndraft: true\n---\n\nBody.\n";+ const configRow = {+ ...assetRow,+ assetId: "config",+ projectId,+ filename: "collection",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "config-storage.json",+ format: "json",+ size: configSource.length,+ },+ };+ const templateRow = {+ ...assetRow,+ assetId: "template",+ projectId,+ filename: "template",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "template-storage.mdx",+ format: "mdx",+ size: templateSource.length,+ },+ };+ const entryFile = {+ ...assetRow.file,+ name: "entry-storage.mdx",+ format: "mdx",+ size: entrySource.length,+ meta: "{}",+ updatedAt: "2026-09-03T00:00:00.000Z",+ };+ const invalidEntryFile = {+ ...entryFile,+ name: "invalid-entry-storage.mdx",+ };+ let inserted = false;+ const entryPatch: Patch[] = [+ {+ op: "add",+ path: ["entry"],+ value: {+ id: "entry",+ projectId,+ name: "entry-storage.mdx",+ filename: "hello-world",+ folderId: "posts",+ type: "file",+ format: "mdx",+ size: entrySource.length,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ },+ },+ ];+ const invalidEntryPatch: Patch[] = [+ {+ op: "add",+ path: ["invalid-entry"],+ value: {+ id: "invalid-entry",+ projectId,+ name: "invalid-entry-storage.mdx",+ filename: "different-slug",+ folderId: "posts",+ type: "file",+ format: "mdx",+ size: entrySource.length,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ },+ },+ ];+ server.use(+ ...editorPermitHandlers(projectId),+ db.get("Asset", () => json([configRow, templateRow])),+ db.get("File", ({ request }) => {+ const url = new URL(request.url);+ expect(url.searchParams.get("status")).toBe("eq.UPLOADED");+ const filter = url.searchParams.get("name") ?? "";+ return json(+ [entryFile, invalidEntryFile].filter(({ name }) =>+ filter.includes(name)+ )+ );+ }),+ db.patch("File", () => empty({ status: 204 })),+ db.post("Asset", () => {+ inserted = true;+ return empty({ status: 201 });+ })+ );++ await expect(+ patchAssets(+ {+ projectId,+ assetStore: createSourceAssetStore({+ [configRow.file.name]: configSource,+ [templateRow.file.name]: templateSource,+ "entry-storage.mdx": entrySource,+ "invalid-entry-storage.mdx": entrySource,+ }),+ },+ invalidEntryPatch,+ createContext()+ )+ ).rejects.toThrow("slug must match the entry filename");+ expect(inserted).toBe(false);++ await expect(+ patchAssets(+ {+ projectId,+ assetStore: createSourceAssetStore({+ [configRow.file.name]: configSource,+ [templateRow.file.name]: templateSource,+ "entry-storage.mdx": entrySource,+ }),+ },+ entryPatch,+ createContext()+ )+ ).resolves.toBeUndefined();+ expect(inserted).toBe(true);+ });++ test("moves a valid entry back into its collection through a sync patch", async () => {+ const projectId = uid();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const entrySource =+ "---\ntitle: Hello world\nslug: hello-world\ndraft: true\n---\n\nBody.\n";+ const configRow = {+ ...assetRow,+ assetId: "config",+ projectId,+ filename: "collection",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "config-storage.json",+ format: "json",+ size: configSource.length,+ },+ };+ const templateRow = {+ ...assetRow,+ assetId: "template",+ projectId,+ filename: "template",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "template-storage.mdx",+ format: "mdx",+ size: templateSource.length,+ },+ };+ const entryRow = {+ ...assetRow,+ assetId: "entry",+ projectId,+ filename: "hello-world",+ folderId: null,+ file: {+ ...assetRow.file,+ name: "entry-storage.mdx",+ format: "mdx",+ size: entrySource.length,+ },+ };+ let folderId: unknown;+ server.use(+ ...editorPermitHandlers(projectId),+ db.get("Asset", () => json([configRow, templateRow, entryRow])),+ db.patch("Asset", async ({ request }) => {+ folderId = ((await request.json()) as { folderId: unknown }).folderId;+ return json({ id: "entry" });+ })+ );++ await expect(+ patchAssets(+ {+ projectId,+ assetStore: createSourceAssetStore({+ [configRow.file.name]: configSource,+ [templateRow.file.name]: templateSource,+ [entryRow.file.name]: entrySource,+ }),+ },+ [{ op: "add", path: ["entry", "folderId"], value: "posts" }],+ createContext()+ )+ ).resolves.toBeUndefined();+ expect(folderId).toBe("posts");+ });++ test("allows invalid collection entries to be repaired one at a time", async () => {+ const projectId = uid();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const invalidEntrySource = "---\nslug: missing-title\ndraft: true\n---\n";+ const configRow = {+ ...assetRow,+ assetId: "config",+ projectId,+ filename: "collection",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "config-storage.json",+ format: "json",+ size: configSource.length,+ },+ };+ const templateRow = {+ ...assetRow,+ assetId: "template",+ projectId,+ filename: "template",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "template-storage.mdx",+ format: "mdx",+ size: templateSource.length,+ },+ };+ const firstEntryRow = {+ ...assetRow,+ assetId: "first-entry",+ projectId,+ filename: "missing-title",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "first-entry-storage.mdx",+ format: "mdx",+ size: invalidEntrySource.length,+ },+ };+ const secondEntryRow = {+ ...assetRow,+ assetId: "second-entry",+ projectId,+ filename: "also-missing-title",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "second-entry-storage.mdx",+ format: "mdx",+ size: invalidEntrySource.length,+ },+ };+ let updatedFolderId: unknown = "not-updated";+ server.use(+ ownershipHandler,+ db.get("Asset", () =>+ json([configRow, templateRow, firstEntryRow, secondEntryRow])+ ),+ db.patch("Asset", async ({ request }) => {+ updatedFolderId = ((await request.json()) as { folderId: unknown })+ .folderId;+ return json({ id: "first-entry", folderId: null });+ })+ );++ await expect(+ patchAssets(+ {+ projectId,+ assetStore: createSourceAssetStore({+ [configRow.file.name]: configSource,+ [templateRow.file.name]: templateSource,+ [firstEntryRow.file.name]: invalidEntrySource,+ [secondEntryRow.file.name]: invalidEntrySource,+ }),+ },+ [{ op: "remove", path: ["first-entry", "folderId"] }],+ createContext()+ )+ ).resolves.toBeUndefined();+ expect(updatedFolderId).toBeNull();+ });++ test("renames supporting assets without validating unchanged entry content", async () => {+ const projectId = uid();+ const configSource = createDefaultCollectionConfig();+ const templateSource = "---\ndraft: true\n---\n";+ const row = (+ id: string,+ filename: string,+ format: string,+ source: string+ ) => ({+ ...assetRow,+ assetId: id,+ projectId,+ filename,+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: `${id}.${format}`,+ format,+ size: source.length,+ },+ });+ const rows = [+ row("config", "collection", "json", configSource),+ row("template", "template", "mdx", templateSource),+ row("invalid", "invalid", "mdx", "missing frontmatter"),+ row("notes", "notes", "txt", "notes"),+ ];+ let filename: unknown;+ server.use(+ ownershipHandler,+ db.get("Asset", () => json(rows)),+ db.patch("Asset", async ({ request }) => {+ filename = ((await request.json()) as { filename: unknown }).filename;+ return json({ id: "notes" });+ })+ );+ const assetStore = createSourceAssetStore({+ "config.json": configSource,+ "template.mdx": templateSource,+ // Neither ordinary content nor unchanged entries should be read.+ });+ await patchAssets(+ { projectId, assetStore },+ [{ op: "replace", path: ["notes", "filename"], value: "renamed" }],+ createContext()+ );+ expect(filename).toBe("renamed");+ await expect(+ patchAssets(+ { projectId, assetStore },+ [+ {+ op: "replace",+ path: ["invalid", "filename"],+ value: "changed-entry",+ },+ ],+ createContext()+ )+ ).rejects.toThrow();+ });++ test("validates collection rules before persisting an asset patch", async () => {+ const projectId = uid();+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = ["*"];+ const configSource = JSON.stringify(schema);+ const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";+ const configRow = {+ ...assetRow,+ assetId: "config",+ projectId,+ filename: "collection",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "config-storage.json",+ format: "json",+ size: configSource.length,+ },+ };+ const templateRow = {+ ...assetRow,+ assetId: "template",+ projectId,+ filename: "template",+ folderId: "posts",+ file: {+ ...assetRow.file,+ name: "template-storage.mdx",+ format: "mdx",+ size: templateSource.length,+ },+ };+ let inserted = false;+ server.use(+ ownershipHandler,+ db.get("Asset", () => json([])),+ db.get("File", () =>+ json([+ {+ ...configRow.file,+ meta: "{}",+ updatedAt: "2026-09-03T00:00:00.000Z",+ },+ {+ ...templateRow.file,+ meta: "{}",+ updatedAt: "2026-09-03T00:00:00.000Z",+ },+ {+ ...assetRow.file,+ name: "notes.txt",+ format: "txt",+ size: 5,+ meta: "{}",+ updatedAt: "2026-09-03T00:00:00.000Z",+ },+ ])+ ),+ db.post("Asset", () => {+ inserted = true;+ return empty({ status: 201 });+ })+ );++ await expect(+ patchAssets(+ {+ projectId,+ assetStore: createSourceAssetStore({+ [configRow.file.name]: configSource,+ [templateRow.file.name]: templateSource,+ }),+ },+ [+ {+ op: "add",+ path: ["config"],+ value: {+ id: "config",+ projectId,+ name: configRow.file.name,+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: configSource.length,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ },+ },+ {+ op: "add",+ path: ["template"],+ value: {+ id: "template",+ projectId,+ name: templateRow.file.name,+ filename: "template",+ folderId: "posts",+ type: "file",+ format: "mdx",+ size: templateSource.length,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ },+ },+ {+ op: "add",+ path: ["notes"],+ value: {+ id: "notes",+ projectId,+ name: "notes.txt",+ filename: "notes",+ folderId: "posts",+ type: "file",+ format: "txt",+ size: 5,+ description: null,+ createdAt: "2026-09-03T00:00:00.000Z",+ meta: {},+ },+ },+ ],+ createContext()+ )+ ).rejects.toThrow('Collection entry "notes.txt" must be an MDX file');+ expect(inserted).toBe(false);+ });++ test("persists legacy null-provenance asset metadata via patch", async () => {+ const projectId = uid();+ let localAssetRow = {+ ...assetRow,+ projectId,+ file: {+ ...assetRow.file,+ name: "font.woff2",+ format: "woff2",+ meta: JSON.stringify({+ family: "Rajdhani",+ style: "normal",+ weight: 400,+ }),+ uploaderProjectId: null,+ },+ };+ let updatedMeta: unknown;++ server.use(+ ownershipHandler,+ db.get("Asset", () => json([localAssetRow])),+ db.get("File", () => json([localAssetRow.file])),+ db.patch("File", async ({ request }) => {+ updatedMeta = ((await request.json()) as { meta: unknown }).meta;+ localAssetRow = {+ ...localAssetRow,+ file: { ...localAssetRow.file, meta: String(updatedMeta) },+ };+ return json({ meta: updatedMeta });+ })+ );++ await patchAssets(+ { projectId, assetStore: unusedAssetStore },+ [+ {+ op: "replace",+ path: ["asset-1", "meta"],+ value: { family: "Rajdhani", style: "normal", weight: 600 },+ },+ ],+ createContext()+ );++ expect(updatedMeta).toBe(+ JSON.stringify({ family: "Rajdhani", style: "normal", weight: 600 })+ );+ await expect(+ loadAssetsByProjectWithClient(projectId, testContext.postgrest.client)+ ).resolves.toEqual([+ expect.objectContaining({+ id: "asset-1",+ meta: { family: "Rajdhani", style: "normal", weight: 600 },+ }),+ ]);+ });++ test("updates asset filename via patch", async () => {+ const projectId = uid();+ let localAssetRow = { ...assetRow, projectId };+ let updatedFilename: string | undefined;++ server.use(+ ownershipHandler,+ db.get("Asset", () => json([localAssetRow])),+ db.get("AssetFileMetadata", () => json([])),+ db.patch("Asset", async ({ request }) => {+ const body = (await request.json()) as { filename?: string };+ updatedFilename = body.filename;+ localAssetRow = {+ ...localAssetRow,+ filename: body.filename ?? localAssetRow.filename,+ };+ return json({+ id: localAssetRow.assetId,+ filename: localAssetRow.filename,+ description: localAssetRow.description,+ });+ })+ );++ const patches: Patch[] = [+ {+ op: "replace",+ path: ["asset-1", "filename"],+ value: "renamed-photo.jpg",+ },+ ];++ await patchAssets(+ { projectId, assetStore: unusedAssetStore },+ patches,+ createContext()+ );+ expect(updatedFilename).toBe("renamed-photo.jpg");+ await expect(+ loadAssetsByProjectWithClient(projectId, testContext.postgrest.client)+ ).resolves.toEqual([+ expect.objectContaining({+ id: "asset-1",+ filename: "renamed-photo.jpg",+ }),+ ]);+ });++ test("atomically swaps an asset file while preserving its id", async () => {+ const projectId = uid();+ const localAssetRow = { ...assetRow, projectId };+ let swapInput: unknown;server.use(ownershipHandler,db.get("Asset", () => json([localAssetRow])),@@ -856,6 +1869,151 @@ describe("patchAssets (msw)", () => {});});+ test("restores a shared clone file without requiring an owned revision", async () => {+ const projectId = uid();+ const sourceProjectId = uid();+ const authoritativeMeta = { width: 1200, height: 800 };+ const forgedMeta = { width: 9999, height: 9999 };+ const staleMeta = { width: 320, height: 200 };+ const sharedFile = {+ ...assetRow.file,+ name: "original_shared.jpg",+ format: "jpg",+ size: 2000,+ meta: JSON.stringify(authoritativeMeta),+ uploaderProjectId: sourceProjectId,+ contentHash: "a".repeat(64),+ isDeleted: false,+ updatedAt: "2026-09-06T00:00:00.000Z",+ };+ const currentFile = {+ ...sharedFile,+ name: "current_clone.jpg",+ size: 1000,+ meta: JSON.stringify(staleMeta),+ uploaderProjectId: projectId,+ contentHash: "f".repeat(64),+ };+ let persistedFile = currentFile;+ let persistedSharedMeta = sharedFile.meta;+ let fileMetadataUpdates = 0;+ const restoredFiles: string[] = [];+ const directSwapInputs: Array<Record<string, unknown>> = [];+ const swapInputs: Array<Record<string, unknown>> = [];+ server.use(+ ownershipHandler,+ db.get("Asset", () =>+ json([+ {+ ...assetRow,+ assetId: "entry",+ projectId,+ filename: "post",+ folderId: null,+ file: persistedFile,+ },+ ])+ ),+ db.get("File", ({ request }) => {+ const url = new URL(request.url);+ const nameFilter = url.searchParams.get("name") ?? "";+ if (nameFilter.includes(sharedFile.name)) {+ return json([{ ...sharedFile, meta: persistedSharedMeta }]);+ }+ return json([]);+ }),+ db.patch("File", async ({ request }) => {+ const url = new URL(request.url);+ const name = url.searchParams.get("name") ?? "";+ const input = (await request.json()) as Record<string, unknown>;+ if (Object.hasOwn(input, "isDeleted")) {+ expect(url.searchParams.get("status")).toBe("eq.UPLOADED");+ expect(input).toEqual({ isDeleted: false });+ restoredFiles.push(name);+ return json({ name: sharedFile.name });+ }+ if (typeof input.meta === "string") {+ fileMetadataUpdates += 1;+ persistedSharedMeta = input.meta;+ return json({ meta: input.meta });+ }+ return json(null);+ }),+ db.patch("Asset", async ({ request }) => {+ const url = new URL(request.url);+ expect(url.searchParams.get("id")).toBe("eq.entry");+ expect(url.searchParams.get("projectId")).toBe(`eq.${projectId}`);+ expect(url.searchParams.get("name")).toBe(`eq.${currentFile.name}`);+ const input = (await request.json()) as Record<string, unknown>;+ directSwapInputs.push(input);+ if (input.name !== sharedFile.name) {+ return json(null);+ }+ persistedFile = sharedFile;+ return json({ id: "entry" });+ }),+ http.post(+ "http://test-postgrest/rpc/swap_asset_file",+ async ({ request }) => {+ const input = (await request.json()) as Record<string, unknown>;+ swapInputs.push(input);+ return HttpResponse.json("invalid_revision");+ }+ )+ );+ const assetStore = {+ readFile: async () => {+ throw new Error("Unexpected asset content read");+ },+ };+ const patches: Patch[] = [+ {+ op: "replace",+ path: ["entry", "name"],+ value: sharedFile.name,+ },+ {+ op: "replace",+ path: ["entry", "meta"],+ value: authoritativeMeta,+ },+ ];++ await expect(+ patchAssets(+ { projectId, assetStore },+ [+ patches[0]!,+ {+ op: "replace",+ path: ["entry", "meta"],+ value: forgedMeta,+ },+ ],+ createContext()+ )+ ).rejects.toThrow("Shared asset metadata does not match its file");+ expect(restoredFiles).toEqual([]);+ expect(directSwapInputs).toEqual([]);+ expect(swapInputs).toEqual([]);+ expect(persistedSharedMeta).toBe(sharedFile.meta);+ expect(persistedFile).toEqual(currentFile);++ await patchAssets({ projectId, assetStore }, patches, createContext());+ await patchAssets({ projectId, assetStore }, patches, createContext());++ expect(restoredFiles).toEqual([`eq.${sharedFile.name}`]);+ expect(directSwapInputs).toEqual([+ {+ name: sharedFile.name,+ },+ ]);+ expect(swapInputs).toEqual([]);+ expect(persistedFile).toEqual(sharedFile);+ expect(persistedSharedMeta).toBe(sharedFile.meta);+ expect(fileMetadataUpdates).toBe(0);+ });+test("persists moving an asset to root as null", async () => {const projectId = uid();let localAssetRow = {@@ -895,7 +2053,7 @@ describe("patchAssets (msw)", () => {);await patchAssets(- { projectId },+ { projectId, assetStore: unusedAssetStore },[{ op: "remove", path: ["asset-1", "folderId"] }],createContext());@@ -924,7 +2082,7 @@ describe("patchAssets (msw)", () => {testContext.postgrest.client);await patchAssets(- { projectId },+ { projectId, assetStore: unusedAssetStore },[{ op: "add", path: [asset.id], value: asset }],createContext());@@ -952,7 +2110,7 @@ describe("patchAssets (msw)", () => {await expect(patchAssets(- { projectId },+ { projectId, assetStore: unusedAssetStore },[{op: "replace",@@ -980,7 +2138,18 @@ describe("patchAssets (msw)", () => {return json([]);}),// File lookup for undo restore- db.get("File", () => json([{ name: "new.jpg" }])),+ db.get("File", () =>+ json([+ {+ ...assetRow.file,+ name: "new.jpg",+ format: "jpg",+ size: 500,+ meta: JSON.stringify({ width: 50, height: 50 }),+ updatedAt: "2024-01-01T00:00:00.000Z",+ },+ ])+ ),// restore isDeleted=falsedb.patch("File", () => empty({ status: 204 })),// asset insert@@ -1009,7 +2178,11 @@ describe("patchAssets (msw)", () => {},];- await patchAssets({ projectId }, patches, createContext());+ await patchAssets(+ { projectId, assetStore: unusedAssetStore },+ patches,+ createContext()+ );expect(insertedAssets).toBeDefined();});@@ -1056,6 +2229,146 @@ describe("patchAssets (msw)", () => {expect(inserted).toBe(false);});+ test("rejects an added asset whose file is not fully uploaded", async () => {+ const projectId = uid();+ let restored = false;+ let inserted = false;+ server.use(+ ownershipHandler,+ db.get("Asset", () => json([])),+ db.get("File", ({ request }) => {+ expect(new URL(request.url).searchParams.get("status")).toBe(+ "eq.UPLOADED"+ );+ return json([+ {+ ...assetRow.file,+ name: "uploading.jpg",+ status: "UPLOADING",+ },+ ]);+ }),+ db.patch("File", () => {+ restored = true;+ return empty({ status: 204 });+ }),+ db.post("Asset", () => {+ inserted = true;+ return empty({ status: 201 });+ })+ );++ await expect(+ patchAssets(+ { projectId, assetStore: unusedAssetStore },+ [+ {+ op: "add",+ path: ["uploading"],+ value: {+ id: "uploading",+ name: "uploading.jpg",+ type: "image",+ projectId,+ format: "jpg",+ size: 1000,+ description: null,+ createdAt: "2024-01-01T00:00:00.000Z",+ meta: { width: 100, height: 100 },+ },+ },+ ],+ createContext()+ )+ ).rejects.toThrow("Asset file not found");+ expect(restored).toBe(false);+ expect(inserted).toBe(false);+ });++ test("chunks uploaded file lookups and restores by bounded filter size", async () => {+ const projectId = uid();+ const fileNames = Array.from(+ { length: 12 },+ (_, index) => `${String(index).padStart(2, "0")}-${"a".repeat(490)}.jpg`+ );+ const assetFileNames = [...fileNames, fileNames[0]!];+ const fileByName = new Map(+ fileNames.map((name) => [+ name,+ {+ ...assetRow.file,+ name,+ status: "UPLOADED",+ },+ ])+ );+ const readBatches: string[][] = [];+ const restoreBatches: string[][] = [];+ const getNames = (request: Request) => {+ const url = new URL(request.url);+ expect(url.search.length).toBeLessThan(4300);+ expect(url.searchParams.get("status")).toBe("eq.UPLOADED");+ const filter = url.searchParams.get("name");+ expect(filter?.startsWith("in.(")).toBe(true);+ return filter?.slice(4, -1).split(",") ?? [];+ };+ server.use(+ ownershipHandler,+ db.get("Asset", () => json([])),+ db.get("File", ({ request }) => {+ const names = getNames(request);+ readBatches.push(names);+ return json(+ names.flatMap((name) => {+ const file = fileByName.get(name);+ return file === undefined ? [] : [file];+ })+ );+ }),+ db.patch("File", ({ request }) => {+ restoreBatches.push(getNames(request));+ return empty({ status: 204 });+ }),+ db.post("Asset", () => empty({ status: 201 }))+ );++ await patchAssets(+ { projectId, assetStore: unusedAssetStore },+ assetFileNames.map((name, index) => ({+ op: "add" as const,+ path: [`asset-${index}`],+ value: {+ id: `asset-${index}`,+ name,+ type: "image" as const,+ projectId,+ format: "jpg",+ size: 1000,+ description: null,+ createdAt: "2024-01-01T00:00:00.000Z",+ meta: { width: 100, height: 100 },+ },+ })),+ createContext()+ );++ expect(readBatches.length).toBeGreaterThan(2);+ expect(restoreBatches.length).toBeGreaterThan(1);+ expect(readBatches.every((batch) => batch.length < fileNames.length)).toBe(+ true+ );+ expect(+ restoreBatches.every((batch) => batch.length < fileNames.length)+ ).toBe(true);+ expect(new Set(readBatches.flat())).toEqual(new Set(fileNames));+ expect(new Set(restoreBatches.flat())).toEqual(new Set(fileNames));+ expect(+ [...readBatches, ...restoreBatches].every(+ (batch) => new Set(batch).size === batch.length+ )+ ).toBe(true);+ });+test("core helper deletes assets and marks unused files as deleted", async () => {const projectId = uid();const localAssetRow = { ...assetRow, projectId };diff --git a/packages/asset-uploader/src/patch.ts b/packages/asset-uploader/src/patch.tsindex dda24346e7..c147f62c38 100644--- a/packages/asset-uploader/src/patch.ts+++ b/packages/asset-uploader/src/patch.ts@@ -2,15 +2,173 @@ import type { Patch } from "immer";import {type AppContext,authorizeProject,+ AuthorizationError,} from "@webstudio-is/trpc-interface/index.server";+import { collectionConfigFilename } from "@webstudio-is/content-engine";+import { formatAssetName, type Asset } from "@webstudio-is/sdk";import { patchAssetsWithClient } from "./asset-patch-core";+import type { AssetObjectReader } from "./client";+import {+ getCollectionFolderIds,+ getCollectionReservedAssetIds,+ validateCollectionFolder,+} from "./collection-persistence";++const collectionAssetChanged = (+ previous: Asset | undefined,+ next: Asset | undefined+) =>+ previous?.name !== next?.name ||+ previous?.filename !== next?.filename ||+ previous?.folderId !== next?.folderId;++const assetChanged = (previous: Asset | undefined, next: Asset | undefined) =>+ collectionAssetChanged(previous, next) ||+ previous?.description !== next?.description ||+ JSON.stringify(previous?.meta) !== JSON.stringify(next?.meta);++const validateCollectionAssetPatch = async ({+ current,+ next,+ assetStore,+ canBuild,+}: {+ current: ReadonlyMap<Asset["id"], Asset>;+ next: ReadonlyMap<Asset["id"], Asset>;+ assetStore: AssetObjectReader;+ canBuild: boolean;+}) => {+ const currentAssets = Array.from(current.values());+ const nextAssets = Array.from(next.values());+ const currentCollectionFolderIds = getCollectionFolderIds(currentAssets);+ const nextCollectionFolderIds = getCollectionFolderIds(nextAssets);+ const changedIds = new Set(+ [...current.keys(), ...next.keys()].filter((assetId) =>+ assetChanged(current.get(assetId), next.get(assetId))+ )+ );+ const collectionChangedIds = new Set(+ [...current.keys(), ...next.keys()].filter((assetId) =>+ collectionAssetChanged(current.get(assetId), next.get(assetId))+ )+ );+ const affectedCollectionFolderIds = new Set<string>();+ for (const assetId of changedIds) {+ const previous = current.get(assetId);+ const following = next.get(assetId);+ if (+ previous?.folderId !== undefined &&+ currentCollectionFolderIds.has(previous.folderId)+ ) {+ affectedCollectionFolderIds.add(previous.folderId);+ }+ if (+ following?.folderId !== undefined &&+ nextCollectionFolderIds.has(following.folderId)+ ) {+ affectedCollectionFolderIds.add(following.folderId);+ }+ }+ const collectionValidationFolderIds = new Set<string>();+ for (const assetId of collectionChangedIds) {+ const following = next.get(assetId);+ if (+ following?.folderId !== undefined &&+ nextCollectionFolderIds.has(following.folderId)+ ) {+ collectionValidationFolderIds.add(following.folderId);+ }+ }+ const changesCollectionConfig = Array.from(changedIds).some((assetId) => {+ const previous = current.get(assetId);+ const following = next.get(assetId);+ return (+ (previous !== undefined &&+ formatAssetName(previous) === collectionConfigFilename) ||+ (following !== undefined &&+ formatAssetName(following) === collectionConfigFilename)+ );+ });+ if (+ affectedCollectionFolderIds.size === 0 &&+ changesCollectionConfig === false+ ) {+ return;+ }++ const [currentReservedIds, nextReservedIds] = await Promise.all([+ getCollectionReservedAssetIds({+ assets: currentAssets,+ assetStore,+ folderIds: affectedCollectionFolderIds,+ }),+ getCollectionReservedAssetIds({+ assets: nextAssets,+ assetStore,+ folderIds: affectedCollectionFolderIds,+ }),+ ]);+ for (const assetId of collectionChangedIds) {+ const previous = current.get(assetId);+ if (+ previous?.folderId !== undefined &&+ currentCollectionFolderIds.has(previous.folderId) &&+ currentReservedIds.has(assetId)+ ) {+ collectionValidationFolderIds.add(previous.folderId);+ }+ }+ if (+ canBuild === false &&+ Array.from(changedIds).some(+ (assetId) =>+ currentReservedIds.has(assetId) || nextReservedIds.has(assetId)+ )+ ) {+ throw new AuthorizationError(+ "You don't have permission to configure this project collections."+ );+ }++ // The public upload and metadata APIs require the dedicated New entry flow.+ // New, renamed, and incoming entries still require validation. Existing+ // entries can be saved and repaired incrementally after a schema change.+ for (const folderId of collectionValidationFolderIds) {+ if (nextCollectionFolderIds.has(folderId)) {+ await validateCollectionFolder({+ assets: nextAssets,+ folderId,+ assetStore,+ entryIdsToValidate: currentCollectionFolderIds.has(folderId)+ ? new Set(+ Array.from(collectionChangedIds).filter((id) => {+ const previous = current.get(id);+ const following = next.get(id);+ return (+ previous === undefined ||+ previous.folderId !== following?.folderId ||+ formatAssetName(previous) !==+ (following === undefined+ ? undefined+ : formatAssetName(following))+ );+ })+ )+ : undefined,+ });+ }+ }+};/*** patchAssets applies asset metadata updates, deletions, and undo restores after* the app layer confirms project edit access.*/export const patchAssets = async (- { projectId }: { projectId: string },+ {+ projectId,+ assetStore,+ }: { projectId: string; assetStore: AssetObjectReader },patches: Array<Patch>,context: AppContext): Promise<void> => {@@ -22,8 +180,25 @@ export const patchAssets = async (throw new Error("You don't have edit access to this project");}+ const canBuild = await authorizeProject.hasProjectPermit(+ { projectId, permit: "build" },+ context+ );+await patchAssetsWithClient({ projectId, client: context.postgrest.client },- patches+ patches,+ {+ // Undo in cloned projects can target a File row retained from the source+ // project. This path is enabled only after the edit permit check above.+ allowSharedFileRestore: true,+ validate: async ({ current, next }) =>+ validateCollectionAssetPatch({+ current,+ next,+ assetStore,+ canBuild,+ }),+ });};diff --git a/packages/asset-uploader/src/publication.test.ts b/packages/asset-uploader/src/publication.test.tsindex c9fdff8a29..824c58f80d 100644--- a/packages/asset-uploader/src/publication.test.ts+++ b/packages/asset-uploader/src/publication.test.ts@@ -1,7 +1,219 @@import { describe, expect, test, vi } from "vitest";-import { preparePublishedAssetData } from "./publication";+import { createDefaultCollectionConfig } from "@webstudio-is/content-engine";+import type { Asset } from "@webstudio-is/sdk";+import {+ preparePublishedAssetData,+ validatePublishedAssetCollections,+} from "./publication";++const createCollectionFixture = () => {+ const configSource = createDefaultCollectionConfig();+ const baseAsset: Asset = {+ id: "config",+ projectId: "project-1",+ name: "config-storage.json",+ filename: "collection",+ folderId: "posts",+ type: "file",+ format: "json",+ size: new TextEncoder().encode(configSource).byteLength,+ description: null,+ createdAt: "2026-09-06T00:00:00.000Z",+ meta: {},+ };+ const configAsset = baseAsset;+ const templateAsset: Asset = {+ ...baseAsset,+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ };+ const entryAsset: Asset = {+ ...templateAsset,+ id: "entry",+ name: "entry-storage.mdx",+ filename: "hello-world",+ };+ const imageAsset: Asset = {+ ...baseAsset,+ id: "image",+ name: "image-storage.png",+ filename: "image",+ folderId: undefined,+ type: "image",+ format: "png",+ meta: { width: 100, height: 100 },+ };+ const assetData = {+ assets: [configAsset, templateAsset, entryAsset, imageAsset],+ assetFolders: [{ id: "posts" }],+ };+ const assetStore = {+ readFile: vi.fn(async (name: string) => {+ if (name !== configAsset.name) {+ throw new Error(`Unexpected asset read: ${name}`);+ }+ return {+ data: new Blob([configSource]).stream(),+ contentLength: configAsset.size,+ };+ }),+ uploadFile: vi.fn(),+ };+ return { assetData, assetStore };+};describe("published asset data", () => {+ test("omits collection configuration and templates from public validation output", async () => {+ const { assetData, assetStore } = createCollectionFixture();+ const validateCollections = vi.fn();+ const dependencies = {+ createRepository: vi.fn(() => ({ validateCollections })),+ loadAssetDataByProject: vi.fn().mockResolvedValue(assetData),+ };++ const publicResult = await validatePublishedAssetCollections(+ {+ projectId: "project-1",+ context: { apiClient: { type: "service" } } as never,+ assetStore: assetStore as never,+ },+ dependencies as never+ );+ expect(publicResult.assets.map(({ id }) => id)).toEqual(["entry", "image"]);++ const authenticatedResult = await validatePublishedAssetCollections(+ {+ projectId: "project-1",+ context: { apiClient: { type: "cli" } } as never,+ assetStore: assetStore as never,+ },+ dependencies as never+ );+ expect(authenticatedResult.assets).toEqual(assetData.assets);+ expect(validateCollections).toHaveBeenCalledWith(assetData.assets);+ expect(assetStore.readFile).toHaveBeenCalledOnce();+ });++ test("omits collection configuration and templates from indexed public output", async () => {+ const { assetData, assetStore } = createCollectionFixture();+ const artifact = { documents: [], assetReferences: {} } as never;+ const prepareIndex = vi.fn().mockResolvedValue(artifact);+ const validateCollections = vi.fn();+ const dependencies = {+ createRepository: vi.fn(() => ({ prepareIndex, validateCollections })),+ loadAssetDataByProject: vi.fn().mockResolvedValue(assetData),+ };++ const result = await preparePublishedAssetData(+ {+ projectId: "project-1",+ context: { apiClient: { type: "service" } } as never,+ assetStore: assetStore as never,+ contentDatabaseMaxBytes: 512_000,+ plan: { queries: [] } as never,+ retainedAssetIds: [],+ },+ dependencies as never+ );++ expect(result.assets.map(({ id }) => id)).toEqual(["entry", "image"]);++ const authenticatedResult = await preparePublishedAssetData(+ {+ projectId: "project-1",+ context: { apiClient: { type: "cli" } } as never,+ assetStore: assetStore as never,+ contentDatabaseMaxBytes: 512_000,+ plan: { queries: [] } as never,+ retainedAssetIds: [],+ },+ dependencies as never+ );+ expect(authenticatedResult.assets).toEqual(assetData.assets);+ expect(prepareIndex).toHaveBeenCalledTimes(2);+ expect(validateCollections).toHaveBeenCalledTimes(2);+ expect(assetStore.readFile).toHaveBeenCalledOnce();+ });++ test("rejects indexed publication when a collection is invalid", async () => {+ const { assetData, assetStore } = createCollectionFixture();+ const validationError = new Error("Collection entry violates its schema");+ const prepareIndex = vi.fn().mockResolvedValue({+ documents: [],+ assetReferences: {},+ });+ const validateCollections = vi.fn().mockRejectedValue(validationError);++ await expect(+ preparePublishedAssetData(+ {+ projectId: "project-1",+ context: { apiClient: { type: "service" } } as never,+ assetStore: assetStore as never,+ contentDatabaseMaxBytes: 512_000,+ plan: { queries: [] } as never,+ retainedAssetIds: [],+ },+ {+ createRepository: vi.fn(() => ({+ prepareIndex,+ validateCollections,+ })),+ loadAssetDataByProject: vi.fn().mockResolvedValue(assetData),+ } as never+ )+ ).rejects.toBe(validationError);++ expect(validateCollections).toHaveBeenCalledWith(assetData.assets);+ expect(prepareIndex).not.toHaveBeenCalled();+ });++ test("validates collections without compiling a content index", async () => {+ const validateCollections = vi.fn();+ const createRepository = vi.fn(() => ({ validateCollections }));+ const staleAssetData = {+ assets: [{ id: "stale-config", type: "file" }],+ assetFolders: [{ id: "stale-folder" }],+ };+ const currentAssetData = {+ assets: [{ id: "current-config", type: "file" }],+ assetFolders: [{ id: "current-folder" }],+ };+ const loadAssetDataByProject = vi+ .fn()+ .mockResolvedValueOnce(staleAssetData)+ .mockResolvedValueOnce(currentAssetData)+ .mockResolvedValueOnce(currentAssetData)+ .mockResolvedValueOnce(currentAssetData);++ await expect(+ validatePublishedAssetCollections(+ {+ projectId: "project-1",+ context: {} as never,+ assetStore: {} as never,+ },+ {+ createRepository,+ loadAssetDataByProject,+ } as never+ )+ ).resolves.toEqual(currentAssetData);++ expect(createRepository).toHaveBeenCalledWith({+ projectId: "project-1",+ context: {},+ assetStore: {},+ });+ expect(validateCollections.mock.calls).toEqual([+ [staleAssetData.assets],+ [currentAssetData.assets],+ ]);+ expect(loadAssetDataByProject).toHaveBeenCalledTimes(4);+ });+test("keeps authored fonts and content database runtime assets", async () => {const artifact = {documents: [{ _id: "post-document" }],@@ -22,7 +234,10 @@ describe("published asset data", () => {const prepareIndex = vi.fn().mockResolvedValue(artifact);const loadAssetDataByProject = vi.fn().mockResolvedValue(assetData);const dependencies = {- createRepository: vi.fn(() => ({ prepareIndex })),+ createRepository: vi.fn(() => ({+ prepareIndex,+ validateCollections: vi.fn(),+ })),loadAssetDataByProject,};@@ -84,7 +299,10 @@ describe("published asset data", () => {retainedAssetIds: [],},{- createRepository: vi.fn(() => ({ prepareIndex })),+ createRepository: vi.fn(() => ({+ prepareIndex,+ validateCollections: vi.fn(),+ })),loadAssetDataByProject,} as never)@@ -121,7 +339,10 @@ describe("published asset data", () => {resolvePlan,},{- createRepository: vi.fn(() => ({ prepareIndex })),+ createRepository: vi.fn(() => ({+ prepareIndex,+ validateCollections: vi.fn(),+ })),loadAssetDataByProject: vi.fn().mockResolvedValue(assetData),} as never);diff --git a/packages/asset-uploader/src/publication.ts b/packages/asset-uploader/src/publication.tsindex e948ed33b2..02f6d041ff 100644--- a/packages/asset-uploader/src/publication.ts+++ b/packages/asset-uploader/src/publication.ts@@ -8,6 +8,7 @@ import type { Asset } from "@webstudio-is/sdk";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import { PostgresAssetRepository } from "./asset-repository";import type { AssetObjectStore } from "./client";+import { getCollectionReservedAssetIds } from "./collection-persistence";import { loadAssetDataByProject } from "./db";const defaultDependencies = {@@ -17,6 +18,105 @@ const defaultDependencies = {loadAssetDataByProject,};+const getOmittedCollectionAssetIds = async ({+ assets,+ assetStore,+ context,+}: {+ assets: readonly Asset[];+ assetStore: AssetObjectStore;+ context: AppContext;+}) => {+ // CLI bundles are authenticated, lossless exports that may be imported+ // again. Public and service publication bundles do not expose collection+ // configuration or templates.+ if (context.apiClient?.type === "cli") {+ return new Set<string>();+ }+ return await getCollectionReservedAssetIds({ assets, assetStore });+};++const prepareStablePublishedAssetData = async <Result>({+ projectId,+ context,+ assetStore,+ validateCollections,+ prepare,+ dependencies,+}: {+ projectId: string;+ context: AppContext;+ assetStore: AssetObjectStore;+ validateCollections: (assets: readonly Asset[]) => Promise<void>;+ prepare: () => Promise<Result>;+ dependencies: typeof defaultDependencies;+}) => {+ for (let attempt = 0; attempt < 2; attempt += 1) {+ const assetDataBefore = await dependencies.loadAssetDataByProject(+ projectId,+ context+ );+ await validateCollections(assetDataBefore.assets);+ const result = await prepare();+ const omittedCollectionAssetIds = await getOmittedCollectionAssetIds({+ assets: assetDataBefore.assets,+ assetStore,+ context,+ });+ const assetDataAfter = await dependencies.loadAssetDataByProject(+ projectId,+ context+ );+ if (+ serializeJsonDeterministically(assetDataBefore) ===+ serializeJsonDeterministically(assetDataAfter)+ ) {+ return {+ result,+ assetData: {+ ...assetDataAfter,+ assets: assetDataAfter.assets.filter(+ (asset: Asset) => omittedCollectionAssetIds.has(asset.id) === false+ ),+ },+ };+ }+ if (attempt === 0) {+ continue;+ }+ throw new Error("Assets changed while preparing publication; retry");+ }+ throw new Error("Asset data was not prepared");+};++export const validatePublishedAssetCollections = async (+ {+ projectId,+ context,+ assetStore,+ }: {+ projectId: string;+ context: AppContext;+ assetStore: AssetObjectStore;+ },+ dependencies = defaultDependencies+) => {+ const repository = dependencies.createRepository({+ projectId,+ context,+ assetStore,+ });+ const { assetData } = await prepareStablePublishedAssetData({+ projectId,+ context,+ assetStore,+ validateCollections: (assets) => repository.validateCollections(assets),+ prepare: async () => undefined,+ dependencies,+ });+ return assetData;+};+export const preparePublishedAssetData = async ({projectId,@@ -45,59 +145,54 @@ export const preparePublishedAssetData = async (assetStore,contentDatabaseMaxBytes,});- for (let attempt = 0; attempt < 2; attempt += 1) {- const assetDataBefore = await dependencies.loadAssetDataByProject(+ const { result: artifact, assetData } = await prepareStablePublishedAssetData(+ {projectId,- context- );- let artifact = await repository.prepareIndex(plan);- if (resolvePlan !== undefined) {- let resolvedPlan = await resolvePlan(artifact);- for (let dependencyPass = 0; dependencyPass < 20; dependencyPass += 1) {- artifact = await repository.prepareIndex(resolvedPlan);- const validatedPlan = await resolvePlan(artifact);- if (- serializeJsonDeterministically(resolvedPlan) ===- serializeJsonDeterministically(validatedPlan)- ) {- break;- }- if (dependencyPass === 19) {- throw new Error(- "Dynamic MDX dependency closure exceeds the safe publication depth"- );+ context,+ assetStore,+ validateCollections: (assets) => repository.validateCollections(assets),+ prepare: async () => {+ let artifact = await repository.prepareIndex(plan);+ if (resolvePlan !== undefined) {+ let resolvedPlan = await resolvePlan(artifact);+ for (+ let dependencyPass = 0;+ dependencyPass < 20;+ dependencyPass += 1+ ) {+ artifact = await repository.prepareIndex(resolvedPlan);+ const validatedPlan = await resolvePlan(artifact);+ if (+ serializeJsonDeterministically(resolvedPlan) ===+ serializeJsonDeterministically(validatedPlan)+ ) {+ break;+ }+ if (dependencyPass === 19) {+ throw new Error(+ "Dynamic MDX dependency closure exceeds the safe publication depth"+ );+ }+ resolvedPlan = validatedPlan;+ }}- resolvedPlan = validatedPlan;- }- }- const assetDataAfter = await dependencies.loadAssetDataByProject(- projectId,- context- );- if (- serializeJsonDeterministically(assetDataBefore) !==- serializeJsonDeterministically(assetDataAfter)- ) {- if (attempt === 0) {- continue;- }- throw new Error("Assets changed while preparing publication; retry");- }-- const runtimeAssetIds = new Set(retainedAssetIds);- for (const assetId of getContentArtifactRuntimeAssetIds({- artifact,- includeDocuments: true,- })) {- runtimeAssetIds.add(assetId);+ return artifact;+ },+ dependencies,}- return {- artifact,- assets: assetDataAfter.assets.filter(- (asset: Asset) => asset.type !== "font" || runtimeAssetIds.has(asset.id)- ),- assetFolders: assetDataAfter.assetFolders,- };+ );+ const runtimeAssetIds = new Set(retainedAssetIds);+ for (const assetId of getContentArtifactRuntimeAssetIds({+ artifact,+ includeDocuments: true,+ })) {+ runtimeAssetIds.add(assetId);}- throw new Error("Asset index was not prepared");+ return {+ artifact,+ assets: assetData.assets.filter(+ (asset: Asset) => asset.type !== "font" || runtimeAssetIds.has(asset.id)+ ),+ assetFolders: assetData.assetFolders,+ };};diff --git a/packages/asset-uploader/src/revision.ts b/packages/asset-uploader/src/revision.tsindex bdaca3897c..2a902c6088 100644--- a/packages/asset-uploader/src/revision.ts+++ b/packages/asset-uploader/src/revision.ts@@ -106,12 +106,17 @@ export const updateAssetContent = async (expectedName,extension,data,+ prepareData,}: {assetId: Asset["id"];projectId: string;expectedName: string;extension?: string;data: ReadableStream<Uint8Array>;+ prepareData?: (input: {+ asset: Asset;+ data: ReadableStream<Uint8Array>;+ }) => Promise<ReadableStream<Uint8Array>>;},assetClient: AssetObjectStore,context: AppContext@@ -146,6 +151,17 @@ export const updateAssetContent = async (throw new Error("The new extension must be an editable text file format");}+ const asset = formatAsset({+ assetId: currentAsset.id,+ projectId: currentAsset.projectId,+ filename: currentAsset.filename,+ description: currentAsset.description,+ folderId: currentAsset.folderId,+ file: currentAsset.file,+ });+ const preparedData =+ prepareData === undefined ? data : await prepareData({ asset, data });+const revisionName = createUniqueAssetFilename(getRevisionFilename({name: currentAsset.name,@@ -165,7 +181,7 @@ export const updateAssetContent = async (const file = await uploadFileData(revisionName,- data,+ preparedData,assetClient,context,undefined,diff --git a/packages/asset-uploader/src/server.ts b/packages/asset-uploader/src/server.tsindex 3bb26c4d70..91140cbac6 100644--- a/packages/asset-uploader/src/server.ts+++ b/packages/asset-uploader/src/server.ts@@ -13,6 +13,8 @@ export * from "./field-catalog";export * from "./query-preview";export * from "./query-performance";export * from "./publication";+export * from "./collection-persistence";+export { formatAsset } from "./utils/format-asset";export * from "./clients/fs/fs";export * from "./clients/s3/s3";export { assetDataOverride } from "./utils/get-asset-data";diff --git a/packages/asset-uploader/src/upload.test.ts b/packages/asset-uploader/src/upload.test.tsindex 13417e70d6..f69990ccd4 100644--- a/packages/asset-uploader/src/upload.test.ts+++ b/packages/asset-uploader/src/upload.test.ts@@ -793,6 +793,17 @@ describe("uploadFile", () => {folderId: null,});}+ if (url.searchParams.get("order") === "id.asc") {+ return json([+ {+ id: "asset-1",+ projectId: "project-1",+ filename: null,+ folderId: null,+ file: uploadedFile,+ },+ ]);+ }expect(url.searchParams.get("id")).toBe("in.(asset-1)");return json([{diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 7a1909a55a..6dad13e890 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -113,9 +113,9 @@ Once the project is linked, use the **`sync`** command to sync it with the cloudwebstudio sync```-Make sure to publish the project in Webstudio Cloud before running the **`sync`** command in your local Webstudio project.+Sync downloads the current saved Builder project and its asset files, then prepares the local content index. Publishing is not required.-`sync` is only for downloading a published project export. It is not part of the MCP editing workflow.+Use the export with `webstudio build` or `webstudio import --to "<target-share-link>"`. Sync is not required for MCP editing.### builddiff --git a/packages/cli/evaluations/high-impact/agent-runner.ts b/packages/cli/evaluations/high-impact/agent-runner.tsindex d12c50cc44..d659e162cc 100644--- a/packages/cli/evaluations/high-impact/agent-runner.ts+++ b/packages/cli/evaluations/high-impact/agent-runner.ts@@ -47,6 +47,19 @@ export type AgentEvaluationResult = {};const fixtureToolNames = {+ "mdx-article-editing-v1": [+ "meta.guide",+ "meta.get-more-tools",+ "inspect-instance",+ "list-variables",+ "connect-content-block-source",+ "inspect-content-block-source",+ "update-content-block-frontmatter",+ "reload-content-block-source",+ "update-text",+ "bind-props",+ "audit",+ ],"authenticated-page-v1": ["meta.guide","inspect-auth-context",diff --git a/packages/cli/evaluations/high-impact/fixture-api.test.ts b/packages/cli/evaluations/high-impact/fixture-api.test.tsindex 55aff4c6f6..8a6734a95f 100644--- a/packages/cli/evaluations/high-impact/fixture-api.test.ts+++ b/packages/cli/evaluations/high-impact/fixture-api.test.ts@@ -6,10 +6,19 @@ import { promisify } from "node:util";import { describe, expect, test } from "vitest";import { getFontFaces } from "@webstudio-is/fonts";import type { FontAsset } from "@webstudio-is/sdk";+import { createProjectAssetContentTransport } from "@webstudio-is/http-client";+import { parseMarkdownDocumentSource } from "@webstudio-is/content-engine";+import {+ createHttpAssetContentRepository,+ readAssetContentBytes,+ AssetRevisionConflictError,+} from "@webstudio-is/content-engine/asset-content-repository";import {authenticatedPageFixture,fontAssetsFixture,markdownBlogFixture,+ mdxArticleFixture,+ mdxArticleSource,} from "./fixtures";import { startHighImpactFixtureApi } from "./fixture-api";import {@@ -28,6 +37,124 @@ import { evaluateHighImpactOutcome } from "./validate";const execFileAsync = promisify(execFile);describe("high-impact fixture API", () => {+ test("connects, edits, and reloads the MDX article through the source CLI", async () => {+ const api = await startHighImpactFixtureApi(mdxArticleFixture);+ const initialProject = api.getProject();+ const directory = await mkdtemp(join(tmpdir(), "mdx-article-fixture-api-"));+ const projectDirectory = join(directory, "project");+ await mkdir(projectDirectory);+ const cli = resolve(import.meta.dirname, "../../local.js");+ const env = {+ ...process.env,+ WEBSTUDIO_CONFIG_DIR: join(directory, "config"),+ };+ const run = async (command: string, input: Record<string, unknown>) => {+ const result = await execFileAsync(+ process.execPath,+ [cli, command, JSON.stringify(input)],+ { cwd: projectDirectory, env }+ );+ expect(JSON.parse(result.stdout)).toMatchObject({ ok: true });+ };+ try {+ await execFileAsync(+ process.execPath,+ [cli, "init", "--link", api.shareLink, "--json"],+ { cwd: projectDirectory, env }+ );+ const occurrence = {+ blockInstanceId: "article-block",+ renderScope: "page:/",+ };+ await run("connect-content-block-source", {+ ...occurrence,+ source: { type: "asset", assetId: "article-file" },+ });+ await run("update-content-block-frontmatter", {+ ...occurrence,+ properties: {+ title: "Aurora trails",+ author: { name: "Noor Silva" },+ readingTime: 6,+ draft: false,+ },+ });+ await run("reload-content-block-source", occurrence);+ await run("inspect-content-block-source", occurrence);+ const document = await parseMarkdownDocumentSource({+ source: api.getAssetSource("article-file")!,+ });+ const original = await parseMarkdownDocumentSource({+ source: mdxArticleSource,+ });+ expect(document.frontmatter).toEqual({+ ...original.frontmatter,+ author: { name: "Noor Silva" },+ });+ expect(document.body).toBe(original.body);+ const headerIds = new Set([+ "article-title",+ "article-author",+ "article-reading-time",+ "article-reading-suffix",+ ]);+ expect(+ api+ .getProject()+ .instances.filter((instance) => headerIds.has(instance.id))+ ).toEqual(+ initialProject.instances.filter((instance) =>+ headerIds.has(instance.id)+ )+ );+ } finally {+ await api.close();+ await rm(directory, { recursive: true, force: true });+ }+ }, 60_000);+ test("persists MDX source revisions and rejects stale writes through the real client", async () => {+ const api = await startHighImpactFixtureApi(mdxArticleFixture);+ try {+ const projectId = "high-impact-evaluation-project";+ const repository = createHttpAssetContentRepository({+ projectId,+ ...createProjectAssetContentTransport({+ projectId,+ origin: api.origin,+ }),+ });+ const initial = await readAssetContentBytes({+ repository,+ assetId: "article-file",+ maxSize: 10_000,+ });+ expect(new TextDecoder().decode(initial.bytes)).toBe(mdxArticleSource);+ const source = mdxArticleSource.replace("Mira Chen", "Noor Silva");+ const updated = await repository.updateContent({+ assetId: "article-file",+ expectedName: initial.asset.name,+ data: new Blob([source]).stream(),+ });+ expect(updated.name).not.toBe(initial.asset.name);+ const reloaded = await readAssetContentBytes({+ repository,+ assetId: "article-file",+ maxSize: 10_000,+ });+ expect(new TextDecoder().decode(reloaded.bytes)).toBe(source);+ expect(api.getAssetSource("article-file")).toBe(source);+ await expect(+ repository.updateContent({+ assetId: "article-file",+ expectedName: initial.asset.name,+ data: new Blob(["stale overwrite"]).stream(),+ })+ ).rejects.toBeInstanceOf(AssetRevisionConflictError);+ expect(api.getAssetSource("article-file")).toBe(source);+ } finally {+ await api.close();+ }+ });test("keeps an untouched fixture page unchanged after persistence", async () => {const fixtureApi = await startHighImpactFixtureApi(fontAssetsFixture);try {diff --git a/packages/cli/evaluations/high-impact/fixture-api.ts b/packages/cli/evaluations/high-impact/fixture-api.tsindex bd3f4a3f47..b31971c070 100644--- a/packages/cli/evaluations/high-impact/fixture-api.ts+++ b/packages/cli/evaluations/high-impact/fixture-api.ts@@ -1,6 +1,10 @@// Serves deterministic in-memory Webstudio project fixtures through the real// local API boundary used by high-impact CLI and MCP evaluations.import type { Server } from "node:http";+import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";+import { createHttpAssetContentRepository } from "@webstudio-is/content-engine/asset-content-repository";+import { createProjectAssetContentTransport } from "@webstudio-is/http-client";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import {executeAssetQuery,getAssetQueryWhereMetrics,@@ -11,11 +15,21 @@ import {} from "@webstudio-is/content-engine";import { fontFormat, fontMeta } from "@webstudio-is/fonts";import { getFileNameParts, type Asset } from "@webstudio-is/sdk";-import { assetsUploadsApiUrl } from "@webstudio-is/sdk/runtime";+import {+ assetsUploadsApiUrl,+ getAssetContentApiUrl,+} from "@webstudio-is/sdk/runtime";+import {+ assetContentDescriptorHeader,+ serializeAssetContentDescriptor,+} from "@webstudio-is/protocol/asset-resource-api";import { migratePages } from "@webstudio-is/project-migrations/pages";import React from "react";import type { BuilderState } from "@webstudio-is/project-build/state";-import { createBuilderStateFreshness } from "@webstudio-is/project-build/state";+import {+ createBuilderStateFreshness,+ createBuilderBuildDataSnapshotFromState,+} from "@webstudio-is/project-build/state";import type { BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime";import type { BuilderPatchTransaction } from "@webstudio-is/project-build/contracts";import type { HighImpactFixture, EvaluationProject } from "./fixtures";@@ -89,6 +103,7 @@ export type HighImpactFixtureApi = {origin: string;shareLink: string;getProject: () => EvaluationProject;+ getAssetSource: (assetId: string) => string | undefined;getToolCalls: () => EvaluationToolCall[];close: () => Promise<void>;};@@ -106,7 +121,9 @@ export const startHighImpactFixtureApi = async (]);const { createBuilderStateFromBuildData, applyBuilderPatchTransactions } =stateAdapters;- const { executeBuilderRuntimeOperation } = runtime;+ const { executeBuilderRuntimeOperation, createContentBlockApplication } =+ runtime;+ let contentBlockApplication: ReturnType<typeof createContentBlockApplication>;const { createLocalProjectBundleFromSessionSnapshot } = projectSession;const { hydrateRestorePointTransaction } = restorePoints;const persistedPages = createPersistedPages(fixture.project);@@ -136,7 +153,12 @@ export const startHighImpactFixtureApi = async (let version = initialVersion;let generatedId = 0;const calls: EvaluationToolCall[] = [];- const uploadedFileContents = new Map<string, Uint8Array>();+ const uploadedFileContents = new Map<string, Uint8Array>(+ Object.entries(fixture.assetSources ?? {}).map(([id, source]) => [+ id,+ new TextEncoder().encode(source),+ ])+ );let origin = "";const validateFixtureAssetQuery = (query: unknown) => {const validation = validateAssetQuery({ query });@@ -212,6 +234,58 @@ export const startHighImpactFixtureApi = async (const fixtureApi = await startRuntimeFixtureApi(async ({ request, response, pathname, operationPath, readInput }) => {let data: unknown;+ const contentAsset = Array.from(state.assets?.values() ?? []).find(+ (asset) => pathname === getAssetContentApiUrl(asset.id)+ );+ if (contentAsset !== undefined) {+ const url = new URL(request.url ?? "", origin);+ if (url.searchParams.get("projectId") !== projectId) {+ response.writeHead(403);+ response.end();+ return;+ }+ if (request.method === "GET") {+ const bytes = uploadedFileContents.get(contentAsset.id);+ if (bytes === undefined) {+ response.writeHead(404);+ response.end();+ return;+ }+ response.writeHead(200, {+ "content-type": "application/octet-stream",+ "content-length": bytes.byteLength,+ [assetContentDescriptorHeader]:+ serializeAssetContentDescriptor(contentAsset),+ });+ response.end(bytes);+ return;+ }+ if (request.method === "PUT") {+ if (url.searchParams.get("expectedName") !== contentAsset.name) {+ response.writeHead(409, { "content-type": "application/json" });+ response.end(JSON.stringify({ message: "Asset revision changed" }));+ return;+ }+ const bytes = await readRuntimeFixtureRequestBody(request);+ const asset = {+ ...contentAsset,+ name: `revision-${generatedId++}.mdx`,+ size: bytes.byteLength,+ };+ uploadedFileContents.set(asset.id, bytes);+ state = {+ ...state,+ assets: new Map(state.assets).set(asset.id, asset),+ };+ version += 1;+ response.writeHead(200, { "content-type": "application/json" });+ response.end(JSON.stringify({ asset }));+ return;+ }+ response.writeHead(405);+ response.end();+ return;+ }if (request.method === "POST" &&pathname.startsWith(`${assetsUploadsApiUrl}/`)@@ -279,8 +353,11 @@ export const startHighImpactFixtureApi = async ();return;}- if (operationPath === "build.loadProjectBundleByProjectId") {- data = createLocalProjectBundleFromSessionSnapshot(+ if (+ operationPath === "build.loadProjectBundleByProjectId" ||+ operationPath === "build.loadData"+ ) {+ const bundle = createLocalProjectBundleFromSessionSnapshot({projectId,buildId,@@ -296,6 +373,21 @@ export const startHighImpactFixtureApi = async (},{ origin });+ data =+ operationPath === "build.loadData"+ ? {+ ...bundle.build,+ ...createBuilderBuildDataSnapshotFromState(state),+ pages: bundle.build.pages,+ assets: bundle.assets,+ assetFolders: bundle.assetFolders,+ project: {+ id: projectId,+ title: "High-impact evaluation",+ domain: "high-impact-evaluation",+ },+ }+ : bundle;} else if (operationPath === "projects.get") {data = {id: projectId,@@ -405,6 +497,7 @@ export const startHighImpactFixtureApi = async (createId: () => `evaluation-${generatedId++}`,projectId,projectVersion: version,+ contentBlockApplication,},});if (@@ -435,12 +528,31 @@ export const startHighImpactFixtureApi = async ();const { server } = fixtureApi;origin = fixtureApi.origin;+ const contentSession = createAssetContentSession({+ repository: createHttpAssetContentRepository({+ projectId,+ ...createProjectAssetContentTransport({ projectId, origin }),+ }),+ authorize: () => true,+ });+ contentBlockApplication = createContentBlockApplication({+ projectId,+ session: contentSession,+ metas: componentMetas,+ });return {server,origin,shareLink: `${origin}/builder/${projectId}?authToken=fixture-only-not-persisted`,getProject: () => stateToProject(state),+ getAssetSource: (assetId) => {+ const bytes = uploadedFileContents.get(assetId);+ return bytes === undefined ? undefined : new TextDecoder().decode(bytes);+ },getToolCalls: () => structuredClone(calls),- close: fixtureApi.close,+ close: async () => {+ contentSession.dispose();+ await fixtureApi.close();+ },};};diff --git a/packages/cli/evaluations/high-impact/fixtures.ts b/packages/cli/evaluations/high-impact/fixtures.tsindex fac47403f6..61c0d2311f 100644--- a/packages/cli/evaluations/high-impact/fixtures.ts+++ b/packages/cli/evaluations/high-impact/fixtures.ts@@ -1,6 +1,13 @@// Declares high-impact agent scenarios, their allowed inputs, and structured// observable outcomes without embedding the expected solution in prompts.-import type { Asset, AssetFolder, Page } from "@webstudio-is/sdk";+import {+ blockComponent,+ blockBodyComponent,+ blockTemplateComponent,+ type Asset,+ type AssetFolder,+ type Page,+} from "@webstudio-is/sdk";import {fontAssetFixtureFiles,fontAssetFixtureUploadMeta,@@ -28,6 +35,7 @@ type EvaluationAgentConfig = {reasoningEffort: EvaluationReasoningEffort;guidance: {workflow:+ | "general"| "authenticated-page"| "design-input"| "font-assets"@@ -53,7 +61,7 @@ export type EvaluationInstance = {children: Array<| { type: "id"; value: string }| { type: "text"; value: string }- | { type: "expression"; value: string }+ | { type: "expression"; value: string; mode?: "read" | "readwrite" }>;};@@ -99,10 +107,12 @@ export type HighImpactFixture = {| "design-input-v1"| "font-assets-v1"| "markdown-blog-v1"- | "markdown-references-discovery-v1";+ | "markdown-references-discovery-v1"+ | "mdx-article-editing-v1";objective: string;project: EvaluationProject;agent: EvaluationAgentConfig;+ assetSources?: Readonly<Record<string, string>>;};const homePage: EvaluationPage = {@@ -314,12 +324,100 @@ export const markdownReferencesDiscoveryFixture: HighImpactFixture = {project: emptyProject(),};+export const mdxArticleSource = `---+title: Aurora trails+author:+ name: Mira Chen+readingTime: 6+draft: false+---++## Plan your route++Follow the marked trail and carry a map.+`;++export const mdxArticleFixture: HighImpactFixture = {+ id: "mdx-article-editing-v1",+ objective:+ "Connect the existing article.mdx Asset (article-file) to the Content Block article-block on Home. Keep its designed header outside the file body. Make the header's article-title, article-author, and article-reading-time text display the file's title, author name, and reading time and remain editable in Content mode. Keep the reading-time number separate from the existing static ‘ min read’ suffix. Change the file's author name to Noor Silva, preserving all other metadata and body content. Reload the connected source and inspect the saved result, then audit the page. Discover the supported editing workflow from MCP guidance. No visual verification is requested.",+ agent: { reasoningEffort: "medium", guidance: { workflow: "general" } },+ assetSources: { "article-file": mdxArticleSource },+ project: {+ ...emptyProject(),+ assets: [+ {+ id: "article-file",+ projectId: "high-impact-evaluation-project",+ name: "article.mdx",+ filename: "article",+ type: "file",+ format: "mdx",+ size: new TextEncoder().encode(mdxArticleSource).byteLength,+ createdAt: "2026-01-01T00:00:00.000Z",+ meta: {},+ },+ ],+ instances: [+ {+ id: "home-root",+ component: "Body",+ tag: "body",+ children: [{ type: "id", value: "article-block" }],+ },+ {+ id: "article-block",+ component: blockComponent,+ children: [+ { type: "id", value: "article-templates" },+ { type: "id", value: "article-title" },+ { type: "id", value: "article-author" },+ { type: "id", value: "article-reading-time" },+ { type: "id", value: "article-reading-suffix" },+ { type: "id", value: "article-body" },+ ],+ },+ {+ id: "article-templates",+ component: blockTemplateComponent,+ children: [],+ },+ { id: "article-body", component: blockBodyComponent, children: [] },+ {+ id: "article-title",+ component: "Heading",+ tag: "h1",+ children: [{ type: "text", value: "Title" }],+ },+ {+ id: "article-author",+ component: "Text",+ tag: "span",+ children: [{ type: "text", value: "Author" }],+ },+ {+ id: "article-reading-time",+ component: "Text",+ tag: "span",+ children: [{ type: "text", value: "0" }],+ },+ {+ id: "article-reading-suffix",+ component: "Text",+ tag: "span",+ children: [{ type: "text", value: " min read" }],+ },+ ],+ },+};+export const highImpactFixtures = [authenticatedPageFixture,designInputFixture,fontAssetsFixture,markdownBlogFixture,markdownReferencesDiscoveryFixture,+ mdxArticleFixture,] as const;export const validateHighImpactFixture = (fixture: HighImpactFixture) => {diff --git a/packages/cli/evaluations/high-impact/mdx-article.test.ts b/packages/cli/evaluations/high-impact/mdx-article.test.tsnew file mode 100644index 0000000000..8fc09ef251--- /dev/null+++ b/packages/cli/evaluations/high-impact/mdx-article.test.ts@@ -0,0 +1,164 @@+import { expect, test } from "vitest";+import { encodeDataSourceVariable } from "@webstudio-is/sdk";+import { mdxArticleFixture } from "./fixtures";+import {+ evaluateHighImpactOutcome,+ type HighImpactEvaluationInput,+} from "./validate";++const successfulInput = (): HighImpactEvaluationInput => {+ const project = structuredClone(mdxArticleFixture.project);+ project.dataSources.push({+ id: "document-data",+ type: "parameter",+ name: "document",+ scopeInstanceId: "article-block",+ });+ project.props.push(+ {+ id: "src",+ instanceId: "article-block",+ name: "src",+ type: "asset",+ value: "article-file",+ },+ {+ id: "document",+ instanceId: "article-block",+ name: "document",+ type: "parameter",+ value: "document-data",+ }+ );+ for (const [id, path] of [+ ["article-title", "title"],+ ["article-author", "author.name"],+ ["article-reading-time", "readingTime"],+ ]) {+ project.instances.find((instance) => instance.id === id)!.children = [+ {+ type: "expression",+ mode: "readwrite",+ value: `${encodeDataSourceVariable("document-data")}.frontmatter.${path}`,+ },+ ];+ }+ return {+ fixture: mdxArticleFixture,+ project,+ toolCalls: [+ "meta.guide",+ "connect-content-block-source",+ "update-content-block-frontmatter",+ "reload-content-block-source",+ "inspect-content-block-source",+ "audit",+ ].map((name) => ({ name })),+ mdxDocument: {+ frontmatter: {+ title: "Aurora trails",+ author: { name: "Noor Silva" },+ readingTime: 6,+ draft: false,+ },+ body: "## Plan your route\n\nFollow the marked trail and carry a map.\n",+ },+ };+};++test("accepts an editable MDX article after its author update and reload", () => {+ expect(evaluateHighImpactOutcome(successfulInput())).toMatchObject({+ passed: true,+ failures: [],+ });+});++test.each([+ ["read-only", "article-author-editable"],+ ["query-bound", "article-author-editable"],+ ["concatenated", "article-reading-time-editable"],+ ["outside-block", "article-title-editable"],+ ["lost-metadata", "mdxMetadataPreserved"],+ ["lost-body", "mdxBodyPreserved"],+ ["disconnected", "mdxSourceConnected"],+ ["not-reloaded", "mdxSavedAndReloaded"],+ ["missing-document-variable", "mdxDocumentVariable"],+ ["wrong-document-scope", "mdxDocumentVariable"],+ ["detached-suffix", "mdxSuffixPreserved"],+] as const)("rejects an article that is %s", (failure, check) => {+ const input = successfulInput();+ const author = input.project.instances.find(+ (instance) => instance.id === "article-author"+ )!;+ const readingTime = input.project.instances.find(+ (instance) => instance.id === "article-reading-time"+ )!;+ if (failure === "read-only") {+ author.children = [+ {+ type: "expression",+ mode: "read",+ value: `${encodeDataSourceVariable("document-data")}.frontmatter.author.name`,+ },+ ];+ }+ if (failure === "query-bound") {+ author.children = [+ {+ type: "expression",+ mode: "readwrite",+ value: `${encodeDataSourceVariable("query-data")}.data.properties.author.name`,+ },+ ];+ }+ if (failure === "concatenated") {+ readingTime.children = [+ {+ type: "expression",+ mode: "readwrite",+ value: `${encodeDataSourceVariable("document-data")}.frontmatter.readingTime + " min read"`,+ },+ ];+ }+ if (failure === "outside-block") {+ const block = input.project.instances.find(+ (instance) => instance.id === "article-block"+ )!;+ block.children = block.children.filter(+ (child) => child.value !== "article-title"+ );+ }+ if (failure === "lost-metadata") {+ delete input.mdxDocument!.frontmatter.draft;+ }+ if (failure === "lost-body") {+ input.mdxDocument!.body = "";+ }+ if (failure === "disconnected") {+ input.project.props = input.project.props.filter(+ (prop) => prop.name !== "src"+ );+ }+ if (failure === "not-reloaded") {+ input.toolCalls = input.toolCalls.filter(+ (call) => call.name !== "reload-content-block-source"+ );+ }+ if (failure === "missing-document-variable") {+ input.project.dataSources = [];+ }+ if (failure === "wrong-document-scope") {+ input.project.dataSources[0].scopeInstanceId = "home-root";+ }+ if (failure === "detached-suffix") {+ const block = input.project.instances.find(+ (instance) => instance.id === "article-block"+ )!;+ block.children = block.children.filter(+ (child) => child.value !== "article-reading-suffix"+ );+ }+ const result = evaluateHighImpactOutcome(input);+ expect(result.passed).toBe(false);+ expect(result.checks[check]).toBe("failed");+});diff --git a/packages/cli/evaluations/high-impact/run-local-agent.ts b/packages/cli/evaluations/high-impact/run-local-agent.tsindex 1685763c11..9fb0445f3a 100644--- a/packages/cli/evaluations/high-impact/run-local-agent.ts+++ b/packages/cli/evaluations/high-impact/run-local-agent.ts@@ -9,7 +9,10 @@ import { pathToFileURL } from "node:url";import { promisify } from "node:util";import yargs from "yargs";import { hideBin } from "yargs/helpers";-import { createContentDatabase } from "@webstudio-is/content-engine";+import {+ createContentDatabase,+ parseMarkdownDocumentSource,+} from "@webstudio-is/content-engine";import { compileContentSource } from "@webstudio-is/content-engine/compiler";import { createReachableAssetContentCompilationPlan } from "@webstudio-is/sdk";import {@@ -17,6 +20,7 @@ import {highImpactFixtures,markdownBlogFixture,markdownReferencesDiscoveryFixture,+ mdxArticleFixture,type HighImpactFixture,} from "./fixtures";import { startHighImpactFixtureApi } from "./fixture-api";@@ -239,6 +243,13 @@ const runFixture = async ({project: fixtureApi.getProject(),toolCalls,artifacts: await collectHighImpactArtifacts(projectDirectory),+ ...(fixture.id === mdxArticleFixture.id+ ? {+ mdxDocument: await parseMarkdownDocumentSource({+ source: fixtureApi.getAssetSource("article-file") ?? "",+ }),+ }+ : {}),...(fixture.id === markdownBlogFixture.id ||fixture.id === markdownReferencesDiscoveryFixture.id? {diff --git a/packages/cli/evaluations/high-impact/validate.test.ts b/packages/cli/evaluations/high-impact/validate.test.tsindex 0a155371a6..b3075a9bbf 100644--- a/packages/cli/evaluations/high-impact/validate.test.ts+++ b/packages/cli/evaluations/high-impact/validate.test.ts@@ -408,18 +408,18 @@ const designCalls: EvaluationToolCall[] = [];describe("high-impact fixture validation", () => {- test("keeps both fixtures complete and deterministic", () => {- expect(highImpactFixtures.map(validateHighImpactFixture)).toEqual([- { valid: true, failures: [] },- { valid: true, failures: [] },- { valid: true, failures: [] },- { valid: true, failures: [] },- { valid: true, failures: [] },- ]);- expect(JSON.stringify(highImpactFixtures)).toBe(- JSON.stringify(highImpactFixtures)- );- });+ test.each(highImpactFixtures)(+ "validates page ownership in $id",+ (fixture) => {+ expect(validateHighImpactFixture(fixture)).toEqual({+ valid: true,+ failures: [],+ });+ const broken = clone(fixture);+ broken.project.instances = [];+ expect(validateHighImpactFixture(broken).valid).toBe(false);+ }+ );});describe("font-assets evaluation", () => {diff --git a/packages/cli/evaluations/high-impact/validate.ts b/packages/cli/evaluations/high-impact/validate.tsindex 01e4eb34a3..ddf74cfc8c 100644--- a/packages/cli/evaluations/high-impact/validate.ts+++ b/packages/cli/evaluations/high-impact/validate.ts@@ -10,6 +10,10 @@ import { getFontFaces } from "@webstudio-is/fonts";import { mapQueryWhere } from "@webstudio-is/query-builder/runtime";import {collectionComponent,+ blockComponent,+ blockBodyComponent,+ blockTemplateComponent,+ getWritableContentBlockDocumentBinding,decodeDataSourceVariable,isAssetsResource,parseStructuredAssetQueryResourceBody,@@ -24,6 +28,7 @@ import {fontAssetsFixture,markdownBlogFixture,markdownReferencesDiscoveryFixture,+ mdxArticleFixture,type EvaluationInstance,type EvaluationProject,type HighImpactFixture,@@ -68,6 +73,7 @@ export type HighImpactEvaluationInput = {project: EvaluationProject;toolCalls: EvaluationToolCall[];artifacts?: EvaluationArtifact[];+ mdxDocument?: { frontmatter: Record<string, unknown>; body: string };contentDatabase?: {usedBytes: number;maxBytes: number;@@ -1320,13 +1326,145 @@ const validateMarkdownBlog = ();};+const validateMdxArticle = (+ input: HighImpactEvaluationInput,+ checks: Record<string, "passed" | "failed">,+ failures: string[]+) => {+ const block = input.project.instances.find(+ (instance) => instance.id === "article-block"+ );+ const source = input.project.props.find(+ (prop) => prop.instanceId === block?.id && prop.name === "src"+ );+ const document = input.project.props.find(+ (prop) =>+ prop.instanceId === block?.id &&+ prop.name === "document" &&+ prop.type === "parameter"+ );+ recordCheck(+ checks,+ failures,+ "mdxDocumentVariable",+ typeof document?.value === "string" &&+ input.project.dataSources.some(+ (dataSource) =>+ dataSource.id === document.value &&+ dataSource.type === "parameter" &&+ dataSource.scopeInstanceId === block?.id+ ),+ "The document parameter must refer to a variable owned by this Content Block."+ );+ const headerInstanceIds = new Set(+ (block?.children ?? []).flatMap((child) => {+ if (child.type !== "id") {+ return [];+ }+ const instance = input.project.instances.find(+ (instance) => instance.id === child.value+ );+ if (+ instance?.component === blockBodyComponent ||+ instance?.component === blockTemplateComponent+ ) {+ return [];+ }+ return descendants(input.project, child.value).map(+ (instance) => instance.id+ );+ })+ );+ recordCheck(+ checks,+ failures,+ "mdxSourceConnected",+ block?.component === blockComponent &&+ ((source?.type === "asset" && source.value === "article-file") ||+ (source?.type === "expression" &&+ typeof source.value === "string" &&+ parseJsonExpression(source.value) === "article-file")),+ "The article Content Block must stay connected to the supplied MDX Asset."+ );+ for (const [id, path] of [+ ["article-title", ["title"]],+ ["article-author", ["author", "name"]],+ ["article-reading-time", ["readingTime"]],+ ] as const) {+ const instance = input.project.instances.find(+ (instance) => instance.id === id+ );+ const binding =+ instance?.children.length === 1 ? instance.children[0] : undefined;+ const writable =+ binding?.type === "expression" && typeof document?.value === "string"+ ? getWritableContentBlockDocumentBinding({+ binding,+ documentDataSourceId: document.value,+ })+ : undefined;+ recordCheck(+ checks,+ failures,+ `${id}-editable`,+ headerInstanceIds.has(id) &&+ JSON.stringify(writable?.frontmatterPath) === JSON.stringify(path),+ `${id} must use a direct writable document binding inside the designed header.`+ );+ }+ recordCheck(+ checks,+ failures,+ "mdxMetadataPreserved",+ input.mdxDocument?.frontmatter.title === "Aurora trails" &&+ JSON.stringify(input.mdxDocument.frontmatter.author) ===+ JSON.stringify({ name: "Noor Silva" }) &&+ input.mdxDocument.frontmatter.readingTime === 6 &&+ input.mdxDocument.frontmatter.draft === false &&+ Object.keys(input.mdxDocument.frontmatter).length === 4,+ "The saved author change must preserve the other frontmatter fields."+ );+ recordCheck(+ checks,+ failures,+ "mdxBodyPreserved",+ input.mdxDocument?.body.trim() ===+ "## Plan your route\n\nFollow the marked trail and carry a map.",+ "Frontmatter editing must preserve the article body."+ );+ recordCheck(+ checks,+ failures,+ "mdxSuffixPreserved",+ headerInstanceIds.has("article-reading-suffix") &&+ JSON.stringify(+ input.project.instances.find(+ (instance) => instance.id === "article-reading-suffix"+ )?.children+ ) === JSON.stringify([{ type: "text", value: " min read" }]),+ "Keep the static suffix separate from the editable reading-time value."+ );+ recordCheck(+ checks,+ failures,+ "mdxSavedAndReloaded",+ hasSuccessfulCall(input.toolCalls, "update-content-block-frontmatter") &&+ hasSuccessfulCall(input.toolCalls, "reload-content-block-source") &&+ hasSuccessfulCall(input.toolCalls, "inspect-content-block-source") &&+ hasSuccessfulCall(input.toolCalls, "audit"),+ "Save through the dedicated source operation, reload, inspect, and audit."+ );+};+export const evaluateHighImpactOutcome = (input: HighImpactEvaluationInput): HighImpactEvaluationResult => {const checks: Record<string, "passed" | "failed"> = {};const failures: string[] = [];validateCommon(input, checks, failures);- if (input.fixture.id === authenticatedPageFixture.id) {+ if (input.fixture.id === mdxArticleFixture.id) {+ validateMdxArticle(input, checks, failures);+ } else if (input.fixture.id === authenticatedPageFixture.id) {validateAuth(input, checks, failures);} else if (input.fixture.id === fontAssetsFixture.id) {validateFontAssets(input, checks, failures);diff --git a/packages/cli/scripts/release-smoke.ts b/packages/cli/scripts/release-smoke.tsindex d4acf9c4f4..b9b4567c05 100644--- a/packages/cli/scripts/release-smoke.ts+++ b/packages/cli/scripts/release-smoke.ts@@ -607,7 +607,22 @@ const startFixtureApi = async (return undefined;}let data: unknown;- if (operationPath === "build.loadProjectBundleByProjectId") {+ if (operationPath === "build.loadData") {+ const snapshot = getCurrentBuildSnapshot();+ data = {+ ...getCurrentSerializedBuild(),+ ...snapshot,+ pages: getCurrentSerializedBuild().pages,+ dataSources: snapshot.variables,+ assets: Array.from(state.assets?.values() ?? []),+ assetFolders: Array.from(state.assetFolders?.values() ?? []),+ project: {+ id: projectId,+ title: "Release smoke project",+ domain: "release-smoke",+ },+ };+ } else if (operationPath === "build.loadProjectBundleByProjectId") {data = { ...fixture.data, build: getCurrentSerializedBuild() };} else if (operationPath === "projects.get") {data = {diff --git a/packages/cli/src/commands/api-command-docs.test.ts b/packages/cli/src/commands/api-command-docs.test.tsindex 4235e0b669..388bb45dbd 100644--- a/packages/cli/src/commands/api-command-docs.test.ts+++ b/packages/cli/src/commands/api-command-docs.test.ts@@ -229,6 +229,32 @@ test("documents MCP examples with current tool input fields", () => {}});+test("the article image recipe enables reference replacement without making shared metadata writable", () => {+ const prefix = "MCP tool: bind-props ";+ const bindings = useCaseScenarios+ .flatMap(({ commands }) => commands)+ .filter((command) => command.startsWith(prefix))+ .flatMap((command) => JSON.parse(command.slice(prefix.length)).bindings);+ const source = bindings.find(+ ({ name, binding }) =>+ name === "src" &&+ binding.value === "document.frontmatter.featureImage.src"+ );+ expect(source?.binding).toEqual({+ type: "expression",+ value: "document.frontmatter.featureImage.src",+ mode: "readwrite",+ });+ const alternativeText = bindings.find(+ ({ instanceId, name }) => instanceId === source.instanceId && name === "alt"+ );+ expect(alternativeText?.binding).toEqual({+ type: "expression",+ value: "document.frontmatter.featureImage.description",+ mode: "read",+ });+});+test("does not document client-supplied generated ids for create operations", () => {const forbiddenGeneratedIdFieldsByCommand = new Map(builderRuntimeOperations.flatMap((operation) => {diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.tsindex 0a890d2470..bf57b1988d 100644--- a/packages/cli/src/commands/mcp.test.ts+++ b/packages/cli/src/commands/mcp.test.ts@@ -25,6 +25,7 @@ import {} from "./mcp";const {+ getMcpDownloadAsset,assertSingleOpCallToolSupported,applyMcpRunOptions,createMcpResourceErrorPayload,@@ -1447,6 +1448,34 @@ test("returns complete prepared diagnostics after an Asset write", async () => {});});+test.each(["png", "woff2", "md", "mdx"])(+ "loads persisted %s assets for downloads without a prior asset query",+ async (format) => {+ const asset = {+ id: "asset-id",+ projectId: "project-id",+ name: `asset.${format}`,+ type: format === "png" ? "image" : format === "woff2" ? "font" : "file",+ format,+ size: 42,+ createdAt: "2026-09-07T00:00:00.000Z",+ updatedAt: "2026-09-07T00:00:00.000Z",+ };+ const ensureNamespaces = vi.fn(async () => ({+ state: { assets: new Map([[asset.id, asset]]) },+ }));+ const session = {+ snapshot: { state: {} },+ ensureNamespaces,+ } as unknown as Parameters<typeof getMcpDownloadAsset>[0];++ await expect(getMcpDownloadAsset(session, asset.id)).resolves.toEqual(+ asset+ );+ expect(ensureNamespaces).toHaveBeenCalledWith(["assets"]);+ }+);+test("rejects invalid UTF-8 downloads with the asset identity", async () => {await expect(validateDownloadedTextAsset({diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsindex 4dce7039e9..4acb363667 100644--- a/packages/cli/src/commands/mcp.ts+++ b/packages/cli/src/commands/mcp.ts@@ -1795,6 +1795,22 @@ const assertSingleOpCallToolSupported = (tool: string) => {}};+const getMcpDownloadAsset = async (+ session: Pick<CliProjectSession, "ensureNamespaces">,+ assetId: string+) => {+ const snapshot = await session.ensureNamespaces(["assets"]);+ const asset = snapshot.state.assets?.get(assetId);+ if (asset === undefined) {+ throw new Error(`Asset not found: ${assetId}`);+ }+ assertTextAssetDescriptorFormats({+ assets: [{ name: asset.name, type: asset.type, format: asset.format }],+ pathPrefix: ["asset"],+ });+ return asset;+};+const createCliMcpHost = async ({projectRoot = cwd(),projectId,@@ -1984,15 +2000,7 @@ const createCliMcpHost = async ({return { imported: true as const };},async downloadAsset(input) {- const snapshot = getLoadedProjectSessionSnapshot(session);- const asset = snapshot.state.assets?.get(input.assetId);- if (asset === undefined) {- throw new Error(`Asset not found: ${input.assetId}`);- }- assertTextAssetDescriptorFormats({- assets: [asset as unknown as Record<string, unknown>],- pathPrefix: ["asset"],- });+ const asset = await getMcpDownloadAsset(session, input.assetId);const localPath = getLocalAssetPath(asset.name, input.assetsDir);const format = getTextAssetFormat(asset.format);if (format !== undefined) {@@ -2740,6 +2748,7 @@ export const mcp = async (};export const __testing__ = {+ getMcpDownloadAsset,createMcpStatusReporter,formatMcpStatusLine,assertSingleOpCallToolSupported,diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.tsindex 3899ba4d0e..f679ee864f 100644--- a/packages/cli/src/commands/preview.test.ts+++ b/packages/cli/src/commands/preview.test.ts@@ -1,4 +1,6 @@import { randomUUID } from "node:crypto";+import { execFile } from "node:child_process";+import { promisify } from "node:util";import {mkdir,mkdtemp,@@ -26,6 +28,79 @@ import {previewDefaultTemplate,} from "./preview";import { generatedFilesManifest } from "../prebuild";+import { getPackageManagerInvocation } from "../preview-server/package-manager";+import { resolveConfig } from "vite";+import reactRouterConfig from "../../templates/react-router/vite.config";++test("keeps generated preview caches separate when dependencies are shared", async () => {+ const directory = await mkdtemp(join(tmpdir(), "webstudio-preview-cache-"));+ try {+ const cachePaths: string[] = [];+ for (const name of ["first", "second"]) {+ const projectDir = join(directory, name);+ await mkdir(projectDir);+ await writeFile(+ join(projectDir, "package.json"),+ await readFile(+ new URL("../../templates/react-router/package.json", import.meta.url)+ )+ );+ await ensurePreviewDependencies(projectDir);+ const config = await resolveConfig(+ {+ ...reactRouterConfig,+ root: projectDir,+ configFile: false,+ plugins: [],+ },+ "serve"+ );+ await mkdir(config.cacheDir, { recursive: true });+ cachePaths.push(await realpath(config.cacheDir));+ }+ expect(cachePaths[0]).not.toBe(cachePaths[1]);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++test.each(["build", "dev", "start"])(+ "runs the React Router %s script with linked development dependencies",+ async (script) => {+ const directory = await mkdtemp(join(tmpdir(), "webstudio-preview-bin-"));+ try {+ await writeFile(+ join(directory, "package.json"),+ await readFile(+ new URL("../../templates/react-router/package.json", import.meta.url)+ )+ );+ await ensurePreviewDependencies(directory);+ // The start script must reach the generated server module, not fail in+ // a package-manager launcher before loading it.+ await mkdir(join(directory, "build", "server"), { recursive: true });+ await writeFile(+ join(directory, "build", "server", "index.js"),+ 'import { writeFileSync } from "node:fs"; writeFileSync("started", "yes"); process.exit(0);'+ );+ const invocation = getPackageManagerInvocation([+ "run",+ script,+ ...(script === "start" ? [] : ["--", "--help"]),+ ]);+ await promisify(execFile)(invocation.command, invocation.args, {+ cwd: directory,+ env: { ...process.env, PORT: "3000" },+ timeout: 20_000,+ });+ if (script === "start") {+ expect(await readFile(join(directory, "started"), "utf8")).toBe("yes");+ }+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+ }+);const readWindowsPackageFile = (path: string) => {if (path.endsWith("node_modules\\pnpm\\package.json")) {@@ -159,7 +234,7 @@ test("prepares preview by syncing missing data and generating the app template",downloadAssetFiles: vi.fn(async () => undefined),isFileExists: vi.fn(async () => true),loadProjectBundleByBuildId: vi.fn(),- loadProjectBundleByProjectId: vi.fn(async () =>+ loadCurrentProjectBundle: vi.fn(async () =>createPublishedProjectBundleFixture()),readFile: vi.fn(),@@ -191,7 +266,7 @@ test("prepares preview by syncing missing data and generating the app template",ensureDependencies: vi.fn(async () => undefined),});- expect(syncDependencies.loadProjectBundleByProjectId).toHaveBeenCalled();+ expect(syncDependencies.loadCurrentProjectBundle).toHaveBeenCalled();expect(prebuildProject).toHaveBeenCalledWith({assets: true,template: ["react-router"],diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.tsindex f720daeae5..49d5061f03 100644--- a/packages/cli/src/commands/preview.ts+++ b/packages/cli/src/commands/preview.ts@@ -351,6 +351,9 @@ export const ensurePreviewDependencies = async (if (usesDevelopmentDependencies) {for (const cliNodeModules of cliNodeModulesCandidates) {if (await hasRequiredDependencies(cliNodeModules)) {+ // React Router scripts invoke package binaries through Node: pnpm's .bin+ // wrappers use paths relative to the original installation and cannot+ // be relocated through this directory link.await operations.symlink(cliNodeModules,previewNodeModules,diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.tsindex a59affce82..961eab4ae5 100644--- a/packages/cli/src/commands/sync.test.ts+++ b/packages/cli/src/commands/sync.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, expect, test, vi } from "vitest";import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { join } from "node:path";import { tmpdir } from "node:os";+import { createServer } from "node:http";import { bundleVersion } from "@webstudio-is/protocol";import {createImageAssetFixture,@@ -9,7 +10,7 @@ import {} from "@webstudio-is/protocol/fixtures";import { createFileIfNotExists, isFileExists } from "../fs-utils";import { resolveApiConnection } from "../api-connection";-import { sync } from "./sync";+import { sync, defaultSyncDependencies } from "./sync";import { apiCompatibilityHeaders } from "./api";import { materializeManagedAgents } from "../managed-agents";@@ -22,6 +23,7 @@ const indicator = {};const loadProjectBundleByBuildId = vi.fn();const loadProjectBundleByProjectId = vi.fn();+const loadCurrentProjectBundle = vi.fn();const downloadAssetFiles = vi.fn();const dependencies = {createFileIfNotExists,@@ -29,6 +31,7 @@ const dependencies = {isFileExists,loadProjectBundleByBuildId,loadProjectBundleByProjectId,+ loadCurrentProjectBundle,readFile,resolveApiConnection,spinner: () => indicator,@@ -48,6 +51,7 @@ beforeEach(async () => {process.chdir(tempDir);loadProjectBundleByBuildId.mockResolvedValue(createProjectBundle());loadProjectBundleByProjectId.mockResolvedValue(createProjectBundle());+ loadCurrentProjectBundle.mockResolvedValue(createProjectBundle());downloadAssetFiles.mockResolvedValue(undefined);indicator.start.mockClear();indicator.message.mockClear();@@ -227,7 +231,7 @@ test("sends linked share token when synchronizing by build id", async () => {});});-test("explains unpublished project bundle errors when synchronizing linked project", async () => {+test("syncs current editable data without requiring a published project", async () => {loadProjectBundleByProjectId.mockRejectedValue(Object.assign(new Error("Not published"), {data: { code: "NOT_FOUND", webstudioCode: "PROJECT_NOT_PUBLISHED" },@@ -239,19 +243,22 @@ test("explains unpublished project bundle errors when synchronizing linked projeprojectId: "project-id",}));- await expect(- sync({}, { ...dependencies, resolveApiConnection })- ).rejects.toThrow("Handled CLI error");-- expect(indicator.stop).toHaveBeenCalledWith(- [- "Unable to synchronize project bundle because the project is not published.",- "`webstudio sync` downloads the published project bundle.",- "Publishing is not required for MCP editing. Do not ask the user to publish; use MCP tools against the latest editable build.",- "For visual verification, use `preview.start` or `webstudio preview --source session` instead.",- ].join("\n"),- 2- );+ const current = createProjectBundle({+ build: { version: 438 },+ assets: [createImageAssetFixture()],+ });+ loadCurrentProjectBundle.mockResolvedValue(current);+ await sync({}, { ...dependencies, resolveApiConnection });+ expect(loadProjectBundleByProjectId).not.toHaveBeenCalled();+ expect(loadCurrentProjectBundle).toHaveBeenCalledWith({+ authToken: "share-token",+ origin: "https://example.com",+ projectId: "project-id",+ headers: apiCompatibilityHeaders,+ });+ const data = JSON.parse(await readFile(".webstudio/data.json", "utf8"));+ expect(data.build.version).toBe(438);+ expect(data.assets).toEqual(current.assets);});test("explains unpublished project bundle errors when synchronizing by build id", async () => {@@ -274,10 +281,8 @@ test("explains unpublished project bundle errors when synchronizing by build id"expect(indicator.stop).toHaveBeenCalledWith([- "Unable to synchronize project bundle because the project is not published.",- "`webstudio sync` downloads the published project bundle.",- "Publishing is not required for MCP editing. Do not ask the user to publish; use MCP tools against the latest editable build.",- "For visual verification, use `preview.start` or `webstudio preview --source session` instead.",+ "The selected build cannot be exported.",+ "Run `webstudio sync` without --buildId to export the current saved project without publishing.",].join("\n"),2);@@ -319,3 +324,102 @@ test("throws handled error when local project config is missing", async () => {2);});++test("repeated sync preserves current build metadata and file formats without publishing", async () => {+ const file = {+ ...createImageAssetFixture(),+ type: "file" as const,+ name: "post.mdx",+ filename: "post",+ format: "mdx",+ meta: {},+ };+ const current = createProjectBundle({+ assets: [file],+ build: {+ version: 438,+ createdAt: "2026-07-30T23:21:20.362Z",+ updatedAt: "2026-09-01T21:44:30.648Z",+ },+ });+ const maps = [+ "breakpoints",+ "styles",+ "styleSources",+ "styleSourceSelections",+ "props",+ "instances",+ "dataSources",+ "resources",+ ] as const;+ const rawBuild = {+ ...current.build,+ ...Object.fromEntries(+ maps.map((key) => [key, current.build[key].map(([, value]) => value)])+ ),+ assets: current.assets,+ assetFolders: [],+ project: {+ id: current.build.projectId,+ title: current.projectTitle,+ domain: current.projectDomain,+ },+ };+ const requests: string[] = [];+ const tokens: Array<string | string[] | undefined> = [];+ const server = createServer((request, response) => {+ const url = new URL(request.url ?? "/", "http://localhost");+ requests.push(url.pathname);+ if (url.pathname === "/cgi/asset/post.mdx") {+ response.setHeader("content-type", "text/mdx");+ response.end("# Post");+ return;+ }+ tokens.push(request.headers["x-auth-token"]);+ response.setHeader("content-type", "application/json");+ if (url.pathname !== "/trpc/build.loadData") {+ response.writeHead(404);+ response.end(JSON.stringify({ error: "unexpected endpoint" }));+ return;+ }+ response.end(JSON.stringify([{ result: { data: rawBuild } }]));+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ try {+ const address = server.address();+ if (address === null || typeof address === "string") {+ throw new Error("Missing test server address");+ }+ const connection = {+ origin: `http://127.0.0.1:${address.port}`,+ projectId: current.build.projectId,+ authToken: "source-token",+ };+ const realDependencies = {+ ...defaultSyncDependencies,+ resolveApiConnection: async () => connection,+ spinner: () => indicator,+ };+ await sync({}, realDependencies);+ const first = await readFile(".webstudio/data.json", "utf8");+ await sync({}, realDependencies);+ expect(await readFile(".webstudio/data.json", "utf8")).toBe(first);+ expect(JSON.parse(first)).toMatchObject({+ build: current.build,+ projectTitle: current.projectTitle,+ projectDomain: current.projectDomain,+ assets: [file],+ });+ expect(await readFile(".webstudio/assets/post.mdx", "utf8")).toBe("# Post");+ expect(requests).toEqual([+ "/trpc/build.loadData",+ "/cgi/asset/post.mdx",+ "/trpc/build.loadData",+ ]);+ expect(tokens).toEqual(["source-token", "source-token"]);+ } finally {+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve()))+ );+ }+});diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.tsindex c9b6156f96..3e6fa30a47 100644--- a/packages/cli/src/commands/sync.ts+++ b/packages/cli/src/commands/sync.ts@@ -2,11 +2,15 @@ import { readFile, writeFile } from "node:fs/promises";import { join } from "node:path";import { cwd } from "node:process";import { spinner } from "@clack/prompts";-import { type PublishedProjectBundle } from "@webstudio-is/protocol";+import {+ bundleVersion,+ publishedProjectBundle,+ type PublishedProjectBundle,+} from "@webstudio-is/protocol";import {getApiErrorCode,loadProjectBundleByBuildId,- loadProjectBundleByProjectId,+ loadBuilderDataByProjectId,toLocalProjectBundle,} from "@webstudio-is/http-client";import { createFileIfNotExists, isFileExists } from "../fs-utils";@@ -20,13 +24,77 @@ import { apiCompatibilityHeaders, stopSpinnerWithError } from "./api";import { downloadAssetFiles } from "../asset-files";import { resolveApiConnection } from "../api-connection";import { materializeManagedAgents } from "../managed-agents";+import { serializedBuild } from "@webstudio-is/project-build/contracts";+import {+ createBuilderStateFromBuildData,+ createSerializedBuilderBuildDataFromState,+} from "@webstudio-is/project-build/state";+import { migratePages } from "@webstudio-is/project-migrations/pages";+import {+ createReachableAssetContentCompilationPlan,+ getHomePage,+} from "@webstudio-is/sdk";+import { compileContentSource } from "@webstudio-is/content-engine/compiler";+import { parseContentDatabaseMaxBytes } from "@webstudio-is/content-engine";+import { createFileSystemContentSource } from "../filesystem-content-source";+import { z } from "zod";+import {+ breakpoint,+ styleDecl,+ styleSource,+ styleSourceSelection,+ prop,+ instance,+ dataSource,+ resource,+} from "@webstudio-is/sdk/schema";++// Builder data uses arrays rather than the keyed pairs in an export bundle.+const builderData = serializedBuild.extend({+ breakpoints: breakpoint.array(),+ styles: styleDecl.array(),+ styleSources: styleSource.array(),+ styleSourceSelections: styleSourceSelection.array(),+ props: prop.array(),+ instances: instance.array(),+ dataSources: dataSource.array(),+ resources: resource.array(),+ assets: publishedProjectBundle.shape.assets,+ assetFolders: publishedProjectBundle.shape.assetFolders,+ project: z.object({ id: z.string(), title: z.string(), domain: z.string() }),+});++const loadCurrentProjectBundle = async (+ connection: Awaited<ReturnType<typeof resolveApiConnection>>+) => {+ const data = builderData.parse(await loadBuilderDataByProjectId(connection));+ if (+ data.projectId !== connection.projectId ||+ data.project.id !== connection.projectId+ ) {+ throw new Error("Source project does not match the linked project");+ }+ const pages = migratePages(data.pages);+ const state = createBuilderStateFromBuildData({ ...data, pages });+ return publishedProjectBundle.parse({+ bundleVersion,+ origin: connection.origin,+ projectDomain: data.project.domain,+ projectTitle: data.project.title,+ page: getHomePage(pages),+ pages: Array.from(pages.pages.values()),+ assets: data.assets,+ assetFolders: data.assetFolders,+ build: { ...data, ...createSerializedBuilderBuildDataFromState(state) },+ });+};export type SyncDependencies = {createFileIfNotExists: typeof createFileIfNotExists;downloadAssetFiles: typeof downloadAssetFiles;isFileExists: typeof isFileExists;loadProjectBundleByBuildId: typeof loadProjectBundleByBuildId;- loadProjectBundleByProjectId: typeof loadProjectBundleByProjectId;+ loadCurrentProjectBundle: typeof loadCurrentProjectBundle;readFile: typeof readFile;resolveApiConnection: typeof resolveApiConnection;spinner: typeof spinner;@@ -39,7 +107,7 @@ export const defaultSyncDependencies: SyncDependencies = {downloadAssetFiles,isFileExists,loadProjectBundleByBuildId,- loadProjectBundleByProjectId,+ loadCurrentProjectBundle,readFile,resolveApiConnection,spinner,@@ -65,10 +133,8 @@ export const syncOptions = (yargs: CommonYargsArgv) =>type SyncOptions = Partial<StrictYargsOptionsToInterface<typeof syncOptions>>;const unpublishedProjectBundleMessage = [- "Unable to synchronize project bundle because the project is not published.",- "`webstudio sync` downloads the published project bundle.",- "Publishing is not required for MCP editing. Do not ask the user to publish; use MCP tools against the latest editable build.",- "For visual verification, use `preview.start` or `webstudio preview --source session` instead.",+ "The selected build cannot be exported.",+ "Run `webstudio sync` without --buildId to export the current saved project without publishing.",].join("\n");const isUnpublishedProjectBundleError = (error: unknown) => {@@ -146,7 +212,7 @@ export const sync = async (origin,headers: apiCompatibilityHeaders,})- : await dependencies.loadProjectBundleByProjectId({+ : await dependencies.loadCurrentProjectBundle({projectId,authToken,origin,@@ -185,6 +251,32 @@ export const sync = async (}}+ if (options.buildId === undefined) {+ const plan = createReachableAssetContentCompilationPlan({+ props: project.build.props.map(([, value]) => value),+ dataSources: project.build.dataSources.map(([, value]) => value),+ resources: project.build.resources.map(([, value]) => value),+ });+ if (plan !== undefined) {+ syncing.message("Preparing local content index");+ const { artifact } = await compileContentSource({+ source: createFileSystemContentSource({+ projectId: project.build.projectId,+ assets: project.assets,+ folders: new Map(+ (project.assetFolders ?? []).map((folder) => [folder.id, folder])+ ),+ }),+ projectId: project.build.projectId,+ plan,+ maxBytes: parseContentDatabaseMaxBytes(+ process.env.CONTENT_DATABASE_MAX_BYTES+ ),+ });+ project.assetIndex = artifact;+ }+ }+const localBuildFilePath = join(cwd(), LOCAL_DATA_FILE);await dependencies.createFileIfNotExists(localBuildFilePath);await dependencies.writeFile(diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex b8864cbc88..e9cef335a1 100644--- a/packages/cli/src/docs.generated.ts+++ b/packages/cli/src/docs.generated.ts@@ -2,15 +2,15 @@// Edit markdown files in src/docs instead.export const cliDocs = {"api-use-cases":- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Enter this workflow only when the user explicitly requests visual verification or opts in after being asked. Do not start preview, screenshots, diffs, OCR, or rendered audits automatically after a mutation.\n- `preview.status` reports whether generated output is `stale`. When no preview is running, `url`, `pid`, and `mode` are omitted. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- MCP preview and path-based screenshot tools select an available loopback port and return the preview URL. Do not pass `host` or `port`.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- After opt-in, use this so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Calling `preview.start` after a committed mutation restarts a stale iterative server so external browsers and HTTP clients receive the newly generated project.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- When launcher metadata is available, Preview reuses a supported npm or pnpm launcher. Without launcher metadata, it defaults to npm.\n- Unless `npm_config_cache` is already configured, npm uses the writable `.webstudio/preview/.npm-cache` directory.\n- For npm cache permission errors, unset `npm_config_cache` to use the preview-local cache, then retry. No cache deletion is required.\n- If dependency installation fails, check the reported package-manager path and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"<uploadedAssetId>","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section ws:style={css`padding: 32px;`}><h2>Product OS</h2><Switch><SwitchThumb /></Switch></section>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- Use lowercase HTML JSX such as `<div>` and `<form>`. The internal `ws:` namespace is not HTML-tag shorthand.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside exactly one direct `ws:block-template` child. A missing or second template container makes the Content Block invalid. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Store Content Block content in MDX\n\nCommands:\n\n- MCP tool: list-assets {"type":"file"}\n- MCP tool: upload-asset {"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\n- MCP tool: connect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\n- MCP tool: switch-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<otherMdxAssetId>"}}\n- MCP tool: inspect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: edit-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":"# Article title\\n\\nArticle body."}\n- MCP tool: update-content-block-frontmatter {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","properties":{"title":"Article title","draft":false}}\n- MCP tool: reload-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: migrate-content-block-template-references {"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\n- MCP tool: disconnect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n\nNotes:\n\n- Create the local `.mdx` file under `.webstudio/assets` before calling `upload-asset`. Use the returned Asset ID when connecting it.\n- Use the Content Block source operations for connecting, switching, inspecting, editing, reloading, and disconnecting. Do not create or delete the `src` prop with generic prop tools; the source operations preserve the Body outlet and Content Block lifecycle.\n- `renderScope` accepts any non-empty stable key for one rendered occurrence. Use a page-based key for a direct Content Block and a distinct key for each repeated Collection occurrence. It does not load a page, route parameters, or resource results. Supply the concrete scoped values needed to resolve an expression through `variables`.\n- For a result-one Assets resource, preview the concrete query, then connect its persisted expression with the previewed item supplied as `variables`, for example `source:{"type":"expression","value":"post.data.id"}` and `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`.\n- Connecting replaces existing Body content. If the result returns `requiresConfirmation:true`, report that replacement to the user and repeat the same call with `confirmReplacement:true` only after approval.\n- Prefer Markdown for standard document content; it automatically uses a unique matching semantic template when one exists. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG with authored properties that Markdown cannot express.\n- Verify that the Content Block has exactly one direct Templates container before connecting or editing MDX. Zero or multiple containers block materialization and publication.\n- Read the Content Block\'s Templates children before writing a custom reference. Use capitalized JSX such as `<PromotionCard />` for its stable **Name**, which is independent from the display label. A matching template wins; otherwise Webstudio uses the exact registered component export. JSX attributes accept quoted static values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported.\n- When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants and retain template styles. A mismatched child structure replaces the root defaults, while each authored child still resolves through a matching template when possible. An explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, so adding a matching semantic or named template later updates existing MDX. Preserve unresolved names and report their diagnostics instead of deleting them.\n- When a template is renamed or deleted, use `migrate-content-block-template-references` to update a selected set of affected MDX files. The first call returns a plan. Report its changed-file, update, omission, and diagnostic counts, then repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its authored children; removing a self-closing reference removes the node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n- `edit-content-block-source` replaces the complete MDX source. Preserve frontmatter and unrelated source when making a bounded edit.\n- `update-content-block-frontmatter` replaces the complete frontmatter mapping. Inspect the current source first and include every property that must remain.\n- Store frontmatter images as exact `$ref` objects. Bind an Image source to the resolved `.src` field and its alt property to `.description` so the Asset description supplies alternative text.\n- Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Keep computed expressions and `$ref` values read-only.\n- Inspect every returned diagnostic. Invalid MDX is saved rather than silently repaired; preserve the source, report the source range, and fix only the requested or invalid part.\n- If an edit in a long-lived MCP session reports a conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<jsonLdInstanceId>","name":"code","binding":{"type":"expression","value":"({ \'@context\': \'https://schema.org\', \'@type\': \'Article\', headline: post.title })"}}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- For fixed structured data, store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- For structured data containing runtime values, use `bind-props` with an expression that evaluates directly to an object or array. Do not call `JSON.stringify` or assemble JSON with string concatenation. Webstudio stores the expression as source text, evaluates it at runtime, and the `JsonLd` component validates and serializes the resulting value.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":{"--color-primary":"#2d3748","--color-accent":"#e53e3e","--space-card":"1.5rem"},"overwrite":true}\n\nNotes:\n\n- Define or overwrite multiple CSS variables atomically by including every name and value in one `vars` object.\n- Pass colors as CSS strings. Structured `hex` color components use normalized values from `0` to `1`, not `0` to `255`.\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":["--color-primary","--color-accent","--space-card"],"force":true}\n\nNotes:\n\n- Delete multiple CSS variables atomically by including every name in one `names` array. Destructive MCP calls still require the returned confirmation token before they commit.\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\'https://api.example.com/posts?tag=\' + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\'Bearer \' + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"result":"many","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body-ref"}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}\n- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body-ref"}}}\n\nNotes:\n\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading the source files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown or MDX, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the document\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- Use `result:"many"` for listings. It returns the ID-keyed map at `<dataSourceName>.data`, with `totalCount` and `hasMore` at `<dataSourceName>.meta`, and remains the default for existing queries. Bind a listing Collection to `posts.data`.\n- Use `result:"one"` for a unique detail route. It returns the selected item or `null` directly at `post.data`, always includes its `id`, and omits pagination. Bind components and page settings directly with expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404`. `result:"first"` and `result:"last"` also return a direct item or `null` but require explicit sorting.\n- Assets always executes a structured query. Omit `query` to use the default many-result query, which selects URL and optional image dimensions. Set `values.query:null` to restore it.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\nNotes:\n\n- Multi-file uploads return `uploaded`, `failed`, and `ambiguous` lists with the\n original input index. Retry only `failed` files. A forced upload in\n `ambiguous` may already be committed; inspect the Assets list before deciding\n whether to upload it again. Successful uploads remain committed.\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- webstudio search-project \'{"query":"pricing"}\'\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","namespaces":["resources"]}\n- MCP tool: search-project {"query":"Brand","namespaces":["styles","styleSources","styleSourceSelections"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- `search-project` is a standalone local-session command over every Builder namespace. It returns matching values with stable match ids, namespace paths, owning entities, references, and affected pages.\n- Use it when a value or id is known. Use list/get tools when the project structure or target is not known.\n- The command synchronizes its required Builder namespaces, then searches locally and returns only matches. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. This reduces data passed to the model, not the initial project-data synchronization.\n- Asset records and file metadata are searchable. Asset binary or document contents are not Builder namespace data and are not searched.\n- Values in recognized credential fields are excluded and counted in `excludedSensitiveValueCount`.\n- Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<article><h2>{expression`collectionItem.title`}</h2></article>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page","taskScope":"structural-project-change","workflow":"authenticated-page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page","taskScope":"visual-change","workflow":"design-input"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section><p>Section copy</p></section>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpoint":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Ask whether the user wants visual verification unless they explicitly requested\n it. If they decline, stop after focused reads and a static audit. If they opt\n in, verify one familiar viewport inside every distinct Builder breakpoint\n range, then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with `workflow:"authenticated-page"`, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with `workflow:"design-input"`, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Enter this workflow only when the user explicitly requests visual verification or opts in after being asked. Do not start preview, screenshots, diffs, OCR, or rendered audits automatically after a mutation.\n- `preview.status` reports whether generated output is `stale`. When no preview is running, `url`, `pid`, and `mode` are omitted. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- MCP preview and path-based screenshot tools select an available loopback port and return the preview URL. Do not pass `host` or `port`.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- After opt-in, use this so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Calling `preview.start` after a committed mutation restarts a stale iterative server so external browsers and HTTP clients receive the newly generated project.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- When launcher metadata is available, Preview reuses a supported npm or pnpm launcher. Without launcher metadata, it defaults to npm.\n- Unless `npm_config_cache` is already configured, npm uses the writable `.webstudio/preview/.npm-cache` directory.\n- For npm cache permission errors, unset `npm_config_cache` to use the preview-local cache, then retry. No cache deletion is required.\n- If dependency installation fails, check the reported package-manager path and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"<uploadedAssetId>","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section ws:style={css`padding: 32px;`}><h2>Product OS</h2><Switch><SwitchThumb /></Switch></section>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- Use lowercase HTML JSX such as `<div>` and `<form>`. The internal `ws:` namespace is not HTML-tag shorthand.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside exactly one direct `ws:block-template` child. A missing or second template container makes the Content Block invalid. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before implementation, inventory every editor-owned field and its intended control and write destination, whether or not the block uses MDX. Check that templates contain the required styling, but do not treat containment or a successful text edit as proof that the whole block is editable. Test every field through Content mode, inspect its saved project data or source file, reload, and restore the original value. Report passed, failed, or not tested for each field; missing or read-only required controls are unfinished requirements.\n- Use controls that match the content: a calendar for dates and an image picker for image replacement. Keep fixed punctuation and units out of directly bound value elements. Preserve stored types and wording: when reading time is already a complete string such as `4 min read`, bind that string directly rather than assuming it is a number.\n- For MDX-backed blocks, containment alone is not enough: the MDX body is editable through its source mapping, but the designed shell needs writable document-frontmatter bindings. Follow the binding recipe below rather than binding editable article fields to query results.\n\n## Store Content Block content in MDX\n\nCommands:\n\n- MCP tool: list-assets {"type":"file"}\n- MCP tool: upload-asset {"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\n- MCP tool: connect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\n- MCP tool: switch-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<otherMdxAssetId>"}}\n- MCP tool: inspect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: edit-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":"# Article title\\n\\nArticle body."}\n- MCP tool: update-content-block-frontmatter {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","properties":{"title":"Article title","draft":false}}\n- MCP tool: reload-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: migrate-content-block-template-references {"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\n- MCP tool: disconnect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n\nNotes:\n\n- Create the local `.mdx` file under `.webstudio/assets` before calling `upload-asset`. Use the returned Asset ID when connecting it.\n- Use the Content Block source operations for connecting, switching, inspecting, editing, reloading, and disconnecting. Do not create or delete the `src` prop with generic prop tools; the source operations preserve the Body outlet and Content Block lifecycle.\n- `renderScope` accepts any non-empty stable key for one rendered occurrence. Use a page-based key for a direct Content Block and a distinct key for each repeated Collection occurrence. It does not load a page, route parameters, or resource results. Supply the concrete scoped values needed to resolve an expression through `variables`.\n- For a result-one Assets resource, preview the concrete query, then connect its persisted expression with the previewed item supplied as `variables`, for example `source:{"type":"expression","value":"post.data.id"}` and `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`.\n- Connecting replaces existing Body content. If the result returns `requiresConfirmation:true`, report that replacement to the user and repeat the same call with `confirmReplacement:true` only after approval.\n- Prefer Markdown for standard document content; it automatically uses a unique matching semantic template when one exists. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG with authored properties that Markdown cannot express.\n- Verify that the Content Block has exactly one direct Templates container before connecting or editing MDX. Zero or multiple containers block materialization and publication.\n- Read the Content Block\'s Templates children before writing a custom reference. Use capitalized JSX such as `<PromotionCard />` for its stable **Name**, which is independent from the display label. A matching template wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. JSX attributes accept quoted static values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported.\n- When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants and retain template styles. A mismatched child structure replaces the root defaults, while each authored child still resolves through a matching template when possible. An explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, so adding a matching semantic or named template later updates existing MDX. Preserve unresolved names and report their diagnostics instead of deleting them.\n- When a template is renamed or deleted, use `migrate-content-block-template-references` to update a selected set of affected MDX files. The first call returns a plan. Report its changed-file, update, omission, and diagnostic counts, then repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its authored children; removing a self-closing reference removes the node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n- `edit-content-block-source` replaces the complete MDX source. Preserve frontmatter and unrelated source when making a bounded edit.\n- `update-content-block-frontmatter` replaces the complete frontmatter mapping. Inspect the current source first and include every property that must remain.\n- Store frontmatter images as exact `$ref` objects. Bind an editable Image source to the resolved `.src` with explicit `binding.mode:"readwrite"`; use `mode:"read"` for its alt binding to `.description`. Omitting the source mode leaves the image visible but not replaceable in Content mode.\n- Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n- Inspect every returned diagnostic. Invalid MDX is saved rather than silently repaired; preserve the source, report the source range, and fix only the requested or invalid part.\n- If an edit in a long-lived MCP session reports a conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly.\n\n## Make an MDX article header editable\n\nUse the resource only to select the connected source, for example `post.data.id`.\nBind article values inside the Content Block to its document parameter instead\nof `post.data.properties.*`. Inspect the block\'s variables first; `document` is\nthe default name, not a name to assume.\n\nThese commands target persistent designed instances inside the connected block.\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<headingInstanceId>","childIndex":0,"text":"document.frontmatter.title","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: update-text {"instanceId":"<readingTimeValueInstanceId>","childIndex":0,"text":"document.frontmatter.readingTime","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<dateInstanceId>","name":"datetime","binding":{"type":"expression","value":"document.frontmatter.publishedAt","mode":"readwrite"}}]}\n\nNotes:\n\n- Create writable bindings explicitly; the default is read-only. Merely moving a heading or Link inside the Content Block does not make its query-bound text editable.\n- The MDX body uses its source mapping. Static designed content outside that body remains protected unless its text or supported props bind to writable frontmatter fields. Do not apply these generic instance tools to MDX-generated instances.\n- Use direct static paths. Property access is already safe. Fallbacks and formatted expressions, such as `document.frontmatter.title ?? "Untitled"`, remain read-only.\n- Keep every intended editable value in its own text element with a single direct read-write binding. For reading time, use three inline siblings: static `— `, the bound reading-time value, and static ` min read`. Preserve whitespace and the stored field type. Do not combine them into a template literal or concatenate strings, and do not put literal siblings inside the value element itself. Keep fixed wording protected in the designed shell.\n- Prefer component formatting controls, such as Date Time formatting with a directly bound date prop, over transforming the expression. Do not silently sacrifice editability for formatting or a fallback; explain unsupported cases and ask before making an intended editable field read-only.\n- A direct writable binding such as `document.frontmatter.author.name` can edit a shared author loaded through `../authors/oleg.md#frontmatter`. The edit saves to the author file and affects every article using it; preserve the article\'s `$ref` marker.\n- Before handoff, inventory every article-owned field, including header text, author details, dates, reading time, categories, hero and inline image sources, alternative text, captions, links, and custom-component content. For each field, inspect its binding and source, edit it through the Content-mode UI, verify the saved MDX or referenced file, reload, and restore the test value. Record passed, failed, or not tested for each field. A correct preview, a successful MCP write, and one representative text edit do not prove the whole article is editable. Do not claim completion while required fields fail or remain untested.\n- Bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. Content mode\'s **Choose source** replaces the article\'s frontmatter image `$ref`; the resolved URL stays read-only. Verify selection, the saved reference, and reload instead of treating a missing write mode as a platform limitation. For alternative text bound to `.description`, use **Choose source → asset actions → Settings → Description** to edit shared Asset metadata. This affects every use of the Asset and is separate from replacing an article\'s image.\n\n## Make an article image replaceable in Content mode\n\nUse this for a persistent designed Image inside a connected Content Block,\nwith `featureImage: { $ref: "./images/hero.png" }` in its MDX frontmatter.\nRead the instance ID and document variable name before adapting the example.\n\nCommands:\n\n- MCP tool: bind-props {"bindings":[{"instanceId":"<imageInstanceId>","name":"src","binding":{"type":"expression","value":"document.frontmatter.featureImage.src","mode":"readwrite"}},{"instanceId":"<imageInstanceId>","name":"alt","binding":{"type":"expression","value":"document.frontmatter.featureImage.description","mode":"read"}}]}\n\nNotes:\n\n- The source mode must be explicit: the default `read` mode displays the image but prevents Content-mode replacement. Do not bind to query-result properties or add a fallback expression.\n- **Choose source** replaces the article\'s `featureImage.$ref`; the disabled resolved-URL input is expected. Do not store a resolved URL string or replace the shared Asset itself.\n- Shared alternative text is a separate action: **Choose source → asset actions → Settings → Description**. Its read-only binding does not require the image source binding to be read-only.\n- If the picker is missing or disabled, inspect the source mode, document scope, loaded reference, and permissions before claiming a product limitation.\n- Verify through Content mode with an approved temporary replacement. Check the saved `$ref`, unchanged unrelated MDX and original shared Asset, reload persistence, and restoration. If that test is not authorized, report it as not tested, not passed.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<jsonLdInstanceId>","name":"code","binding":{"type":"expression","value":"({ \'@context\': \'https://schema.org\', \'@type\': \'Article\', headline: post.title })"}}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- For fixed structured data, store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- For structured data containing runtime values, use `bind-props` with an expression that evaluates directly to an object or array. Do not call `JSON.stringify` or assemble JSON with string concatenation. Webstudio stores the expression as source text, evaluates it at runtime, and the `JsonLd` component validates and serializes the resulting value.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":{"--color-primary":"#2d3748","--color-accent":"#e53e3e","--space-card":"1.5rem"},"overwrite":true}\n\nNotes:\n\n- Define or overwrite multiple CSS variables atomically by including every name and value in one `vars` object.\n- Pass colors as CSS strings. Structured `hex` color components use normalized values from `0` to `1`, not `0` to `255`.\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":["--color-primary","--color-accent","--space-card"],"force":true}\n\nNotes:\n\n- Delete multiple CSS variables atomically by including every name in one `names` array. Destructive MCP calls still require the returned confirmation token before they commit.\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\'https://api.example.com/posts?tag=\' + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\'Bearer \' + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"result":"many","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body-ref"}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}\n- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body-ref"}}}\n\nNotes:\n\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading the source files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown or MDX, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the document\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- Use `result:"many"` for listings. It returns the ID-keyed map at `<dataSourceName>.data`, with `totalCount` and `hasMore` at `<dataSourceName>.meta`, and remains the default for existing queries. Bind a listing Collection to `posts.data`.\n- Use `result:"one"` for a unique detail route. It returns the selected item or `null` directly at `post.data`, always includes its `id`, and omits pagination. Bind components and page settings directly with expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404`. `result:"first"` and `result:"last"` also return a direct item or `null` but require explicit sorting.\n- Assets always executes a structured query. Omit `query` to use the default many-result query, which selects URL and optional image dimensions. Set `values.query:null` to restore it.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\nNotes:\n\n- Multi-file uploads return `uploaded`, `failed`, and `ambiguous` lists with the\n original input index. Retry only `failed` files. A forced upload in\n `ambiguous` may already be committed; inspect the Assets list before deciding\n whether to upload it again. Successful uploads remain committed.\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- webstudio search-project \'{"query":"pricing"}\'\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","namespaces":["resources"]}\n- MCP tool: search-project {"query":"Brand","namespaces":["styles","styleSources","styleSourceSelections"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- `search-project` is a standalone local-session command over every Builder namespace. It returns matching values with stable match ids, namespace paths, owning entities, references, and affected pages.\n- Use it when a value or id is known. Use list/get tools when the project structure or target is not known.\n- The command synchronizes its required Builder namespaces, then searches locally and returns only matches. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. This reduces data passed to the model, not the initial project-data synchronization.\n- Asset records and file metadata are searchable. Asset binary or document contents are not Builder namespace data and are not searched.\n- Values in recognized credential fields are excluded and counted in `excludedSensitiveValueCount`.\n- Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<article><h2>{expression`collectionItem.title`}</h2></article>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page","taskScope":"structural-project-change","workflow":"authenticated-page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page","taskScope":"visual-change","workflow":"design-input"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section><p>Section copy</p></section>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpoint":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Ask whether the user wants visual verification unless they explicitly requested\n it. If they decline, stop after focused reads and a static audit. If they opt\n in, verify one familiar viewport inside every distinct Builder breakpoint\n range, then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with `workflow:"authenticated-page"`, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with `workflow:"design-input"`, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',"manual-api":'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## Search project data\n\nRun `webstudio search-project \'{"query":"known value"}\'` to search all Builder\nnamespaces in the local project session. Narrow it with\n`{"query":"Brand","namespaces":["styleSources","styles"]}` when only specific\nnamespaces are relevant. Results contain the current value, stable match id,\nnamespace path, owning entity, resolved references, and affected pages.\n\nValues in recognized credential fields are excluded and reported in\n`excludedSensitiveValueCount`.\n\nThe command synchronizes its required Builder namespaces, then searches locally\nand returns only matches. Namespace filters limit values matched; related\nnamespaces may still supply route and reference context, and synchronization is\nunchanged. This reduces data sent to the model, not project synchronization. It\nsearches asset metadata, not asset binaries or document contents.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, and `json`. Use `json`\nfor all arrays and objects, including tags, selected categories, and nested API\nfilter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',"manual-llm":- '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the readable payload in `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nSingle quotes inside the JSX keep the JSON valid without backslash-escaped attributes. The same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS. For simpler cases, use React-style object syntax such as`style={{ padding: 24 }}`. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in exactly one direct `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes editable Content Block body content. A missing or second template container makes the block invalid. Verify this structure before handoff.\n\nWhen the Content Block body must be stored in an `.mdx` Asset, use the dedicated `connect-content-block-source`, `switch-content-block-source`, `inspect-content-block-source`, `edit-content-block-source`, `update-content-block-frontmatter`, `reload-content-block-source`, and `disconnect-content-block-source` tools. Do not manipulate its `src` with generic prop tools. Connecting replaces existing Body content, so report `requiresConfirmation:true` and retry with `confirmReplacement:true` only after user approval. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX first resolves the stable template **Name**, then the exact registered component export. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep their template styles. A mismatched child structure replaces defaults, while an explicit empty pair clears defaults and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, including when a matching template is added after the MDX element. Preserve invalid MDX and unresolved template names, inspect all source-located diagnostics, and resolve revision conflicts by reloading before reapplying the change. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy updates across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nFrontmatter is part of the same MDX source. `update-content-block-frontmatter` receives the complete replacement property map, so inspect and preserve properties the user did not ask to remove. Store frontmatter images as exact `$ref` objects, bind Image sources to their resolved `.src`, and bind alt properties to their Asset `.description`. Use `update-content-block-frontmatter` for MCP frontmatter edits; MDX-rendered elements are not persistent targets for generic prop or text mutations. Preserve existing `mode:"readwrite"` bindings, which are valid only for exact direct frontmatter paths. Computed expressions and `$ref` values stay read-only. For an expression-bound source inside a Collection, pass the occurrence\'s scoped values and a distinct stable `renderScope`; for example, resolve `post.assetId` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<button onClick={new ActionValue(["event"], expression`console.log(event)`)}>\n Open\n</button>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <section\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <h2>Launch metrics</h2>\n <p>A polished card that fades up as it enters the viewport.</p>\n </section>\n</AnimateChildren>\n```\n\nFor Text Animation, keep `AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <AnimateText splitBy="space" slidingWindow={5} easing="easeOutQuart">\n <h2>Animate words with controlled rhythm</h2>\n </AnimateText>\n</AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `StaggerAnimation`:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <StaggerAnimation>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </article>\n </StaggerAnimation>\n</AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <VideoAnimation timeline={true}>\n <Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </VideoAnimation>\n</AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. When a value or id is known, call `search-project` once instead of passing broad snapshots or several lists to the model. Use semantic list/get reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, and `list-breakpoints` when the structure or target is not known. Use `snapshot` only when exact raw patch paths are needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n For a Builder link from **Copy link to instance**, parse the URL with `URL`/`URLSearchParams`. The decoded `instance` query parameter is a comma-separated selector ordered from the target instance to the page root. Pass its first entry to `inspect-instance`, for example `?pageId=page-id&instance=heading-id%2Cslot-id%2Cbody-id` becomes `{"instanceId":"heading-id","include":["props","styles","children","ancestors"]}`. Use `pageId` and the remaining selector entries to check the page and shared Slot occurrence before changing it. Shared Slot descendants are shared records; editing one changes all occurrences. Verify that the configured MCP project matches the linked project before editing; stop if they differ. The URL does not authorize switching projects. If the instance is missing, ask for an updated link instead of guessing another target. Never send a Builder link to screenshot tools or echo its `authToken`.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, ask whether the user wants visual verification unless they explicitly requested it. Only after they opt in, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Ask whether the user wants visual verification unless they explicitly requested screenshots, visual verification, or a rendered audit. Do not start preview, screenshots, screenshot diffs, OCR installation, or rendered audits until they opt in.\n5. After they opt in, keep generated project files current, start preview, and capture the changed page with `screenshot`.\n6. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n7. If the user declines or vision tooling is unavailable, use focused non-visual assertions and state that vision was not run.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Ask whether the user wants visual verification unless they explicitly requested it. Do not capture responsive screenshots until they opt in.\n4. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n5. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n6. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n7. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource that always executes a structured query. `result:"many"` returns the existing ID-keyed collection shape and is the backward-compatible default. `result:"one"`, `result:"first"`, and `result:"last"` return one direct item or `null`; first and last require explicit sorting. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output.\n- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.\n- Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use `content.mode:"none"`. This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as `system.params.slug` on the detail route.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected files from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding the document.\n- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.\n- Deferred Markdown or MDX bodies exclude frontmatter and resolve conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- For `result:"many"`, Assets expose an ID-keyed map at `<dataSourceName>.data` and `totalCount`/`hasMore` at `<dataSourceName>.meta`; bind a listing Collection to `posts.data`. Single-result modes expose the selected item or `null` directly at `<dataSourceName>.data`, always include its `id`, and expose `totalCount` in meta. Bind detail components and page settings directly from expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404` without a Collection.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can use an expression such as `"Bearer " + auth.token`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access without optional chaining. Use nullish coalescing when a fallback is required.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',+ '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the readable payload in `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nSingle quotes inside the JSX keep the JSON valid without backslash-escaped attributes. The same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS. For simpler cases, use React-style object syntax such as`style={{ padding: 24 }}`. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in exactly one direct `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes editable Content Block body content. A missing or second template container makes the block invalid. Verify this structure before handoff.\n\nWhen the Content Block body must be stored in an `.mdx` Asset, use the dedicated `connect-content-block-source`, `switch-content-block-source`, `inspect-content-block-source`, `edit-content-block-source`, `update-content-block-frontmatter`, `reload-content-block-source`, and `disconnect-content-block-source` tools. Do not manipulate its `src` with generic prop tools. Connecting replaces existing Body content, so report `requiresConfirmation:true` and retry with `confirmReplacement:true` only after user approval. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep their template styles. A mismatched child structure replaces defaults, while an explicit empty pair clears defaults and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, including when a matching template is added after the MDX element. Preserve invalid MDX and unresolved template names, inspect all source-located diagnostics, and resolve revision conflicts by reloading before reapplying the change. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy updates across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nFrontmatter is part of the same MDX source. `update-content-block-frontmatter` receives the complete replacement property map, so inspect and preserve properties the user did not ask to remove. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits; MDX-rendered elements are not persistent targets for generic prop or text mutations. Preserve existing `mode:"readwrite"` bindings, which are valid only for exact direct frontmatter paths. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. For an expression-bound source inside a Collection, pass the occurrence\'s scoped values and a distinct stable `renderScope`; for example, resolve `post.assetId` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<button onClick={new ActionValue(["event"], expression`console.log(event)`)}>\n Open\n</button>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <section\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <h2>Launch metrics</h2>\n <p>A polished card that fades up as it enters the viewport.</p>\n </section>\n</AnimateChildren>\n```\n\nFor Text Animation, keep `AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <AnimateText splitBy="space" slidingWindow={5} easing="easeOutQuart">\n <h2>Animate words with controlled rhythm</h2>\n </AnimateText>\n</AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `StaggerAnimation`:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <StaggerAnimation>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </article>\n </StaggerAnimation>\n</AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <VideoAnimation timeline={true}>\n <Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </VideoAnimation>\n</AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. When a value or id is known, call `search-project` once instead of passing broad snapshots or several lists to the model. Use semantic list/get reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, and `list-breakpoints` when the structure or target is not known. Use `snapshot` only when exact raw patch paths are needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n For a Builder link from **Copy link to instance**, parse the URL with `URL`/`URLSearchParams`. The decoded `instance` query parameter is a comma-separated selector ordered from the target instance to the page root. Pass its first entry to `inspect-instance`, for example `?pageId=page-id&instance=heading-id%2Cslot-id%2Cbody-id` becomes `{"instanceId":"heading-id","include":["props","styles","children","ancestors"]}`. Use `pageId` and the remaining selector entries to check the page and shared Slot occurrence before changing it. Shared Slot descendants are shared records; editing one changes all occurrences. Verify that the configured MCP project matches the linked project before editing; stop if they differ. The URL does not authorize switching projects. If the instance is missing, ask for an updated link instead of guessing another target. Never send a Builder link to screenshot tools or echo its `authToken`.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, ask whether the user wants visual verification unless they explicitly requested it. Only after they opt in, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Ask whether the user wants visual verification unless they explicitly requested screenshots, visual verification, or a rendered audit. Do not start preview, screenshots, screenshot diffs, OCR installation, or rendered audits until they opt in.\n5. After they opt in, keep generated project files current, start preview, and capture the changed page with `screenshot`.\n6. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n7. If the user declines or vision tooling is unavailable, use focused non-visual assertions and state that vision was not run.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Ask whether the user wants visual verification unless they explicitly requested it. Do not capture responsive screenshots until they opt in.\n4. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n5. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n6. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n7. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource that always executes a structured query. `result:"many"` returns the existing ID-keyed collection shape and is the backward-compatible default. `result:"one"`, `result:"first"`, and `result:"last"` return one direct item or `null`; first and last require explicit sorting. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output.\n- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.\n- Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use `content.mode:"none"`. This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as `system.params.slug` on the detail route.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected files from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding the document.\n- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.\n- Deferred Markdown or MDX bodies exclude frontmatter and resolve conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- For `result:"many"`, Assets expose an ID-keyed map at `<dataSourceName>.data` and `totalCount`/`hasMore` at `<dataSourceName>.meta`; bind a listing Collection to `posts.data`. Single-result modes expose the selected item or `null` directly at `<dataSourceName>.data`, always include its `id`, and expose `totalCount` in meta. Bind detail components and page settings directly from expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404` without a Collection.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can use an expression such as `"Bearer " + auth.token`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access. Use nullish coalescing when a fallback is required.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',"manual-mcp":- '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<section style={{ padding: 32, borderRadius: 16 }}>\n <h2>Operations Console</h2>\n <p>\n React-style object styles become editable Webstudio styles.\n </p>\n</section>\n\n<section ws:tokens={[token("accent", css`color: #0f766e;`)]}>\n <button\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </button>\n</section>\n\n<section>\n <Switch>\n <SwitchThumb />\n </Switch>\n</section>\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. Use direct animation component identifiers such as `<AnimateChildren>`; `animation` is accepted only as legacy input and is not a callable CSS keyframes helper.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## MDX-backed Content Blocks\n\nUse a connected `.mdx` Asset when editors should change a Content Block body visually while the document remains stored as a file.\n\n1. Create the `.mdx` file under `.webstudio/assets`, then upload it and keep the returned Asset ID.\n2. Inspect the Content Block and verify that it has exactly one direct Templates container. Every custom template referenced from MDX needs a unique top-level instance name. A missing or second Templates container blocks connected MDX materialization and publication.\n3. Connect the Asset with `connect-content-block-source`. Use a stable page-based `renderScope` for a direct occurrence.\n4. If the result returns `requiresConfirmation:true`, tell the user that connecting will replace the existing Body content. Repeat the same call with `confirmReplacement:true` only after approval.\n5. Edit the complete source with `edit-content-block-source`, or replace the complete frontmatter map with `update-content-block-frontmatter`.\n6. Inspect every returned diagnostic. Invalid MDX is preserved, not silently repaired.\n\n```sh\nwebstudio upload-asset \'{"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\'\nwebstudio connect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\'\nwebstudio inspect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio edit-content-block-source --input-file .temp/edit-content-block-source.json\nwebstudio reload-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio migrate-content-block-template-references \'{"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\'\n```\n\nPrefer Markdown for standard document content. Markdown nodes automatically use a unique matching semantic template when one exists and keep their normal semantic fallback otherwise. Use lowercase JSX such as `<section>` or `<svg>` for a standard HTML or SVG element with authored properties Markdown cannot express.\n\nReference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template\'s stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins; otherwise the exact registered component export is used. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.\n\nWhen explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants so template styles stay intact. A mismatched child structure replaces the root defaults, and each authored child still resolves through a matching template when possible. An explicit empty pair such as `<PromotionCard></PromotionCard>` clears the defaults. A self-closing reference such as `<PromotionCard />` keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live: adding a missing semantic or named template later also updates existing MDX without rewriting it. Preserve unresolved template names and report their diagnostics.\n\nWhen a template is renamed or deleted, use `migrate-content-block-template-references` to update the affected MDX files. Its first call returns a plan with changed-file, update, omission, and diagnostic counts. Report the plan and repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its explicit authored children; removing a self-closing reference removes that node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n\nUse the dedicated connect, switch, inspect, edit, update-frontmatter, reload, and disconnect operations instead of creating or deleting the Content Block\'s `src` with generic prop tools. An expression-bound source inside a Collection also needs the occurrence\'s scoped values and a distinct stable `renderScope`. For example, use `source:{"type":"expression","value":"post.assetId"}` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\n`renderScope` is any non-empty stable identity for one rendered occurrence, such as `page:/articles/example`. It does not load that page, its route parameters, or its resource results. To connect a result-one Assets resource, run `preview-asset-query` with concrete values, keep the saved source expression such as `post.data.id`, and supply the previewed item for this occurrence with `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`. The operation validates that concrete Asset while persisting the dynamic expression.\n\nA source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects, bind Image sources to their resolved `.src`, and bind alt properties to their Asset `.description`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Computed expressions and `$ref` values remain read-only.\n\nIf an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n- `search-project`: find a known value or id with `webstudio search-project \'{"query":"pricing"}\'` or MCP `search-project {"query":"pricing"}`; use focused list/get tools when the target structure is unknown\n\n`meta.guide` returns structured `routing` with the selected workflow and any broad context bundle it recommends. Authentication and design context bundles appear only when their specialized workflow is selected. Set `authoredFragment` when using an authored fragment and `reuseDesignSystem` when its recommendations should retain design-system discovery tools.\n\nSet `taskScope` and `workflow` explicitly; `meta.guide` does not infer them or the authored-fragment flags from the brief. Specialized workflows are `markdown-blog`, `json-ld`, `collection`, `expression`, `authenticated-page`, `font-assets`, `design-input`, and `craft`; otherwise use `general`. For work that must not change project or local state, pass `{"brief":"Inventory custom code","taskScope":"read-only-audit","workflow":"general"}`. The resulting `read-only-discovery` workflow excludes mutation and side-effecting session tools and uses focused search, list, get, inspect, and snapshot tools.\n\n`search-project` follows normal ProjectSession synchronization, then searches in the CLI process. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. Only paged matches enter model context. Recognized credential fields and asset binary or document bodies are excluded.\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Search all Builder namespaces for a known value or id without putting complete namespace data in model context.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n{{contentEngineReferenceMarkdown}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',+ '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<section style={{ padding: 32, borderRadius: 16 }}>\n <h2>Operations Console</h2>\n <p>\n React-style object styles become editable Webstudio styles.\n </p>\n</section>\n\n<section ws:tokens={[token("accent", css`color: #0f766e;`)]}>\n <button\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </button>\n</section>\n\n<section>\n <Switch>\n <SwitchThumb />\n </Switch>\n</section>\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. Use direct animation component identifiers such as `<AnimateChildren>`; `animation` is accepted only as legacy input and is not a callable CSS keyframes helper.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## MDX-backed Content Blocks\n\nUse a connected `.mdx` Asset when editors should change a Content Block body visually while the document remains stored as a file.\n\n1. Create the `.mdx` file under `.webstudio/assets`, then upload it and keep the returned Asset ID.\n2. Inspect the Content Block and verify that it has exactly one direct Templates container. Every custom template referenced from MDX needs a unique top-level instance name. A missing or second Templates container blocks connected MDX materialization and publication.\n3. Connect the Asset with `connect-content-block-source`. Use a stable page-based `renderScope` for a direct occurrence.\n4. If the result returns `requiresConfirmation:true`, tell the user that connecting will replace the existing Body content. Repeat the same call with `confirmReplacement:true` only after approval.\n5. Edit the complete source with `edit-content-block-source`, or replace the complete frontmatter map with `update-content-block-frontmatter`.\n6. Inspect every returned diagnostic. Invalid MDX is preserved, not silently repaired.\n\n```sh\nwebstudio upload-asset \'{"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\'\nwebstudio connect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\'\nwebstudio inspect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio edit-content-block-source --input-file .temp/edit-content-block-source.json\nwebstudio reload-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio migrate-content-block-template-references \'{"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\'\n```\n\nPrefer Markdown for standard document content. Markdown nodes automatically use a unique matching semantic template when one exists and keep their normal semantic fallback otherwise. Use lowercase JSX such as `<section>` or `<svg>` for a standard HTML or SVG element with authored properties Markdown cannot express.\n\nReference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template\'s stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.\n\nWhen explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants so template styles stay intact. A mismatched child structure replaces the root defaults, and each authored child still resolves through a matching template when possible. An explicit empty pair such as `<PromotionCard></PromotionCard>` clears the defaults. A self-closing reference such as `<PromotionCard />` keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live: adding a missing semantic or named template later also updates existing MDX without rewriting it. Preserve unresolved template names and report their diagnostics.\n\nWhen a template is renamed or deleted, use `migrate-content-block-template-references` to update the affected MDX files. Its first call returns a plan with changed-file, update, omission, and diagnostic counts. Report the plan and repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its explicit authored children; removing a self-closing reference removes that node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n\nUse the dedicated connect, switch, inspect, edit, update-frontmatter, reload, and disconnect operations instead of creating or deleting the Content Block\'s `src` with generic prop tools. An expression-bound source inside a Collection also needs the occurrence\'s scoped values and a distinct stable `renderScope`. For example, use `source:{"type":"expression","value":"post.assetId"}` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\n`renderScope` is any non-empty stable identity for one rendered occurrence, such as `page:/articles/example`. It does not load that page, its route parameters, or its resource results. To connect a result-one Assets resource, run `preview-asset-query` with concrete values, keep the saved source expression such as `post.data.id`, and supply the previewed item for this occurrence with `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`. The operation validates that concrete Asset while persisting the dynamic expression.\n\nA source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nIf an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n- `search-project`: find a known value or id with `webstudio search-project \'{"query":"pricing"}\'` or MCP `search-project {"query":"pricing"}`; use focused list/get tools when the target structure is unknown\n\n`meta.guide` returns structured `routing` with the selected workflow and any broad context bundle it recommends. Authentication and design context bundles appear only when their specialized workflow is selected. Set `authoredFragment` when using an authored fragment and `reuseDesignSystem` when its recommendations should retain design-system discovery tools.\n\nSet `taskScope` and `workflow` explicitly; `meta.guide` does not infer them or the authored-fragment flags from the brief. Specialized workflows are `markdown-blog`, `json-ld`, `collection`, `expression`, `authenticated-page`, `font-assets`, `design-input`, and `craft`; otherwise use `general`. For work that must not change project or local state, pass `{"brief":"Inventory custom code","taskScope":"read-only-audit","workflow":"general"}`. The resulting `read-only-discovery` workflow excludes mutation and side-effecting session tools and uses focused search, list, get, inspect, and snapshot tools.\n\n`search-project` follows normal ProjectSession synchronization, then searches in the CLI process. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. Only paged matches enter model context. Recognized credential fields and asset binary or document bodies are excluded.\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Search all Builder namespaces for a known value or id without putting complete namespace data in model context.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n{{contentEngineReferenceMarkdown}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',"mcp-startup-epilogue":- 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in exactly one direct `ws:block-template` child. A missing or second template container makes the block invalid. Templates themselves are protected; an editor\'s inserted copy becomes editable Content Block body content. Verify this structure before handoff.\n\nFor an MDX-backed Content Block, use the dedicated content-source tools instead of generic prop mutations: connect, switch, inspect, edit, update frontmatter, reload, or disconnect the source. Confirm before replacing existing Body content. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX first resolves the stable template **Name**, then the exact registered component export. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep template styles. A mismatched child structure replaces defaults, an explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live when matching templates are added later. Preserve invalid source and unresolved names, inspect all diagnostics, and reload before retrying a revision conflict. A frontmatter update replaces the complete property map; preserve fields the user did not ask to remove. Store frontmatter images as exact `$ref` objects; bind Image sources to `.src` and alt properties to the Asset `.description`. Only exact direct frontmatter bindings may use `mode:"readwrite"`. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy changes across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get-more-tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nWhen `report-issue` is available, use it when the user explicitly asks to report a problem. Also use it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. Write a complete anonymous report with the generalized user story, attempted workflow, expected behavior, actual result, recovery attempts, impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, exact unique values, or raw contextual tool data.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',+ 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in exactly one direct `ws:block-template` child. A missing or second template container makes the block invalid. Templates themselves are protected; an editor\'s inserted copy becomes editable Content Block body content. Verify this structure before handoff.\n\nFor an MDX-backed Content Block, use the dedicated content-source tools instead of generic prop mutations: connect, switch, inspect, edit, update frontmatter, reload, or disconnect the source. Confirm before replacing existing Body content. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep template styles. A mismatched child structure replaces defaults, an explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live when matching templates are added later. Preserve invalid source and unresolved names, inspect all diagnostics, and reload before retrying a revision conflict. A frontmatter update replaces the complete property map; preserve fields the user did not ask to remove. Store frontmatter images as exact `$ref` objects; bind editable Image sources to `.src` with explicit `binding.mode:"readwrite"` and alt properties to the Asset `.description` with `mode:"read"`. Omitting the source mode leaves the image visible but not replaceable in Content mode. Only exact direct frontmatter bindings may use `mode:"readwrite"`. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy changes across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get-more-tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nWhen `report-issue` is available, use it when the user explicitly asks to report a problem. Also use it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. Write a complete anonymous report with the generalized user story, attempted workflow, expected behavior, actual result, recovery attempts, impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, exact unique values, or raw contextual tool data.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',"mcp-vision":'# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.\n- Session previews download missing project assets into `.webstudio/assets`. If `PREVIEW_ASSET_DOWNLOAD_FAILED` occurs, restore network and project asset access, then retry `preview.start`.\n- When launcher metadata is available, dependency installation reuses a supported npm or pnpm launcher. Without launcher metadata, it defaults to npm.\n- When npm is selected, dependency installation honors `npm_config_cache`. If it is unset, preview uses the writable `.webstudio/preview/.npm-cache` directory instead of the user\'s default npm cache.\n- For npm cache permission errors, unset `npm_config_cache` to use the preview-local cache, then retry. No cache deletion is required.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, the error includes the selected package-manager path and sanitized diagnostics. Check that path and the network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n\n## Visual Verification Rule\n\nAsk the user whether they want visual verification before starting it, unless the user explicitly requested screenshots, visual verification, or a rendered audit. Never start `preview.start`, `screenshot`, `screenshot.diff`, `vision.install-ocr`, or a rendered audit automatically. If the user does not opt in, use focused non-visual assertions and report that vision was not run. After the user opts in, use `preview.start` and `screenshot({ path })` so vision can inspect the current MCP session and verify that generated project files are current. Iterative preview is the default: it keeps one generated-site server and browser alive, regenerates changed files, and performs an ordinary page reload without Vite HMR. Use `mode: "production"` only for release-like verification; rendered audit selects it automatically. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\nAn authenticated project share URL is used with `webstudio init --link`; it is\nnot a generated-site preview URL. Project screenshots and rendered audits use\nthe generated local preview owned by the current CLI/MCP process. Do not pass a\nBuilder/share URL to `screenshot`, even without query parameters. Use `path`\nafter starting preview, or use `baseUrl` only for an intentional generated site\nthat is already running. Path captures verify the generated-site root marker\nand fail instead of returning a screenshot of Builder chrome.\n\n## Vision Verification Loop\n\n- Ask the user whether they want visual verification unless they explicitly requested it. Stop before calling preview, capture, comparison, OCR, or rendered-audit tools until the user opts in.\n- Make focused page/content/style changes with semantic MCP tools.\n- Call preview.start once to keep the iterative generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- Read `preview.status.stale` before relying on generated output. When present, `renderedProjectVersion` identifies the last project version materialized into the preview; a stale preview refreshes automatically on the next managed screenshot or `preview.start` call.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate the current session in place, wait for its exact project version, and normally reload the route. The server and browser remain alive. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running generated site without starting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- The MCP runner selects an available loopback port and returns the preview URL. Do not pass `host` or `port` to MCP preview or screenshot tools. To capture a generated site already running in another process, pass its `baseUrl` with `path`.\n- Automatic browser discovery checks system installations, configured browser paths, and Chromium installations in the Playwright browser cache.\n- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nAfter the user explicitly requests or approves visual verification, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after focused mutations; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing. Use mode: "production" only for release-like verification.\n\n## Workflow Summary Without Diff\n\nAfter the user explicitly requests or approves visual verification, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after focused mutations; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Inspect every PNG with vision before finishing. Use mode: "production" only for release-like verification.\n\nEach screenshot result includes rendered `layout` metrics when the local browser\nprovides them. `layout.horizontalOverflow: true` is deterministic evidence that\nthe rendered document exceeds the requested viewport width. Use vision for\nclipping, wrapping, hierarchy, and other judgments that layout dimensions alone\ncannot establish.\n\nPass `includeImageMetrics: true` when an ordinary screenshot needs\n`layout.images`; rendered audit enables it automatically. The array includes\neach rendered image\'s Webstudio instance id when available, loading mode,\ncompletion state, natural dimensions, rendered dimensions, and document\nposition. Rendered audits use this evidence to report broken images, eager\nloading below the fold, and sources more than 2x the rendered dimensions in\nboth axes. Oversized-source results are optimization evidence, not universal\nperformance conformance.\n\nPass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized\nResource Timing evidence; rendered audit enables it automatically. Resource\nmetrics contain only the URL pathname, initiator type, transfer/body sizes,\nduration, and browser-provided render-blocking status. Origins and query strings\nare omitted. Rendered audits report explicitly blocking resources and legacy\n`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size\nbudget.\n\n## Screenshot Verification Summary\n\nAfter the user explicitly requests or approves visual verification, call preview.start once inside a long-running MCP server, then use screenshot({ path, viewport }) for fast repeated checks across multiple pages. Iterative mode is the default: after MCP mutations, path screenshots regenerate changed files and reload the requested route while keeping the server and browser alive. Use mode: "production" only for release-like verification. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',} as const;@@ -103,7 +103,7 @@ export const cliDocSections = {'For dynamic resource query parameters prefer searchParams, for example {"name":"tag","value":"filters.tag"}. Use {"type":"literal","value":"website"} for fixed request text. Header values can use an expression such as "Bearer " + auth.token. Body can be an object expression, including GraphQL payloads such as { query: "...", variables: { slug: system.params.slug } }.','Resource methods are get, post, put, and delete. Optional resource controls are graphql and system. Use control:"graphql" for GraphQL POST resources with query bodies. Use control:"system" for built-in local resource URLs such as "/$resources/current-date" and for resources reading the built-in system parameter. The built-in system fields are system.origin, system.pathname, system.params, and system.search; do not use system.path.',"Whenever an array or object from a resource or data variable should render repeated UI, call insert-collection with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use collectionItem and collectionItemKey expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique value bindings.",- "Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, new, this, await, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access without optional chaining. Use nullish coalescing when a fallback is required.",+ "Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, new, this, await, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access. Use nullish coalescing when a fallback is required.",],rules: ["Never guess ids for existing records. Read them first.",diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.mdindex 49a3b78369..4eae30bb37 100644--- a/packages/cli/src/docs/api-use-cases.md+++ b/packages/cli/src/docs/api-use-cases.md@@ -452,7 +452,9 @@ Notes:- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.- Put reusable insertable options inside exactly one direct `ws:block-template` child. A missing or second template container makes the Content Block invalid. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.-- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.+- Before implementation, inventory every editor-owned field and its intended control and write destination, whether or not the block uses MDX. Check that templates contain the required styling, but do not treat containment or a successful text edit as proof that the whole block is editable. Test every field through Content mode, inspect its saved project data or source file, reload, and restore the original value. Report passed, failed, or not tested for each field; missing or read-only required controls are unfinished requirements.+- Use controls that match the content: a calendar for dates and an image picker for image replacement. Keep fixed punctuation and units out of directly bound value elements. Preserve stored types and wording: when reading time is already a complete string such as `4 min read`, bind that string directly rather than assuming it is a number.+- For MDX-backed blocks, containment alone is not enough: the MDX body is editable through its source mapping, but the designed shell needs writable document-frontmatter bindings. Follow the binding recipe below rather than binding editable article fields to query results.## Store Content Block content in MDX@@ -478,16 +480,60 @@ Notes:- Connecting replaces existing Body content. If the result returns `requiresConfirmation:true`, report that replacement to the user and repeat the same call with `confirmReplacement:true` only after approval.- Prefer Markdown for standard document content; it automatically uses a unique matching semantic template when one exists. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG with authored properties that Markdown cannot express.- Verify that the Content Block has exactly one direct Templates container before connecting or editing MDX. Zero or multiple containers block materialization and publication.-- Read the Content Block's Templates children before writing a custom reference. Use capitalized JSX such as `<PromotionCard />` for its stable **Name**, which is independent from the display label. A matching template wins; otherwise Webstudio uses the exact registered component export. JSX attributes accept quoted static values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported.+- Read the Content Block's Templates children before writing a custom reference. Use capitalized JSX such as `<PromotionCard />` for its stable **Name**, which is independent from the display label. A matching template wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block's Templates. JSX attributes accept quoted static values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported.- When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants and retain template styles. A mismatched child structure replaces the root defaults, while each authored child still resolves through a matching template when possible. An explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, so adding a matching semantic or named template later updates existing MDX. Preserve unresolved names and report their diagnostics instead of deleting them.- When a template is renamed or deleted, use `migrate-content-block-template-references` to update a selected set of affected MDX files. The first call returns a plan. Report its changed-file, update, omission, and diagnostic counts, then repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its authored children; removing a self-closing reference removes the node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.- `edit-content-block-source` replaces the complete MDX source. Preserve frontmatter and unrelated source when making a bounded edit.- `update-content-block-frontmatter` replaces the complete frontmatter mapping. Inspect the current source first and include every property that must remain.-- Store frontmatter images as exact `$ref` objects. Bind an Image source to the resolved `.src` field and its alt property to `.description` so the Asset description supplies alternative text.-- Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document's frontmatter. Keep computed expressions and `$ref` values read-only.+- Store frontmatter images as exact `$ref` objects. Bind an editable Image source to the resolved `.src` with explicit `binding.mode:"readwrite"`; use `mode:"read"` for its alt binding to `.description`. Omitting the source mode leaves the image visible but not replaceable in Content mode.+- Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document's frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.- Inspect every returned diagnostic. Invalid MDX is saved rather than silently repaired; preserve the source, report the source range, and fix only the requested or invalid part.- If an edit in a long-lived MCP session reports a conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly.+## Make an MDX article header editable++Use the resource only to select the connected source, for example `post.data.id`.+Bind article values inside the Content Block to its document parameter instead+of `post.data.properties.*`. Inspect the block's variables first; `document` is+the default name, not a name to assume.++These commands target persistent designed instances inside the connected block.++Commands:++- MCP tool: update-text {"instanceId":"<headingInstanceId>","childIndex":0,"text":"document.frontmatter.title","mode":"expression","expressionBindingMode":"readwrite"}+- MCP tool: update-text {"instanceId":"<readingTimeValueInstanceId>","childIndex":0,"text":"document.frontmatter.readingTime","mode":"expression","expressionBindingMode":"readwrite"}+- MCP tool: bind-props {"bindings":[{"instanceId":"<dateInstanceId>","name":"datetime","binding":{"type":"expression","value":"document.frontmatter.publishedAt","mode":"readwrite"}}]}++Notes:++- Create writable bindings explicitly; the default is read-only. Merely moving a heading or Link inside the Content Block does not make its query-bound text editable.+- The MDX body uses its source mapping. Static designed content outside that body remains protected unless its text or supported props bind to writable frontmatter fields. Do not apply these generic instance tools to MDX-generated instances.+- Use direct static paths. Property access is already safe. Fallbacks and formatted expressions, such as `document.frontmatter.title ?? "Untitled"`, remain read-only.+- Keep every intended editable value in its own text element with a single direct read-write binding. For reading time, use three inline siblings: static `— `, the bound reading-time value, and static ` min read`. Preserve whitespace and the stored field type. Do not combine them into a template literal or concatenate strings, and do not put literal siblings inside the value element itself. Keep fixed wording protected in the designed shell.+- Prefer component formatting controls, such as Date Time formatting with a directly bound date prop, over transforming the expression. Do not silently sacrifice editability for formatting or a fallback; explain unsupported cases and ask before making an intended editable field read-only.+- A direct writable binding such as `document.frontmatter.author.name` can edit a shared author loaded through `../authors/oleg.md#frontmatter`. The edit saves to the author file and affects every article using it; preserve the article's `$ref` marker.+- Before handoff, inventory every article-owned field, including header text, author details, dates, reading time, categories, hero and inline image sources, alternative text, captions, links, and custom-component content. For each field, inspect its binding and source, edit it through the Content-mode UI, verify the saved MDX or referenced file, reload, and restore the test value. Record passed, failed, or not tested for each field. A correct preview, a successful MCP write, and one representative text edit do not prove the whole article is editable. Do not claim completion while required fields fail or remain untested.+- Bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. Content mode's **Choose source** replaces the article's frontmatter image `$ref`; the resolved URL stays read-only. Verify selection, the saved reference, and reload instead of treating a missing write mode as a platform limitation. For alternative text bound to `.description`, use **Choose source → asset actions → Settings → Description** to edit shared Asset metadata. This affects every use of the Asset and is separate from replacing an article's image.++## Make an article image replaceable in Content mode++Use this for a persistent designed Image inside a connected Content Block,+with `featureImage: { $ref: "./images/hero.png" }` in its MDX frontmatter.+Read the instance ID and document variable name before adapting the example.++Commands:++- MCP tool: bind-props {"bindings":[{"instanceId":"<imageInstanceId>","name":"src","binding":{"type":"expression","value":"document.frontmatter.featureImage.src","mode":"readwrite"}},{"instanceId":"<imageInstanceId>","name":"alt","binding":{"type":"expression","value":"document.frontmatter.featureImage.description","mode":"read"}}]}++Notes:++- The source mode must be explicit: the default `read` mode displays the image but prevents Content-mode replacement. Do not bind to query-result properties or add a fallback expression.+- **Choose source** replaces the article's `featureImage.$ref`; the disabled resolved-URL input is expected. Do not store a resolved URL string or replace the shared Asset itself.+- Shared alternative text is a separate action: **Choose source → asset actions → Settings → Description**. Its read-only binding does not require the image source binding to be read-only.+- If the picker is missing or disabled, inspect the source mode, document scope, loaded reference, and permissions before claiming a product limitation.+- Verify through Content mode with an approved temporary replacement. Check the saved `$ref`, unchanged unrelated MDX and original shared Asset, reload persistence, and restoration. If that test is not authorized, report it as not tested, not passed.+## Move elementsCommands:diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.mdindex 755dacefce..8cb6fdf2a7 100644--- a/packages/cli/src/docs/manual-llm.md+++ b/packages/cli/src/docs/manual-llm.md@@ -90,9 +90,30 @@ When authoring JSX for `insert-fragment`, use Webstudio component helpers and WeWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in exactly one direct `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes editable Content Block body content. A missing or second template container makes the block invalid. Verify this structure before handoff.-When the Content Block body must be stored in an `.mdx` Asset, use the dedicated `connect-content-block-source`, `switch-content-block-source`, `inspect-content-block-source`, `edit-content-block-source`, `update-content-block-frontmatter`, `reload-content-block-source`, and `disconnect-content-block-source` tools. Do not manipulate its `src` with generic prop tools. Connecting replaces existing Body content, so report `requiresConfirmation:true` and retry with `confirmReplacement:true` only after user approval. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX first resolves the stable template **Name**, then the exact registered component export. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep their template styles. A mismatched child structure replaces defaults, while an explicit empty pair clears defaults and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, including when a matching template is added after the MDX element. Preserve invalid MDX and unresolved template names, inspect all source-located diagnostics, and resolve revision conflicts by reloading before reapplying the change. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy updates across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.+When the Content Block body must be stored in an `.mdx` Asset, use the dedicated `connect-content-block-source`, `switch-content-block-source`, `inspect-content-block-source`, `edit-content-block-source`, `update-content-block-frontmatter`, `reload-content-block-source`, and `disconnect-content-block-source` tools. Do not manipulate its `src` with generic prop tools. Connecting replaces existing Body content, so report `requiresConfirmation:true` and retry with `confirmReplacement:true` only after user approval. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block's Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep their template styles. A mismatched child structure replaces defaults, while an explicit empty pair clears defaults and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, including when a matching template is added after the MDX element. Preserve invalid MDX and unresolved template names, inspect all source-located diagnostics, and resolve revision conflicts by reloading before reapplying the change. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy updates across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.-Frontmatter is part of the same MDX source. `update-content-block-frontmatter` receives the complete replacement property map, so inspect and preserve properties the user did not ask to remove. Store frontmatter images as exact `$ref` objects, bind Image sources to their resolved `.src`, and bind alt properties to their Asset `.description`. Use `update-content-block-frontmatter` for MCP frontmatter edits; MDX-rendered elements are not persistent targets for generic prop or text mutations. Preserve existing `mode:"readwrite"` bindings, which are valid only for exact direct frontmatter paths. Computed expressions and `$ref` values stay read-only. For an expression-bound source inside a Collection, pass the occurrence's scoped values and a distinct stable `renderScope`; for example, resolve `post.assetId` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.+Frontmatter is part of the same MDX source. `update-content-block-frontmatter` receives the complete replacement property map, so inspect and preserve properties the user did not ask to remove. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits; MDX-rendered elements are not persistent targets for generic prop or text mutations. Preserve existing `mode:"readwrite"` bindings, which are valid only for exact direct frontmatter paths. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. For an expression-bound source inside a Collection, pass the occurrence's scoped values and a distinct stable `renderScope`; for example, resolve `post.assetId` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.++For an editable MDX article, use the resource to select the Content Block's source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.++### Content Block completion checklist++For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.++### Complete article editability is required++When the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.++Before handoff:++1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block's document bindings.+2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.+3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.+4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.++**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.++Keep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.@@ -481,7 +502,7 @@ Before authoring unfamiliar expressions, read `webstudio://project/expressions`- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can use an expression such as `"Bearer " + auth.token`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.-- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access without optional chaining. Use nullish coalescing when a fallback is required.+- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access. Use nullish coalescing when a fallback is required.## Pick Read Commanddiff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.mdindex de17c00cca..f9ff7060ab 100644--- a/packages/cli/src/docs/manual-mcp.md+++ b/packages/cli/src/docs/manual-mcp.md@@ -152,7 +152,7 @@ webstudio migrate-content-block-template-references '{"assetIds":["<mdxAssetId>"Prefer Markdown for standard document content. Markdown nodes automatically use a unique matching semantic template when one exists and keep their normal semantic fallback otherwise. Use lowercase JSX such as `<section>` or `<svg>` for a standard HTML or SVG element with authored properties Markdown cannot express.-Reference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template's stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins; otherwise the exact registered component export is used. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.+Reference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template's stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block's Templates. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants so template styles stay intact. A mismatched child structure replaces the root defaults, and each authored child still resolves through a matching template when possible. An explicit empty pair such as `<PromotionCard></PromotionCard>` clears the defaults. A self-closing reference such as `<PromotionCard />` keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live: adding a missing semantic or named template later also updates existing MDX without rewriting it. Preserve unresolved template names and report their diagnostics.@@ -162,7 +162,28 @@ Use the dedicated connect, switch, inspect, edit, update-frontmatter, reload, an`renderScope` is any non-empty stable identity for one rendered occurrence, such as `page:/articles/example`. It does not load that page, its route parameters, or its resource results. To connect a result-one Assets resource, run `preview-asset-query` with concrete values, keep the saved source expression such as `post.data.id`, and supply the previewed item for this occurrence with `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`. The operation validates that concrete Asset while persisting the dynamic expression.-A source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects, bind Image sources to their resolved `.src`, and bind alt properties to their Asset `.description`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document's frontmatter. Computed expressions and `$ref` values remain read-only.+A source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document's frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.++For an editable MDX article, use the resource to select the Content Block's source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.++### Content Block completion checklist++For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.++### Complete article editability is required++When the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.++Before handoff:++1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block's document bindings.+2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.+3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.+4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.++**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.++Keep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.If an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.diff --git a/packages/cli/src/docs/mcp-startup-epilogue.md b/packages/cli/src/docs/mcp-startup-epilogue.mdindex 3678f7097f..6dbdf4477c 100644--- a/packages/cli/src/docs/mcp-startup-epilogue.md+++ b/packages/cli/src/docs/mcp-startup-epilogue.md@@ -31,7 +31,28 @@ For simple authored/styled sections, run the three commands above. Do not grep sWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in exactly one direct `ws:block-template` child. A missing or second template container makes the block invalid. Templates themselves are protected; an editor's inserted copy becomes editable Content Block body content. Verify this structure before handoff.-For an MDX-backed Content Block, use the dedicated content-source tools instead of generic prop mutations: connect, switch, inspect, edit, update frontmatter, reload, or disconnect the source. Confirm before replacing existing Body content. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX first resolves the stable template **Name**, then the exact registered component export. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep template styles. A mismatched child structure replaces defaults, an explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live when matching templates are added later. Preserve invalid source and unresolved names, inspect all diagnostics, and reload before retrying a revision conflict. A frontmatter update replaces the complete property map; preserve fields the user did not ask to remove. Store frontmatter images as exact `$ref` objects; bind Image sources to `.src` and alt properties to the Asset `.description`. Only exact direct frontmatter bindings may use `mode:"readwrite"`. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy changes across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.+For an MDX-backed Content Block, use the dedicated content-source tools instead of generic prop mutations: connect, switch, inspect, edit, update frontmatter, reload, or disconnect the source. Confirm before replacing existing Body content. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block's Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep template styles. A mismatched child structure replaces defaults, an explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live when matching templates are added later. Preserve invalid source and unresolved names, inspect all diagnostics, and reload before retrying a revision conflict. A frontmatter update replaces the complete property map; preserve fields the user did not ask to remove. Store frontmatter images as exact `$ref` objects; bind editable Image sources to `.src` with explicit `binding.mode:"readwrite"` and alt properties to the Asset `.description` with `mode:"read"`. Omitting the source mode leaves the image visible but not replaceable in Content mode. Only exact direct frontmatter bindings may use `mode:"readwrite"`. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy changes across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.++For an editable MDX article, use the resource to select the Content Block's source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.++### Content Block completion checklist++For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.++### Complete article editability is required++When the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.++Before handoff:++1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block's document bindings.+2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.+3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.+4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.++**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.++Keep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.Run it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.diff --git a/packages/cli/src/preview-server/package-manager.test.ts b/packages/cli/src/preview-server/package-manager.test.tsindex 4be0e68272..d99dbeae31 100644--- a/packages/cli/src/preview-server/package-manager.test.ts+++ b/packages/cli/src/preview-server/package-manager.test.ts@@ -8,6 +8,44 @@ import {resolveWindowsLauncherPath,} from "./test-utils";+test.each(["npm", "pnpm"] as const)(+ "forwards script options through %s without changing their meaning",+ (name) => {+ const launcher = `/opt/${name}/bin/cli.js`;+ const scriptArgs = [+ "--host",+ "127.0.0.1",+ "--port",+ "4321",+ "--",+ "literal",+ ];+ expect(+ getPackageManagerInvocation(["run", "dev", "--", ...scriptArgs], {+ nodeExecPath: "/usr/bin/node",+ npmExecPath: launcher,+ platform: "linux",+ readPackageFile: (path) => {+ if (path === `/opt/${name}/package.json`) {+ return JSON.stringify({ name, bin: { [name]: "bin/cli.js" } });+ }+ throw Object.assign(new Error("missing"), { code: "ENOENT" });+ },+ resolveLauncherPath: (path) => path,+ })+ ).toEqual({+ command: "/usr/bin/node",+ args: [+ launcher,+ "run",+ "dev",+ ...(name === "npm" ? ["--"] : []),+ ...scriptArgs,+ ],+ });+ }+);+test("reuses the npm cli that launched webstudio for preview commands", () => {expect(getPackageManagerInvocation(["run", "build"], {diff --git a/packages/cli/src/preview-server/package-manager.ts b/packages/cli/src/preview-server/package-manager.tsindex 443b5afbb7..b54e1e5ebe 100644--- a/packages/cli/src/preview-server/package-manager.ts+++ b/packages/cli/src/preview-server/package-manager.ts@@ -197,8 +197,13 @@ export const getPackageManagerInvocation = (options: PreviewPackageManagerOptions = defaultPreviewServerDependencies) => {const packageManager = resolvePreviewPackageManager(options);+ // npm consumes this separator; pnpm forwards it to the script instead.+ const commandArgs =+ packageManager.name === "pnpm" && args[0] === "run" && args[2] === "--"+ ? [...args.slice(0, 2), ...args.slice(3)]+ : args;return {command: packageManager.command,- args: [...packageManager.argsPrefix, ...args],+ args: [...packageManager.argsPrefix, ...commandArgs],};};diff --git a/packages/cli/templates/react-router/package.json b/packages/cli/templates/react-router/package.jsonindex 9e211b0c93..1de026278d 100644--- a/packages/cli/templates/react-router/package.json+++ b/packages/cli/templates/react-router/package.json@@ -3,9 +3,9 @@"private": true,"sideEffects": false,"scripts": {- "build": "react-router build",- "dev": "react-router dev",- "start": "react-router-serve ./build/server/index.js",+ "build": "node ./node_modules/@react-router/dev/bin.js build",+ "dev": "node ./node_modules/@react-router/dev/bin.js dev",+ "start": "node ./node_modules/@react-router/serve/bin.js ./build/server/index.js","typecheck": "tsc --noEmit"},"dependencies": {diff --git a/packages/cli/templates/react-router/vite.config.ts b/packages/cli/templates/react-router/vite.config.tsindex f843eb1b94..32e453175c 100644--- a/packages/cli/templates/react-router/vite.config.ts+++ b/packages/cli/templates/react-router/vite.config.ts@@ -5,6 +5,8 @@ const sourceConditions =process.env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED === "1" ? ["webstudio"] : [];export default defineConfig({+ // Local previews share node_modules, but must not share optimizer state.+ cacheDir: ".react-router/vite",plugins: [reactRouter()],server: {hmr: process.env.WEBSTUDIO_PREVIEW_HMR === "disabled" ? false : undefined,diff --git a/packages/content-engine/package.json b/packages/content-engine/package.jsonindex 22ab35f17b..1be08dda2f 100644--- a/packages/content-engine/package.json+++ b/packages/content-engine/package.json@@ -19,6 +19,7 @@"@hyperjump/json-pointer": "1.1.2","@webstudio-is/expression": "workspace:*","@webstudio-is/query-builder": "workspace:*",+ "ajv": "8.20.0","canonicalize": "3.0.0","estree-util-is-identifier-name": "3.0.0","hast-util-to-mdast": "9.0.0",@@ -38,6 +39,7 @@"remark-parse": "10.0.2","svg-tags": "1.0.0","unified": "10.1.2",+ "urlpattern-polyfill": "^10.1.0","yaml": "2.9.0","zod": "^4.4.3"},diff --git a/packages/content-engine/src/compilation-plan.ts b/packages/content-engine/src/compilation-plan.tsindex 0f4486a2b4..52bb141731 100644--- a/packages/content-engine/src/compilation-plan.ts+++ b/packages/content-engine/src/compilation-plan.ts@@ -115,13 +115,13 @@ const containsDocumentReference = (value: JsonValue): boolean => {};const isFieldAffectedByDocumentReference = (- document: AssetFileDocument,+ document: ContentDatabaseDocument,field: AssetQueryFieldPath) => {if (field[0] !== "properties") {return false;}- let value: JsonValue = document.properties;+ let value: JsonValue = document.properties ?? {};for (const segment of field.slice(1)) {if (typeof getJsonReferenceMarkerValue(value) === "string") {return true;@@ -151,7 +151,7 @@ const evaluateWhere = ({where,available,}: {- document: AssetFileDocument;+ document: ContentDatabaseDocument;where: ContentCompilationWhere;available: "base" | "all";}): boolean | undefined => {@@ -280,7 +280,7 @@ export const selectContentHydrationCandidates = ({documents,plan,}: {- documents: readonly AssetFileDocument[];+ documents: readonly ContentDatabaseDocument[];plan: ContentCompilationPlan;}) => {const selected = new Set<string>();diff --git a/packages/content-engine/src/compiler.ts b/packages/content-engine/src/compiler.tsindex 457ac1aa89..24d916d519 100644--- a/packages/content-engine/src/compiler.ts+++ b/packages/content-engine/src/compiler.ts@@ -9,6 +9,7 @@ export * from "./document-metadata";export * from "./asset-value-references";export { serializeJsonDeterministically } from "./canonical-json";export {+ ByteLimitExceededError,decodeUtf8,readableStreamToAsyncIterable,readBoundedBytes,diff --git a/packages/content-engine/src/content-collection.test.ts b/packages/content-engine/src/content-collection.test.tsnew file mode 100644index 0000000000..ff047e7628--- /dev/null+++ b/packages/content-engine/src/content-collection.test.ts@@ -0,0 +1,1247 @@+import { describe, expect, test } from "vitest";+import {+ collectionConfigFilename,+ collectionEntryFieldClearValue,+ createCollectionEntry,+ createDefaultCollectionConfig,+ getCollectionFieldValidationError,+ getCollectionFieldValidationIssue,+ getCollectionTemplateValidationError,+ getCollectionValidationError,+ getCollectionEntryValidationIssues,+ getCollectionEntrySourceIssues,+ getCollectionEntryCreationError,+ getCollectionFieldLimitsIssue,+ parseCollectionConfig,+ normalizeCollectionSlug,+ serializeCollectionConfig,+ inspectContentCollection,+} from "./content-collection";++type MutableCollectionSchema = Record<string, unknown> & {+ properties: Record<string, Record<string, unknown>>;+};++describe("content collections", () => {+ test("rejects slug limits that only allow an empty string in settings", async () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ delete schema.properties.slug.minLength;+ schema.properties.slug.maxLength = 0;+ const config = parseCollectionConfig(JSON.stringify(schema));+ const slug = config.fields.find((field) => field.key === "slug")!;+ expect(getCollectionFieldLimitsIssue(slug)?.input).toBe("maxLength");+ expect(+ getCollectionFieldLimitsIssue({ ...slug, minLength: 0 })?.input+ ).toBe("maxLength");+ expect(+ getCollectionFieldLimitsIssue({ ...slug, control: "text" })+ ).toBeUndefined();+ schema.properties.slug.maxLength = 1;+ const repaired = parseCollectionConfig(JSON.stringify(schema));+ expect(+ getCollectionFieldLimitsIssue(+ repaired.fields.find((field) => field.key === "slug")!+ )+ ).toBeUndefined();+ const entry = await createCollectionEntry({+ config: repaired,+ templateSource: "",+ values: { title: "Post", slug: "a" },+ existingFilenames: [],+ });+ expect(entry.filename).toBe("a.mdx");+ });+ test("requires generated-filename patterns when no slug field is configured", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ delete schema.properties.slug;+ schema.required = ["title"];+ delete schema["x-webstudio"].slugField;+ delete schema["x-webstudio"].generateSlugFrom;+ for (const entries of [["post-*.mdx"], ["*.mdx", "!entry-*.mdx"]]) {+ schema["x-webstudio"].entries = entries;+ const config = parseCollectionConfig(JSON.stringify(schema));+ expect(getCollectionEntryCreationError(config)).toBeDefined();+ }+ schema["x-webstudio"].entries = ["entry-*.mdx"];+ expect(+ getCollectionEntryCreationError(+ parseCollectionConfig(JSON.stringify(schema))+ )+ ).toBeUndefined();+ expect(+ parseCollectionConfig(JSON.stringify(schema)).matchesEntry(+ "entry-123.mdx"+ )+ ).toBe(true);+ });+ test("rejects integer limits with no possible integer", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.count = { type: "integer", minimum: 0.2, maximum: 0.8 };+ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow();+ schema.properties.count.maximum = 1;+ expect(+ parseCollectionConfig(JSON.stringify(schema)).validate({+ title: "Post",+ slug: "post",+ count: 1,+ }).success+ ).toBe(true);+ });+ test("reports all invalid entry fields without changing their values", () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ const properties = {+ title: "",+ slug: "different",+ draft: "yes",+ extra: true,+ };+ const issues = getCollectionEntryValidationIssues({+ config,+ properties,+ basename: "post",+ });+ expect(new Set(issues.map(({ fieldKey }) => fieldKey))).toEqual(+ new Set(["title", "slug", "draft", "extra"])+ );+ expect(properties).toEqual({+ title: "",+ slug: "different",+ draft: "yes",+ extra: true,+ });+ expect(+ getCollectionEntryValidationIssues({+ config,+ properties: { title: "Post", slug: "post", draft: false },+ basename: "post",+ })+ ).toEqual([]);+ });++ test.each(["\n", "\r\n"])(+ "locates collection errors in YAML values with %j line endings",+ async (newline) => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ const source = [+ "\uFEFF---",+ '"title": ""',+ "slug: post",+ "draft: yes",+ "---",+ "Body",+ ].join(newline);+ const issues = await getCollectionEntrySourceIssues({+ config,+ source,+ basename: "post",+ });+ expect(issues.map(({ fieldKey }) => fieldKey)).toEqual([+ "title",+ "draft",+ ]);+ expect(issues.map(({ from, to }) => source.slice(from, to))).toEqual([+ '""',+ "yes",+ ]);+ const missing = await getCollectionEntrySourceIssues({+ config,+ source: "Body only",+ basename: "post",+ });+ expect(missing.some(({ fieldKey }) => fieldKey === "title")).toBe(true);+ expect(missing.every(({ from, to }) => from === 0 && to === 1)).toBe(+ true+ );+ }+ );++ test("resolves the bundled slug reference and applies sibling constraints", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.slug = {+ $ref: "https://webstudio.is/schemas/slug",+ title: "URL slug",+ minLength: 2,+ maxLength: 3,+ "x-webstudio": { control: "slug" },+ };+ const config = parseCollectionConfig(JSON.stringify(schema));+ expect(config.fields.find(({ key }) => key === "slug")).toMatchObject({+ type: "string",+ control: "slug",+ minLength: 2,+ maxLength: 3,+ });+ for (const slug of ["你好", "abc"]) {+ expect(config.validate({ title: "Title", slug }).success).toBe(true);+ }+ for (const slug of ["a", "abcd", "A-b", "a/b", 12]) {+ expect(config.validate({ title: "Title", slug }).success).toBe(false);+ }+ const saved = JSON.parse(+ serializeCollectionConfig({ config, fields: config.fields })+ );+ expect(saved.properties.slug.$ref).toBe(+ "https://webstudio.is/schemas/slug"+ );+ expect(saved.properties.slug).not.toHaveProperty("pattern");+ });++ test.each([+ "https://example.com/slug",+ "#/properties/slug",+ "https://webstudio.is/schemas/slug#unknown",+ ])("rejects an unknown schema reference %s", ($ref) => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.slug.$ref = $ref;+ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow();+ });++ test("validation preserves additional frontmatter without filling defaults or coercing types", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.additionalProperties = true;+ schema.properties.title.default = "Default title";+ const config = parseCollectionConfig(JSON.stringify(schema));+ const value = { slug: "hello", extra: { nested: true } };+ expect(config.validate(value).success).toBe(false);+ expect(value).toEqual({ slug: "hello", extra: { nested: true } });+ const valid = { ...value, title: "Title" };+ expect(config.validate(valid).success).toBe(true);+ expect(valid.extra).toEqual({ nested: true });+ expect(config.validate({ ...valid, draft: "false" }).success).toBe(false);+ });+ test("maps missing and invalid values to exact field keys without losing template errors", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ const key = 'author/name~"';+ schema.properties[key] = { type: "string", minLength: 2 };+ schema.required.push(key);+ const config = parseCollectionConfig(JSON.stringify(schema));+ const base = { title: "Title", slug: "hello" };+ expect(getCollectionFieldValidationIssue(config, base)?.fieldKey).toBe(key);+ expect(+ getCollectionFieldValidationIssue(config, { ...base, [key]: "a" })+ ?.fieldKey+ ).toBe(key);+ expect(getCollectionTemplateValidationError(config, {})).toBeUndefined();+ expect(+ getCollectionTemplateValidationError(config, { [key]: "a" })+ ).toBeDefined();+ expect(+ getCollectionTemplateValidationError(config, { extra: true })+ ).toBeDefined();+ });++ test("keeps independent validators and counts Unicode code points at both length boundaries", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.title.minLength = 1;+ schema.properties.title.maxLength = 1;+ const short = parseCollectionConfig(JSON.stringify(schema));+ schema.properties.title.minLength = 2;+ schema.properties.title.maxLength = 2;+ const long = parseCollectionConfig(JSON.stringify(schema));+ for (let repeat = 0; repeat < 2; repeat += 1) {+ expect(short.validate({ title: "😀", slug: "a" }).success).toBe(true);+ expect(short.validate({ title: "😀😀", slug: "a" }).success).toBe(false);+ expect(long.validate({ title: "😀", slug: "a" }).success).toBe(false);+ expect(long.validate({ title: "😀😀", slug: "a" }).success).toBe(true);+ }+ });++ test("matches current-folder filenames with URLPattern and preserves patterns in settings", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = [+ "post-*.mdx",+ "!post-private-*.mdx",+ "статья*.mdx",+ ];+ const config = parseCollectionConfig(JSON.stringify(schema));+ const updated = parseCollectionConfig(+ serializeCollectionConfig({ config, fields: config.fields })+ );+ expect(updated.entries).toEqual(schema["x-webstudio"].entries);+ for (const filename of [+ "post-one.mdx",+ "POST-TWO.MDX",+ "post-with spaces.mdx",+ "post-#?%.mdx",+ "статья.mdx",+ ]) {+ expect(updated.matchesEntry(filename)).toBe(true);+ }+ for (const filename of [+ "post-private-one.mdx",+ "post-one.md",+ "other.mdx",+ "nested/post-one.mdx",+ "collection.json",+ "template.mdx",+ ]) {+ expect(updated.matchesEntry(filename)).toBe(false);+ }+ delete schema["x-webstudio"].entries;+ const legacy = parseCollectionConfig(JSON.stringify(schema));+ expect(legacy.entries).toEqual(["*.mdx"]);+ expect(legacy.matchesEntry("other.mdx")).toBe(true);+ expect(legacy.matchesEntry("other.md")).toBe(false);+ });++ test.each(+ [+ [],+ [""],+ ["!"],+ ["!*.mdx"],+ ["nested/*.mdx"],+ ["[".repeat(257)],+ ["("],+ Array(65).fill("*.mdx"),+ ].map((entries) => [entries])+ )("rejects invalid entry pattern configuration %j", (entries) => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = entries;+ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow();+ });++ test("validates only selected entries and never reads ignored files", async () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].entries = ["post-*.mdx"];+ const sources = new Map([+ ["collection.json", JSON.stringify(schema)],+ ["template.mdx", "---\ndraft: true\n---\nBody"],+ ["post-one.mdx", "---\ntitle: One\nslug: post-one\n---\nBody"],+ ]);+ const files = [+ ...sources.keys(),+ "notes.md",+ "cover.png",+ "ignored.mdx",+ ].map((filename) => ({+ file: filename,+ id: filename,+ filename,+ basename: filename.slice(0, filename.lastIndexOf(".")),+ isMdx: filename.endsWith(".mdx"),+ }));+ const result = await inspectContentCollection({+ files,+ readSource: async ({ filename }) => {+ const source = sources.get(filename);+ if (source === undefined) {+ throw new Error(`Unexpected read: ${filename}`);+ }+ return source;+ },+ });+ expect(result.entryFiles.map(({ filename }) => filename)).toEqual([+ "post-one.mdx",+ ]);+ await expect(+ createCollectionEntry({+ config: result.config,+ templateSource: sources.get("template.mdx")!,+ values: { title: "Other", slug: "other" },+ existingFilenames: [],+ })+ ).rejects.toThrow("does not match");+ const entry = await createCollectionEntry({+ config: result.config,+ templateSource: sources.get("template.mdx")!,+ values: { title: "Two", slug: "post-two" },+ existingFilenames: [],+ });+ expect(entry.filename).toBe("post-two.mdx");+ });+ test.each([+ ["фывафыва", "фывафыва"],+ ["Привет мир", "привет-мир"],+ ["你好世界", "你好世界"],+ ["日本語 の記事", "日本語-の記事"],+ ["हिन्दी लेख", "हिन्दी-लेख"],+ ["مرحبا بالعالم", "مرحبا-بالعالم"],+ ["Hello 世界 Привет", "hello-世界-привет"],+ ["Cafe\u0301", "café"],+ ["İstanbul", "i\u0307stanbul"],+ ["Hello / World?#%\\test", "hello-world-test"],+ ["\u0301Hello 🚀", "hello"],+ ])("creates a Unicode slug and filename for %s", async (title, slug) => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ expect(normalizeCollectionSlug(title)).toBe(slug);+ expect(normalizeCollectionSlug(slug)).toBe(slug);+ const entry = await createCollectionEntry({+ config,+ templateSource: "Body",+ values: { title },+ existingFilenames: [],+ });+ expect(entry.filename).toBe(`${slug}.mdx`);+ expect(entry.frontmatter.slug).toBe(slug);+ expect(config.validate(entry.frontmatter).success).toBe(true);+ });++ test.each(["🚀🎉", "///", "\u0301"])(+ "requires a manual slug when %s has no letters or numbers",+ async (title) => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ expect(normalizeCollectionSlug(title)).toBe("");+ await expect(+ createCollectionEntry({+ config,+ templateSource: "Body",+ values: { title },+ existingFilenames: [],+ })+ ).rejects.toThrow();+ const entry = await createCollectionEntry({+ config,+ templateSource: "Body",+ values: { title, slug: "my-entry" },+ existingFilenames: [],+ });+ expect(entry.filename).toBe("my-entry.mdx");+ }+ );++ test.each([+ "Привет",+ "hello/world",+ "你好?",+ "a\nb",+ "hello\n",+ "-hello",+ "hello--world",+ "\u0301hello",+ "🚀",+ ])("rejects invalid slug %s", (slug) => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ expect(config.validate({ title: "Title", slug }).success).toBe(false);+ });++ test.each([+ "^[a-z0-9]+(?:-[a-z0-9]+)*$",+ "^(?!.*[\\p{Lu}\\p{Lt}])[\\p{L}\\p{N}][\\p{L}\\p{M}\\p{N}]*(?:-[\\p{L}\\p{N}][\\p{L}\\p{M}\\p{N}]*)*$(?![\\s\\S])",+ ])(+ "upgrades generated slug rules to the bundled reference (%s)",+ (pattern) => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ delete schema.properties.slug.$ref;+ schema.properties.slug.pattern = pattern;+ const legacy = parseCollectionConfig(JSON.stringify(schema));+ expect(legacy.validate({ title: "Title", slug: "hello" }).success).toBe(+ true+ );+ expect(legacy.validate({ title: "Title", slug: "你好" }).success).toBe(+ true+ );+ const serialized = serializeCollectionConfig({+ config: legacy,+ fields: legacy.fields,+ });+ const saved = JSON.parse(serialized);+ expect(saved.properties.slug.$ref).toBe(+ "https://webstudio.is/schemas/slug"+ );+ expect(saved.properties.slug).not.toHaveProperty("pattern");+ const updated = parseCollectionConfig(serialized);+ expect(+ serializeCollectionConfig({ config: updated, fields: updated.fields })+ ).toBe(serialized);+ expect(updated.validate({ title: "Title", slug: "你好" }).success).toBe(+ true+ );+ }+ );++ test.each([undefined, "Café Déjà"])(+ "generates slugs compatible with a legacy collection (manual: %s)",+ async (slug) => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ delete schema.properties.slug.$ref;+ schema.properties.slug.pattern = "^[a-z0-9]+(?:-[a-z0-9]+)*$";+ const config = parseCollectionConfig(JSON.stringify(schema));+ const entry = await createCollectionEntry({+ config,+ templateSource: "Body",+ values: { title: "Café Déjà", ...(slug === undefined ? {} : { slug }) },+ existingFilenames: [],+ });+ expect(entry.filename).toBe("café-déjà.mdx");+ expect(config.validate(entry.frontmatter).success).toBe(true);+ }+ );++ test("rejects canonically equivalent existing filenames", async () => {+ await expect(+ createCollectionEntry({+ config: parseCollectionConfig(createDefaultCollectionConfig()),+ templateSource: "Body",+ values: { title: "Café" },+ existingFilenames: ["cafe\u0301.mdx"],+ })+ ).rejects.toThrow();+ });+ test("retries slugless entries with a stable request ID", async () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ delete schema.properties.slug;+ schema.required = ["title"];+ delete schema["x-webstudio"].slugField;+ delete schema["x-webstudio"].generateSlugFrom;+ const config = parseCollectionConfig(JSON.stringify(schema));+ const request = {+ config,+ templateSource: "Body",+ values: { title: "Entry" },+ existingFilenames: [],+ requestId: "91f1de15-e03b-40ae-9b2f-6c19a8bbf1fa",+ };+ const first = await createCollectionEntry(request);+ const retry = await createCollectionEntry(request);+ expect(retry).toEqual(first);+ expect(first.filename).toBe(`entry-${request.requestId}.mdx`);+ });++ test("creates entries without slug fields and keeps generated filenames out of frontmatter", async () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ delete schema["x-webstudio"].slugField;+ delete schema["x-webstudio"].generateSlugFrom;+ delete schema.properties.slug;+ schema.required = schema.required.filter((key: string) => key !== "slug");+ const config = parseCollectionConfig(JSON.stringify(schema));+ const first = await createCollectionEntry({+ config,+ templateSource: "---\ndraft: true\n---\nBody",+ values: { title: "A title" },+ existingFilenames: [],+ });+ const second = await createCollectionEntry({+ config,+ templateSource: "---\ndraft: true\n---\nBody",+ values: { title: "A title" },+ existingFilenames: [first.filename],+ });+ expect(first.filename.endsWith(".mdx")).toBe(true);+ expect(second.filename).not.toBe(first.filename);+ expect(first.frontmatter).toEqual({ title: "A title", draft: true });+ });++ test("allows a manually entered slug without a generation source", async () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ delete schema["x-webstudio"].generateSlugFrom;+ const config = parseCollectionConfig(JSON.stringify(schema));+ const entry = await createCollectionEntry({+ config,+ templateSource: "",+ values: { title: "A title", slug: "manual-slug" },+ existingFilenames: [],+ });+ expect(entry.filename).toBe("manual-slug.mdx");+ });+ test("uses collection.json as the folder entry point", () => {+ expect(collectionConfigFilename).toBe("collection.json");+ expect(+ parseCollectionConfig(createDefaultCollectionConfig())+ ).toMatchObject({+ template: "template.mdx",+ slugField: "slug",+ generateSlugFrom: "title",+ });+ });++ test("ignores and removes the obsolete dynamic preview setting", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].previewPage = "blog-post";+ const config = parseCollectionConfig(JSON.stringify(schema));++ expect(config).not.toHaveProperty("previewPage");+ expect(+ JSON.parse(serializeCollectionConfig({ config, fields: config.fields }))[+ "x-webstudio"+ ]+ ).not.toHaveProperty("previewPage");+ });++ test("requires a separate field for automatic slug generation", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema["x-webstudio"].generateSlugFrom = "slug";++ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow(+ "Slug source field must be different from the slug field"+ );+ });++ test("preserves schema keywords that are not managed by the configurator", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.summary = {+ type: "string",+ title: "Summary",+ description: "Shown in external schema tools",+ "x-webstudio": {+ help: "Start with a capital letter",+ },+ };+ schema["x-webstudio"].customSetting = "keep";+ const config = parseCollectionConfig(JSON.stringify(schema));+ const fields = config.fields.map((field) =>+ field.key === "summary" ? { ...field, key: "excerpt" } : field+ );++ const serialized = JSON.parse(+ serializeCollectionConfig({ config, fields })+ );++ expect(serialized.properties.excerpt).toMatchObject({+ description: "Shown in external schema tools",+ "x-webstudio": { help: "Start with a capital letter" },+ });+ expect(serialized["x-webstudio"].customSetting).toBe("keep");+ });++ test("rejects JSON Schema semantics outside the supported subset", () => {+ const unsupportedSchemas = [+ {+ update: (schema: MutableCollectionSchema) => {+ schema.$schema = "https://json-schema.org/draft/2019-09/schema";+ },+ message: "Only JSON Schema draft 2020-12 is supported",+ },+ {+ update: (schema: MutableCollectionSchema) => {+ schema.minProperties = 1;+ },+ message:+ 'Unsupported JSON Schema keyword "minProperties" at schema root',+ },+ {+ update: (schema: MutableCollectionSchema) => {+ schema.properties.title.enum = ["Only this title"];+ },+ message: 'Unsupported JSON Schema keyword "enum" at #/properties/title',+ },+ {+ update: (schema: MutableCollectionSchema) => {+ schema.properties.tags = {+ type: "array",+ items: { type: "string" },+ uniqueItems: true,+ };+ },+ message:+ "type must be string, number, integer, or boolean at #/properties/tags/type",+ },+ {+ update: (schema: MutableCollectionSchema) => {+ schema.properties.title.pattern = ".*";+ },+ message:+ "Only Webstudio's slug schema reference is supported; custom patterns are not supported",+ },+ ];++ for (const { update, message } of unsupportedSchemas) {+ const schema = JSON.parse(createDefaultCollectionConfig());+ update(schema);+ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow(+ message+ );+ }+ });++ test("rejects malformed supported JSON Schema keywords", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.title.minLength = -1;+ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow(+ "minLength must be a whole number of zero or greater at #/properties/title/minLength"+ );++ schema.properties.title.minLength = 10;+ schema.properties.title.maxLength = 5;+ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow(+ "minLength cannot exceed maxLength at #/properties/title"+ );+ });++ test("limits collection schema size, depth, fields, and strings", () => {+ const oversizedSource = `${createDefaultCollectionConfig()}${" ".repeat(+ 1024 * 1024+ )}`;+ expect(() => parseCollectionConfig(oversizedSource)).toThrow(+ "collection.json exceeds the 1 MiB size limit"+ );++ const tooManyFields = JSON.parse(createDefaultCollectionConfig());+ for (let index = 0; index < 300; index += 1) {+ tooManyFields.properties[`field${index}`] = { type: "string" };+ }+ expect(() => parseCollectionConfig(JSON.stringify(tooManyFields))).toThrow(+ "collection.json exceeds the supported schema complexity"+ );++ const tooDeep = JSON.parse(createDefaultCollectionConfig());+ let nested: {+ type: string;+ properties: Record<string, unknown>;+ } = { type: "object", properties: {} };+ tooDeep.properties.metadata = nested;+ for (let depth = 0; depth < 10; depth += 1) {+ const child = { type: "object", properties: {} };+ nested.properties.child = child;+ nested = child;+ }+ expect(() => parseCollectionConfig(JSON.stringify(tooDeep))).toThrow(+ "collection.json exceeds the supported schema complexity"+ );++ const longString = JSON.parse(createDefaultCollectionConfig());+ longString.properties.title.description = "a".repeat(17 * 1024);+ expect(() => parseCollectionConfig(JSON.stringify(longString))).toThrow(+ "collection.json exceeds the supported schema complexity"+ );+ });++ test("blocks prototype-sensitive collection field keys", () => {+ const source = createDefaultCollectionConfig().replace(+ '"title": {',+ '"__proto__": { "type": "string" }, "title": {'+ );+ expect(() => parseCollectionConfig(source)).toThrow(+ 'Property key "__proto__" is not supported'+ );++ const config = parseCollectionConfig(createDefaultCollectionConfig());+ expect(() =>+ serializeCollectionConfig({+ config,+ fields: config.fields.map((field, index) =>+ index === 0 ? { ...field, key: "constructor" } : field+ ),+ })+ ).toThrow('Property key "constructor" is not supported');+ });++ test("rejects schema properties unsupported by the configurator", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.metadata = {+ type: "object",+ properties: { author: { type: "string" } },+ };+ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow(+ "type must be string, number, integer, or boolean at #/properties/metadata/type"+ );+ });++ test("rejects required keys that have no declared property", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.required.push("future");+ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow(+ 'Required property "future" is not defined in properties'+ );+ });++ test("rejects empty and duplicate editable field keys", () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ expect(() =>+ serializeCollectionConfig({+ config,+ fields: config.fields.map((field, index) =>+ index === 0 ? { ...field, key: "" } : field+ ),+ })+ ).toThrow("Every field needs a non-empty, unique key");+ expect(() =>+ serializeCollectionConfig({+ config,+ fields: config.fields.map((field) => ({ ...field, key: "same" })),+ })+ ).toThrow("Every field needs a non-empty, unique key");+ expect(() =>+ serializeCollectionConfig({+ config,+ fields: config.fields.map((field, index) =>+ index === 0 ? { ...field, label: " " } : field+ ),+ })+ ).toThrow("Every field needs a label");+ });++ test("rejects duplicate original field ownership", () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ const fields = config.fields.map((field) =>+ field.key === "draft" ? { ...field, originalKey: "title" } : field+ );++ expect(() => serializeCollectionConfig({ config, fields })).toThrow(+ 'Original field "title" cannot be edited more than once'+ );+ });++ test("uses the field key when a schema title is empty", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.title.title = "";++ const config = parseCollectionConfig(JSON.stringify(schema));++ expect(config.fields.find(({ key }) => key === "title")?.label).toBe(+ "title"+ );++ const serialized = JSON.parse(+ serializeCollectionConfig({ config, fields: config.fields })+ );+ expect(serialized.properties.title.title).toBe("");+ });++ test("does not add missing field annotations during a no-op save", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ delete schema.properties.draft.title;+ schema.properties.draft["x-webstudio"] = {};+ const config = parseCollectionConfig(JSON.stringify(schema));++ const serialized = JSON.parse(+ serializeCollectionConfig({ config, fields: config.fields })+ );++ expect(Object.hasOwn(serialized.properties.draft, "title")).toBe(false);+ expect(serialized.properties.draft["x-webstudio"]).toEqual({});+ });++ test("rejects invalid field limits through schema validation", () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ const titleIndex = config.fields.findIndex(({ key }) => key === "title");+ const withTitle = (values: Partial<(typeof config.fields)[number]>) =>+ config.fields.map((field, index) =>+ index === titleIndex ? { ...field, ...values } : field+ );++ expect(() =>+ serializeCollectionConfig({+ config,+ fields: withTitle({ minLength: -1 }),+ })+ ).toThrow("minLength must be a whole number of zero or greater");+ expect(() =>+ serializeCollectionConfig({+ config,+ fields: withTitle({ minLength: 5, maxLength: 4 }),+ })+ ).toThrow("minLength cannot exceed maxLength");++ const numericFields = withTitle({+ type: "number",+ control: "number",+ minLength: undefined,+ maximum: 4,+ minimum: 5,+ });+ expect(() =>+ serializeCollectionConfig({ config, fields: numericFields })+ ).toThrow("minimum cannot exceed maximum");+ });++ test("preserves the configured slug field invariant", () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ const fields = config.fields.map((field) =>+ field.key === "slug"+ ? { ...field, control: "text" as const, required: false }+ : field+ );++ const serialized = JSON.parse(+ serializeCollectionConfig({ config, fields })+ );++ expect(serialized.required).toContain("slug");+ expect(serialized.properties.slug.$ref).toBe(+ "https://webstudio.is/schemas/slug"+ );+ expect(+ parseCollectionConfig(JSON.stringify(serialized)).validate({+ title: "Title",+ slug: "你好",+ }).success+ ).toBe(true);+ expect(serialized.properties.slug["x-webstudio"]).toEqual({+ control: "slug",+ });+ });++ test("moves slug semantics when the configured slug field changes", () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());++ const nextConfig = parseCollectionConfig(+ serializeCollectionConfig({+ config,+ fields: config.fields,+ settings: { slugField: "title", generateSlugFrom: "slug" },+ })+ );+ const title = nextConfig.schema.properties as Record<+ string,+ Record<string, unknown>+ >;++ expect(nextConfig.slugField).toBe("title");+ expect(nextConfig.generateSlugFrom).toBe("slug");+ expect(title.title.$ref).toBe("https://webstudio.is/schemas/slug");+ expect(+ nextConfig.validate({ title: "привет", slug: "Text, not a slug!" })+ .success+ ).toBe(true);+ expect(title.title["x-webstudio"]).toMatchObject({ control: "slug" });+ expect(title.slug.$ref).toBeUndefined();+ expect(title.slug["x-webstudio"]).toBeUndefined();+ expect(+ nextConfig.fields.filter(({ control }) => control === "slug")+ ).toHaveLength(1);+ });++ test("preserves explicitly declared supported controls", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.title["x-webstudio"] = {+ control: "text",+ help: "Shown above the field",+ };+ schema.properties.draft["x-webstudio"] = { control: "checkbox" };+ const config = parseCollectionConfig(JSON.stringify(schema));++ const serialized = JSON.parse(+ serializeCollectionConfig({ config, fields: config.fields })+ );++ expect(serialized.properties.title["x-webstudio"]).toEqual({+ control: "text",+ help: "Shown above the field",+ });+ expect(serialized.properties.draft["x-webstudio"]).toEqual({+ control: "checkbox",+ });+ });++ test("rejects field controls the configurator cannot represent", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.title["x-webstudio"] = { control: "rich-text" };++ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow(+ 'Control "rich-text" is not supported for property "title"'+ );+ });++ test("serializes explicit collection setting changes", () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ const fields = config.fields.map((field) => {+ if (field.key === "title") {+ return { ...field, key: "headline" };+ }+ if (field.key === "slug") {+ return { ...field, key: "permalink" };+ }+ return field;+ });++ const nextConfig = parseCollectionConfig(+ serializeCollectionConfig({+ config,+ fields,+ settings: {+ template: "entry.mdx",+ slugField: "permalink",+ generateSlugFrom: "headline",+ },+ })+ );++ expect(nextConfig).toMatchObject({+ template: "entry.mdx",+ slugField: "permalink",+ generateSlugFrom: "headline",+ });++ const withTemplateOnly = parseCollectionConfig(+ serializeCollectionConfig({+ config: nextConfig,+ fields: nextConfig.fields,+ settings: { template: "post.mdx" },+ })+ );+ expect(withTemplateOnly.template).toBe("post.mdx");+ });++ test("validates explicit collection setting changes while serializing", () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());++ expect(() =>+ serializeCollectionConfig({+ config,+ fields: config.fields,+ settings: { template: "../entry.mdx" },+ })+ ).toThrow("Template must be an MDX file in the collection folder");+ expect(() =>+ serializeCollectionConfig({+ config,+ fields: config.fields,+ settings: { slugField: "missing" },+ })+ ).toThrow("Slug field is not defined in properties");+ });++ test("creates an independent MDX entry from template defaults", async () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ const entry = await createCollectionEntry({+ config,+ templateSource: "---\ndraft: true\n---\n\nStart writing.\n",+ values: { title: "Designing With Constraints" },+ existingFilenames: ["another-post.mdx"],+ });++ expect(entry.filename).toBe("designing-with-constraints.mdx");+ expect(entry.frontmatter).toEqual({+ draft: true,+ slug: "designing-with-constraints",+ title: "Designing With Constraints",+ });+ expect(entry.source).toContain("Start writing.");+ });++ test("rejects entry values for unknown properties", async () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());++ await expect(+ createCollectionEntry({+ config,+ templateSource: "---\ndraft: true\n---\n",+ values: { title: "Unknown value", unknown: true },+ existingFilenames: [],+ })+ ).rejects.toThrow(+ 'Property "unknown" cannot be set when creating an entry'+ );+ });++ test("clears optional editable properties inherited from the template", async () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ expect(+ getCollectionFieldValidationError(config, {+ title: "Published entry",+ slug: "published-entry",+ draft: collectionEntryFieldClearValue,+ })+ ).toBeUndefined();++ const entry = await createCollectionEntry({+ config,+ templateSource: "---\ndraft: true\n---\n",+ values: {+ title: "Published entry",+ draft: collectionEntryFieldClearValue,+ },+ existingFilenames: [],+ });++ expect(Object.hasOwn(entry.frontmatter, "draft")).toBe(false);+ expect(entry.source).not.toContain("draft:");+ });++ test("treats schema defaults as annotations instead of missing values", async () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.required.push("draft");+ schema.properties.draft.default = true;+ const config = parseCollectionConfig(JSON.stringify(schema));+ const values = {+ title: "No draft value",+ slug: "no-draft-value",+ };++ expect(getCollectionValidationError(config, values)).toBeDefined();+ await expect(+ createCollectionEntry({+ config,+ templateSource: "",+ values: { title: "No draft value" },+ existingFilenames: [],+ })+ ).rejects.toThrow("Draft:");++ const entry = await createCollectionEntry({+ config,+ templateSource: "---\ndraft: true\n---\n",+ values: { title: "Has a draft value" },+ existingFilenames: [],+ });+ expect(entry.frontmatter.draft).toBe(true);+ });++ test("preserves schema defaults as annotations when field rules change", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.title.default = "An old title that is no longer valid";+ const config = parseCollectionConfig(JSON.stringify(schema));+ const title = config.fields.find(({ key }) => key === "title");+ if (title === undefined) {+ throw new Error("Expected title field");+ }++ const serialized = JSON.parse(+ serializeCollectionConfig({+ config,+ fields: config.fields.map((field) =>+ field.key === "title" ? { ...field, maxLength: 5 } : field+ ),+ })+ );++ expect(serialized.properties.title.default).toBe(+ "An old title that is no longer valid"+ );+ });++ test("uses JSON Schema character counts for string limits", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.title.minLength = 2;+ const config = parseCollectionConfig(JSON.stringify(schema));++ expect(+ getCollectionValidationError(config, {+ title: "😀",+ slug: "emoji",+ draft: true,+ })+ ).toBe("Title must contain at least 2 characters");+ });++ test("rejects nested object and array fields", () => {+ for (const field of [+ { type: "object", properties: { author: { type: "string" } } },+ { type: "array", items: { type: "string" } },+ ]) {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.properties.advanced = field;+ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow(+ "type must be string, number, integer, or boolean at #/properties/advanced/type"+ );+ }+ });++ test("rejects a template with an invalid MDX body", async () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());++ await expect(+ createCollectionEntry({+ config,+ templateSource: "---\ndraft: true\n---\n\n<Broken",+ values: { title: "Broken template" },+ existingFilenames: [],+ })+ ).rejects.toThrow("Collection template is invalid");+ });++ test("reports schema failures and duplicate generated filenames", async () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());++ expect(+ getCollectionValidationError(config, {+ title: "",+ slug: "invalid slug",+ draft: true,+ })+ ).toBe("Title must contain at least 1 character");++ expect(+ getCollectionTemplateValidationError(config, { draft: true })+ ).toBeUndefined();+ expect(getCollectionTemplateValidationError(config, { draft: "yes" })).toBe(+ "Draft: must be boolean"+ );+ expect(+ getCollectionTemplateValidationError(config, { unknown: true })+ ).toBeDefined();++ await expect(+ createCollectionEntry({+ config,+ templateSource: "",+ values: { title: "" },+ existingFilenames: [],+ })+ ).rejects.toThrow("Title must contain at least 1 character");++ await expect(+ createCollectionEntry({+ config,+ templateSource: "",+ values: { title: "Hello world" },+ existingFilenames: ["hello-world.mdx"],+ })+ ).rejects.toThrow('An entry named "hello-world.mdx" already exists');+ });++ test("checks ASCII filename collisions independently of locale", async () => {+ const config = parseCollectionConfig(createDefaultCollectionConfig());+ const localeLowerCase = String.prototype.toLocaleLowerCase;+ String.prototype.toLocaleLowerCase = function () {+ return localeLowerCase.call(this, "tr");+ };+ try {+ await expect(+ createCollectionEntry({+ config,+ templateSource: "",+ values: { title: "I" },+ existingFilenames: ["I.MDX"],+ })+ ).rejects.toThrow('An entry named "i.mdx" already exists');+ } finally {+ String.prototype.toLocaleLowerCase = localeLowerCase;+ }+ });++ test("rejects collection references outside the folder", () => {+ const source = createDefaultCollectionConfig().replace(+ '"template": "template.mdx"',+ '"template": "../template.mdx"'+ );+ expect(() => parseCollectionConfig(source)).toThrow(+ "Template must be an MDX file in the collection folder"+ );+ });++ test("rejects invalid slug and slug-source field types", () => {+ const slugSchema = JSON.parse(createDefaultCollectionConfig());+ slugSchema.properties.slug = { title: "URL slug", type: "boolean" };+ expect(() => parseCollectionConfig(JSON.stringify(slugSchema))).toThrow(+ "Slug field must be a string"+ );++ const sourceSchema = JSON.parse(createDefaultCollectionConfig());+ sourceSchema.properties.title = { title: "Title", type: "number" };+ expect(() => parseCollectionConfig(JSON.stringify(sourceSchema))).toThrow(+ "Slug source field must be a string"+ );+ });++ test("requires the configured slug property", () => {+ const schema = JSON.parse(createDefaultCollectionConfig());+ schema.required = schema.required.filter(+ (key: string) => key !== schema["x-webstudio"].slugField+ );++ expect(() => parseCollectionConfig(JSON.stringify(schema))).toThrow(+ "Slug field must be required"+ );+ });++ test("requires exactly one canonical slug control", () => {+ const missingControl = JSON.parse(createDefaultCollectionConfig());+ delete missingControl.properties.slug.$ref;+ delete missingControl.properties.slug["x-webstudio"];+ expect(() => parseCollectionConfig(JSON.stringify(missingControl))).toThrow(+ "Slug field must use the slug control"+ );++ const extraControl = JSON.parse(createDefaultCollectionConfig());+ extraControl.properties.alias = {+ type: "string",+ pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$",+ "x-webstudio": { control: "slug" },+ };+ expect(() => parseCollectionConfig(JSON.stringify(extraControl))).toThrow(+ 'Only the configured slug field can use the slug control; found "alias"'+ );+ });+});diff --git a/packages/content-engine/src/content-collection.ts b/packages/content-engine/src/content-collection.tsnew file mode 100644index 0000000000..9f90336c06--- /dev/null+++ b/packages/content-engine/src/content-collection.ts@@ -0,0 +1,1513 @@+import { z } from "zod";+import { Ajv2020, type ErrorObject } from "ajv/dist/2020.js";+import { pointerSegments } from "@hyperjump/json-pointer";+import { isMap, parseDocument } from "yaml";+import { findMarkdownFrontmatter } from "./markdown-scanner";+import { URLPattern } from "urlpattern-polyfill";+import { getUtf8ByteLength } from "./byte-stream";+import {+ extractMarkdownFrontmatter,+ replaceMarkdownFrontmatter,+} from "./frontmatter";+import { contentEngineLimits } from "./limits";+import { parseMdxDocument } from "./mdx";+import {+ normalizeStructuredDataObject,+ StructuredDataError,+} from "./structured-data";++export const collectionConfigFilename = "collection.json";+/** Pass this value to remove an optional editable property inherited from the template. */+export const collectionEntryFieldClearValue = null;+const legacyCollectionSlugPattern = "^[a-z0-9]+(?:-[a-z0-9]+)*$";+// Keep historical patterns recognizable even when the bundled schema changes.+// Each segment starts with a letter or number. Marks stay attached to preserve+// scripts such as Hindi; uppercase letters, separators and symbols are excluded.+const legacyUnicodeCollectionSlugPattern =+ "^(?!.*[\\p{Lu}\\p{Lt}])[\\p{L}\\p{N}][\\p{L}\\p{M}\\p{N}]*(?:-[\\p{L}\\p{N}][\\p{L}\\p{M}\\p{N}]*)*$(?![\\s\\S])";+const collectionSlugSchemaId = "https://webstudio.is/schemas/slug";+const collectionSlugSchema = {+ $id: collectionSlugSchemaId,+ type: "string",+ pattern: legacyUnicodeCollectionSlugPattern,+};+const collectionSchemaDialect = "https://json-schema.org/draft/2020-12/schema";+const maximumPropertyKeyBytes = 256;+export const defaultCollectionTemplateFilename = "template.mdx";++const collectionSettings = z.object({+ template: z.string().min(1),+ entries: z+ .array(z.string().min(1).max(256))+ .min(1)+ .max(64)+ .default(["*.mdx"]),+ slugField: z.string().min(1).optional(),+ generateSlugFrom: z.string().min(1).optional(),+});++export type CollectionField = Readonly<{+ key: string;+ originalKey?: string;+ label: string;+ type: "string" | "number" | "integer" | "boolean";+ control: "text" | "textarea" | "slug" | "number" | "checkbox";+ required: boolean;+ minLength?: number;+ maxLength?: number;+ minimum?: number;+ maximum?: number;+}>;++export type ContentCollectionConfig = Readonly<{+ schema: Record<string, unknown>;+ template: string;+ entries: readonly string[];+ matchesEntry: (filename: string) => boolean;+ slugField?: string;+ generateSlugFrom?: string;+ fields: readonly CollectionField[];+ validate: (value: unknown) => { success: boolean; errors: ErrorObject[] };+}>;++export class ContentCollectionError extends Error {}++export class ContentCollectionInspectionError extends ContentCollectionError {+ fileId?: string;+ missingTemplateFilename?: string;+ forbiddenFileId?: string;+ repairAction?: "edit" | "move";+ templateFileId?: string;++ constructor(+ message: string,+ details: {+ fileId?: string;+ missingTemplateFilename?: string;+ forbiddenFileId?: string;+ repairAction?: "edit" | "move";+ templateFileId?: string;+ cause?: unknown;+ } = {}+ ) {+ super(message, { cause: details.cause });+ this.fileId = details.fileId;+ this.missingTemplateFilename = details.missingTemplateFilename;+ this.forbiddenFileId = details.forbiddenFileId;+ this.repairAction = details.repairAction;+ this.templateFileId = details.templateFileId;+ }+}++const isObject = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null && Array.isArray(value) === false;++const prototypeSensitiveKeys = new Set([+ "__proto__",+ "constructor",+ "prototype",+]);++const validatePropertyKey = (key: string) => {+ if (prototypeSensitiveKeys.has(key)) {+ throw new ContentCollectionError(`Property key "${key}" is not supported`);+ }+ if (key.trim() === "") {+ throw new ContentCollectionError("Property keys cannot be empty");+ }+ if (getUtf8ByteLength(key) > maximumPropertyKeyBytes) {+ throw new ContentCollectionError(+ `Property key "${key.slice(0, 32)}…" exceeds the 256-byte limit`+ );+ }+};++type CollectionFieldType = "string" | "number" | "integer" | "boolean";++const collectionFieldTypes = new Set<CollectionFieldType>([+ "string",+ "number",+ "integer",+ "boolean",+]);++// Limit schemas to fields the configurator can represent. Ajv owns validation+// semantics; x-* extensions are preserved as annotations.+const commonSchemaKeywords = new Set([+ "type",+ "title",+ "description",+ "default",+ "examples",+ "deprecated",+ "readOnly",+ "writeOnly",+ "$comment",+]);++const schemaKeywordsByType: Readonly<+ Record<CollectionFieldType, ReadonlySet<string>>+> = {+ string: new Set(["minLength", "maxLength", "$ref"]),+ number: new Set(["minimum", "maximum"]),+ integer: new Set(["minimum", "maximum"]),+ boolean: new Set(),+};++const escapeJsonPointerSegment = (value: string) =>+ value.replaceAll("~", "~0").replaceAll("/", "~1");++const getSchemaLocation = (path: readonly string[]) =>+ path.length === 0+ ? "schema root"+ : `#/${path.map(escapeJsonPointerSegment).join("/")}`;++const getSchemaKeywordLocation = (path: readonly string[], keyword: string) =>+ getSchemaLocation([...path, keyword]);++const getFieldSchemaType = (+ schema: Readonly<Record<string, unknown>>,+ path: readonly string[]+): CollectionFieldType => {+ if (+ typeof schema.type !== "string" ||+ collectionFieldTypes.has(schema.type as CollectionFieldType) === false+ ) {+ throw new ContentCollectionError(+ `type must be string, number, integer, or boolean at ${getSchemaKeywordLocation(+ path,+ "type"+ )}`+ );+ }+ return schema.type as CollectionFieldType;+};++const validateSchemaAnnotations = (+ schema: Readonly<Record<string, unknown>>,+ path: readonly string[]+) => {+ for (const keyword of ["title", "description", "$comment"] as const) {+ if (Object.hasOwn(schema, keyword) && typeof schema[keyword] !== "string") {+ throw new ContentCollectionError(+ `${keyword} must be a string at ${getSchemaKeywordLocation(+ path,+ keyword+ )}`+ );+ }+ }+ for (const keyword of ["deprecated", "readOnly", "writeOnly"] as const) {+ if (+ Object.hasOwn(schema, keyword) &&+ typeof schema[keyword] !== "boolean"+ ) {+ throw new ContentCollectionError(+ `${keyword} must be a boolean at ${getSchemaKeywordLocation(+ path,+ keyword+ )}`+ );+ }+ }+ if (+ Object.hasOwn(schema, "examples") &&+ Array.isArray(schema.examples) === false+ ) {+ throw new ContentCollectionError(+ `examples must be an array at ${getSchemaKeywordLocation(+ path,+ "examples"+ )}`+ );+ }+};++const getOptionalNonnegativeIntegerKeyword = ({+ schema,+ path,+ keyword,+}: {+ schema: Readonly<Record<string, unknown>>;+ path: readonly string[];+ keyword: "minLength" | "maxLength";+}) => {+ if (Object.hasOwn(schema, keyword) === false) {+ return;+ }+ const value = schema[keyword];+ if (+ typeof value !== "number" ||+ Number.isSafeInteger(value) === false ||+ value < 0+ ) {+ throw new ContentCollectionError(+ `${keyword} must be a whole number of zero or greater at ${getSchemaKeywordLocation(+ path,+ keyword+ )}`+ );+ }+ return value;+};++const getOptionalFiniteNumberKeyword = ({+ schema,+ path,+ keyword,+}: {+ schema: Readonly<Record<string, unknown>>;+ path: readonly string[];+ keyword: "minimum" | "maximum";+}) => {+ if (Object.hasOwn(schema, keyword) === false) {+ return;+ }+ const value = schema[keyword];+ if (typeof value !== "number" || Number.isFinite(value) === false) {+ throw new ContentCollectionError(+ `${keyword} must be a finite number at ${getSchemaKeywordLocation(+ path,+ keyword+ )}`+ );+ }+ return value;+};++const getRequiredPropertyKeys = ({+ schema,+ properties,+ path,+}: {+ schema: Readonly<Record<string, unknown>>;+ properties: Readonly<Record<string, unknown>>;+ path: readonly string[];+}) => {+ if (Object.hasOwn(schema, "required") === false) {+ return new Set<string>();+ }+ if (+ Array.isArray(schema.required) === false ||+ schema.required.some((key) => typeof key !== "string")+ ) {+ throw new ContentCollectionError(+ `required must be an array of property keys at ${getSchemaKeywordLocation(+ path,+ "required"+ )}`+ );+ }+ const required = schema.required as string[];+ if (new Set(required).size !== required.length) {+ throw new ContentCollectionError(+ `required cannot contain duplicate keys at ${getSchemaKeywordLocation(+ path,+ "required"+ )}`+ );+ }+ for (const key of required) {+ validatePropertyKey(key);+ if (Object.hasOwn(properties, key) === false) {+ throw new ContentCollectionError(+ `Required property "${key}" is not defined in properties`+ );+ }+ }+ return new Set(required);+};++const validateFieldSchema = (+ schema: Readonly<Record<string, unknown>>,+ path: readonly string[]+) => {+ const type = getFieldSchemaType(schema, path);+ const supportedTypeKeywords = schemaKeywordsByType[type];+ for (const keyword of Object.keys(schema)) {+ if (+ commonSchemaKeywords.has(keyword) ||+ supportedTypeKeywords.has(keyword) ||+ keyword.startsWith("x-")+ ) {+ continue;+ }+ throw new ContentCollectionError(+ `Unsupported JSON Schema keyword "${keyword}" at ${getSchemaLocation(+ path+ )}`+ );+ }+ validateSchemaAnnotations(schema, path);++ if (type === "string") {+ const minLength = getOptionalNonnegativeIntegerKeyword({+ schema,+ path,+ keyword: "minLength",+ });+ const maxLength = getOptionalNonnegativeIntegerKeyword({+ schema,+ path,+ keyword: "maxLength",+ });+ if (+ minLength !== undefined &&+ maxLength !== undefined &&+ minLength > maxLength+ ) {+ throw new ContentCollectionError(+ `minLength cannot exceed maxLength at ${getSchemaLocation(path)}`+ );+ }+ }++ if (type === "number" || type === "integer") {+ const minimum = getOptionalFiniteNumberKeyword({+ schema,+ path,+ keyword: "minimum",+ });+ const maximum = getOptionalFiniteNumberKeyword({+ schema,+ path,+ keyword: "maximum",+ });+ if (minimum !== undefined && maximum !== undefined && minimum > maximum) {+ throw new ContentCollectionError(+ `minimum cannot exceed maximum at ${getSchemaLocation(path)}`+ );+ }+ if (+ type === "integer" &&+ minimum !== undefined &&+ maximum !== undefined &&+ Math.ceil(minimum) > Math.floor(maximum)+ ) {+ throw new ContentCollectionError(+ `Limits must allow at least one whole number at ${getSchemaLocation(path)}`+ );+ }+ }+};++const validateCollectionSchema = (+ schema: Readonly<Record<string, unknown>>,+ properties: Readonly<Record<string, unknown>>+) => {+ const supportedRootKeywords = new Set([+ ...commonSchemaKeywords,+ "$schema",+ "properties",+ "required",+ "additionalProperties",+ ]);+ for (const keyword of Object.keys(schema)) {+ if (supportedRootKeywords.has(keyword) || keyword.startsWith("x-")) {+ continue;+ }+ throw new ContentCollectionError(+ `Unsupported JSON Schema keyword "${keyword}" at schema root`+ );+ }+ validateSchemaAnnotations(schema, []);+ if (+ Object.hasOwn(schema, "additionalProperties") &&+ typeof schema.additionalProperties !== "boolean"+ ) {+ throw new ContentCollectionError(+ "additionalProperties must be true or false at #/additionalProperties"+ );+ }+ getRequiredPropertyKeys({ schema, properties, path: [] });+ for (const [key, propertySchema] of Object.entries(properties)) {+ validatePropertyKey(key);+ if (isObject(propertySchema) === false) {+ throw new ContentCollectionError(+ `Property "${key}" must contain a schema object`+ );+ }+ if (Object.hasOwn(propertySchema, "$ref")) {+ if (propertySchema.$ref !== collectionSlugSchemaId) {+ throw new ContentCollectionError(+ `Unsupported schema reference at #/properties/${escapeJsonPointerSegment(key)}/$ref`+ );+ }+ if (+ propertySchema.type !== undefined &&+ propertySchema.type !== "string"+ ) {+ throw new ContentCollectionError(+ `Slug reference requires a string field at #/properties/${escapeJsonPointerSegment(key)}`+ );+ }+ }+ validateFieldSchema(+ propertySchema.$ref === collectionSlugSchemaId+ ? { type: "string", ...propertySchema }+ : propertySchema,+ ["properties", key]+ );+ }+};++const getNonnegativeInteger = (value: unknown) =>+ Number.isInteger(value) && Number(value) >= 0 ? Number(value) : undefined;++const getFiniteNumber = (value: unknown) =>+ typeof value === "number" && Number.isFinite(value) ? value : undefined;++const getField = ({+ key,+ value,+ required,+}: {+ key: string;+ value: unknown;+ required: boolean;+}): CollectionField | undefined => {+ if (isObject(value) === false) {+ return;+ }+ const type =+ value.type ??+ (value.$ref === collectionSlugSchemaId ? "string" : undefined);+ const label =+ typeof value.title === "string" && value.title.trim() !== ""+ ? value.title+ : key;+ const rawExtension = value["x-webstudio"];+ if (Object.hasOwn(value, "x-webstudio") && isObject(rawExtension) === false) {+ throw new ContentCollectionError(+ `x-webstudio must be an object for property "${key}"`+ );+ }+ const extension = isObject(rawExtension) ? rawExtension : undefined;+ const declaredControl = extension?.control;+ const supportedControls =+ type === "string"+ ? new Set(["text", "textarea", "slug"])+ : type === "number" || type === "integer"+ ? new Set(["number"])+ : type === "boolean"+ ? new Set(["checkbox"])+ : new Set<string>();+ if (+ declaredControl !== undefined &&+ (typeof declaredControl !== "string" ||+ supportedControls.has(declaredControl) === false)+ ) {+ const control =+ typeof declaredControl === "string"+ ? `"${declaredControl}"`+ : JSON.stringify(declaredControl);+ throw new ContentCollectionError(+ `Control ${control} is not supported for property "${key}"`+ );+ }+ if (type === "string") {+ const hasSlugReference = value.$ref === collectionSlugSchemaId;+ if (declaredControl === "slug" && !hasSlugReference) {+ throw new ContentCollectionError(+ `Slug control for property "${key}" must use Webstudio's slug schema reference`+ );+ }+ if (hasSlugReference && declaredControl !== "slug") {+ throw new ContentCollectionError(+ `Webstudio's slug schema reference requires a slug control for property "${key}"`+ );+ }+ const control =+ declaredControl === "text" ||+ declaredControl === "textarea" ||+ declaredControl === "slug"+ ? declaredControl+ : "text";+ return {+ key,+ originalKey: key,+ label,+ type: "string",+ control,+ required,+ minLength: getNonnegativeInteger(value.minLength),+ maxLength: getNonnegativeInteger(value.maxLength),+ };+ }+ if (type === "number" || type === "integer") {+ return {+ key,+ originalKey: key,+ label,+ type: type,+ control: "number",+ required,+ minimum: getFiniteNumber(value.minimum),+ maximum: getFiniteNumber(value.maximum),+ };+ }+ if (type === "boolean") {+ return {+ key,+ originalKey: key,+ label,+ type: "boolean",+ control: "checkbox",+ required,+ };+ }+};++const validateTemplatePath = (template: string) => {+ if (+ template.endsWith(".mdx") === false ||+ template === ".mdx" ||+ template.includes("/") ||+ template.includes("\\") ||+ template === "." ||+ template === ".."+ ) {+ throw new ContentCollectionError(+ "Template must be an MDX file in the collection folder"+ );+ }+};++export const parseCollectionConfig = (+ source: string+): ContentCollectionConfig => {+ if (getUtf8ByteLength(source) > contentEngineLimits.jsonBytes) {+ throw new ContentCollectionError(+ "collection.json exceeds the 1 MiB size limit"+ );+ }+ let value: unknown;+ try {+ value = JSON.parse(source);+ } catch {+ throw new ContentCollectionError("collection.json contains invalid JSON");+ }+ if (isObject(value) === false) {+ throw new ContentCollectionError("collection.json must contain an object");+ }+ let schema: Record<string, unknown>;+ try {+ schema = normalizeStructuredDataObject(value, {+ depth: contentEngineLimits.jsonDepth,+ fields: contentEngineLimits.jsonFields,+ stringBytes: contentEngineLimits.jsonStringBytes,+ serializedBytes: contentEngineLimits.jsonBytes,+ });+ } catch (error) {+ if (error instanceof StructuredDataError) {+ throw new ContentCollectionError(+ error.code === "INVALID"+ ? "collection.json contains values that cannot be represented safely"+ : "collection.json exceeds the supported schema complexity",+ { cause: error }+ );+ }+ throw error;+ }+ if (schema.type !== "object" || isObject(schema.properties) === false) {+ throw new ContentCollectionError(+ "collection.json must describe an object with properties"+ );+ }+ if (+ Object.hasOwn(schema, "$schema") &&+ schema.$schema !== collectionSchemaDialect+ ) {+ throw new ContentCollectionError(+ "Only JSON Schema draft 2020-12 is supported"+ );+ }+ // Upgrade only previously generated rules, never arbitrary custom patterns.+ // This normalizes the in-memory config; the file changes only on settings save.+ for (const [key, property] of Object.entries(schema.properties)) {+ if (isObject(property) && Object.hasOwn(property, "pattern")) {+ if (+ property.pattern !== legacyCollectionSlugPattern &&+ property.pattern !== legacyUnicodeCollectionSlugPattern+ ) {+ throw new ContentCollectionError(+ `Only Webstudio's slug schema reference is supported; custom patterns are not supported at #/properties/${escapeJsonPointerSegment(key)}/pattern`+ );+ }+ if (property.$ref === undefined) {+ property.$ref = collectionSlugSchemaId;+ }+ delete property.pattern;+ }+ }+ validateCollectionSchema(schema, schema.properties);+ // Scope Ajv to this config so its generated-code registry cannot retain old+ // settings forever. Only bundled references are registered; no loadSchema.+ const validator = new Ajv2020({+ allErrors: true,+ strictSchema: false, // Preserve x-* annotations.+ strictTypes: false, // A referenced schema can supply the field's type.+ ownProperties: true,+ schemas: [collectionSlugSchema],+ });+ let parser;+ try {+ parser = validator.compile(schema);+ } catch (cause) {+ throw new ContentCollectionError("Invalid collection JSON Schema", {+ cause,+ });+ }+ const settingsResult = collectionSettings.safeParse(schema["x-webstudio"]);+ if (settingsResult.success === false) {+ throw new ContentCollectionError(+ "collection.json must define Webstudio collection settings"+ );+ }+ const settings = settingsResult.data;+ validateTemplatePath(settings.template);+ const patterns = settings.entries.map((value) => {+ const exclude = value.startsWith("!");+ const pattern = exclude ? value.slice(1) : value;+ if (pattern.length === 0 || pattern.includes("/")) {+ throw new ContentCollectionError(+ "Entry patterns must match filenames in the current folder, without slashes"+ );+ }+ try {+ return {+ exclude,+ pattern: new URLPattern(+ { pathname: `/${pattern}` },+ // Supported at runtime; urlpattern-polyfill 10.1.0 omits this overload.+ // @ts-expect-error Incomplete upstream constructor declarations.+ { ignoreCase: true }+ ),+ };+ } catch {+ throw new ContentCollectionError(+ `Invalid entry filename pattern "${value}"`+ );+ }+ });+ if (patterns.every(({ exclude }) => exclude)) {+ throw new ContentCollectionError(+ "Entry patterns need at least one inclusion pattern"+ );+ }+ const required = new Set(schema.required as string[] | undefined);+ const fields = Object.entries(schema.properties).map(([key, field]) => {+ const parsed = getField({ key, value: field, required: required.has(key) });+ if (parsed === undefined) {+ throw new ContentCollectionError(+ `Property "${key}" must use a supported flat field type`+ );+ }+ return parsed;+ });+ const slugField = fields.find(({ key }) => key === settings.slugField);+ if (settings.slugField !== undefined) {+ if (slugField === undefined) {+ throw new ContentCollectionError(+ "Slug field is not defined in properties"+ );+ }+ if (slugField.type !== "string") {+ throw new ContentCollectionError("Slug field must be a string");+ }+ if (slugField.required === false) {+ throw new ContentCollectionError("Slug field must be required");+ }+ if (slugField.control !== "slug") {+ throw new ContentCollectionError("Slug field must use the slug control");+ }+ }+ const additionalSlugField = fields.find(+ ({ key, control }) => key !== settings.slugField && control === "slug"+ );+ if (additionalSlugField !== undefined) {+ throw new ContentCollectionError(+ `Only the configured slug field can use the slug control; found "${additionalSlugField.key}"`+ );+ }+ const slugSourceField = fields.find(+ ({ key }) => key === settings.generateSlugFrom+ );+ if (settings.generateSlugFrom !== undefined) {+ if (settings.slugField === undefined) {+ throw new ContentCollectionError("Slug generation requires a slug field");+ }+ if (slugSourceField === undefined) {+ throw new ContentCollectionError(+ "Slug source field is not defined in properties"+ );+ }+ if (slugSourceField.type !== "string") {+ throw new ContentCollectionError("Slug source field must be a string");+ }+ if (settings.generateSlugFrom === settings.slugField) {+ throw new ContentCollectionError(+ "Slug source field must be different from the slug field"+ );+ }+ }+ return {+ schema,+ template: settings.template,+ entries: settings.entries,+ matchesEntry: (filename) => {+ if (+ filename.includes("/") ||+ filename === collectionConfigFilename ||+ filename === settings.template+ ) {+ return false;+ }+ const input = { pathname: `/${encodeURIComponent(filename)}` };+ return (+ patterns.some(+ ({ exclude, pattern }) => !exclude && pattern.test(input)+ ) &&+ !patterns.some(({ exclude, pattern }) => exclude && pattern.test(input))+ );+ },+ slugField: settings.slugField,+ generateSlugFrom: settings.generateSlugFrom,+ fields,+ validate: (candidate) => ({+ success: parser(candidate),+ errors: parser.errors ?? [],+ }),+ };+};++export const normalizeCollectionSlug = (value: string) => {+ return (+ value+ .normalize("NFC")+ .toLowerCase()+ .normalize("NFC")+ .match(/[\p{L}\p{N}][\p{L}\p{M}\p{N}]*/gu)+ ?.join("-") ?? ""+ );+};++const getValidationFieldKey = (issue: ErrorObject): string | undefined => {+ if (issue.keyword === "additionalProperties") {+ return issue.params.additionalProperty;+ }+ if (issue.keyword === "required") {+ return issue.params.missingProperty;+ }+ return pointerSegments(issue.instancePath).next().value;+};++const getValidationError = (+ config: ContentCollectionConfig,+ issue: ErrorObject+) => {+ const key = getValidationFieldKey(issue);+ const field = config.fields.find((candidate) => candidate.key === key);+ const label = field?.label ?? key ?? "Entry";+ if (issue.keyword === "minLength") {+ const minimum = Number(issue.params.limit);+ return `${label} must contain at least ${minimum} ${+ minimum === 1 ? "character" : "characters"+ }`;+ }+ if (issue.keyword === "maxLength") {+ const maximum = Number(issue.params.limit);+ return `${label} must contain at most ${maximum} ${+ maximum === 1 ? "character" : "characters"+ }`;+ }+ if (issue.keyword === "pattern" && field?.control === "slug") {+ return `${label}: Use lowercase letters and numbers separated by single dashes`;+ }+ if (issue.keyword === "required") {+ return `${label}: A value is required`;+ }+ if (issue.keyword === "additionalProperties") {+ return `${label}: This field is not defined in the collection`;+ }+ return `${label}: ${issue.message}`;+};++export const getCollectionValidationError = (+ config: ContentCollectionConfig,+ properties: unknown+) => {+ const validation = config.validate(properties);+ if (validation.success) {+ return;+ }+ return getValidationError(config, validation.errors[0]);+};++export const getCollectionEntryValidationIssues = ({+ config,+ properties,+ basename,+}: {+ config: ContentCollectionConfig;+ properties: Readonly<Record<string, unknown>>;+ basename: string;+}) => {+ const validation = config.validate(properties);+ const issues = validation.errors.map((issue) => ({+ fieldKey: getValidationFieldKey(issue),+ message: getValidationError(config, issue),+ }));+ if (+ config.slugField !== undefined &&+ properties[config.slugField] !== basename+ ) {+ issues.push({+ fieldKey: config.slugField,+ message: "The slug must match the entry filename",+ });+ }+ return issues;+};++/** Field ranges use the YAML parser, including quoted keys and multiline values. */+export const getCollectionEntrySourceIssues = async ({+ config,+ source,+ basename,+}: {+ config: ContentCollectionConfig;+ source: string;+ basename: string;+}) => {+ const { properties } = await extractMarkdownFrontmatter(source);+ const bytes = new TextEncoder().encode(source);+ const envelope = findMarkdownFrontmatter(bytes, true);+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });+ const start = !envelope+ ? 0+ : decoder.decode(bytes.subarray(0, envelope.yamlStart)).length;+ const document = !envelope+ ? undefined+ : parseDocument(+ decoder.decode(bytes.subarray(envelope.yamlStart, envelope.yamlEnd))+ );+ return getCollectionEntryValidationIssues({+ config,+ properties,+ basename,+ }).map((issue) => {+ const node =+ document !== undefined &&+ isMap(document.contents) &&+ issue.fieldKey !== undefined+ ? document.contents.get(issue.fieldKey, true)+ : undefined;+ const range =+ node !== null && typeof node === "object" && "range" in node+ ? node.range+ : undefined;+ const from = range ? start + range[0] : start;+ const to = range ? start + range[1] : Math.min(source.length, from + 1);+ return { ...issue, from, to };+ });+};++export const getCollectionFieldValidationIssue = (+ config: ContentCollectionConfig,+ properties: unknown+) => {+ let validationProperties = properties;+ if (isObject(properties)) {+ const candidate = { ...properties };+ for (const field of config.fields) {+ if (+ field.required === false &&+ properties[field.key] === collectionEntryFieldClearValue+ ) {+ delete candidate[field.key];+ }+ }+ validationProperties = candidate;+ }+ const validation = config.validate(validationProperties);+ if (validation.success) {+ return;+ }+ const fieldKeys = new Set(config.fields.map(({ key }) => key));+ const issue = validation.errors.find((issue) => {+ const key = getValidationFieldKey(issue);+ return key !== undefined && fieldKeys.has(key);+ });+ if (issue === undefined) {+ return;+ }+ return {+ fieldKey: getValidationFieldKey(issue)!,+ message: getValidationError(config, issue),+ };+};++export const getCollectionFieldValidationError = (+ config: ContentCollectionConfig,+ properties: unknown+) => getCollectionFieldValidationIssue(config, properties)?.message;++export const getCollectionTemplateValidationError = (+ config: ContentCollectionConfig,+ properties: Readonly<Record<string, unknown>>+) => {+ const validation = config.validate(properties);+ if (validation.success) {+ return;+ }+ const issue = validation.errors.find((issue) => {+ if (issue.keyword === "additionalProperties") {+ return true;+ }+ const key = getValidationFieldKey(issue);+ return key !== undefined && Object.hasOwn(properties, key);+ });+ return issue === undefined ? undefined : getValidationError(config, issue);+};++const parseCollectionTemplate = async (source: string) => {+ try {+ return await parseMdxDocument({ source });+ } catch (error) {+ const details = error instanceof Error ? `: ${error.message}` : "";+ throw new ContentCollectionError(+ `Collection template is invalid${details}`,+ { cause: error }+ );+ }+};++export type ContentCollectionFile<File> = Readonly<{+ file: File;+ id: string;+ filename: string;+ basename: string;+ isMdx: boolean;+}>;++export const inspectContentCollection = async <File>({+ files,+ readSource,+ readFrontmatter,+ validateTemplate = true,+ validateEntries = true,+ entryIdsToValidate,+}: {+ files: readonly ContentCollectionFile<File>[];+ readSource: (file: ContentCollectionFile<File>) => Promise<string>;+ readFrontmatter?: (+ file: ContentCollectionFile<File>+ ) => Promise<Readonly<Record<string, unknown>>>;+ validateTemplate?: boolean;+ validateEntries?: boolean;+ entryIdsToValidate?: ReadonlySet<string>;+}) => {+ const configFiles = files.filter(+ (file) => file.filename === collectionConfigFilename+ );+ const configFile = configFiles[0];+ if (configFile === undefined || configFiles.length !== 1) {+ throw new ContentCollectionInspectionError(+ "A collection folder must contain exactly one collection.json",+ { fileId: configFile?.id }+ );+ }+ let config: ContentCollectionConfig;+ try {+ config = parseCollectionConfig(await readSource(configFile));+ } catch (error) {+ if (error instanceof ContentCollectionError === false) {+ throw error;+ }+ throw new ContentCollectionInspectionError(error.message, {+ fileId: configFile.id,+ repairAction: "edit",+ cause: error,+ });+ }+ const entryFiles = files.filter((file) => config.matchesEntry(file.filename));+ const forbiddenFile = entryFiles.find((file) => file.isMdx === false);+ if (forbiddenFile !== undefined) {+ throw new ContentCollectionInspectionError(+ `Collection entry "${forbiddenFile.filename}" must be an MDX file. Exclude it using the entry patterns.`,+ {+ fileId: forbiddenFile.id,+ forbiddenFileId: forbiddenFile.id,+ repairAction: "move",+ }+ );+ }+ const templateFiles = files.filter(+ (file) => file.filename === config.template && file.isMdx+ );+ const templateFile = templateFiles[0];+ if (templateFile === undefined) {+ throw new ContentCollectionInspectionError(+ `Collection template "${config.template}" not found`,+ {+ fileId: configFile.id,+ missingTemplateFilename: config.template,+ }+ );+ }+ if (templateFiles.length !== 1) {+ throw new ContentCollectionInspectionError(+ `Collection template "${config.template}" is ambiguous`,+ {+ fileId: templateFile.id,+ templateFileId: templateFile.id,+ }+ );+ }+ const filenames = new Set<string>();+ for (const file of [...entryFiles, configFile, templateFile]) {+ const normalizedFilename = file.filename.toLowerCase();+ if (filenames.has(normalizedFilename)) {+ throw new ContentCollectionInspectionError(+ `Collection folder contains duplicate filename "${file.filename}"`,+ {+ fileId: file.id,+ repairAction: "move",+ templateFileId: templateFile.id,+ }+ );+ }+ filenames.add(normalizedFilename);+ }+ let templateProperties: Readonly<Record<string, unknown>> = {};+ if (validateTemplate) {+ let templateDocument: Awaited<ReturnType<typeof parseCollectionTemplate>>;+ try {+ templateDocument = await parseCollectionTemplate(+ await readSource(templateFile)+ );+ } catch (error) {+ if (error instanceof ContentCollectionError === false) {+ throw error;+ }+ throw new ContentCollectionInspectionError(error.message, {+ fileId: templateFile.id,+ repairAction: "edit",+ templateFileId: templateFile.id,+ cause: error,+ });+ }+ templateProperties = templateDocument.frontmatter.properties;+ const templateError = getCollectionTemplateValidationError(+ config,+ templateProperties+ );+ if (templateError !== undefined) {+ throw new ContentCollectionInspectionError(+ `Collection template "${config.template}": ${templateError}`,+ {+ fileId: templateFile.id,+ repairAction: "edit",+ templateFileId: templateFile.id,+ }+ );+ }+ }+ if (validateEntries) {+ for (let index = 0; index < entryFiles.length; index += 1) {+ const entryFile = entryFiles[index];+ if (+ entryIdsToValidate !== undefined &&+ !entryIdsToValidate.has(entryFile.id)+ ) {+ continue;+ }+ let properties: Readonly<Record<string, unknown>>;+ try {+ properties =+ readFrontmatter === undefined+ ? (await extractMarkdownFrontmatter(await readSource(entryFile)))+ .properties+ : await readFrontmatter(entryFile);+ } catch (error) {+ if (error instanceof ContentCollectionError) {+ throw error;+ }+ const details = error instanceof Error ? `: ${error.message}` : "";+ throw new ContentCollectionInspectionError(+ `Collection entry "${entryFile.filename}" is invalid${details}`,+ {+ fileId: entryFile.id,+ repairAction: "edit",+ templateFileId: templateFile.id,+ cause: error,+ }+ );+ }+ const validationError = getCollectionValidationError(config, properties);+ if (validationError !== undefined) {+ throw new ContentCollectionInspectionError(+ `Collection entry "${entryFile.filename}": ${validationError}`,+ {+ fileId: entryFile.id,+ repairAction: "edit",+ templateFileId: templateFile.id,+ }+ );+ }+ if (+ config.slugField !== undefined &&+ properties[config.slugField] !== entryFile.basename+ ) {+ throw new ContentCollectionInspectionError(+ `Collection entry "${entryFile.filename}": The slug must match the entry filename`,+ {+ fileId: entryFile.id,+ repairAction: "edit",+ templateFileId: templateFile.id,+ }+ );+ }+ }+ }+ return {+ configFile,+ templateFile,+ entryFiles,+ config,+ templateProperties,+ };+};++export const createCollectionEntry = async ({+ config,+ templateSource,+ values,+ existingFilenames,+ requestId,+}: {+ config: ContentCollectionConfig;+ templateSource: string;+ values: Readonly<Record<string, unknown>>;+ existingFilenames: readonly string[];+ requestId?: string;+}) => {+ const template = await parseCollectionTemplate(templateSource);+ const frontmatter = { ...template.frontmatter.properties };+ const fields = new Map(config.fields.map((field) => [field.key, field]));+ for (const [key, value] of Object.entries(values)) {+ const field = fields.get(key);+ if (field === undefined) {+ throw new ContentCollectionError(+ `Property "${key}" cannot be set when creating an entry`+ );+ }+ if (value === collectionEntryFieldClearValue && field.required === false) {+ delete frontmatter[key];+ continue;+ }+ frontmatter[key] = value;+ }+ if (config.slugField !== undefined) {+ const currentSlug = frontmatter[config.slugField];+ if (typeof currentSlug !== "string" || currentSlug.trim() === "") {+ const source =+ config.generateSlugFrom === undefined+ ? undefined+ : frontmatter[config.generateSlugFrom];+ if (typeof source === "string") {+ frontmatter[config.slugField] = normalizeCollectionSlug(source);+ }+ } else {+ frontmatter[config.slugField] = normalizeCollectionSlug(currentSlug);+ }+ }+ const validationError = getCollectionValidationError(config, frontmatter);+ if (validationError !== undefined) {+ throw new ContentCollectionError(validationError);+ }+ const slug =+ config.slugField === undefined+ ? `entry-${requestId === undefined ? crypto.randomUUID() : z.uuid().parse(requestId)}`+ : frontmatter[config.slugField];+ if (typeof slug !== "string" || slug === "") {+ throw new ContentCollectionError("Slug cannot be empty");+ }+ const filename = `${slug}.mdx`;+ if (config.matchesEntry(filename) === false) {+ throw new ContentCollectionError(+ `The filename "${filename}" does not match the collection entry patterns`+ );+ }+ if (+ existingFilenames.some(+ (existingFilename) =>+ existingFilename.normalize("NFC").toLowerCase() ===+ filename.toLowerCase()+ )+ ) {+ throw new ContentCollectionError(+ `An entry named "${filename}" already exists`+ );+ }+ return {+ filename,+ frontmatter,+ source: await replaceMarkdownFrontmatter({+ source: templateSource,+ properties: frontmatter,+ }),+ };+};++export const createDefaultCollectionConfig = () =>+ `${JSON.stringify(+ {+ $schema: collectionSchemaDialect,+ title: "Collection entry",+ type: "object",+ required: ["title", "slug"],+ properties: {+ title: {+ title: "Title",+ type: "string",+ minLength: 1,+ maxLength: 120,+ },+ slug: {+ title: "URL slug",+ type: "string",+ minLength: 1,+ maxLength: 120,+ $ref: collectionSlugSchemaId,+ "x-webstudio": { control: "slug" },+ },+ draft: { title: "Draft", type: "boolean" },+ },+ additionalProperties: false,+ "x-webstudio": {+ template: defaultCollectionTemplateFilename,+ entries: ["*.mdx"],+ slugField: "slug",+ generateSlugFrom: "title",+ },+ },+ undefined,+ 2+ )}\n`;++export const createDefaultCollectionTemplate = () =>+ "---\ndraft: true\n---\n\nStart writing.\n";++/** Keep existing collections readable; only configuration changes need this guarantee. */+export const getCollectionEntryCreationError = (+ config: ContentCollectionConfig+) => {+ if (+ config.slugField === undefined &&+ (config.entries.length !== 1 ||+ !["*.mdx", "entry-*.mdx"].includes(config.entries[0]))+ ) {+ return "Without a Slug field, use *.mdx or entry-*.mdx for entry patterns so generated filenames always match. Add a Slug field to use custom patterns.";+ }+};++const serializeCollectionField = (+ field: CollectionField,+ originalValue: unknown+) => {+ const original = isObject(originalValue) ? originalValue : {};+ const result: Record<string, unknown> = {+ ...original,+ type: field.type,+ };+ const hasExplicitLabel =+ typeof original.title === "string" && original.title.trim() !== "";+ if (hasExplicitLabel || field.label !== field.key) {+ result.title = field.label;+ }+ for (const keyword of [+ "properties",+ "required",+ "additionalProperties",+ "items",+ "minItems",+ "maxItems",+ "minLength",+ "maxLength",+ "pattern",+ "$ref",+ "minimum",+ "maximum",+ ]) {+ delete result[keyword];+ }+ if (field.type === "string") {+ if (field.minLength !== undefined) {+ result.minLength = field.minLength;+ }+ if (field.maxLength !== undefined) {+ result.maxLength = field.maxLength;+ }+ } else if (field.type === "number" || field.type === "integer") {+ if (field.minimum !== undefined) {+ result.minimum = field.minimum;+ }+ if (field.maximum !== undefined) {+ result.maximum = field.maximum;+ }+ }+ const originalExtension = isObject(original["x-webstudio"])+ ? original["x-webstudio"]+ : {};+ const preserveEmptyExtension =+ Object.hasOwn(original, "x-webstudio") &&+ Object.keys(originalExtension).length === 0;+ const extension = { ...originalExtension };+ delete extension.control;+ if (field.control === "textarea" || field.control === "slug") {+ extension.control = field.control;+ } else if (originalExtension.control === field.control) {+ extension.control = field.control;+ }+ if (Object.keys(extension).length === 0 && preserveEmptyExtension === false) {+ delete result["x-webstudio"];+ } else {+ result["x-webstudio"] = extension;+ }+ if (field.control === "slug") {+ result.$ref = collectionSlugSchemaId;+ }+ return result;+};++export const serializeCollectionConfig = ({+ config,+ fields,+ settings,+}: {+ config: ContentCollectionConfig;+ fields: readonly CollectionField[];+ settings?: {+ template?: string;+ slugField?: string;+ generateSlugFrom?: string;+ };+}) => {+ const ownedOriginalKeys = new Set<string>();+ for (const { originalKey } of fields) {+ if (originalKey === undefined) {+ continue;+ }+ if (ownedOriginalKeys.has(originalKey)) {+ throw new ContentCollectionError(+ `Original field "${originalKey}" cannot be edited more than once`+ );+ }+ ownedOriginalKeys.add(originalKey);+ }+ const template = settings?.template ?? config.template;+ const slugField =+ settings && Object.hasOwn(settings, "slugField")+ ? settings.slugField+ : config.slugField;+ const generateSlugFrom =+ slugField === undefined+ ? undefined+ : settings && Object.hasOwn(settings, "generateSlugFrom")+ ? settings.generateSlugFrom+ : config.generateSlugFrom;+ const serializedFields = fields.map((field) => {+ if (field.key === slugField) {+ return field.type === "string"+ ? { ...field, control: "slug" as const, required: true }+ : { ...field, required: true };+ }+ if (field.control === "slug") {+ return { ...field, control: "text" as const };+ }+ return field;+ });+ const fieldKeys = serializedFields.map(({ key }) => key);+ if (+ fieldKeys.some((key) => key.trim() === "") ||+ new Set(fieldKeys).size !== fieldKeys.length+ ) {+ throw new ContentCollectionError(+ "Every field needs a non-empty, unique key"+ );+ }+ if (serializedFields.some(({ label }) => label.trim() === "")) {+ throw new ContentCollectionError("Every field needs a label");+ }+ for (const field of serializedFields) {+ validatePropertyKey(field.key);+ }+ const originalProperties = isObject(config.schema.properties)+ ? config.schema.properties+ : {};+ const originalSettings = isObject(config.schema["x-webstudio"])+ ? { ...config.schema["x-webstudio"] }+ : {};+ delete originalSettings.previewPage;+ const value = {+ ...config.schema,+ required: serializedFields+ .filter(({ required }) => required)+ .map(({ key }) => key),+ properties: Object.fromEntries(+ serializedFields.map((field) => [+ field.key,+ serializeCollectionField(+ field,+ field.originalKey === undefined+ ? undefined+ : originalProperties[field.originalKey]+ ),+ ])+ ),+ "x-webstudio": {+ ...originalSettings,+ template,+ slugField,+ generateSlugFrom,+ },+ };+ const source = `${JSON.stringify(value, undefined, 2)}\n`;+ parseCollectionConfig(source);+ return source;+};++/** Identify the input responsible for a field's invalid limits. */+export const getCollectionFieldLimitsIssue = (field: CollectionField) => {+ // The referenced slug schema requires a nonempty value even when the local+ // minLength is unset. Keep existing configurations readable for repairs.+ if (field.control === "slug" && field.maxLength === 0) {+ return {+ input: "maxLength",+ message: "A slug must allow at least one character.",+ };+ }+ try {+ validateFieldSchema(serializeCollectionField(field, undefined), [+ "properties",+ field.key,+ ]);+ } catch (error) {+ const input =+ field.type === "string"+ ? field.minLength !== undefined &&+ (!Number.isSafeInteger(field.minLength) || field.minLength < 0)+ ? "minLength"+ : "maxLength"+ : field.minimum !== undefined && !Number.isFinite(field.minimum)+ ? "minimum"+ : "maximum";+ return {+ input,+ message:+ error instanceof Error ? error.message : "Check this field’s limits.",+ };+ }+};diff --git a/packages/content-engine/src/index.ts b/packages/content-engine/src/index.tsindex e4da5922ec..c367eeaa26 100644--- a/packages/content-engine/src/index.ts+++ b/packages/content-engine/src/index.ts@@ -14,5 +14,8 @@ export * from "./query-error-details";export * from "./document-graph";export * from "./asset-value-references";export * from "./json-assets";+export * from "./content-collection";+export { extractMarkdownFrontmatter } from "./frontmatter";+export { MarkdownMetadataError } from "./markdown-errors";export { createUniqueAssetIdsByPath } from "./asset-path-resolution";export { appendAssetFieldPath } from "./canonical";diff --git a/packages/design-system/src/brand.ts b/packages/design-system/src/brand.tsindex 4b1c6b6625..b0c6f61057 100644--- a/packages/design-system/src/brand.ts+++ b/packages/design-system/src/brand.ts@@ -1,8 +1,16 @@-// Fixed Webstudio identity artwork. These values do not follow the-// user-selectable application theme.+import { cssVar } from "./css-var";++const background = cssVar("--background-primary");++// Brand glows stay fixed; the neutral base and highlight follow the theme.export const webstudioBrand = {- backgroundGradient:- "radial-gradient(65.88% 47.48% at 50% 50%, #fff 0%, #fff0 100%), linear-gradient(0deg, #fff0 49.46%, #ffffff54 100%), linear-gradient(180deg, #ffae3c00 0%, #e63cfe54 100%), radial-gradient(211.58% 161.63% at 3.13% 100%, #ffae3c4d 0%, #e335ff00 100%), radial-gradient(107.1% 32.15% at 92.96% 5.04%, #35ffb633 0%, #4a4efa33 100%), #ebfffc",+ backgroundGradient: [+ `radial-gradient(65.88% 47.48% at 50% 50%, oklch(from ${background} calc(l * 0.85 + 0.07) c h) 0%, oklch(from ${background} calc(l * 0.85 + 0.07) c h / 0) 100%)`,+ "linear-gradient(180deg, #ffae3c00 0%, #e63cfe54 100%)",+ "radial-gradient(211.58% 161.63% at 3.13% 100%, #ffae3c4d 0%, #e335ff00 100%)",+ "radial-gradient(107.1% 32.15% at 92.96% 5.04%, #35ffb64d 0%, #4a4efa4d 100%)",+ `oklch(from ${background} calc(l * 0.8 + 0.08) c h)`,+ ].join(", "),progressGradient:"linear-gradient(90deg, #39fbbb00 0%, #39fbbb 20%, #4a4efa 40.03%, #e63cfe 60.02%, #ffae3c 80.04%, #ffae3c00 100%)",progressShadow: "0 0 32px #4a4efa80",diff --git a/packages/design-system/src/colors/README.md b/packages/design-system/src/colors/README.mdindex cc5402584e..28bc7d281f 100644--- a/packages/design-system/src/colors/README.md+++ b/packages/design-system/src/colors/README.md@@ -167,8 +167,10 @@ are rejected.## Fixed brand artwork-`webstudioBrand` exports fixed Webstudio identity gradients and effects that do-not follow the user-selectable theme. It contains only brand-specific artwork.+`webstudioBrand` exports Webstudio identity gradients and effects with fixed+brand hues and geometry. The background derives its neutral base and highlight+from `--background-primary`, so the same gradient follows light, dark, and+custom themes without a separate override. It contains only brand-specific artwork.Generic surfaces, content, borders, and overlays must use semantic colors orderive a local composition from them instead of being added to the brand API.diff --git a/packages/design-system/src/components/button-contrast.browser.test.ts b/packages/design-system/src/components/button-contrast.browser.test.tsindex 29e21a1971..a126b8b3b8 100644--- a/packages/design-system/src/components/button-contrast.browser.test.ts+++ b/packages/design-system/src/components/button-contrast.browser.test.ts@@ -39,6 +39,70 @@ const readColor = (color: string) => {return Array.from(context.getImageData(0, 0, 1, 1).data);};+test("ghost-destructive shares ghost surfaces and destructive text in both themes", () => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ for (const mode of ["light", "dark"]) {+ document.documentElement.dataset.colorScheme = mode;+ for (const state of [+ "auto",+ "hover",+ "focus",+ "pressed",+ "pending",+ "disabled",+ ] as const) {+ act(() =>+ root?.render(+ createElement(+ "div",+ null,+ ...(+ ["ghost", "neutral-destructive", "ghost-destructive"] as const+ ).map((color) =>+ createElement(+ Button,+ {+ key: color,+ color,+ state: state === "disabled" ? undefined : state,+ disabled: state === "disabled",+ },+ color+ )+ ),+ createElement(+ LinkButton,+ {+ color: "ghost-destructive",+ href: "#",+ state: state === "disabled" ? undefined : state,+ "aria-disabled": state === "disabled",+ },+ "Link"+ )+ )+ )+ );+ const [ghost, danger, combined] = Array.from(+ container.querySelectorAll("button"),+ (button) => getComputedStyle(button)+ );+ const link = getComputedStyle(container.querySelector("a")!);+ expect(combined.backgroundColor).toBe(ghost.backgroundColor);+ expect(combined.backgroundImage).toBe(ghost.backgroundImage);+ expect(combined.color).toBe(danger.color);+ expect(combined.outlineStyle).toBe(ghost.outlineStyle);+ expect(link.backgroundColor).toBe(combined.backgroundColor);+ expect(link.color).toBe(combined.color);+ if (state === "auto") {+ expect(readColor(combined.backgroundColor)[3]).toBe(0);+ }+ }+ }+});+const readRenderedBackground = async (element: Element) => {const { base64, path } = await page.elementLocator(element)@@ -279,6 +343,7 @@ test("link buttons use anchor semantics and button interaction states", async ()expect(link.href).toBe("https://example.com/path");expect(link.target).toBe("_blank");expect(link.dataset.state).toBe("hover");+ expect(getComputedStyle(link).cursor).toBe("pointer");expect(getComputedStyle(link).backgroundImage).not.toBe("none");act(() => {diff --git a/packages/design-system/src/components/button.stories.tsx b/packages/design-system/src/components/button.stories.tsxindex 54af56cafa..13e6e57f47 100644--- a/packages/design-system/src/components/button.stories.tsx+++ b/packages/design-system/src/components/button.stories.tsx@@ -16,6 +16,7 @@ const colors: ReadonlyArray<ComponentProps<typeof ButtonComponent>["color"]> = ["destructive","neutral-destructive","ghost",+ "ghost-destructive",];const states: ReadonlyArray<ComponentProps<typeof ButtonComponent>["state"]> = [diff --git a/packages/design-system/src/components/button.tsx b/packages/design-system/src/components/button.tsxindex d2c00d7eef..11b4e83149 100644--- a/packages/design-system/src/components/button.tsx+++ b/packages/design-system/src/components/button.tsx@@ -24,6 +24,7 @@ const colors = ["destructive","neutral","ghost",+ "ghost-destructive","neutral-destructive",] as const;@@ -47,6 +48,7 @@ const backgrounds: Record<ButtonColor, string> = {"neutral-destructive": neutralControlBackground,destructive: cssVar("--background-negative"),ghost: "transparent",+ "ghost-destructive": "transparent",};const foregrounds: Record<ButtonColor, string> = {@@ -55,10 +57,11 @@ const foregrounds: Record<ButtonColor, string> = {"neutral-destructive": cssVar("--foreground-negative"),neutral: cssVar("--foreground-primary"),ghost: cssVar("--foreground-primary"),+ "ghost-destructive": cssVar("--foreground-negative"),};const perColorStyle = (variant: ButtonColor) => {- const isTransparent = variant === "ghost";+ const isTransparent = variant === "ghost" || variant === "ghost-destructive";const isChromatic = variant === "primary" || variant === "destructive";let hoverOverlay = cssVar("--overlay-interaction-hover");let pressedOverlay = cssVar("--overlay-interaction-pressed");@@ -78,11 +81,12 @@ const perColorStyle = (variant: ButtonColor) => {: withInteractionOverlay(backgrounds[variant], hoverOverlay),},- "&[data-state=auto]:focus-visible, &[data-state=focus]": {- color: foregrounds[variant],- outline: `1px solid ${cssVar("--border-focus")}`,- outlineOffset: "1px",- },+ "&[data-state=auto]:focus-visible, &[data-state=auto][data-dialog-autofocus]:focus, &[data-state=focus]":+ {+ color: foregrounds[variant],+ outline: `1px solid ${cssVar("--border-focus")}`,+ outlineOffset: "1px",+ },"&[data-state=auto]:active, &[data-state=pressed]": {color: foregrounds[variant],@@ -117,6 +121,13 @@ export const buttonStyle = css({borderRadius: theme.borderRadius[4],whiteSpace: "nowrap",+ "&[href]": {+ cursor: "pointer",+ },+ "&[href][aria-disabled=true]:not([data-state=pending])": {+ cursor: "default",+ },+variants: {color: {primary: perColorStyle("primary"),@@ -124,6 +135,7 @@ export const buttonStyle = css({"neutral-destructive": perColorStyle("neutral-destructive"),neutral: perColorStyle("neutral"),ghost: perColorStyle("ghost"),+ "ghost-destructive": perColorStyle("ghost-destructive"),},},@@ -243,6 +255,7 @@ export const Button = forwardRef(aria-pressed={ariaPressed}disabled={disabled || state === "pending"}data-state={finalState ?? "auto"}+ data-button-color={color ?? "neutral"}ref={ref}className={buttonStyle({ color, className, css })}>@@ -294,6 +307,7 @@ export const LinkButton = forwardRef({...restProps}aria-disabled={state === "pending" ? true : ariaDisabled}data-state={finalState ?? "auto"}+ data-button-color={color ?? "neutral"}ref={ref}className={buttonStyle({ color, className, css })}onClick={(event) => {diff --git a/packages/design-system/src/components/dialog.browser.test.tsx b/packages/design-system/src/components/dialog.browser.test.tsxnew file mode 100644index 0000000000..771dd251a2--- /dev/null+++ b/packages/design-system/src/components/dialog.browser.test.tsx@@ -0,0 +1,248 @@+import { createRoot, type Root } from "react-dom/client";+import { act } from "react-dom/test-utils";+import { afterEach, expect, test, vi } from "vitest";+import "../colors/colors.css";+import { Button, LinkButton } from "./button";+import { Dialog, DialogContent, DialogTitle } from "./dialog";+import { useState } from "react";+import { userEvent } from "@vitest/browser/context";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+} from "./dropdown-menu";++let root: Root | undefined;++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(() => {+ act(() => root?.unmount());+ root = undefined;+ document.body.innerHTML = "";+});++test("keeps the first and subsequent drag positions when only the title must remain visible", async () => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ await act(async () => {+ root?.render(+ <Dialog open draggable>+ <DialogContent width={640} height={480} aria-describedby={undefined}>+ <DialogTitle>MDX editor</DialogTitle>+ </DialogContent>+ </Dialog>+ );+ });+ const dialog = document.querySelector<HTMLElement>('[role="dialog"]')!;+ const title = dialog.querySelector<HTMLElement>('[draggable="true"]')!;+ for (const top of [window.innerHeight - 150, window.innerHeight - 100]) {+ const initial = dialog.getBoundingClientRect();+ const dataTransfer = new DataTransfer();+ await act(async () => {+ title.dispatchEvent(+ new DragEvent("dragstart", {+ bubbles: true,+ clientX: initial.x + 20,+ clientY: initial.y + 20,+ dataTransfer,+ })+ );+ title.dispatchEvent(+ new DragEvent("drag", {+ bubbles: true,+ clientX: initial.x + 20,+ clientY: top + 20,+ dataTransfer,+ })+ );+ title.dispatchEvent(+ new DragEvent("dragend", { bubbles: true, dataTransfer })+ );+ });+ expect(dialog.getBoundingClientRect().top).toBe(top);+ expect(dialog.getBoundingClientRect().height).toBe(initial.height);+ }+ await act(async () => {+ root?.render(+ <Dialog open draggable>+ <DialogContent width={300} height={150} aria-describedby={undefined}>+ <DialogTitle>MDX editor</DialogTitle>+ </DialogContent>+ </Dialog>+ );+ });+ expect(dialog.getBoundingClientRect().width).toBe(300);+ expect(dialog.getBoundingClientRect().height).toBe(150);+});++test.each([false, true])(+ "contains Escape within the dialog (dismissal prevented: %s)",+ async (preventDismissal) => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ const panelKeyDown = vi.fn();+ const dialogKeyDown = vi.fn();+ const onOpenChange = vi.fn();+ await act(async () => {+ root?.render(+ <div onKeyDown={panelKeyDown}>+ <Dialog open onOpenChange={onOpenChange}>+ <DialogContent+ aria-describedby={undefined}+ onKeyDown={dialogKeyDown}+ onEscapeKeyDown={(event) => {+ if (preventDismissal) {+ event.preventDefault();+ }+ }}+ >+ <DialogTitle>Confirmation</DialogTitle>+ <Button color="primary">Continue</Button>+ </DialogContent>+ </Dialog>+ </div>+ );+ });+ await act(async () => {+ await userEvent.keyboard("{Escape}");+ await new Promise(requestAnimationFrame);+ });+ expect(dialogKeyDown).toHaveBeenCalledOnce();+ expect(panelKeyDown).not.toHaveBeenCalled();+ if (preventDismissal) {+ expect(onOpenChange).not.toHaveBeenCalled();+ } else {+ expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false);+ }+ await act(async () => userEvent.keyboard("a"));+ expect(panelKeyDown).toHaveBeenCalledOnce();+ }+);++test.each([false, true])(+ "keeps the primary action visibly focused after opening (menu: %s)",+ async (menu) => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ const Example = () => {+ const [open, setOpen] = useState(false);+ return (+ <>+ {menu ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button>Actions</Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem onSelect={() => setOpen(true)}>+ Convert+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <Button onClick={() => setOpen(true)}>Convert</Button>+ )}+ {open && (+ <Dialog open>+ <DialogContent aria-describedby={undefined}>+ <DialogTitle>Confirm conversion</DialogTitle>+ <Button>Cancel</Button>+ <Button color="destructive">Confirm</Button>+ </DialogContent>+ </Dialog>+ )}+ </>+ );+ };+ await act(async () => root?.render(<Example />));+ await act(async () => userEvent.click(container.querySelector("button")!));+ if (menu) {+ await act(async () =>+ userEvent.click(document.querySelector('[role="menuitem"]')!)+ );+ }+ await act(async () => new Promise((resolve) => setTimeout(resolve, 100)));+ const action = document.querySelector('[data-button-color="destructive"]');+ expect(action).not.toBeNull();+ expect(document.activeElement).toBe(action);+ expect(getComputedStyle(action!).outlineStyle).toBe("solid");+ expect(getComputedStyle(action!).outlineWidth).toBe("1px");+ await act(async () =>+ userEvent.click(document.querySelector('[role="dialog"] button')!)+ );+ expect(document.activeElement).not.toBe(action);+ expect(getComputedStyle(action!).outlineStyle).toBe("none");+ }+);++test.each(["primary", "destructive", "link"] as const)(+ "focuses the enabled %s action on opening, without activating it",+ async (variant) => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ let action: HTMLElement | null = null;+ let activated = false;+ await act(async () => {+ root?.render(+ <Dialog open>+ <DialogContent aria-describedby={undefined}>+ <DialogTitle>Confirmation</DialogTitle>+ <Button>Cancel</Button>+ <Button color="primary" disabled>+ Unavailable+ </Button>+ <Button color="primary" state="pending">+ Pending+ </Button>+ <Button color="primary" css={{ display: "none" }}>+ Hidden+ </Button>+ <Button color="primary" css={{ visibility: "hidden" }}>+ Invisible+ </Button>+ <LinkButton color="primary" href="#" aria-disabled>+ Unavailable link+ </LinkButton>+ {variant === "link" ? (+ <LinkButton+ color="primary"+ href="#"+ ref={(element) => {+ action = element;+ }}+ onClick={() => {+ activated = true;+ }}+ >+ Continue+ </LinkButton>+ ) : (+ <Button+ color={variant}+ ref={(element) => {+ action = element;+ }}+ onClick={() => {+ activated = true;+ }}+ >+ Continue+ </Button>+ )}+ </DialogContent>+ </Dialog>+ );+ });+ expect(action).not.toBeNull();+ expect(document.activeElement).toBe(action);+ expect(activated).toBe(false);+ }+);diff --git a/packages/design-system/src/components/dialog.tsx b/packages/design-system/src/components/dialog.tsxindex f9f174bd0d..cd849a5c65 100644--- a/packages/design-system/src/components/dialog.tsx+++ b/packages/design-system/src/components/dialog.tsx@@ -367,18 +367,30 @@ const useDraggable = ({if (isMaximized === false) {if (x !== undefined && y !== undefined) {+ const draggedRect = lastDragDataRef.current?.rect;// Get actual rendered dimensions if width/height not specified- const actualWidth = width ?? ref.current?.offsetWidth ?? bounds.width;+ const actualWidth =+ width ??+ draggedRect?.width ??+ ref.current?.offsetWidth ??+ bounds.width;const actualHeight =- height ?? ref.current?.offsetHeight ?? bounds.height;+ height ??+ draggedRect?.height ??+ ref.current?.offsetHeight ??+ bounds.height;const constrained = applyBoundaries(x,y,actualWidth,- actualHeight,+ // After dragging, keep the title reachable without snapping the+ // entire dialog back inside the boundary.+ draggedRect+ ? Math.min(actualHeight, DIALOG_TITLE_HEIGHT)+ : actualHeight,bounds,- boundaryTolerance+ draggedRect ? undefined : boundaryTolerance);style.left = constrained.x;@@ -387,7 +399,7 @@ const useDraggable = ({style.width = constrained.width;}if (height !== undefined) {- style.height = constrained.height;+ style.height = draggedRect ? actualHeight : constrained.height;}style.right = "auto";style.bottom = "auto";@@ -525,14 +537,12 @@ const useDraggable = ({}const rect = target.getBoundingClientRect();- // Apply constraints to snap to the closest valid position- let constrainedX = Math.max(rect.x, bounds.x);- constrainedX = Math.min(constrainedX, bounds.x + bounds.width - rect.width);- let constrainedY = Math.max(rect.y, bounds.y);- // Keep at least title visible at the bottom- constrainedY = Math.min(- constrainedY,- bounds.y + bounds.height - DIALOG_TITLE_HEIGHT+ const { x: constrainedX, y: constrainedY } = applyBoundaries(+ rect.x,+ rect.y,+ rect.width,+ Math.min(rect.height, DIALOG_TITLE_HEIGHT),+ bounds);setX(constrainedX);@@ -620,6 +630,41 @@ const ContentContainer = forwardRef(onDragEndCapture={setPointerEvents("auto")}{...draggableProps}{...props}+ onKeyDown={(event) => {+ props.onKeyDown?.(event);+ // Radix handles dismissal; keep the same Escape from closing a parent+ // panel, including when the dialog refuses dismissal during a save.+ if (event.key === "Escape") {+ event.stopPropagation();+ }+ }}+ onOpenAutoFocus={(event) => {+ props.onOpenAutoFocus?.(event);+ if (event.defaultPrevented) {+ return;+ }+ // Primary actions include destructive confirmations. Leave Radix's+ // normal focus order in place when no enabled action is available.+ const actions = ref.current?.querySelectorAll<HTMLElement>(+ '[data-button-color="primary"], [data-button-color="destructive"]'+ );+ for (const action of actions ?? []) {+ if (+ action.closest('[role="dialog"]') !== ref.current ||+ action.matches(':disabled, [aria-disabled="true"]') ||+ !action.checkVisibility({ checkVisibilityCSS: true })+ ) {+ continue;+ }+ action.focus();+ if (document.activeElement === action) {+ // Mouse-opened dialogs still need a visible initial focus target.+ action.setAttribute("data-dialog-autofocus", "");+ event.preventDefault();+ return;+ }+ }+ }}ref={mergeRefs(forwardedRef, ref, setElement)}>{children}diff --git a/packages/design-system/src/components/input-field.tsx b/packages/design-system/src/components/input-field.tsxindex 256885c733..56011c7874 100644--- a/packages/design-system/src/components/input-field.tsx+++ b/packages/design-system/src/components/input-field.tsx@@ -28,6 +28,8 @@ export const inputFieldTypes = ["url","number","search",+ "date",+ "datetime-local",] as const;export const inputFieldColors = ["placeholder", "set", "error"] as const;diff --git a/packages/design-system/src/components/inset-list.browser.test.tsx b/packages/design-system/src/components/inset-list.browser.test.tsxnew file mode 100644index 0000000000..d7b0975003--- /dev/null+++ b/packages/design-system/src/components/inset-list.browser.test.tsx@@ -0,0 +1,123 @@+import { createRoot, type Root } from "react-dom/client";+import { act } from "react-dom/test-utils";+import { afterEach, expect, test, vi } from "vitest";+import { userEvent } from "@vitest/browser/context";+import { InsetList, InsetListItem } from "./inset-list";+import { List, ListItem } from "./primitives/list";++let root: Root | undefined;++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(() => {+ act(() => root?.unmount());+ root = undefined;+ document.body.innerHTML = "";+});++const pressArrow = (element: HTMLElement, key: string) => {+ act(() => {+ element.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));+ });+};++test("keeps navigation labels left aligned beside their icons", () => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ act(() =>+ root?.render(+ <InsetList css={{ width: 220 }}>+ <InsetListItem asChild>+ <a href="#projects">+ <svg width="16" height="16" />+ <span>Projects</span>+ </a>+ </InsetListItem>+ <InsetListItem>Settings</InsetListItem>+ </InsetList>+ )+ );+ const link = container.querySelector("a")!;+ const icon = link.querySelector("svg")!.getBoundingClientRect();+ const label = link.querySelector("span")!.getBoundingClientRect();+ expect(label.left - icon.right).toBeLessThanOrEqual(8);+ expect(getComputedStyle(container.querySelector("button")!).textAlign).toBe(+ "left"+ );+});++test.each(["{Enter}", " "])("activates list items with %s", async (key) => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ const onSelect = vi.fn();+ act(() =>+ root?.render(+ <List>+ <ListItem index={0} onSelect={onSelect}>+ Item+ </ListItem>+ </List>+ )+ );+ container.querySelector<HTMLElement>('[role="option"]')!.focus();+ await act(async () => userEvent.keyboard(key));+ expect(onSelect).toHaveBeenCalledOnce();+});++test.each([false, true])(+ "uses vertical arrows between items and horizontal arrows within an item (inset: %s)",+ (inset) => {+ const Container = inset ? InsetList : "div";+ const Row = inset ? InsetListItem : "div";+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);++ act(() => {+ root?.render(+ <List asChild>+ <Container>+ {["First", "Second"].map((label, index) => (+ <ListItem asChild index={index} key={label}>+ <Row {...(inset ? { asChild: true } : {})}>+ <div>+ <span>{label}</span>+ <button type="button" tabIndex={-1}>+ {label} action+ </button>+ </div>+ </Row>+ </ListItem>+ ))}+ </Container>+ </List>+ );+ });++ const items = Array.from(+ container.querySelectorAll<HTMLElement>('[role="option"]')+ );+ const firstAction = container.querySelector<HTMLButtonElement>("button")!;+ items[0]?.focus();++ pressArrow(items[0]!, "ArrowDown");+ expect(document.activeElement).toBe(items[1]);++ pressArrow(items[1]!, "ArrowUp");+ expect(document.activeElement).toBe(items[0]);++ pressArrow(items[0]!, "ArrowRight");+ expect(document.activeElement).toBe(firstAction);+ pressArrow(firstAction, "ArrowDown");+ expect(document.activeElement).toBe(items[1]);+ pressArrow(items[1]!, "ArrowDown");+ expect(document.activeElement).toBe(items[0]);+ pressArrow(items[0]!, "ArrowRight");+ pressArrow(firstAction, "ArrowLeft");+ expect(document.activeElement).toBe(items[0]);+ }+);diff --git a/packages/design-system/src/components/inset-list.stories.tsx b/packages/design-system/src/components/inset-list.stories.tsxnew file mode 100644index 0000000000..fb0d02edc7--- /dev/null+++ b/packages/design-system/src/components/inset-list.stories.tsx@@ -0,0 +1,87 @@+import { useState } from "react";+import { GearIcon } from "@webstudio-is/icons";+import { Grid } from "./grid";+import { InsetList, InsetListItem } from "./inset-list";+import { List, ListItem } from "./primitives/list";+import { StorySection } from "./storybook";+import { Text } from "./text";+import { theme } from "../stitches.config";++export default {+ title: "Inset list",+};++const items = ["General", "Publishing", "Authentication"];++export const Navigation = () => {+ const [current, setCurrent] = useState(items[0]);+ return (+ <StorySection title="Navigation">+ <List asChild aria-label="Project settings sections">+ <InsetList css={{ width: 220 }}>+ {items.map((item, index) => (+ <ListItem+ key={item}+ asChild+ index={index}+ current={item === current}+ onSelect={() => setCurrent(item)}+ >+ <InsetListItem>{item}</InsetListItem>+ </ListItem>+ ))}+ </InsetList>+ </List>+ </StorySection>+ );+};++export const SupportingText = () => (+ <StorySection title="Supporting text">+ <List asChild aria-label="Collection fields">+ <InsetList css={{ width: 220 }}>+ <ListItem asChild index={0} current>+ <InsetListItem css={{ minHeight: theme.spacing[15] }}>+ <Grid gap={1} css={{ minWidth: 0 }}>+ <Text variant="labels">Title</Text>+ <Text variant="tiny" color="subtle">+ Text · Required+ </Text>+ </Grid>+ </InsetListItem>+ </ListItem>+ </InsetList>+ </List>+ </StorySection>+);++export const NavigationWithIcons = () => (+ <StorySection title="Navigation with icons">+ <InsetList css={{ width: 220 }}>+ {items.map((item) => (+ <InsetListItem key={item}>+ <GearIcon />+ <Text variant="labels">{item}</Text>+ </InsetListItem>+ ))}+ </InsetList>+ </StorySection>+);++export const Columns = () => (+ <StorySection title="Columns">+ <List asChild aria-label="Projects">+ <InsetList css={{ width: 520 }}>+ {["Starter", "Portfolio"].map((name, index) => (+ <ListItem asChild index={index} key={name}>+ <InsetListItem css={{ gridTemplateColumns: "2fr 1fr 1fr", gap: 0 }}>+ <Text variant="labels">{name}</Text>+ <Text color="subtle">Today</Text>+ <Text color="subtle">Published</Text>+ </InsetListItem>+ </ListItem>+ ))}+ </InsetList>+ </List>+ </StorySection>+);diff --git a/packages/design-system/src/components/inset-list.tsx b/packages/design-system/src/components/inset-list.tsxnew file mode 100644index 0000000000..10a06644a2--- /dev/null+++ b/packages/design-system/src/components/inset-list.tsx@@ -0,0 +1,64 @@+import { forwardRef, type ComponentProps, type Ref } from "react";+import { Slot } from "@radix-ui/react-slot";+import { buttonStyle } from "./button";+import { selectedItemBackground } from "./component-state-color";+import { css, styled, theme, type CSS } from "../stitches.config";++export const InsetList = styled("div", {+ boxSizing: "border-box",+ minWidth: 0,+ minHeight: 0,+ display: "grid",+ alignContent: "start",+ flexShrink: 0,+ gap: theme.spacing[3],+ padding: theme.spacing[3],+});++const insetListItemStyle = css(buttonStyle, {+ height: "auto",+ minHeight: theme.spacing[13],+ padding: theme.spacing[3],+ justifyContent: "start",+ textAlign: "left",+ overflow: "hidden",+ gap: theme.spacing[5],+ cursor: "pointer",+ "&[aria-current=true], &[aria-current=page], &[data-state=selected]": {+ background: selectedItemBackground,+ },+});++export type InsetListItemProps = Omit<ComponentProps<"button">, "color"> & {+ asChild?: boolean;+ css?: CSS;+ "data-state"?: string;+};++export const InsetListItem = forwardRef(+ (+ {+ asChild,+ className,+ css: cssProp,+ "data-state": dataState,+ ...props+ }: InsetListItemProps,+ ref: Ref<HTMLButtonElement>+ ) => {+ const Component = asChild ? Slot : "button";+ return (+ <Component+ {...props}+ ref={ref}+ data-state={dataState ?? "auto"}+ className={insetListItemStyle({+ color: "ghost",+ className,+ css: cssProp,+ })}+ />+ );+ }+);+InsetListItem.displayName = "InsetListItem";diff --git a/packages/design-system/src/components/panel-content.stories.tsx b/packages/design-system/src/components/panel-content.stories.tsxnew file mode 100644index 0000000000..4b9a670ee1--- /dev/null+++ b/packages/design-system/src/components/panel-content.stories.tsx@@ -0,0 +1,49 @@+import type { ReactNode } from "react";+import { Box } from "./box";+import { Flex } from "./flex";+import { Grid } from "./grid";+import { PanelContent } from "./panel-content";+import { Separator } from "./separator";+import { StoryGrid, StorySection } from "./storybook";+import { Text } from "./text";+import { cssVar } from "../css-var";++export default {+ title: "Panel content",+};++const PanelFrame = ({ children }: { children: ReactNode }) => (+ <Box+ css={{+ width: 320,+ border: `1px solid ${cssVar("--border-default")}`,+ }}+ >+ {children}+ </Box>+);++export const ContentSections = () => (+ <StorySection title="Content sections">+ <StoryGrid horizontal>+ <PanelFrame>+ <PanelContent>+ <Text variant="titles">Default content</Text>+ </PanelContent>+ <Separator />+ <PanelContent as={Grid} gap={2}>+ <Text variant="labels">Grid content</Text>+ <Text color="subtle">+ Content uses the standard panel inset while the separator reaches+ both edges.+ </Text>+ </PanelContent>+ <Separator />+ <PanelContent as={Flex} justify="between">+ <Text>Left</Text>+ <Text>Right</Text>+ </PanelContent>+ </PanelFrame>+ </StoryGrid>+ </StorySection>+);diff --git a/packages/design-system/src/components/panel-content.tsx b/packages/design-system/src/components/panel-content.tsxnew file mode 100644index 0000000000..f7f8b1f441--- /dev/null+++ b/packages/design-system/src/components/panel-content.tsx@@ -0,0 +1,46 @@+import {+ forwardRef,+ type ComponentPropsWithoutRef,+ type ElementType,+ type ReactElement,+ type Ref,+} from "react";+import { css, theme, type CSS } from "../stitches.config";++const panelContentStyle = css({+ boxSizing: "border-box",+ minWidth: 0,+ padding: theme.panel.padding,+});++type PanelContentProps<Component extends ElementType> = {+ as?: Component;+ css?: CSS;+} & Omit<ComponentPropsWithoutRef<Component>, "as" | "css">;++type PanelContentComponent = <Component extends ElementType = "div">(+ props: PanelContentProps<Component> & { ref?: Ref<HTMLElement> }+) => ReactElement | null;++const PanelContentRoot = forwardRef(+ (+ {+ as: Component = "div",+ className,+ css,+ ...props+ }: PanelContentProps<ElementType>,+ ref: Ref<HTMLElement>+ ) => {+ return (+ <Component+ {...props}+ ref={ref}+ className={panelContentStyle({ className, css })}+ />+ );+ }+);+PanelContentRoot.displayName = "PanelContent";++export const PanelContent = PanelContentRoot as PanelContentComponent;diff --git a/packages/design-system/src/components/primitives/list.tsx b/packages/design-system/src/components/primitives/list.tsxindex f0d965bb51..f5aed6b1bf 100644--- a/packages/design-system/src/components/primitives/list.tsx+++ b/packages/design-system/src/components/primitives/list.tsx@@ -6,13 +6,28 @@ type ListProps = SlotProps & {asChild?: boolean;};-export const List = ({ asChild, ...props }: ListProps) => {+export const List = ({ asChild, onKeyDown, ...props }: ListProps) => {const Component = asChild ? Slot : "ul";return (<ArrowFocusrender={({ handleKeyDown }) => {return (- <Component role="listbox" onKeyDown={handleKeyDown} {...props} />+ <Component+ role="listbox"+ {...props}+ data-keyboard-list+ onKeyDown={(event) => {+ onKeyDown?.(event);+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {+ handleKeyDown(event, {+ accept: (element) =>+ element.hasAttribute("data-keyboard-list-item") &&+ element.closest("[data-keyboard-list]") ===+ event.currentTarget,+ });+ }+ }}+ />);}}/>@@ -34,6 +49,7 @@ export const ListItem = ({index,onSelect,asChild,+ onKeyDown,...props}: ListItemProps) => {const stateProp =@@ -49,15 +65,30 @@ export const ListItem = ({});const Component = asChild ? Slot : "li";return (- <Component- tabIndex={index === 0 ? 0 : -1}- role="option"- key={index}- {...(state === "selected" ? { "aria-selected": true } : undefined)}- {...(current ? { "aria-current": true } : undefined)}- {...props}- {...stateProp}- {...pressProps}+ <ArrowFocus+ render={({ handleKeyDown }) => (+ <Component+ tabIndex={index === 0 ? 0 : -1}+ role="option"+ key={index}+ {...(state === "selected" ? { "aria-selected": true } : undefined)}+ {...(current ? { "aria-current": true } : undefined)}+ {...props}+ {...stateProp}+ {...pressProps}+ data-keyboard-list-item+ onKeyDown={(event) => {+ onKeyDown?.(event);+ if (event.defaultPrevented) {+ return;+ }+ pressProps.onKeyDown?.(event);+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {+ handleKeyDown(event);+ }+ }}+ />+ )}/>);};diff --git a/packages/design-system/src/components/resettable-label.browser.test.tsx b/packages/design-system/src/components/resettable-label.browser.test.tsxnew file mode 100644index 0000000000..c703b77c26--- /dev/null+++ b/packages/design-system/src/components/resettable-label.browser.test.tsx@@ -0,0 +1,181 @@+import { createRoot, type Root } from "react-dom/client";+import { act } from "react-dom/test-utils";+import { afterEach, expect, test, vi } from "vitest";+import { userEvent } from "@vitest/browser/context";+import "../colors/colors.css";+import { ResettableLabel } from "./resettable-label";+import { TooltipProvider } from "./tooltip";+import { Label } from "./label";++let root: Root | undefined;+(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;+afterEach(() => {+ act(() => root?.unmount());+ document.body.innerHTML = "";+});++test("a label without information or a reset action focuses its input without a tooltip", async () => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ await act(async () =>+ root?.render(+ <TooltipProvider delayDuration={0}>+ <ResettableLabel htmlFor="empty">Summary</ResettableLabel>+ <input id="empty" />+ </TooltipProvider>+ )+ );+ const label = container.querySelector<HTMLElement>('label[for="empty"]')!;+ await act(async () => userEvent.click(label));+ expect(document.querySelector('[role="tooltip"]')).toBeNull();+ expect(document.activeElement).toBe(container.querySelector("input"));+ expect(label.getAttribute("role")).not.toBe("button");+});++test.each(["block", "grid", "flex"])(+ "sizes the label to its text in a %s layout without overflowing",+ async (display) => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ await act(async () =>+ root?.render(+ <TooltipProvider>+ <div+ data-layout+ style={{ display, flexDirection: "column", width: 300 }}+ >+ <ResettableLabel data-label>Summary</ResettableLabel>+ <ResettableLabel data-label>+ A very long field label that must not overflow the available space+ in its container+ </ResettableLabel>+ </div>+ </TooltipProvider>+ )+ );+ const layout = container.querySelector<HTMLElement>("[data-layout]")!;+ const [short, long] = layout.querySelectorAll<HTMLElement>("[data-label]");+ const textRange = document.createRange();+ textRange.selectNodeContents(short);+ expect(short.getBoundingClientRect().width).toBeGreaterThanOrEqual(+ textRange.getBoundingClientRect().width+ );+ expect(short.getBoundingClientRect().width).toBeLessThan(150);+ expect(short.parentElement!.getBoundingClientRect().width).toBeLessThan(+ 150+ );+ expect(long.getBoundingClientRect().width).toBeLessThanOrEqual(300);+ expect(layout.scrollWidth).toBe(layout.clientWidth);+ }+);++test.each(["mouse", "alt", "keyboard"])(+ "resets via %s without submitting or bubbling Alt-click",+ async (method) => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ const onReset = vi.fn();+ const onSubmit = vi.fn();+ const onClick = vi.fn();+ await act(async () =>+ root?.render(+ <TooltipProvider>+ <form onSubmit={onSubmit} onClick={onClick}>+ <ResettableLabel htmlFor="value" onReset={onReset} color="local">+ Summary+ </ResettableLabel>+ <input id="value" />+ </form>+ </TooltipProvider>+ )+ );+ const label = container.querySelector<HTMLElement>('[role="button"]')!;+ expect(+ document.querySelector<HTMLInputElement>("#value")?.labels?.[0]+ ).toBe(label);+ if (method === "alt") {+ act(() =>+ label.dispatchEvent(+ new MouseEvent("click", {+ bubbles: true,+ cancelable: true,+ altKey: true,+ })+ )+ );+ expect(onClick).not.toHaveBeenCalled();+ } else {+ if (method === "keyboard") {+ act(() => label.focus());+ await act(async () => userEvent.keyboard("{Enter}"));+ await act(async () => userEvent.tab());+ expect(document.activeElement?.tagName).toBe("BUTTON");+ await act(async () => userEvent.keyboard("{Enter}"));+ } else {+ await act(async () => userEvent.click(label));+ const reset = document.querySelector<HTMLButtonElement>(+ 'button[type="button"]'+ )!;+ expect(reset).not.toBeNull();+ await act(async () => userEvent.click(reset));+ }+ }+ expect(onReset).toHaveBeenCalledOnce();+ expect(onSubmit).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(label);+ }+);++test.each([true, false])(+ "preserves caller colors independently of reset availability (disabled: %s)",+ async (disabled) => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ const onReset = vi.fn();+ await act(async () =>+ root?.render(+ <TooltipProvider>+ <ResettableLabel+ asChild+ color="overwritten"+ resetDisabled={disabled}+ onReset={onReset}+ content={<div data-custom-content>Source information</div>}+ >+ <Label>Color</Label>+ </ResettableLabel>+ <Label color="overwritten" data-reference>+ Reference+ </Label>+ </TooltipProvider>+ )+ );+ const label = container.querySelector<HTMLElement>('[role="button"]')!;+ expect(getComputedStyle(label).backgroundColor).toBe(+ getComputedStyle(container.querySelector("[data-reference]")!)+ .backgroundColor+ );+ act(() =>+ label.dispatchEvent(+ new MouseEvent("click", {+ bubbles: true,+ cancelable: true,+ altKey: true,+ })+ )+ );+ expect(onReset).toHaveBeenCalledTimes(disabled ? 0 : 1);+ await act(async () => userEvent.click(label));+ expect(document.querySelector("[data-custom-content]")).not.toBeNull();+ const reset = document.querySelector<HTMLButtonElement>(+ 'button[type="button"]'+ )!;+ expect(reset.disabled).toBe(disabled);+ }+);diff --git a/packages/design-system/src/components/resettable-label.stories.tsx b/packages/design-system/src/components/resettable-label.stories.tsxnew file mode 100644index 0000000000..afa86454c7--- /dev/null+++ b/packages/design-system/src/components/resettable-label.stories.tsx@@ -0,0 +1,65 @@+import { useState } from "react";+import { ResettableLabel } from "./resettable-label";+import { TooltipProvider } from "./tooltip";+import { Grid } from "./grid";+import { InputField } from "./input-field";+import { Text } from "./text";+import { SectionTitleLabel } from "./section-title";+import { theme } from "../stitches.config";++export default { title: "Resettable label", component: ResettableLabel };++export const States = () => {+ const [value, setValue] = useState("An optional summary");+ return (+ <TooltipProvider>+ <Grid gap={4} css={{ width: 320, padding: theme.panel.padding }}>+ <ResettableLabel+ htmlFor="summary"+ color={value ? "local" : "default"}+ description="An optional summary for this entry."+ onReset={value ? () => setValue("") : undefined}+ >+ Summary+ </ResettableLabel>+ <InputField+ id="summary"+ value={value}+ onChange={(event) => setValue(event.target.value)}+ />+ {(["default", "preset", "local", "remote", "overwritten"] as const).map(+ (color) => (+ <ResettableLabel+ key={color}+ color={color}+ description="Color is chosen by the caller, independently of reset availability."+ onReset={+ color === "local" || color === "overwritten"+ ? () => {}+ : undefined+ }+ >+ {color}+ </ResettableLabel>+ )+ )}+ <ResettableLabel color="local" onReset={() => {}} resetDisabled>+ Read-only value+ </ResettableLabel>+ <ResettableLabel+ asChild+ color="overwritten"+ onReset={() => {}}+ content={+ <>+ <Text variant="titles">Typography</Text>+ <Text>Value comes from a local override.</Text>+ </>+ }+ >+ <SectionTitleLabel>Typography</SectionTitleLabel>+ </ResettableLabel>+ </Grid>+ </TooltipProvider>+ );+};diff --git a/packages/design-system/src/components/resettable-label.tsx b/packages/design-system/src/components/resettable-label.tsxnew file mode 100644index 0000000000..05533b73ac--- /dev/null+++ b/packages/design-system/src/components/resettable-label.tsx@@ -0,0 +1,156 @@+import { useRef, useState, type ComponentProps, type ReactNode } from "react";+import { Slot } from "@radix-ui/react-slot";+import { ResetIcon } from "@webstudio-is/icons";+import { Label } from "./label";+import { Tooltip } from "./tooltip";+import { Button } from "./button";+import { Flex } from "./flex";+import { Text } from "./text";+import { Kbd } from "./kbd";+import { theme } from "../stitches.config";++export const ResettableLabel = ({+ children,+ color = "default",+ description,+ content,+ onReset,+ resetDisabled = false,+ resetLabel = "Reset value",+ asChild = false,+ disabled,+ ...props+}: Omit<ComponentProps<typeof Label>, "onReset" | "content"> & {+ description?: ReactNode;+ /** Replaces the default tooltip heading and description, not its reset action. */+ content?: ReactNode;+ onReset?: () => void;+ resetDisabled?: boolean;+ resetLabel?: string;+ /** Use an existing label variant, such as SectionTitleLabel. */+ asChild?: boolean;+}) => {+ const [open, setOpen] = useState(false);+ const labelRef = useRef<HTMLLabelElement>(null);+ const resetRef = useRef<HTMLButtonElement>(null);+ const movingFocus = useRef(false);+ const canReset = onReset !== undefined && !resetDisabled && !disabled;+ const reset = () => {+ if (!canReset) {+ return;+ }+ onReset();+ setOpen(false);+ labelRef.current?.focus();+ };+ const Trigger = asChild ? Slot : Label;+ if (!description && !content && !onReset) {+ return (+ <Flex align="center" css={{ width: "fit-content", maxWidth: "100%" }}>+ <Trigger+ truncate+ {...props}+ ref={labelRef}+ tag="label"+ color={color === "default" ? undefined : color}+ disabled={disabled}+ >+ {children}+ </Trigger>+ </Flex>+ );+ }+ return (+ <Flex align="center" css={{ width: "fit-content", maxWidth: "100%" }}>+ <Tooltip+ open={open}+ onOpenChange={(nextOpen) => {+ if (!nextOpen && movingFocus.current) {+ return;+ }+ setOpen(nextOpen);+ }}+ onEscapeKeyDown={() => {+ setOpen(false);+ labelRef.current?.focus();+ }}+ content={+ <Flex+ direction="column"+ gap="2"+ css={{ maxWidth: theme.spacing[28] }}+ >+ {content ?? (+ <>+ <Text variant="titles">{children}</Text>+ {description && <Text>{description}</Text>}+ </>+ )}+ {onReset && (+ <Button+ ref={resetRef}+ type="button"+ color="neutral-destructive"+ disabled={!canReset}+ prefix={<ResetIcon />}+ suffix={<Kbd value={["alt", "click"]} color="moreSubtle" />}+ css={{ gridTemplateColumns: "1fr max-content 1fr" }}+ onClick={reset}+ onBlur={() => setOpen(false)}+ >+ {resetLabel}+ </Button>+ )}+ </Flex>+ }+ >+ <Trigger+ truncate+ {...props}+ ref={labelRef}+ color={color}+ disabled={disabled}+ tag={props.htmlFor ? "label" : "button"}+ role="button"+ tabIndex={props.tabIndex ?? 0}+ onClick={(event) => {+ props.onClick?.(event);+ if (event.defaultPrevented) {+ return;+ }+ event.preventDefault();+ if (event.altKey) {+ event.stopPropagation();+ reset();+ return;+ }+ setOpen(true);+ }}+ onKeyDown={(event) => {+ props.onKeyDown?.(event);+ if (event.defaultPrevented) {+ return;+ }+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ event.stopPropagation();+ if (event.altKey) {+ reset();+ } else {+ setOpen(true);+ }+ }+ if (event.key === "Tab" && !event.shiftKey && open && canReset) {+ event.preventDefault();+ movingFocus.current = true;+ resetRef.current?.focus();+ movingFocus.current = false;+ }+ }}+ >+ {children}+ </Trigger>+ </Tooltip>+ </Flex>+ );+};diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.tsindex 3d35614493..cae5a4b37e 100644--- a/packages/design-system/src/index.ts+++ b/packages/design-system/src/index.ts@@ -12,10 +12,13 @@ export { type SlotProps, Slot } from "@radix-ui/react-slot";export * from "./components/text";export * from "./components/panel-title";+export * from "./components/panel-content";+export * from "./components/inset-list";export * from "./components/section-title";export * from "./components/separator";export * from "./components/button";export * from "./components/label";+export * from "./components/resettable-label";export { styleSourceColor } from "./components/style-source-color";export * from "./components/select";export * from "./components/combobox";diff --git a/packages/expression/src/expression.test.ts b/packages/expression/src/expression.test.tsindex e8077816cb..6e9682f2b4 100644--- a/packages/expression/src/expression.test.ts+++ b/packages/expression/src/expression.test.ts@@ -43,6 +43,19 @@ describe("static member paths", () => {});describe("direct path expressions", () => {+ test.each([+ "document.frontmatter.author?.name",+ "document?.frontmatter?.author?.name",+ 'document.frontmatter?.["author"].name',+ "(document.frontmatter?.author).name",+ ])("preserves the writable location of %s", (expression) => {+ expect(parseDirectPathExpression(expression)).toEqual({+ type: "direct-path",+ expression,+ path: ["document", "frontmatter", "author", "name"],+ });+ });+test("distinguishes a writable location from a derived expression", () => {expect(parseDirectPathExpression("document.frontmatter.title")).toEqual({type: "direct-path",diff --git a/packages/expression/src/index.ts b/packages/expression/src/index.tsindex b129ba1e61..e1615778a2 100644--- a/packages/expression/src/index.ts+++ b/packages/expression/src/index.ts@@ -482,26 +482,20 @@ export const parseStringLiteralExpression = (expression: string) => {}};-const getStaticMemberPath = (- node: Expression,- allowOptional = true-): string[] | undefined => {+const getStaticMemberPath = (node: Expression): string[] | undefined => {if (node.type === "Identifier") {return [node.name];}- if (node.type === "ChainExpression") {- return allowOptional- ? getStaticMemberPath(node.expression, allowOptional)- : undefined;- }if (- node.type !== "MemberExpression" ||- node.object.type === "Super" ||- (allowOptional === false && node.optional)+ node.type === "ChainExpression" ||+ node.type === "ParenthesizedExpression") {+ return getStaticMemberPath(node.expression);+ }+ if (node.type !== "MemberExpression" || node.object.type === "Super") {return;}- const objectPath = getStaticMemberPath(node.object, allowOptional);+ const objectPath = getStaticMemberPath(node.object);if (objectPath === undefined) {return;}@@ -534,7 +528,7 @@ export const parseDirectPathExpression = (): DirectPathExpression | undefined => {try {const node = parseCompleteExpression(expression);- const path = getStaticMemberPath(node, false);+ const path = getStaticMemberPath(node);if (path === undefined || path.length === 0) {return;}diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.tsindex 618395bebd..d950e69713 100644--- a/packages/http-client/src/index.test.ts+++ b/packages/http-client/src/index.test.ts@@ -2183,148 +2183,193 @@ test("imports project bundle through staged upload", async () => {expect(JSON.stringify(trpcBody)).not.toContain("largeContent");});-test("imports project bundle with assets and retries missing asset uploads", async () => {- const asset = createImageAssetFixture({ name: "image.png" });- const bundle = createPublishedProjectBundleFixture({ assets: [asset] });- const calls: string[] = [];- const uploadUrls: string[] = [];- const uploadOffsets = new Map<string, number>();- let importAttempts = 0;- let uploadAttempts = 0;+test.each([undefined, "source-folder"])(+ "imports assets from folder %s and preserves their final placement",+ async (folderId) => {+ const asset = createImageAssetFixture({ name: "image.png", folderId });+ const assetFolders =+ folderId === undefined+ ? []+ : [+ {+ id: folderId,+ name: "Images",+ projectId: "source-project",+ createdAt: "2026-09-09T00:00:00.000Z",+ },+ ];+ const bundle = createPublishedProjectBundleFixture({+ assets: [asset],+ assetFolders,+ });+ const uploadChunks = new Map<string, Buffer[]>();+ const readAssets: unknown[] = [];+ const calls: string[] = [];+ const uploadUrls: string[] = [];+ const uploadOffsets = new Map<string, number>();+ let importAttempts = 0;+ let uploadAttempts = 0;++ const server = createServer(async (request, response) => {+ const url = new URL(request.url ?? "/", "http://localhost");+ calls.push(`${request.method} ${url.pathname}`);++ if (+ request.method === "GET" &&+ url.pathname === "/trpc/build.checkProjectBuildPermission"+ ) {+ response.writeHead(200, { "content-type": "application/json" });+ response.end(JSON.stringify([{ result: { data: undefined } }]));+ return;+ }- const server = createServer(async (request, response) => {- const url = new URL(request.url ?? "/", "http://localhost");- calls.push(`${request.method} ${url.pathname}`);+ if (+ request.method === "POST" &&+ url.pathname === "/rest/assets/uploads/image.png"+ ) {+ uploadAttempts += 1;+ uploadUrls.push(url.href);+ await readRequestBody(request);+ response.writeHead(200, { "content-type": "application/json" });+ response.end(+ JSON.stringify({+ uploadedAssets: [+ createImageAssetFixture({+ id: `server-generated-asset-${uploadAttempts}`,+ name: "image_destination.png",+ }),+ ],+ deduplicated: false,+ })+ );+ return;+ }- if (- request.method === "GET" &&- url.pathname === "/trpc/build.checkProjectBuildPermission"- ) {- response.writeHead(200, { "content-type": "application/json" });- response.end(JSON.stringify([{ result: { data: undefined } }]));- return;- }+ if (request.method === "POST" && url.pathname === stagedUploadPath) {+ response.writeHead(201, {+ Location: `http://${request.headers.host}${stagedUploadPath}/upload-id-${importAttempts}`,+ "Tus-Resumable": "1.0.0",+ });+ response.end();+ return;+ }- if (- request.method === "POST" &&- url.pathname === "/rest/assets/uploads/image.png"- ) {- uploadAttempts += 1;- uploadUrls.push(url.href);- await readRequestBody(request);- response.writeHead(200, { "content-type": "application/json" });- response.end(- JSON.stringify({- uploadedAssets: [- createImageAssetFixture({- id: `server-generated-asset-${uploadAttempts}`,- name: "image_destination.png",- }),- ],- deduplicated: false,- })- );- return;- }+ if (+ request.method === "PATCH" &&+ url.pathname.startsWith(`${stagedUploadPath}/upload-id-`)+ ) {+ const chunk = await readRequestBody(request);+ const chunks = uploadChunks.get(url.pathname) ?? [];+ chunks.push(chunk);+ uploadChunks.set(url.pathname, chunks);+ const offset =+ (uploadOffsets.get(url.pathname) ?? 0) + chunk.byteLength;+ uploadOffsets.set(url.pathname, offset);+ response.writeHead(204, {+ "Tus-Resumable": "1.0.0",+ "Upload-Offset": String(offset),+ });+ response.end();+ return;+ }- if (request.method === "POST" && url.pathname === stagedUploadPath) {- response.writeHead(201, {- Location: `http://${request.headers.host}${stagedUploadPath}/upload-id-${importAttempts}`,- "Tus-Resumable": "1.0.0",- });- response.end();- return;- }+ if (+ request.method === "POST" &&+ url.pathname === "/trpc/build.importProjectBundle"+ ) {+ importAttempts += 1;+ await readRequestBody(request);+ response.writeHead(200, { "content-type": "application/json" });+ response.end(+ JSON.stringify([+ importAttempts === 1+ ? {+ error: {+ message: "Imported asset files are missing: image.png",+ code: -32603,+ data: { code: "INTERNAL_SERVER_ERROR" },+ },+ }+ : { result: { data: { version: 2 } } },+ ])+ );+ return;+ }- if (- request.method === "PATCH" &&- url.pathname.startsWith(`${stagedUploadPath}/upload-id-`)- ) {- const chunk = await readRequestBody(request);- const offset = (uploadOffsets.get(url.pathname) ?? 0) + chunk.byteLength;- uploadOffsets.set(url.pathname, offset);- response.writeHead(204, {- "Tus-Resumable": "1.0.0",- "Upload-Offset": String(offset),- });+ response.writeHead(404);response.end();- return;- }-- if (- request.method === "POST" &&- url.pathname === "/trpc/build.importProjectBundle"- ) {- importAttempts += 1;- await readRequestBody(request);- response.writeHead(200, { "content-type": "application/json" });- response.end(- JSON.stringify([- importAttempts === 1- ? {- error: {- message: "Imported asset files are missing: image.png",- code: -32603,- data: { code: "INTERNAL_SERVER_ERROR" },- },- }- : { result: { data: { version: 2 } } },- ])- );- return;- }+ });- response.writeHead(404);- response.end();- });+ await new Promise<void>((resolve) => {+ server.listen(0, "127.0.0.1", resolve);+ });- await new Promise<void>((resolve) => {- server.listen(0, "127.0.0.1", resolve);- });+ const importAttemptMessages: string[] = [];+ const missingAssetMessages: string[] = [];+ const uploadAssetMessages: string[] = [];- const importAttemptMessages: string[] = [];- const missingAssetMessages: string[] = [];- const uploadAssetMessages: string[] = [];+ try {+ const address = server.address();+ if (address === null || typeof address === "string") {+ throw new Error("Server address is unavailable");+ }- try {- const address = server.address();- if (address === null || typeof address === "string") {- throw new Error("Server address is unavailable");+ await expect(+ importProjectBundleWithAssets({+ authToken: "token",+ origin: `http://127.0.0.1:${address.port}`,+ projectId: "project-id",+ data: bundle,+ readAssetData: async (asset) => {+ readAssets.push(asset);+ return new Blob(["asset"]);+ },+ onImportAttempt: () => importAttemptMessages.push("attempt"),+ onMissingAssets: (assets) =>+ missingAssetMessages.push(+ assets.map((asset) => asset.name).join(",")+ ),+ onUploadAssets: (assets) =>+ uploadAssetMessages.push(+ assets.map((asset) => asset.name).join(",")+ ),+ })+ ).resolves.toEqual({ version: 2 });+ } finally {+ await new Promise<void>((resolve, reject) => {+ server.close((error) => (error ? reject(error) : resolve()));+ });}- await expect(- importProjectBundleWithAssets({- authToken: "token",- origin: `http://127.0.0.1:${address.port}`,- projectId: "project-id",- data: bundle,- readAssetData: async () => new Blob(["asset"]),- onImportAttempt: () => importAttemptMessages.push("attempt"),- onMissingAssets: (assets) =>- missingAssetMessages.push(- assets.map((asset) => asset.name).join(",")- ),- onUploadAssets: (assets) =>- uploadAssetMessages.push(assets.map((asset) => asset.name).join(",")),- })- ).resolves.toEqual({ version: 2 });- } finally {- await new Promise<void>((resolve, reject) => {- server.close((error) => (error ? reject(error) : resolve()));- });+ expect(calls).toContain("GET /trpc/build.checkProjectBuildPermission");+ expect(importAttempts).toBe(2);+ expect(uploadAttempts).toBe(1);+ expect(+ uploadUrls.map((url) => new URL(url).searchParams.get("folderId"))+ ).toEqual([null]);+ expect(readAssets).toHaveLength(1);+ expect(readAssets[0]).toBe(asset);+ expect(bundle.assets[0]).toEqual(asset);+ const importedBundles = Array.from(uploadChunks.values(), (chunks) =>+ JSON.parse(Buffer.concat(chunks).toString("utf8"))+ );+ expect(importedBundles.map((bundle) => bundle.assetFolders)).toEqual([+ assetFolders,+ assetFolders,+ ]);+ expect(importedBundles.map((bundle) => bundle.assets)).toEqual([+ [asset],+ [{ ...asset, name: "image_destination.png" }],+ ]);+ expect(uploadUrls.every((url) => url.includes("assetId=") === false)).toBe(+ true+ );+ expect(uploadOffsets.size).toBe(2);+ expect(importAttemptMessages).toEqual(["attempt", "attempt"]);+ expect(missingAssetMessages).toEqual([]);+ expect(uploadAssetMessages).toEqual(["image.png"]);}-- expect(calls).toContain("GET /trpc/build.checkProjectBuildPermission");- expect(importAttempts).toBe(2);- expect(uploadAttempts).toBe(1);- expect(uploadUrls.every((url) => url.includes("assetId=") === false)).toBe(- true- );- expect(uploadOffsets.size).toBe(2);- expect(importAttemptMessages).toEqual(["attempt", "attempt"]);- expect(missingAssetMessages).toEqual([]);- expect(uploadAssetMessages).toEqual(["image.png"]);-});+);test("rejects project bundles over the import size limit", async () => {let requestCount = 0;diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex 3ed5cb23f2..51a87f6a49 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -1271,6 +1271,11 @@ export const getProjectInfo = projectQuery(getPublicApiOperationPath("inspect"));+export const loadBuilderDataByProjectId = (params: AuthProjectParams) =>+ createAuthTrpcClient(params).query("build.loadData", {+ projectId: params.projectId,+ });+export const getProjectPermissions = projectQuery(getPublicApiOperationPath("permissions"));@@ -2418,10 +2423,19 @@ export const importProjectBundleWithAssets = async (} else {params.onMissingAssets?.(missingAssets);}+ const originalAssetsById = new Map(+ missingAssets.map((asset) => [asset.id, asset])+ );const uploadedAssets = await uploadAssets({...params,- assets: missingAssets,- readAssetData,+ // Source folders do not exist in the destination yet. The final+ // bundle import creates them and restores the original assignments.+ assets: missingAssets.map((asset) => ({+ ...asset,+ folderId: undefined,+ })),+ readAssetData: (asset) =>+ readAssetData(originalAssetsById.get(asset.id)!),});if (uploadedAssets.length !== missingAssets.length) {throw new Error(diff --git a/packages/project-build/src/content-database.test.ts b/packages/project-build/src/content-database.test.tsindex 9d29397247..ecf332f430 100644--- a/packages/project-build/src/content-database.test.ts+++ b/packages/project-build/src/content-database.test.ts@@ -235,7 +235,7 @@ describe("Content Block MDX compilation", () => {value: "private.mdx",});- const source = '{unsafe}\n\n<ws.element ws:name="Hero" />';+ const source = '{unsafe}\n\n<ws.element ws:name="Hero" />\n\n<Missing />';const artifact = {format: "webstudio-content-database",version: 1,@@ -256,10 +256,18 @@ describe("Content Block MDX compilation", () => {contents: { "article.mdx": source },} as unknown as ContentArtifactV1;+ const omissions: { assetId: string; templateName: string }[] = [];const plan = await resolvePublishedMdxDependencyClosure({build,artifact,+ onTemplateOmission: (issue) => omissions.push(issue),});+ expect(omissions).toEqual([+ expect.objectContaining({+ assetId: "article.mdx",+ templateName: "Missing",+ }),+ ]);const queryIds = plan?.queries.map(({ id }) => id);expect(queryIds).toContain("__content-block-mdx__:nested.mdx");@@ -408,10 +416,26 @@ describe("Content Block MDX compilation", () => {}),});const artifact = {+ documentGraph: {+ nodes: [+ { id: "post", revision: "r1", contentRef: "post" },+ { id: "author", revision: "r1", contentRef: "author" },+ ],+ edges: [+ {+ sourceId: "post",+ referenceId: "#frontmatter/author",+ reference: {+ documentId: "author",+ revision: "r1",+ representation: { type: "document" },+ },+ },+ ],+ },documents: [{_id: "post",- _type: "asset.file",name: "post.json",path: "post.json",key: "post",@@ -422,7 +446,6 @@ describe("Content Block MDX compilation", () => {},{_id: "private-post",- _type: "asset.file",name: "private.json",path: "private.json",key: "private",@@ -433,7 +456,6 @@ describe("Content Block MDX compilation", () => {},{_id: "second-post",- _type: "asset.file",name: "second.json",path: "second.json",key: "second",@@ -464,6 +486,18 @@ describe("Content Block MDX compilation", () => {expect(plan?.queries.map(({ id }) => id)).not.toContain("__content-block-mdx__:second.mdx");++ // Returning an unrelated author is safe; using that unresolved reference+ // as the MDX source is still rejected, including inside a Collection.+ build.props[0].value =+ kind === "detail"+ ? `${resourceVariable}.data.properties.author.mdx`+ : `${itemVariable}.properties.author.mdx`;+ expect(() =>+ resolvePublishedMdxAssetCandidates({ build, artifact })+ ).toThrow(+ "Dynamic MDX source candidates through resolved document references"+ );});diff --git a/packages/project-build/src/content-database.ts b/packages/project-build/src/content-database.tsindex 39c13c83a9..44fda1443c 100644--- a/packages/project-build/src/content-database.ts+++ b/packages/project-build/src/content-database.ts@@ -5,6 +5,8 @@ import {createDocumentGraph,createLiteralContentCompilationQuery,getDocumentGraphQueryRootIds,+ isDocumentGraphFieldAffected,+ type DocumentGraph,hasDynamicContentCompilationValues,type AssetQueryInput,type ContentCompilationPlan,@@ -12,7 +14,7 @@ import {defaultAssetResourceOutputSelection,getAssetQueryFieldValue,selectContentHydrationCandidates,- type AssetFileDocument,+ type ContentDatabaseDocument,} from "@webstudio-is/content-engine";import {blockComponent,@@ -219,9 +221,15 @@ export const createPublishedBuildContentCompilationPlan = (export const resolvePublishedMdxDependencyClosure = async ({build,artifact,+ onTemplateOmission,}: {build: PublishedContentDatabaseBuild;artifact: ContentArtifactV1;+ onTemplateOmission?: (issue: {+ blockInstanceId: string;+ assetId: string;+ templateName: string;+ }) => void;}) => {const instances = new Map(getBuildValues<Instance>(build.instances).map((instance) => [@@ -313,6 +321,12 @@ export const resolvePublishedMdxDependencyClosure = async ({for (const reference of resolution.references) {if (reference.type === "resolved-template") {visitTemplateSubtree(reference.templateInstanceId);+ } else {+ onTemplateOmission?.({+ blockInstanceId: blockId,+ assetId,+ templateName: reference.templateName,+ });}}}@@ -332,7 +346,8 @@ export const resolvePublishedMdxDependencyClosure = async ({const candidateDocumentKey = Symbol("candidate-document");type CandidateDocument = Readonly<{- [candidateDocumentKey]: AssetFileDocument;+ [candidateDocumentKey]: ContentDatabaseDocument;+ graph?: DocumentGraph;}>;const isCandidateDocument = (value: unknown): value is CandidateDocument =>@@ -343,6 +358,19 @@ const getValueAtPath = (path: readonly string[]): unknown => {if (isCandidateDocument(value)) {+ if (+ path[0] === "properties" &&+ value.graph !== undefined &&+ isDocumentGraphFieldAffected({+ graph: value.graph,+ sourceId: value[candidateDocumentKey]._id,+ field: ["properties", ...path.slice(1)],+ })+ ) {+ throw new Error(+ "Dynamic MDX source candidates through resolved document references are not supported safely for publication"+ );+ }return path.length === 0? value[candidateDocumentKey]._id: getAssetQueryFieldValue(value[candidateDocumentKey], [...path]);@@ -396,9 +424,9 @@ export const resolvePublishedMdxAssetCandidates = ({artifact?.documentGraph === undefined? undefined: createDocumentGraph(artifact.documentGraph);- const documents = (artifact?.documents ?? []).filter(- (document): document is AssetFileDocument => document._type === "asset.file"- );+ // Compiled documents are projected file records; metadata such as _type+ // can be omitted by the resource's output selection.+ const documents = artifact?.documents ?? [];const evaluateDataSource = (dataSourceId: string,@@ -436,8 +464,16 @@ export const resolvePublishedMdxAssetCandidates = ({}if (documentGraph !== undefined) {if (- getDocumentGraphQueryRootIds({ graph: documentGraph, query }).length >- 0+ getDocumentGraphQueryRootIds({+ graph: documentGraph,+ // Only filtering and sorting affect candidate membership here.+ // Check the field used by src when it is read below, not every+ // unrelated reference included in the resource output.+ query: {+ ...query,+ output: { mode: "fields", fields: [], includeMetadata: false },+ },+ }).length > 0) {throw new Error("Dynamic MDX source candidates through resolved document references are not supported safely for publication"@@ -463,8 +499,12 @@ export const resolvePublishedMdxAssetCandidates = ({fieldPath.length === 0? ({[candidateDocumentKey]: document,+ graph: documentGraph,} satisfies CandidateDocument)- : getAssetQueryFieldValue(document, [...fieldPath])+ : getValueAtPath(+ { [candidateDocumentKey]: document, graph: documentGraph },+ fieldPath+ ));}const collection = instances.get(dataSource.scopeInstanceId ?? "");diff --git a/packages/project-build/src/docs.generated.ts b/packages/project-build/src/docs.generated.tsindex c29103a97d..d043c9e7ff 100644--- a/packages/project-build/src/docs.generated.ts+++ b/packages/project-build/src/docs.generated.ts@@ -4,9 +4,9 @@ export const projectBuildDocs = {"accessibility-review":'<!-- Adapted for Webstudio MCP from Community-Access/accessibility-agents, web-accessibility-wizard/SKILL.md (MIT): https://github.com/Community-Access/accessibility-agents/blob/main/codex-skills/web-accessibility-wizard/SKILL.md -->\n\n# Webstudio Accessibility Review\n\nUse this workflow when creating or reviewing a page, component, form, menu,\ndialog, or responsive layout. It is an LLM-assisted review, not proof of WCAG\nconformance. Do not claim that a page is accessible solely because this review\nhas no findings.\n\n## Evidence First\n\n1. Read `meta.index` and use focused project tools. Do not inspect Webstudio\n source code or generated files for normal project reviews.\n2. Run `audit` with `{"scopes":["accessibility"]}` before changing\n anything. It detects deterministic metadata issues such as labels, landmark\n structure, positive tabindex values, invalid static ARIA states, and unmuted\n autoplay. Fix confirmed static findings first.\n3. Ask whether the user wants visual verification unless they explicitly\n requested it. Only after they opt in, use `preview.start` and capture each\n changed route with `screenshot` at desktop, tablet, and mobile widths. Use\n `waitForSelector` or `waitForTimeout` only when the page has an actual\n delayed ready state. If they do not opt in, continue with static evidence\n and mark visual findings as manual verification items.\n4. Use `get-page-by-path`, `list-instances`, `inspect-instance`, and focused\n prop/style reads to verify semantics and authored state that screenshots\n cannot prove.\n5. Make only supported, evidence-based fixes with semantic MCP tools. Recheck\n the affected route and the static accessibility search after every fix.\n\n## Review Areas\n\nReview these areas in priority order. Record the evidence for every finding.\n\n### 1. Names, Semantics, and Structure\n\n- Every image has purposeful alternative text or an explicitly empty alt when\n decorative. Image-submit inputs need a non-empty alt label describing their\n action.\n- For `missing-image-description` findings, inspect the rendered image in its\n page context and call `set-image-descriptions` with either a concise generated\n description or `decorative: true`. Re-run the audit after saving the decision.\n- Buttons, links, icon-only controls, and form controls have accessible names.\n- Prefer native HTML semantics over ARIA roles.\n- Non-native elements using `role="button"` or `role="link"` must be\n keyboard-focusable.\n- Use one sensible page h1, ordered heading levels, meaningful link text, and\n a main landmark.\n- Iframes have titles. Static HTML ids are unique, ARIA reference props point\n to real ids, and static boolean/select/numeric ARIA values are valid.\n- Focusable controls must not be hidden from assistive technology with\n `aria-hidden`.\n\n### 2. Keyboard and Focus\n\n- Interactive controls should be native or have a documented keyboard model.\n- Visible focus must not be removed without a visible replacement.\n- Hover-only information or controls need a keyboard-accessible equivalent.\n- Do not use positive tabindex values.\n- Mark keyboard behavior as **manual verification required** when the available\n evidence cannot prove tab order, Escape handling, or focus restoration.\n\n### 3. Dialogs, Menus, and Other Overlays\n\n- Dialogs need an accessible name and a close action.\n- Opening an overlay should move focus into it, trap focus where appropriate,\n and restore focus to its trigger on close.\n- Menus, popovers, disclosures, and tabs must expose their expanded/selected\n state and remain usable without a pointer.\n- If the current MCP/browser tools cannot exercise the interaction, report it\n as a manual verification item instead of guessing.\n\n### 4. Forms and Errors\n\n- Inputs have labels, required state, helpers, and errors associated with the\n right control.\n- Invalid controls expose `aria-invalid` when applicable.\n- Error, loading, and success feedback is not conveyed only by color or a\n transient visual toast.\n- Submit controls do not become unexplained dead ends when disabled.\n\n### 5. Visual, Responsive, Media, and Motion\n\n- At each target width, text remains readable, controls remain reachable, and\n no content is clipped, overlapped, or dependent on hover alone.\n- Do not rely only on color, position, shape, or iconography to convey meaning.\n- Keep non-text contrast, text contrast, focus indicators, and small text as\n visual review items unless measured evidence is available.\n- Videos with meaningful speech need captions; non-essential motion should\n respect reduced-motion preferences. Do not autoplay sound.\n\n### 6. Dynamic Content and Data\n\n- Loading, empty, error, and success states have understandable visible text.\n- Important dynamic updates and validation feedback need an appropriate\n announcement strategy.\n- Check repeated resource-driven content for unique labels, headings, ids, and\n meaningful empty states.\n\n## Findings and Fixes\n\nClassify every item as one of:\n\n- **Confirmed:** directly shown by `audit`, project data, or a rendered\n screenshot.\n- **Likely:** a credible issue inferred from rendered evidence; explain what\n would confirm it.\n- **Manual verification required:** needs keyboard, screen-reader, contrast, or\n interaction testing that the available tools cannot prove.\n\nFor each item include: severity (`critical`, `high`, `medium`, or `low`), page\npath, affected element or instance id when known, evidence, short user impact,\nand the smallest supported fix. Fix critical and high items first. Do not add\nARIA attributes, alt text, labels, or live regions when their meaning cannot be\nknown from the project; ask the user or report the missing context.\n\nFinish with a concise summary of fixed findings, remaining findings, and manual\nverification items. Use screenshots as evidence of the rendered state, not as\nproof of accessibility compliance.\n',expressions:- '# Webstudio Expressions\n\nUse an expression only when a value must be computed at runtime from scoped\ndata. Use direct text and direct prop values for fixed content.\n\n## Source Format\n\nExpression-capable MCP fields receive JavaScript expression source as a JSON\nstring. Send one expression, without a `return` statement or surrounding\nfunction. For example:\n\n```json\n{ "binding": { "type": "expression", "value": "post.title ?? \\"Untitled\\"" } }\n```\n\nInside that string, use readable JavaScript syntax rather than serialized JSON.\nFor object expressions, leave identifier property names unquoted, for example\n`{ query: queryText, variables: { slug: system.params.slug } }`. Quote a property\nname only when JavaScript requires it, such as `{ "published-at": date }`. Do\nnot pass a JSON-stringified object as an expression.\n\nDo not send a fixed prop string as an expression. Use `update-props` with\n`type:"string"`. Page metadata and resource URLs accept plain fixed strings and\nnormalize them for storage. Expression-only resource headers, search parameters,\nand bodies accept `{ "type": "literal", "value": "fixed text" }` when the\nvalue is not dynamic.\n\n## Read and read-write bindings\n\nExpression bindings use `mode:"read"` by default. Use `mode:"readwrite"` only\nfor an exact direct path into the frontmatter of an MDX source connected to the\ncontaining Content Block, for example:\n\n```json\n{\n "binding": {\n "type": "expression",\n "value": "document.frontmatter.title",\n "mode": "readwrite"\n }\n}\n```\n\nThis lets Content mode save a direct edit back to that frontmatter field.\nComputed expressions, including fallbacks and concatenation, are always\nread-only. The mutation is rejected when the expression is not a direct path or\ndoes not belong to a connected Content Block document. Use the variable name\nreturned by `inspect-instance`; do not assume it is `document`.\n\n## Scope\n\n- Data variables are available on their scope instance and descendants.\n- An inner variable with the same name masks the outer variable.\n- A scoped resource result is a variable. Read its payload from its result\n wrapper, usually `resourceName.data`; APIs may nest the desired value deeper.\n- Collection creates internal `collectionItem` and `collectionItemKey`\n parameters. They are available only to that Collection\'s descendants.\n Preserve those generated parameters and do not reuse encoded parameter ids\n copied from another Collection.\n- Array Collection iteration exposes the current item. Object iteration exposes\n the current key and value.\n- The built-in `system` context is available only where supplied by the runtime.\n Its documented fields are `system.origin`, `system.pathname`, `system.params`,\n and `system.search`. There is no `system.path`.\n- Actions expose only their declared arguments, such as `event`, plus data that\n is in scope.\n\nRead `list-variables`, `list-resources`, `inspect-instance`, and existing\nbindings before writing an expression. Do not guess identifier names. Syntax is\nvalidated when a mutation is submitted. A valid expression that references an\nidentifier unavailable in that scope is accepted with a structured warning\ncontaining the field path, source range, affected record, and remediation.\n\n## Supported Syntax\n\nExpressions support literals, arrays, objects, property and index access, unary\nand arithmetic operators, comparisons, logical operators, nullish coalescing,\nternaries, and template literals.\n\nWebstudio automatically makes property and index access safe when an\nintermediate value is missing. Write direct access such as `post.author.name`.\nUse nullish coalescing when the expression needs a fallback value.\n\nSupported string methods:\n\n{{allowedStringMethods}}\n\nSupported array methods:\n\n{{allowedArrayMethods}}\n\nOther values support `toString`. Arbitrary global functions and arbitrary\nmethod calls are not supported.\n\n## Unsupported Syntax\n\nDo not use statements, declarations, functions, arrow functions, classes,\n`new`, `this`, `await`, imports, tagged templates, sequence expressions,\nincrement/decrement, or destructuring assignment. Assignment is allowed only\ninside actions. Use an explicit assignment there rather than `++` or `--`.\n\n## Common Examples\n\n- Text: `post.title ?? "Untitled"`\n- Prop: `post.url`\n- Nested API array for Collection: `posts.data.items`\n- Resource URL: `"https://api.example.com/posts?tag=" + filters.tag`\n- Header: `"Bearer " + auth.token`\n- Search parameter: `String(filters.page ?? 1)` is not supported because global\n function calls are forbidden; use `(filters.page ?? 1).toString()` instead.\n- Resource body: `{ query: queryText, variables: { slug: system.params.slug } }`\n- Conditional: `featured ? "Featured" : "Standard"`\n- Nested access with a fallback: `post.author.name ?? "Unknown author"`\n\n## Collections\n\nWhenever an array or object should render repeated UI, call `insert-collection`\nwith the complete iterable and one repeated-item JSX root. Do not pass the\nresponse wrapper or one indexed item. The command creates the Collection and\nits private item parameters atomically, then renders the item root once per\nentry. Bind descendants with expressions such as `collectionItem.name`; for\nobject iteration, `collectionItemKey` contains the current key. Wrap multiple\nrepeated siblings in one lowercase HTML root such as `<div>`.\n\n## Verification\n\nInspect every returned expression warning. Correct warnings that indicate a\nmisspelled or unavailable variable, then run `verify-bindings` for persisted\nsyntax, scope, and reference integrity. A warning does not roll back the\nmutation, and successful static verification does not prove runtime data has\nthe expected shape. `verify-bindings` never executes external resources or\nresolves rendered values. Preview representative data, empty/null data, and\nCollection item counts; use `audit` for relevant structural findings.\n',+ '# Webstudio Expressions\n\nUse an expression only when a value must be computed at runtime from scoped\ndata. Use direct text and direct prop values for fixed content.\n\n## Source Format\n\nExpression-capable MCP fields receive JavaScript expression source as a JSON\nstring. Send one expression, without a `return` statement or surrounding\nfunction. For example:\n\n```json\n{ "binding": { "type": "expression", "value": "post.title ?? \\"Untitled\\"" } }\n```\n\nInside that string, use readable JavaScript syntax rather than serialized JSON.\nFor object expressions, leave identifier property names unquoted, for example\n`{ query: queryText, variables: { slug: system.params.slug } }`. Quote a property\nname only when JavaScript requires it, such as `{ "published-at": date }`. Do\nnot pass a JSON-stringified object as an expression.\n\nDo not send a fixed prop string as an expression. Use `update-props` with\n`type:"string"`. Page metadata and resource URLs accept plain fixed strings and\nnormalize them for storage. Expression-only resource headers, search parameters,\nand bodies accept `{ "type": "literal", "value": "fixed text" }` when the\nvalue is not dynamic.\n\n## Read and read-write bindings\n\nExpression bindings use `mode:"read"` by default. Use `mode:"readwrite"` only\nfor an exact direct path into the frontmatter of an MDX source connected to the\ncontaining Content Block, for example:\n\n```json\n{\n "binding": {\n "type": "expression",\n "value": "document.frontmatter.title",\n "mode": "readwrite"\n }\n}\n```\n\nThis lets Content mode save a direct edit back to that frontmatter field.\nComputed expressions, including fallbacks and concatenation, are always\nread-only. The mutation is rejected when the expression is not a direct path or\ndoes not belong to a connected Content Block document. Use the variable name\nreturned by `inspect-instance`; do not assume it is `document`.\n\nFor an MDX-backed article, use the query resource to select the Content Block\'s\nsource Asset, for example `post.data.id`. Inside the block, bind article fields\nto the block\'s document parameter, not `post.data.properties.title` or other\nequivalent query-result values. A query binding can display the correct value\nwithout supporting Content-mode edits.\n\nThe MDX body is editable through its source mapping. Designer-created elements\noutside that body, such as an article header, stay protected unless their text\nor supported props have writable frontmatter bindings. Containment in the\nContent Block alone is not enough. Use `update-text` with\n`expressionBindingMode:"readwrite"` for a designed heading\'s text, and\n`bind-props` with `binding.mode:"readwrite"` for a supported prop. These target\npersistent designed instances, not MDX-generated instances.\n\nUse direct paths for writable bindings, such as\n`document.frontmatter.title`; property access is already safe. Adding `??`\nfallbacks or formatting makes the expression read-only. Direct bindings through\nloaded Markdown or MDX `$ref` values ending in `#frontmatter` save to the\nreferenced file, with its write permissions enforced. For example, editing\n`document.frontmatter.author.name` updates the shared author file, affecting\nevery article using it while preserving the article\'s reference. JSON/body\nreferences remain read-only. Image replacement is a supported reference write,\nnot a write to shared resolved metadata; use the image recipe below.\n\n### Make an article image replaceable\n\nFor `featureImage: { $ref: "./images/hero.png" }`, bind the designed Image\'s\n`src` to `document.frontmatter.featureImage.src` with explicit `mode:"readwrite"`.\nThe default `read` mode renders the image but does not let the Content-mode\neditor replace it. A disabled resolved-URL input is expected; the active\n**Choose source** picker is the replacement control.\n\nUse `bind-props` with the actual Image instance ID and document variable name:\n\n```json\n{\n "bindings": [\n {\n "instanceId": "<imageInstanceId>",\n "name": "src",\n "binding": {\n "type": "expression",\n "value": "document.frontmatter.featureImage.src",\n "mode": "readwrite"\n }\n },\n {\n "instanceId": "<imageInstanceId>",\n "name": "alt",\n "binding": {\n "type": "expression",\n "value": "document.frontmatter.featureImage.description",\n "mode": "read"\n }\n }\n ]\n}\n```\n\nThe picker saves a new `$ref` in the article. It must not save a resolved URL\nstring or modify the original shared Asset. Shared alternative text uses\n**Choose source → asset actions → Settings → Description** instead.\n\nIf the picker is absent or disabled, first inspect the source binding\'s mode,\ndocument scope, loaded `$ref`, and permissions. Do not infer that replacement\nis unsupported from a correctly rendered image or the disabled URL input.\n\n### Verify the whole article, not just its body\n\nIf the user asks for full Content-mode editing, inventory every article field,\nincluding the designed header, hero image source, alternative text, captions,\nauthor details, dates, reading time, links, and custom-component content.\nVerify each field through its Content-mode UI, inspect the saved MDX or\nreferenced file, reload, then restore and verify the original value. A valid\nbinding, correct preview, or successful MCP edit is not a UI-editability test.\nReport each field as passed, failed, or not tested; do not call the article\nfully editable with required fields missing or untested.\n\nFor images, use the recipe above and verify the picker, changed `$ref`, reload,\nand restoration with an approved temporary replacement. Confirm unrelated MDX\nand the original shared Asset remain unchanged. A metadata edit or a disabled\nURL input does not test image replacement. If the replacement test is not\nauthorized, record it as not tested rather than passed.\n\n### Keep editable values separate from formatting\n\nWhen a field must be editable in Content mode, do not concatenate its value\nwith labels, units, or punctuation, or wrap it in a template literal, fallback,\nor formatting call. Keep the value in its own text element with one direct\nread-write binding. Put the fixed prefix and suffix in separate sibling text\nelements. Do not mix literal and expression children in the value element.\n\nFor example, display reading time as three inline siblings: fixed `— `,\nan element bound to `document.frontmatter.readingTime`, and fixed ` min read`.\nSet `expressionBindingMode:"readwrite"` on the middle element with `update-text`.\nThe number remains editable while the surrounding wording stays protected.\nPreserve spacing and the field\'s stored type. For dates, prefer a Date Time\ncomponent with its date prop bound directly and formatting configured separately.\n\nDo not silently choose a read-only expression to achieve the requested display.\nIf a required transformation has no editable presentation, explain the limitation\nand ask before making that field read-only. This does not extend the supported\nwrite targets or override permissions.\n\n## Scope\n\n- Data variables are available on their scope instance and descendants.\n- An inner variable with the same name masks the outer variable.\n- A scoped resource result is a variable. Read its payload from its result\n wrapper, usually `resourceName.data`; APIs may nest the desired value deeper.\n- Collection creates internal `collectionItem` and `collectionItemKey`\n parameters. They are available only to that Collection\'s descendants.\n Preserve those generated parameters and do not reuse encoded parameter ids\n copied from another Collection.\n- Array Collection iteration exposes the current item. Object iteration exposes\n the current key and value.\n- The built-in `system` context is available only where supplied by the runtime.\n Its documented fields are `system.origin`, `system.pathname`, `system.params`,\n and `system.search`. There is no `system.path`.\n- Actions expose only their declared arguments, such as `event`, plus data that\n is in scope.\n\nRead `list-variables`, `list-resources`, `inspect-instance`, and existing\nbindings before writing an expression. Do not guess identifier names. Syntax is\nvalidated when a mutation is submitted. A valid expression that references an\nidentifier unavailable in that scope is accepted with a structured warning\ncontaining the field path, source range, affected record, and remediation.\n\n## Supported Syntax\n\nExpressions support literals, arrays, objects, property and index access, unary\nand arithmetic operators, comparisons, logical operators, nullish coalescing,\nternaries, and template literals.\n\nWebstudio automatically makes property and index access safe when an\nintermediate value is missing. Write direct access such as `post.author.name`.\nUse nullish coalescing when the expression needs a fallback value.\n\nSupported string methods:\n\n{{allowedStringMethods}}\n\nSupported array methods:\n\n{{allowedArrayMethods}}\n\nOther values support `toString`. Arbitrary global functions and arbitrary\nmethod calls are not supported.\n\n## Unsupported Syntax\n\nDo not use statements, declarations, functions, arrow functions, classes,\n`new`, `this`, `await`, imports, tagged templates, sequence expressions,\nincrement/decrement, or destructuring assignment. Assignment is allowed only\ninside actions. Use an explicit assignment there rather than `++` or `--`.\n\n## Common Examples\n\n- Text: `post.title ?? "Untitled"`\n- Prop: `post.url`\n- Nested API array for Collection: `posts.data.items`\n- Resource URL: `"https://api.example.com/posts?tag=" + filters.tag`\n- Header: `"Bearer " + auth.token`\n- Search parameter: `String(filters.page ?? 1)` is not supported because global\n function calls are forbidden; use `(filters.page ?? 1).toString()` instead.\n- Resource body: `{ query: queryText, variables: { slug: system.params.slug } }`\n- Conditional: `featured ? "Featured" : "Standard"`\n- Nested access with a fallback: `post.author.name ?? "Unknown author"`\n\n## Collections\n\nWhenever an array or object should render repeated UI, call `insert-collection`\nwith the complete iterable and one repeated-item JSX root. Do not pass the\nresponse wrapper or one indexed item. The command creates the Collection and\nits private item parameters atomically, then renders the item root once per\nentry. Bind descendants with expressions such as `collectionItem.name`; for\nobject iteration, `collectionItemKey` contains the current key. Wrap multiple\nrepeated siblings in one lowercase HTML root such as `<div>`.\n\n## Verification\n\nInspect every returned expression warning. Correct warnings that indicate a\nmisspelled or unavailable variable, then run `verify-bindings` for persisted\nsyntax, scope, and reference integrity. A warning does not roll back the\nmutation, and successful static verification does not prove runtime data has\nthe expected shape. `verify-bindings` never executes external resources or\nresolves rendered values. Preview representative data, empty/null data, and\nCollection item counts; use `audit` for relevant structural findings.\n',"mcp-startup-guidance":- 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get-more-tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get-more-tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, and do not edit generated files for normal content/design changes. Never run visual verification automatically: ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit, and only then use `preview.start` plus screenshot/vision.\n\nWhen `report-issue` is available and the user explicitly asks to report a problem, call it once without requiring a GitHub login. Also call it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. The LLM must write a complete anonymous technical report with the generalized user story, summary, attempted workflow, expected behavior, actual result, recovery attempts, user impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, or exact unique values. Do not copy raw tool inputs, outputs, or contextual errors; preserve only stable tool names, schema fields, error codes, CLI versions, and generalized input shapes. Use `unknown` instead of guessing unavailable model metadata.\n',+ 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get-more-tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get-more-tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, and do not edit generated files for normal content/design changes. Never run visual verification automatically: ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit, and only then use `preview.start` plus screenshot/vision.\n\nWhen `report-issue` is available and the user explicitly asks to report a problem, call it once without requiring a GitHub login. Also call it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. The LLM must write a complete anonymous technical report with the generalized user story, summary, attempted workflow, expected behavior, actual result, recovery attempts, user impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, or exact unique values. Do not copy raw tool inputs, outputs, or contextual errors; preserve only stable tool names, schema fields, error codes, CLI versions, and generalized input shapes. Use `unknown` instead of guessing unavailable model metadata.\n\n## Content Block completion\n\nContent Block work is not complete after one editable heading works. For every creation, migration, or repair, with or without MDX, inventory all intended editor-owned fields and their write destinations before implementation. Use semantic controls (calendar for dates, image picker for image replacement), keep fixed wording separate from direct writable bindings, and preserve existing field types and wording. Verify each field through Content mode, saved data, and reload; restore test values. Report passed, failed, or not tested per field. Missing or read-only required controls are unfinished requirements. Never substitute a correct preview or MCP write for the UI test.\n\nFor MDX articles, include the designed header, reading time, dates, images, alternative text, links, author fields, and custom-component content—not just the body. For a designed Image, use `bind-props` with `src` bound directly to `document.frontmatter.featureImage.src` and explicit `binding.mode:"readwrite"`; the default read-only mode can render correctly while hiding replacement controls. **Choose source** changes the article\'s image `$ref`, not shared resolved Asset metadata; the disabled URL input is expected. Keep the `.description` alt binding read-only and edit shared Description through Asset settings. Inspect binding mode, document scope, loaded reference, and permissions before claiming image replacement is unsupported. Follow the expressions guide\'s image recipe and whole-article verification checklist before handoff.\n',} as const;export type ProjectBuildDocName = keyof typeof projectBuildDocs;diff --git a/packages/project-build/src/docs/expressions.md b/packages/project-build/src/docs/expressions.mdindex 76658b2fbf..2117f1d7a8 100644--- a/packages/project-build/src/docs/expressions.md+++ b/packages/project-build/src/docs/expressions.md@@ -47,6 +47,110 @@ read-only. The mutation is rejected when the expression is not a direct path ordoes not belong to a connected Content Block document. Use the variable namereturned by `inspect-instance`; do not assume it is `document`.+For an MDX-backed article, use the query resource to select the Content Block's+source Asset, for example `post.data.id`. Inside the block, bind article fields+to the block's document parameter, not `post.data.properties.title` or other+equivalent query-result values. A query binding can display the correct value+without supporting Content-mode edits.++The MDX body is editable through its source mapping. Designer-created elements+outside that body, such as an article header, stay protected unless their text+or supported props have writable frontmatter bindings. Containment in the+Content Block alone is not enough. Use `update-text` with+`expressionBindingMode:"readwrite"` for a designed heading's text, and+`bind-props` with `binding.mode:"readwrite"` for a supported prop. These target+persistent designed instances, not MDX-generated instances.++Use direct paths for writable bindings, such as+`document.frontmatter.title`; property access is already safe. Adding `??`+fallbacks or formatting makes the expression read-only. Direct bindings through+loaded Markdown or MDX `$ref` values ending in `#frontmatter` save to the+referenced file, with its write permissions enforced. For example, editing+`document.frontmatter.author.name` updates the shared author file, affecting+every article using it while preserving the article's reference. JSON/body+references remain read-only. Image replacement is a supported reference write,+not a write to shared resolved metadata; use the image recipe below.++### Make an article image replaceable++For `featureImage: { $ref: "./images/hero.png" }`, bind the designed Image's+`src` to `document.frontmatter.featureImage.src` with explicit `mode:"readwrite"`.+The default `read` mode renders the image but does not let the Content-mode+editor replace it. A disabled resolved-URL input is expected; the active+**Choose source** picker is the replacement control.++Use `bind-props` with the actual Image instance ID and document variable name:++```json+{+ "bindings": [+ {+ "instanceId": "<imageInstanceId>",+ "name": "src",+ "binding": {+ "type": "expression",+ "value": "document.frontmatter.featureImage.src",+ "mode": "readwrite"+ }+ },+ {+ "instanceId": "<imageInstanceId>",+ "name": "alt",+ "binding": {+ "type": "expression",+ "value": "document.frontmatter.featureImage.description",+ "mode": "read"+ }+ }+ ]+}+```++The picker saves a new `$ref` in the article. It must not save a resolved URL+string or modify the original shared Asset. Shared alternative text uses+**Choose source → asset actions → Settings → Description** instead.++If the picker is absent or disabled, first inspect the source binding's mode,+document scope, loaded `$ref`, and permissions. Do not infer that replacement+is unsupported from a correctly rendered image or the disabled URL input.++### Verify the whole article, not just its body++If the user asks for full Content-mode editing, inventory every article field,+including the designed header, hero image source, alternative text, captions,+author details, dates, reading time, links, and custom-component content.+Verify each field through its Content-mode UI, inspect the saved MDX or+referenced file, reload, then restore and verify the original value. A valid+binding, correct preview, or successful MCP edit is not a UI-editability test.+Report each field as passed, failed, or not tested; do not call the article+fully editable with required fields missing or untested.++For images, use the recipe above and verify the picker, changed `$ref`, reload,+and restoration with an approved temporary replacement. Confirm unrelated MDX+and the original shared Asset remain unchanged. A metadata edit or a disabled+URL input does not test image replacement. If the replacement test is not+authorized, record it as not tested rather than passed.++### Keep editable values separate from formatting++When a field must be editable in Content mode, do not concatenate its value+with labels, units, or punctuation, or wrap it in a template literal, fallback,+or formatting call. Keep the value in its own text element with one direct+read-write binding. Put the fixed prefix and suffix in separate sibling text+elements. Do not mix literal and expression children in the value element.++For example, display reading time as three inline siblings: fixed `— `,+an element bound to `document.frontmatter.readingTime`, and fixed ` min read`.+Set `expressionBindingMode:"readwrite"` on the middle element with `update-text`.+The number remains editable while the surrounding wording stays protected.+Preserve spacing and the field's stored type. For dates, prefer a Date Time+component with its date prop bound directly and formatting configured separately.++Do not silently choose a read-only expression to achieve the requested display.+If a required transformation has no editable presentation, explain the limitation+and ask before making that field read-only. This does not extend the supported+write targets or override permissions.+## Scope- Data variables are available on their scope instance and descendants.diff --git a/packages/project-build/src/docs/mcp-startup-guidance.md b/packages/project-build/src/docs/mcp-startup-guidance.mdindex dfd7a3df1b..17bdc2e868 100644--- a/packages/project-build/src/docs/mcp-startup-guidance.md+++ b/packages/project-build/src/docs/mcp-startup-guidance.md@@ -1,3 +1,9 @@If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get-more-tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get-more-tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, and do not edit generated files for normal content/design changes. Never run visual verification automatically: ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit, and only then use `preview.start` plus screenshot/vision.When `report-issue` is available and the user explicitly asks to report a problem, call it once without requiring a GitHub login. Also call it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. The LLM must write a complete anonymous technical report with the generalized user story, summary, attempted workflow, expected behavior, actual result, recovery attempts, user impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, or exact unique values. Do not copy raw tool inputs, outputs, or contextual errors; preserve only stable tool names, schema fields, error codes, CLI versions, and generalized input shapes. Use `unknown` instead of guessing unavailable model metadata.++## Content Block completion++Content Block work is not complete after one editable heading works. For every creation, migration, or repair, with or without MDX, inventory all intended editor-owned fields and their write destinations before implementation. Use semantic controls (calendar for dates, image picker for image replacement), keep fixed wording separate from direct writable bindings, and preserve existing field types and wording. Verify each field through Content mode, saved data, and reload; restore test values. Report passed, failed, or not tested per field. Missing or read-only required controls are unfinished requirements. Never substitute a correct preview or MCP write for the UI test.++For MDX articles, include the designed header, reading time, dates, images, alternative text, links, author fields, and custom-component content—not just the body. For a designed Image, use `bind-props` with `src` bound directly to `document.frontmatter.featureImage.src` and explicit `binding.mode:"readwrite"`; the default read-only mode can render correctly while hiding replacement controls. **Choose source** changes the article's image `$ref`, not shared resolved Asset metadata; the disabled URL input is expected. Keep the `.description` alt binding read-only and edit shared Description through Asset settings. Inspect binding mode, document scope, loaded reference, and permissions before claiming image replacement is unsupported. Follow the expressions guide's image recipe and whole-article verification checklist before handoff.diff --git a/packages/project-build/src/runtime/asset-folders.test.ts b/packages/project-build/src/runtime/asset-folders.test.tsindex 9977f5aaec..88fe9c42a0 100644--- a/packages/project-build/src/runtime/asset-folders.test.ts+++ b/packages/project-build/src/runtime/asset-folders.test.ts@@ -36,6 +36,30 @@ const asset = (id: string, folderId?: string): Asset => ({meta: {},});+const collectionAsset = ({+ id,+ name,+ filename,+ format,+}: {+ id: string;+ name: string;+ filename: string;+ format: "json" | "mdx";+}): Asset => ({+ id,+ projectId: "project",+ name,+ filename,+ folderId: "posts",+ type: "file",+ size: 1,+ format,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+});+describe("asset folders", () => {test("creates a nested folder with a trimmed name", () => {const result = createAssetFolder(@@ -127,14 +151,20 @@ describe("asset folders", () => {test("duplicates a folder subtree and its assets", () => {const ids = ["copy", "child-copy", "asset-copy"];+ const unrelatedCopy = asset("unrelated", "other");+ unrelatedCopy.filename = "asset copy";const result = duplicateAssetFolder({assetFolders: folders(folder("source", undefined, "Media"),folder("existing-copy", undefined, "Media copy"),- folder("child", "source", "Photos")+ folder("child", "source", "Photos"),+ folder("other")),- assets: new Map([["asset", asset("asset", "child")]]),+ assets: new Map([+ ["asset", asset("asset", "child")],+ [unrelatedCopy.id, unrelatedCopy],+ ]),},{ folderId: "source", parentId: null },{ projectId: "project", createId: () => ids.shift()! }@@ -182,6 +212,64 @@ describe("asset folders", () => {]);});+ test("preserves logical filenames when duplicating a collection folder", () => {+ const config = collectionAsset({+ id: "config",+ name: "config-storage.json",+ filename: "collection",+ format: "json",+ });+ const template = collectionAsset({+ id: "template",+ name: "template-storage.mdx",+ filename: "template",+ format: "mdx",+ });+ const entry = collectionAsset({+ id: "entry",+ name: "entry-storage.mdx",+ filename: "hello-world",+ format: "mdx",+ });+ const ids = ["posts-copy", "config-copy", "template-copy", "entry-copy"];++ const result = duplicateAssetFolder(+ {+ assetFolders: folders(folder("posts", undefined, "Posts")),+ assets: new Map(+ [config, template, entry].map((value) => [value.id, value])+ ),+ },+ { folderId: "posts" },+ { projectId: "project", createId: () => ids.shift()! }+ );++ const assetPatches = result.payload.find(+ ({ namespace }) => namespace === "assets"+ )?.patches;+ expect(+ assetPatches?.map((patch) =>+ patch.op === "add" || patch.op === "replace" ? patch.value : undefined+ )+ ).toEqual([+ expect.objectContaining({+ id: "config-copy",+ filename: "collection",+ folderId: "posts-copy",+ }),+ expect.objectContaining({+ id: "template-copy",+ filename: "template",+ folderId: "posts-copy",+ }),+ expect.objectContaining({+ id: "entry-copy",+ filename: "hello-world",+ folderId: "posts-copy",+ }),+ ]);+ });+test("moves a folder to the root without changing its name", () => {const result = updateAssetFolder({diff --git a/packages/project-build/src/runtime/asset-folders.ts b/packages/project-build/src/runtime/asset-folders.tsindex 18a79379cf..ee2f55efaa 100644--- a/packages/project-build/src/runtime/asset-folders.ts+++ b/packages/project-build/src/runtime/asset-folders.ts@@ -4,10 +4,12 @@ import {assetFolderName,assetFolders,createAssetFolderHierarchy,+ formatAssetName,type Asset,type AssetFolder,type AssetFolders,} from "@webstudio-is/sdk";+import { collectionConfigFilename } from "@webstudio-is/content-engine";import type { BuilderState } from "../state/builder-state";import {appendOptionalPropertyPatch,@@ -208,8 +210,15 @@ export const duplicateAssetFolder = (});}- const displayFilenames = new Set(- Array.from(state.assets?.values() ?? [], getAssetDisplayFilename)+ const duplicatedLogicalFilenames = new Map<string, Set<string>>();+ const collectionFolderIds = new Set(+ Array.from(state.assets?.values() ?? []).flatMap((asset) =>+ asset.folderId !== undefined &&+ sourceFolderIds.has(asset.folderId) &&+ formatAssetName(asset) === collectionConfigFilename+ ? [asset.folderId]+ : []+ ));const duplicatedAssets: Asset[] = [];for (const asset of state.assets?.values() ?? []) {@@ -219,17 +228,31 @@ export const duplicateAssetFolder = () {continue;}- const filename = createCopyName(- getAssetDisplayFilename(asset),- (candidate) => displayFilenames.has(candidate)- );- displayFilenames.add(filename);- duplicatedAssets.push({+ const displayFilename = getAssetDisplayFilename(asset);+ const targetFolderId = duplicatedIds.get(asset.folderId)!;+ let logicalFilenames = duplicatedLogicalFilenames.get(targetFolderId);+ if (logicalFilenames === undefined) {+ logicalFilenames = new Set();+ duplicatedLogicalFilenames.set(targetFolderId, logicalFilenames);+ }+ // Collection filenames are part of the folder protocol. In particular,+ // renaming collection.json would silently turn the copied folder into an+ // ordinary folder, while renaming an entry would break its slug identity.+ const filename = collectionFolderIds.has(asset.folderId)+ ? displayFilename+ : createCopyName(displayFilename, (candidate) =>+ logicalFilenames.has(+ formatAssetName({ ...asset, filename: candidate })+ )+ );+ const duplicatedAsset = {...asset,id: context.createId(),filename,- folderId: duplicatedIds.get(asset.folderId),- });+ folderId: targetFolderId,+ };+ logicalFilenames.add(formatAssetName(duplicatedAsset));+ duplicatedAssets.push(duplicatedAsset);}const nextFolders = new Map(folders);diff --git a/packages/project-build/src/runtime/assets.test.ts b/packages/project-build/src/runtime/assets.test.tsindex 0a39a47775..03534c1618 100644--- a/packages/project-build/src/runtime/assets.test.ts+++ b/packages/project-build/src/runtime/assets.test.ts@@ -212,13 +212,18 @@ describe("asset runtime operations", () => {test("duplicates an asset into a target folder with a unique filename", () => {const source = imageAsset("source", "hero.png");- const existingCopy = imageAsset("existing-copy", "other.png");- existingCopy.filename = "hero copy";+ const copyInOtherFolder = imageAsset("other-copy", "other.png");+ copyInOtherFolder.filename = "hero copy";+ copyInOtherFolder.folderId = "other";+ const copyWithOtherExtension = imageAsset("jpg-copy", "other.jpg");+ copyWithOtherExtension.filename = "hero copy";+ copyWithOtherExtension.folderId = "target";const result = duplicateAsset({assets: new Map([[source.id, source],- [existingCopy.id, existingCopy],+ [copyInOtherFolder.id, copyInOtherFolder],+ [copyWithOtherExtension.id, copyWithOtherExtension],]),assetFolders: new Map([[@@ -244,13 +249,100 @@ describe("asset runtime operations", () => {value: {...source,id: "copy",- filename: "hero copy 2",+ filename: "hero copy",folderId: "target",},},]);});+ test("increments a duplicate name only when the full name exists in the target folder", () => {+ const source = imageAsset("source", "hero.png");+ const existingCopy = imageAsset("existing-copy", "other.png");+ existingCopy.filename = "hero copy";+ existingCopy.folderId = "target";++ const result = duplicateAsset(+ {+ assets: new Map([+ [source.id, source],+ [existingCopy.id, existingCopy],+ ]),+ assetFolders: new Map([+ [+ "target",+ {+ id: "target",+ projectId: "project",+ name: "Target",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),+ },+ { assetId: source.id, folderId: "target" },+ { createId: () => "copy", projectId: "project" }+ );++ expect(result.payload[0]?.patches[0]).toEqual({+ op: "add",+ path: ["copy"],+ value: expect.objectContaining({ filename: "hero copy 2" }),+ });+ });++ test("creates a duplicate payload in a collection folder for persistence validation", () => {+ const source = imageAsset("source", "hero.png");+ const collectionConfig: Asset = {+ id: "collection-config",+ projectId: "project",+ name: "collection.json",+ type: "file",+ folderId: "target",+ size: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ format: "json",+ meta: {},+ };++ expect(+ duplicateAsset(+ {+ assets: new Map([+ [source.id, source],+ [collectionConfig.id, collectionConfig],+ ]),+ assetFolders: new Map([+ [+ "target",+ {+ id: "target",+ projectId: "project",+ name: "Target",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),+ },+ { assetId: source.id, folderId: "target" },+ { createId: () => "copy", projectId: "project" }+ )+ ).toMatchObject({+ payload: [+ {+ namespace: "assets",+ patches: [+ {+ op: "add",+ path: ["copy"],+ value: { folderId: "target", filename: "hero copy" },+ },+ ],+ },+ ],+ });+ });+test("lists assets with usage counts", () => {expect(listAssets(state, { sort: "usage" })).toMatchObject({items: [@@ -1089,6 +1181,88 @@ describe("addAsset", () => {)).toThrow("Asset folder not found");});++ test("creates asset payloads in collection folders for persistence validation", () => {+ const collectionConfig: Asset = {+ id: "collection-config",+ projectId: "project",+ name: "collection.json",+ type: "file",+ folderId: "posts",+ size: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ format: "json",+ meta: {},+ };++ expect(+ addAsset(+ {+ assets: new Map([[collectionConfig.id, collectionConfig]]),+ assetFolders: new Map([+ [+ "posts",+ {+ id: "posts",+ projectId: "project",+ name: "Posts",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),+ },+ { asset: { ...assetInput, folderId: "posts" } },+ { projectId: "project" }+ )+ ).toMatchObject({+ payload: [+ {+ namespace: "assets",+ patches: [{ op: "add", value: { ...assetInput, folderId: "posts" } }],+ },+ ],+ });++ expect(+ addAsset(+ {+ assets: new Map([[collectionConfig.id, collectionConfig]]),+ assetFolders: new Map([+ [+ "posts",+ {+ id: "posts",+ projectId: "project",+ name: "Posts",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),+ },+ {+ asset: {+ id: "entry",+ name: "entry.mdx",+ filename: "entry",+ type: "file",+ folderId: "posts",+ size: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ format: "mdx",+ meta: {},+ },+ },+ { projectId: "project" }+ )+ ).toMatchObject({+ payload: [+ {+ namespace: "assets",+ patches: [{ op: "add", value: { id: "entry", folderId: "posts" } }],+ },+ ],+ });+ });});test("creates asset delete payload", () => {@@ -1101,6 +1275,96 @@ test("creates asset delete payload", () => {});describe("updateAsset", () => {+ test("defers MDX filename pattern validation to persistence", () => {+ const entry: Asset = {+ id: "entry",+ projectId: "project",+ name: "hello-world.mdx",+ filename: "hello-world",+ type: "file",+ folderId: "posts",+ size: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ format: "mdx",+ meta: {},+ };+ const collectionConfig: Asset = {+ ...entry,+ id: "collection-config",+ name: "collection.json",+ filename: "collection",+ format: "json",+ };++ expect(+ updateAsset(+ {+ assets: new Map([+ [entry.id, entry],+ [collectionConfig.id, collectionConfig],+ ]),+ },+ { assetId: entry.id, values: { filename: "renamed" } }+ )+ ).toMatchObject({+ payload: [+ {+ namespace: "assets",+ patches: [+ { op: "replace", path: ["entry", "filename"], value: "renamed" },+ ],+ },+ ],+ });+ });++ test("creates a move payload into a collection folder for persistence validation", () => {+ const source = imageAsset("source", "hero.png");+ const collectionConfig: Asset = {+ id: "collection-config",+ projectId: "project",+ name: "collection.json",+ type: "file",+ folderId: "target",+ size: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ format: "json",+ meta: {},+ };++ expect(+ updateAsset(+ {+ assets: new Map([+ [source.id, source],+ [collectionConfig.id, collectionConfig],+ ]),+ assetFolders: new Map([+ [+ "target",+ {+ id: "target",+ projectId: "project",+ name: "Target",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),+ },+ { assetId: source.id, values: { folderId: "target" } }+ )+ ).toMatchObject({+ payload: [+ {+ namespace: "assets",+ patches: [+ { op: "add", path: ["source", "folderId"], value: "target" },+ ],+ },+ ],+ });+ });+test("updates font metadata without discarding the other fields", () => {const result = updateAsset({ assets: new Map([["font-1", fontAsset("font-1")]]) },@@ -1271,6 +1535,89 @@ describe("updateAsset", () => {).toThrow("Filename already used");});+ test("checks renamed full filenames only in the effective target folder", () => {+ const renamed = imageAsset("renamed", "renamed.png");+ renamed.folderId = "source";+ const sameNameElsewhere = imageAsset("elsewhere", "elsewhere.png");+ sameNameElsewhere.filename = "Hero";+ sameNameElsewhere.folderId = "other";+ const sameBasenameOtherExtension = imageAsset(+ "other-extension",+ "file.jpg"+ );+ sameBasenameOtherExtension.filename = "Hero";+ sameBasenameOtherExtension.folderId = "target";++ const result = updateAsset(+ {+ assets: new Map([+ [renamed.id, renamed],+ [sameNameElsewhere.id, sameNameElsewhere],+ [sameBasenameOtherExtension.id, sameBasenameOtherExtension],+ ]),+ assetFolders: new Map([+ [+ "target",+ {+ id: "target",+ projectId: "project",+ name: "Target",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),+ },+ {+ assetId: renamed.id,+ values: { filename: "Hero", folderId: "target" },+ }+ );++ expect(result.payload[0]?.patches).toEqual([+ {+ op: "add",+ path: [renamed.id, "filename"],+ value: "Hero",+ },+ {+ op: "replace",+ path: [renamed.id, "folderId"],+ value: "target",+ },+ ]);+ });++ test("rejects moving an asset onto the same full filename", () => {+ const moved = imageAsset("moved", "hero.png");+ moved.folderId = "source";+ const existing = imageAsset("existing", "different.png");+ existing.filename = "hero";+ existing.folderId = "target";++ expect(() =>+ updateAsset(+ {+ assets: new Map([+ [moved.id, moved],+ [existing.id, existing],+ ]),+ assetFolders: new Map([+ [+ "target",+ {+ id: "target",+ projectId: "project",+ name: "Target",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),+ },+ { assetId: moved.id, values: { folderId: "target" } }+ )+ ).toThrow("Filename already used");+ });+test("moves an asset into an existing folder", () => {const result = updateAsset({diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.tsindex d3a9a732c3..e6484ba5a5 100644--- a/packages/project-build/src/runtime/assets.ts+++ b/packages/project-build/src/runtime/assets.ts@@ -601,6 +601,9 @@ const assertAssetFolderExists = (}};+// Asset metadata alone cannot identify collection entries. Persistence validates+// the resulting files against collection.json; the UI uses its loaded patterns.+export const addAsset = (state: Pick<BuilderState, "assets" | "assetFolders">,input: z.infer<typeof assetAddInput>,@@ -646,14 +649,16 @@ export const duplicateAsset = (: (input.folderId ?? undefined);assertAssetFolderExists(state.assetFolders, folderId);- const displayFilenames = new Set(- Array.from(assets.values(), getAssetDisplayFilename)+ const logicalFilenames = new Set(+ Array.from(assets.values())+ .filter((candidate) => candidate.folderId === folderId)+ .map(formatAssetName));const duplicatedAsset: Asset = {...asset,id: context.createId(),filename: createCopyName(getAssetDisplayFilename(asset), (candidate) =>- displayFilenames.has(candidate)+ logicalFilenames.has(formatAssetName({ ...asset, filename: candidate }))),folderId,};@@ -702,14 +707,6 @@ export const updateAsset = (if (isValidFilename(input.values.filename) === false) {return throwBuilderRuntimeError("BAD_REQUEST", "Invalid filename");}- for (const currentAsset of assets.values()) {- if (- currentAsset.id !== asset.id &&- getAssetDisplayFilename(currentAsset) === input.values.filename- ) {- return throwBuilderRuntimeError("CONFLICT", "Filename already used");- }- }if (asset.filename !== input.values.filename) {appendOptionalPropertyPatch(patches, {path: [asset.id, "filename"],@@ -738,6 +735,27 @@ export const updateAsset = (});}+ const nextFolderId =+ input.values.folderId === null+ ? undefined+ : (input.values.folderId ?? asset.folderId);+ const nextLogicalFilename = formatAssetName({+ ...asset,+ filename: input.values.filename ?? asset.filename,+ });+ if (+ (nextFolderId !== asset.folderId ||+ nextLogicalFilename !== formatAssetName(asset)) &&+ Array.from(assets.values()).some(+ (candidate) =>+ candidate.id !== asset.id &&+ candidate.folderId === nextFolderId &&+ formatAssetName(candidate) === nextLogicalFilename+ )+ ) {+ return throwBuilderRuntimeError("CONFLICT", "Filename already used");+ }+return createRuntimeMutation({payload: patches.length === 0 ? [] : [{ namespace: "assets", patches }],result: { assetId: asset.id },diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.tsindex 2a304f6a6d..aef4d6c5b4 100644--- a/packages/project-build/src/runtime/components.test.ts+++ b/packages/project-build/src/runtime/components.test.ts@@ -1,6 +1,8 @@import { expect, test } from "vitest";import {blockTemplateComponent,+ blockBodyComponent,+ blockComponent,collectionComponent,elementComponent,encodeDataVariableId,@@ -116,6 +118,96 @@ const createIdFactory = () => {return () => `generated-${index++}`;};+test("rejects Add-panel components inside MDX before changing state, but allows shell and unconnected content", () => {+ const block: Instance = {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "mdx" },+ { type: "id", value: "shell" },+ ],+ };+ const state = createState(block);+ state.instances.set("mdx", {+ type: "instance",+ id: "mdx",+ component: blockBodyComponent,+ children: [{ type: "id", value: "paragraph" }],+ });+ state.instances.set("paragraph", {+ type: "instance",+ id: "paragraph",+ component: elementComponent,+ tag: "p",+ children: [],+ });+ state.instances.set("shell", {+ type: "instance",+ id: "shell",+ component: elementComponent,+ tag: "div",+ children: [],+ });+ state.props.set("source", {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "article",+ });+ const original = structuredClone(state);+ const component = "@webstudio-is/sdk-components-react-radix:Accordion";+ for (const parentInstanceId of ["mdx", "paragraph"]) {+ expect(() =>+ insertComponent(+ state,+ { parentInstanceId, component },+ { createId: createIdFactory() }+ )+ ).toThrow("template picker");+ expect(state).toEqual(original);+ }+ expect(+ insertComponent(+ state,+ { parentInstanceId: "shell", component },+ { createId: createIdFactory() }+ ).result.rootInstanceIds+ ).toHaveLength(1);+ expect(+ insertComponent(+ state,+ { parentInstanceId: "mdx", component: elementComponent, tag: "p" },+ { createId: createIdFactory() }+ ).result.rootInstanceIds+ ).toHaveLength(1);+ state.instances.set("templates", {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ });+ block.children = [{ type: "id", value: "templates" }];+ state.instances = new Map(state.instances);+ expect(+ insertComponent(+ state,+ { parentInstanceId: "templates", component },+ { createId: createIdFactory() }+ ).result.rootInstanceIds+ ).toHaveLength(1);+ block.children.push({ type: "id", value: "mdx" });+ state.props.delete("source");+ expect(+ insertComponent(+ state,+ { parentInstanceId: "mdx", component },+ { createId: createIdFactory() }+ ).result.rootInstanceIds+ ).toHaveLength(1);+});+test("assigns a unique name when inserting into a Templates list", async () => {const parent: Instance = {type: "instance",diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.tsindex cdbf057710..b5f1b313d0 100644--- a/packages/project-build/src/runtime/components.ts+++ b/packages/project-build/src/runtime/components.ts@@ -1,6 +1,10 @@import equal from "fast-deep-equal";import {blockTemplateComponent,+ blockBodyComponent,+ blockComponent,+ getContentBlockSource,+ findContentBlockBodyContainers,assignUniqueBlockTemplateNamesMutable,elementComponent,instanceComponent,@@ -71,6 +75,7 @@ import {} from "./matcher";import { z } from "zod";import { getBlockTemplateNameConfirmation } from "./block";+import { hasMdxComponentAdapter } from "./mdx-component-adapters";const conflictResolutionInput = z.enum(["ours", "theirs", "merge"])@@ -1031,6 +1036,48 @@ export const insertComponent = (return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");}+ if (+ input.component !== elementComponent &&+ !hasMdxComponentAdapter(input.component)+ ) {+ const { instanceSelector } = findPageAndSelectorByInstanceId(+ mutationState.pages,+ mutationState.instances,+ parent.id+ );+ let insideBody = false;+ for (const id of instanceSelector) {+ const ancestor = mutationState.instances.get(id);+ if (ancestor?.component === blockTemplateComponent) {+ break;+ }+ if (ancestor?.component === blockBodyComponent) {+ insideBody = true;+ }+ if (ancestor?.component !== blockComponent) {+ continue;+ }+ const source = getContentBlockSource({+ blockInstanceId: id,+ props: mutationState.props.values(),+ });+ if (+ source !== undefined &&+ (insideBody ||+ findContentBlockBodyContainers({+ blockInstance: ancestor,+ instances: mutationState.instances,+ }).length === 0)+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "To add this component to MDX content, add it to this Content Block’s Templates and insert it from the template picker. You can add a one-off instance outside MDX content."+ );+ }+ break;+ }+ }+const templates = getComponentTemplates();const template = templates.get(input.component);const meta = componentMetas.get(input.component);diff --git a/packages/project-build/src/runtime/content-block-application.test.ts b/packages/project-build/src/runtime/content-block-application.test.tsindex e8f54a7933..6091d34b09 100644--- a/packages/project-build/src/runtime/content-block-application.test.ts+++ b/packages/project-build/src/runtime/content-block-application.test.ts@@ -117,6 +117,38 @@ const createFixture = () => {};describe("createContentBlockApplication", () => {+ test("inspects unresolved JSX in a dynamically resolved source context", async () => {+ const { state } = createFixture();+ state.props?.set("src", {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "expression",+ value: "collection.data._id",+ });+ expect(+ getMdxAssetSourceBlockInstanceIds({ assetId: "asset", state })+ ).toEqual([]);+ const diagnostics = await inspectMdxAssetSource({+ source: "<Accordion />",+ assetId: "asset",+ state,+ metas: componentMetas,+ projectId: "project",+ sourceBlockInstanceIds: ["block"],+ });+ expect(diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ templateName: "Accordion",+ blockInstanceId: "block",+ sourceRange: expect.objectContaining({+ start: expect.objectContaining({ offset: 0 }),+ end: expect.objectContaining({ offset: 13 }),+ }),+ }),+ ]);+ });test("inspects an Asset in each resolvable Content Block context", async () => {const fixture = createFixture();fixture.state.dataSources?.set("selectedAsset", {diff --git a/packages/project-build/src/runtime/content-block-application.ts b/packages/project-build/src/runtime/content-block-application.tsindex 09718c2d3b..bef3f00053 100644--- a/packages/project-build/src/runtime/content-block-application.ts+++ b/packages/project-build/src/runtime/content-block-application.ts@@ -95,12 +95,15 @@ export const inspectMdxAssetSource = async ({state,metas,projectId,+ sourceBlockInstanceIds = [],}: {source: string;assetId: string;state: BuilderState;metas: Map<string, WsComponentMeta>;projectId: string;+ /** Source blocks resolved by the caller's live rendering context. */+ sourceBlockInstanceIds?: readonly string[];}) => {const validation = await validateTextAssetSource({ source, format: "mdx" });if (validation.format !== "mdx") {@@ -127,10 +130,11 @@ export const inspectMdxAssetSource = async ({return diagnostics;}const data = getData(state);- for (const blockInstanceId of getMdxAssetSourceBlockInstanceIds({- assetId,- state,- })) {+ const blockInstanceIds = new Set([+ ...getMdxAssetSourceBlockInstanceIds({ assetId, state }),+ ...sourceBlockInstanceIds,+ ]);+ for (const blockInstanceId of blockInstanceIds) {const identity = createContentBlockExternalContentIdentity({blockInstanceId,asset,diff --git a/packages/project-build/src/runtime/content-model.test.tsx b/packages/project-build/src/runtime/content-model.test.tsxindex 1fc02654b3..baf7610a28 100644--- a/packages/project-build/src/runtime/content-model.test.tsx+++ b/packages/project-build/src/runtime/content-model.test.tsx@@ -17,6 +17,7 @@ import {} from "./content-model";const Body = createTemplateComponentFixture("Body");+const BlockTemplate = createTemplateComponentFixture("ws:block-template");const Bold = createTemplateComponentFixture("Bold");const Box = createTemplateComponentFixture("Box");const CodeText = createTemplateComponentFixture("CodeText");@@ -35,6 +36,89 @@ const XmlNode = createTemplateComponentFixture("XmlNode");const defaultMetas = componentMetas;+test.each(["body", "templates", "list-item"])(+ "validates template HTML independently when starting at %s",+ (start) => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="body">+ <ws.block ws:id="block">+ <BlockTemplate ws:id="templates">+ <ws.element ws:tag="li" ws:id="list-item">+ <ws.element ws:tag="p">Item</ws.element>+ </ws.element>+ </BlockTemplate>+ </ws.block>+ </ws.element>+ );+ const selector = ["list-item", "templates", "block", "body"];+ expect(+ isTreeSatisfyingContentModel({+ instances,+ props,+ metas: defaultMetas,+ instanceSelector: selector.slice(selector.indexOf(start)),+ })+ ).toBe(true);+ }+);++test.each(["list", "templates", "box", "paragraph"])(+ "does not inherit a description-list parent into a template from %s",+ (start) => {+ const data = renderData(+ <ws.element ws:tag="dl" ws:id="list">+ <ws.block ws:id="block">+ <BlockTemplate ws:id="templates">+ <ws.element ws:tag="div" ws:id="box">+ <ws.element ws:tag="p" ws:id="paragraph">+ Content+ </ws.element>+ </ws.element>+ </BlockTemplate>+ </ws.block>+ </ws.element>+ );+ const selector = ["paragraph", "box", "templates", "block", "list"];+ expect(+ isTreeSatisfyingContentModel({+ ...data,+ metas: defaultMetas,+ instanceSelector: selector.slice(selector.indexOf(start)),+ })+ ).toBe(true);+ }+);++test.each(["template", "body"])(+ "still rejects invalid list nesting in %s content",+ (location) => {+ const invalid = <ws.element ws:tag="li" ws:id="invalid" />;+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="body">+ <ws.block>+ <BlockTemplate>+ {location === "template" ? (+ <ws.element ws:tag="li">{invalid}</ws.element>+ ) : undefined}+ </BlockTemplate>+ {location === "body" ? invalid : undefined}+ </ws.block>+ </ws.element>+ );+ const errors: string[][] = [];+ expect(+ isTreeSatisfyingContentModel({+ instances,+ props,+ metas: defaultMetas,+ instanceSelector: ["body"],+ onError: (_message, selector) => errors.push(selector),+ })+ ).toBe(false);+ expect(errors[0][0]).toBe("invalid");+ }+);+test("checks direct text capability without promoting the outer rich-text root", () => {const { instances, props } = renderData(<ws.element ws:tag="body" ws:id="bodyId">diff --git a/packages/project-build/src/runtime/content-model.ts b/packages/project-build/src/runtime/content-model.tsindex e3a0e08206..3994df5972 100644--- a/packages/project-build/src/runtime/content-model.ts+++ b/packages/project-build/src/runtime/content-model.ts@@ -1,5 +1,6 @@import { elementsByTag } from "@webstudio-is/html-data";import {+ blockTemplateComponent,elementComponent,getHtmlTagFromInstance,getHtmlTagsFromProps,@@ -199,6 +200,12 @@ const computeAllowedCategories = ({if (instance === undefined) {continue;}+ // Template roots are reusable definitions, not children of the page HTML.+ if (instance.component === blockTemplateComponent) {+ allowedCategories = undefined;+ parentTag = undefined;+ continue;+ }const tag = getTag({ instance, metas, props, htmlTagsByInstanceId });allowedCategories = getElementChildren(tag, allowedCategories, parentTag);// Tagless components do not change the rendered HTML parent.@@ -234,6 +241,13 @@ const findHtmlConstraintInstance = ({if (ancestor === undefined) {continue;}+ if (ancestor.component === blockTemplateComponent) {+ allowedCategories = undefined;+ parentTag = undefined;+ constraintInstance = undefined;+ wasSatisfying = true;+ continue;+ }const ancestorTag = getTag({instance: ancestor,metas,@@ -571,7 +585,10 @@ export const isTreeSatisfyingContentModel = ({htmlTagsByInstanceId,instanceSelector: [child.value, ...instanceSelector],onError,- _allowedCategories: allowedCategories,+ _allowedCategories:+ instance.component === blockTemplateComponent+ ? undefined+ : allowedCategories,_parentTag: tag ?? parentTag,_allowedParentCategories: allowedParentCategories,_allowedAncestorCategories: allowedAncestorCategories,diff --git a/packages/project-build/src/runtime/mdx-authored-content.test.ts b/packages/project-build/src/runtime/mdx-authored-content.test.tsindex c3ee894b40..144f4c3218 100644--- a/packages/project-build/src/runtime/mdx-authored-content.test.ts+++ b/packages/project-build/src/runtime/mdx-authored-content.test.ts@@ -11,6 +11,7 @@ import {type WebstudioFragment,} from "@webstudio-is/sdk";import {+ adoptMdxAuthoredContentFragment,materializeMdxAuthoredContent,MdxAuthoredContentConflictError,rebaseMdxAuthoredContent,@@ -78,7 +79,35 @@ const createCodeTextFragment = (theme = "github-light"): WebstudioFragment => ({});describe("MDX authored content", () => {- test("materializes and round-trips exact registered component JSX", async () => {+ test("adopts a live fragment without unused resolved assets", async () => {+ const root = materializeMdxAuthoredContent({+ identity,+ document: await parseMdxDocument({ source: "Before" }),+ templateMaterialization: emptyTemplates,+ });+ const live = structuredClone(root.fragment);+ root.fragment.assets.push({+ id: "unused",+ projectId: "project",+ name: "author.md",+ type: "file",+ format: "md",+ size: 7,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+ });+ const adopted = adoptMdxAuthoredContentFragment({ root, fragment: live });+ const edited = structuredClone(live);+ edited.instances[0].children = [{ type: "text", value: "After" }];+ expect(+ serializeMdxDocument(+ reconcileMdxAuthoredContent({ root: adopted, fragment: edited })+ )+ ).toBe("After\n");+ });++ test("does not materialize registered JSX without a resolved template", async () => {const source ="<PromotionCard><Heading>Launch offer</Heading></PromotionCard>\n";const document = await parseMdxDocument({ source });@@ -93,19 +122,13 @@ describe("MDX authored content", () => {metas,});- expect(root.fragment.instances).toEqual([- expect.objectContaining({ component: "Heading" }),- expect.objectContaining({- component: "PromotionCard",- children: [{ type: "id", value: expect.any(String) }],- }),- ]);+ expect(root.fragment.instances).toEqual([]);await expect(serializeMdxAuthoredContent({ root, fragment: root.fragment })).resolves.toBe(source);});- test("materializes static props on an exact registered component", async () => {+ test("does not materialize props on registered JSX without a template", async () => {const source = '<Heading tag="h2">Test</Heading>\n';const document = await parseMdxDocument({ source });const root = materializeMdxAuthoredContent({@@ -115,12 +138,8 @@ describe("MDX authored content", () => {metas: componentMetas,});- expect(root.fragment.instances).toEqual([- expect.objectContaining({ component: "Heading" }),- ]);- expect(root.fragment.props).toEqual([- expect.objectContaining({ name: "tag", type: "string", value: "h2" }),- ]);+ expect(root.fragment.instances).toEqual([]);+ expect(root.fragment.props).toEqual([]);await expect(serializeMdxAuthoredContent({ root, fragment: root.fragment })).resolves.toBe(source);@@ -177,6 +196,10 @@ describe("MDX authored content", () => {jsxPropContext: htmlJsxPropContext,propNameMappings: [],ignoredJsxPropNames: [],+ htmlTags: [+ { instanceId: "card", tag: "section" },+ { instanceId: "replaced-child", tag: "p" },+ ],},],diagnostics: [],@@ -187,8 +210,12 @@ describe("MDX authored content", () => {expect(root.fragment.instances[0]?.children).toEqual([{ type: "text", value: "Template default" },]);+ const adopted = adoptMdxAuthoredContentFragment({+ root,+ fragment: root.fragment,+ });await expect(- serializeMdxAuthoredContent({ root, fragment: root.fragment })+ serializeMdxAuthoredContent({ root: adopted, fragment: adopted.fragment })).resolves.toBe("<Card />\n");});@@ -1776,6 +1803,52 @@ describe("MDX authored content", () => {{ type: "id", value: "missing" },{ type: "text", value: "After" },]);+ expect(+ reconcileMdxAuthoredContent({ root, fragment: root.fragment }).children+ ).toMatchObject([+ {+ type: "element",+ children:+ document.children[0].type === "element"+ ? document.children[0].children+ : [],+ },+ ]);+ const live = structuredClone(root.fragment);+ for (const instance of live.instances) {+ if (instance.id === "missing") {+ instance.id = "live-missing";+ }+ instance.children = instance.children.map((child) =>+ child.type === "id" && child.value === "missing"+ ? { ...child, value: "live-missing" }+ : child+ );+ }+ const adopted = adoptMdxAuthoredContentFragment({ root, fragment: live });+ expect(adopted.provenance.unresolvedTemplates[0].markerId).toBe(+ "live-missing"+ );+ const next = structuredClone(adopted.fragment);+ next.instances = next.instances.filter(({ id }) => id !== "live-missing");+ for (const instance of next.instances) {+ instance.children = instance.children.filter(+ (child) => child.type !== "id" || child.value !== "live-missing"+ );+ }+ const result = reconcileMdxAuthoredContent({+ root: adopted,+ fragment: next,+ });+ expect(result.children).toMatchObject([+ {+ type: "element",+ children: [+ { type: "text", value: "Before" },+ { type: "text", value: "After" },+ ],+ },+ ]);});test("keeps an inline comment anchored when adjacent text is deleted", async () => {diff --git a/packages/project-build/src/runtime/mdx-authored-content.ts b/packages/project-build/src/runtime/mdx-authored-content.tsindex 7bb701a91a..8e831d1c9e 100644--- a/packages/project-build/src/runtime/mdx-authored-content.ts+++ b/packages/project-build/src/runtime/mdx-authored-content.ts@@ -22,7 +22,6 @@ import {} from "@webstudio-is/content-engine/jsx-attributes";import {elementComponent,- getComponentByJsxName,getContentBlockMdxTemplateDescriptor,getDefaultContentBlockTemplateName,getStyleDeclKey,@@ -1246,13 +1245,16 @@ export const materializeMdxAuthoredContent = ({preservedJsxPropNames: template.preservedJsxPropNames,ignoredJsxPropNames: template.ignoredJsxPropNames,expandedInstanceIds: resolvedFragment.instances.map(({ id }) => id),- htmlTags:+ htmlTags: (template.htmlTags ??resolvedFragment.instances.flatMap((instance) =>instance.tag === undefined? []: [{ instanceId: instance.id, tag: instance.tag }]- ),+ )+ ).filter(({ instanceId }) =>+ resolvedFragment.instances.some(({ id }) => id === instanceId)+ ),overlaidDescendants,assetProps,namespaceKeys: unsupportedNamespaces.flatMap((namespace) =>@@ -1265,30 +1267,15 @@ export const materializeMdxAuthoredContent = ({children.push({ type: "id", value: rootId });continue;}- const registeredComponent =- node.type === "template" && node.syntax === "jsx" && metas !== undefined- ? getComponentByJsxName({- name: node.name,- components: metas.keys(),- })- : undefined;- const materializedComponent = materializeMdxComponent(- node,- registeredComponent- );+ const materializedComponent = materializeMdxComponent(node);if (materializedComponent !== undefined) {- const isDirectRegisteredComponent =- "authoredChildren" in materializedComponent;const createId = createMdxScopeIdGenerator({ identity, path });const instanceId = createId();const instance: Instance = {type: "instance",id: instanceId,component: materializedComponent.component,- children:- "authoredChildren" in materializedComponent- ? visit(node.children, path)- : materializedComponent.children,+ children: materializedComponent.children,};fragment.instances.push(instance);const componentData =@@ -1450,19 +1437,8 @@ export const materializeMdxAuthoredContent = ({assetId: assetReference?.assetId,});} else {- const declaredType = metas?.get(instance.component)?.props?.[- instanceProp.name- ]?.type;- const directBinding =- isDirectRegisteredComponent &&- (declaredType === "string" ||- declaredType === "number" ||- declaredType === "boolean")- ? parseMdxStaticProp({ prop: instanceProp, type: declaredType })- : undefined;const binding =- directBinding ??- (assetReference === undefined+ assetReference === undefined? getMdxPropBinding({capabilities: componentCapabilities,instance,@@ -1476,7 +1452,7 @@ export const materializeMdxAuthoredContent = ({jsxPropName,}).editable? { type: "asset" as const, value: assetReference.assetId }- : undefined);+ : undefined;if (binding === undefined) {const eligibility = getMdxPropEligibility({capabilities: componentCapabilities,@@ -1694,6 +1670,29 @@ export const adoptMdxAuthoredContentFragment = ({}const propIds = new Map<string, string>();+ const inheritedPropIds = new Set<string>();+ for (const node of root.provenance.nodes) {+ if (node.type !== "template") {+ continue;+ }+ const authoredNames = new Set(+ node.authoredPropNames.map(+ (name) =>+ node.propNameMappings.find(({ jsxPropName }) => jsxPropName === name)+ ?.instancePropName ?? name+ )+ );+ for (const prop of root.fragment.props) {+ if (+ node.expandedInstanceIds.includes(prop.instanceId) &&+ (prop.instanceId === node.instanceId+ ? authoredNames.has(prop.name) === false+ : node.overridesTemplateChildren === false)+ ) {+ inheritedPropIds.add(prop.id);+ }+ }+ }const unusedTargetProps = new Set(fragment.props.map(({ id }) => id));for (const source of root.fragment.props) {const targetInstanceId = instanceIds.get(source.instanceId);@@ -1705,6 +1704,11 @@ export const adoptMdxAuthoredContentFragment = ({candidate.type === source.type);if (target === undefined) {+ // Content-mode cloning omits noneditable template defaults. They remain+ // inherited from the template, not authored overrides in the MDX file.+ if (inheritedPropIds.has(source.id)) {+ continue;+ }throw new Error("Live MDX fragment props do not match its document");}propIds.set(source.id, target.id);@@ -1716,6 +1720,31 @@ export const adoptMdxAuthoredContentFragment = ({const namespaceKeys = new Map<string, string>();for (const namespace of unsupportedNamespaces) {+ if (namespace === "assets") {+ // Resolved frontmatter and template defaults can load assets that the+ // rendered body never uses. Assets retain their project IDs, unlike+ // cloned instances and styles.+ const sourceAssets = new Map(+ root.fragment.assets.map((asset) => [asset.id, asset])+ );+ const targetAssets = new Map(+ fragment.assets.map((asset) => [asset.id, asset])+ );+ if (+ fragment.assets.some(+ (asset) => !equal(sourceAssets.get(asset.id), asset)+ ) ||+ fragment.props.some(+ (prop) => prop.type === "asset" && !targetAssets.has(prop.value)+ )+ ) {+ throw new Error("Live MDX fragment assets do not match its document");+ }+ for (const asset of root.fragment.assets) {+ namespaceKeys.set(`assets:${asset.id}`, asset.id);+ }+ continue;+ }const sourceRecords = root.fragment[namespace];const targetRecords = fragment[namespace];if (sourceRecords.length !== targetRecords.length) {@@ -1759,6 +1788,12 @@ export const adoptMdxAuthoredContentFragment = ({fragment,provenance: {...root.provenance,+ unresolvedTemplates: root.provenance.unresolvedTemplates.map(+ (reference) => ({+ ...reference,+ markerId: instanceIds.get(reference.markerId) ?? reference.markerId,+ })+ ),nodes: root.provenance.nodes.map((node) =>node.type === "element"? {@@ -1891,10 +1926,6 @@ const assertSupportedNamespaces = ({nextKeys.length !== nextKeySet.size ||Array.from(originalByKey.keys()).some((key) => !nextKeySet.has(key) && !removableKeys.has(key)- ) ||- !equal(- nextKeys,- Array.from(originalByKey.keys()).filter((key) => nextKeySet.has(key)))) {throw new Error(@@ -1994,6 +2025,14 @@ export const reconcileMdxAuthoredContent = ({const originalInstanceById = new Map(root.fragment.instances.map((instance) => [instance.id, instance]));+ const unresolvedById = new Map(+ root.provenance.unresolvedTemplates+ .filter(({ markerId }) => originalInstanceById.has(markerId))+ .map((reference) => [reference.markerId, reference])+ );+ const unresolvedPaths = new Set(+ Array.from(unresolvedById.values(), ({ path }) => pathKey(path))+ );const indexPropsByInstanceId = (props: readonly Prop[]) => {const index = new Map<Instance["id"], Prop[]>();for (const prop of props) {@@ -2295,6 +2334,20 @@ export const reconcileMdxAuthoredContent = ({if (instance === undefined) {throw new Error(`Authored MDX instance "${instanceId}" is missing`);}+ const unresolved = unresolvedById.get(instanceId);+ if (unresolved !== undefined) {+ if (serializedInstanceIds.has(instanceId)) {+ throw new Error(`Authored MDX instance "${instanceId}" is reused`);+ }+ const original = originalNodeByPath.get(pathKey(unresolved.path));+ if (original === undefined) {+ throw new Error(+ "Missing template placeholder has no authored MDX node"+ );+ }+ serializedInstanceIds.add(instanceId);+ return original;+ }const provenance = provenanceById.get(instanceId);if (provenance?.type === "template") {if (serializedInstanceIds.has(instanceId)) {@@ -3031,7 +3084,9 @@ export const reconcileMdxAuthoredContent = ({}const provenance = provenanceById.get(child.value);const authoredPath =- provenance?.path ?? overlaidDescendantById.get(child.value)?.path;+ provenance?.path ??+ overlaidDescendantById.get(child.value)?.path ??+ unresolvedById.get(child.value)?.path;return {key:authoredPath === undefined@@ -3057,7 +3112,10 @@ export const reconcileMdxAuthoredContent = ({const key =node.type === "text"? `text:${index}`- : provenance === undefined && isOverlaidDescendant === false+ : provenance === undefined &&+ isOverlaidDescendant === false &&+ (originalPath === undefined ||+ unresolvedPaths.has(originalPath) === false)? undefined: `node:${originalPath}`;if (key !== undefined && surviving.has(key)) {diff --git a/packages/project-build/src/runtime/mdx-component-adapters.ts b/packages/project-build/src/runtime/mdx-component-adapters.tsindex f88443f88b..a0a4c2e7f1 100644--- a/packages/project-build/src/runtime/mdx-component-adapters.ts+++ b/packages/project-build/src/runtime/mdx-component-adapters.ts@@ -537,10 +537,7 @@ export const serializeMdxComponentFallback = ({};};-export const materializeMdxComponent = (- node: MdxAuthoredNode,- registeredComponent?: Instance["component"]-) => {+export const materializeMdxComponent = (node: MdxAuthoredNode) => {if (node.type === "template") {if (node.syntax !== "jsx") {return;@@ -550,14 +547,6 @@ export const materializeMdxComponent = (if (component !== undefined && adapter !== undefined) {return { ...component, component: adapter.component };}- if (registeredComponent !== undefined) {- return {- component: registeredComponent,- children: [] as Instance["children"],- props: materializeNamedProps(node.props),- authoredChildren: true as const,- };- }return;}for (const adapter of componentAdapters.values()) {diff --git a/packages/project-build/src/runtime/mdx-namespace-order.test.ts b/packages/project-build/src/runtime/mdx-namespace-order.test.tsnew file mode 100644index 0000000000..c1ff03a968--- /dev/null+++ b/packages/project-build/src/runtime/mdx-namespace-order.test.ts@@ -0,0 +1,103 @@+import { expect, test } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type WebstudioData,+} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { materializeMdxSource } from "./mdx-source";+import { serializeMdxAuthoredContent } from "./mdx-authored-content";++test("saves content when extracting template records changes their map order", async () => {+ const data: Omit<WebstudioData, "pages"> = {+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [+ { type: "id", value: "heading" },+ { type: "id", value: "paragraph" },+ ],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: elementComponent,+ tag: "h2",+ children: [],+ },+ ],+ [+ "paragraph",+ {+ type: "instance",+ id: "paragraph",+ component: elementComponent,+ tag: "p",+ children: [],+ },+ ],+ ]),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ assets: new Map(),+ breakpoints: new Map(),+ styles: new Map(),+ styleSources: new Map([+ ["heading-style", { type: "local", id: "heading-style" }],+ ["paragraph-style", { type: "local", id: "paragraph-style" }],+ ]),+ styleSourceSelections: new Map([+ ["heading", { instanceId: "heading", values: ["heading-style"] }],+ ["paragraph", { instanceId: "paragraph", values: ["paragraph-style"] }],+ ]),+ };+ const { root } = await materializeMdxSource({+ source: "## Heading\n\nParagraph",+ identity: {+ blockInstanceId: "block",+ assetId: "article",+ revision: "one",+ contentRef: "article.mdx",+ format: "mdx",+ renderScope: "page",+ },+ data,+ metas: componentMetas,+ projectId: "project",+ });+ const fragment = structuredClone(root.fragment);+ expect(fragment.styleSourceSelections).toHaveLength(2);+ fragment.styleSourceSelections.reverse();+ fragment.styleSources.reverse();+ fragment.instances.find(({ tag }) => tag === "h2")!.children = [+ { type: "text", value: "Updated heading" },+ ];+ const source = await serializeMdxAuthoredContent({ root, fragment });+ expect(source).toContain("Updated heading");+ expect(source).toContain("Paragraph");+ expect(source).not.toContain("heading-style");++ // Changing selections themselves must still be rejected, not silently lost.+ fragment.styleSourceSelections[0].values.push("another-style");+ await expect(serializeMdxAuthoredContent({ root, fragment })).rejects.toThrow(+ "Changes to styleSourceSelections"+ );+});diff --git a/packages/project-build/src/runtime/mdx-template-resolution.test.ts b/packages/project-build/src/runtime/mdx-template-resolution.test.tsindex 4d3f0810f9..3615b3787d 100644--- a/packages/project-build/src/runtime/mdx-template-resolution.test.ts+++ b/packages/project-build/src/runtime/mdx-template-resolution.test.ts@@ -384,7 +384,7 @@ describe("resolveMdxTemplates", () => {]);});- test("resolves templates nested inside a direct registered component", async () => {+ test("requires a template even for registered JSX and does not render its descendants", async () => {const instances = createInstances();instances.set("heading-2",@@ -395,32 +395,33 @@ describe("resolveMdxTemplates", () => {value: "heading-2",});const document = await parseMdxDocument({- source: "<Box><h2>Nested</h2><Missing /></Box>\n",+ source: "<Accordion><h2>Nested</h2><Missing /></Accordion>\n",});const result = resolveMdxTemplates({document,identity,instances,- metas: new Map([...metas, ["Box", { label: "Box" }]]),+ metas: new Map([+ ...metas,+ [+ "@webstudio-is/sdk-components-react-radix:Accordion",+ { label: "Accordion" },+ ],+ ]),});expect(result.references).toEqual([- expect.objectContaining({- type: "resolved-template",- path: [0, 0],- templateInstanceId: "heading-2",- }),expect.objectContaining({type: "unresolved-template",- path: [0, 1],- templateName: "Missing",+ path: [0],+ templateName: "Accordion",}),]);expect(result.diagnostics).toEqual([expect.objectContaining({code: "unresolved-template",- templateName: "Missing",+ templateName: "Accordion",}),]);});diff --git a/packages/project-build/src/runtime/mdx-template-resolution.ts b/packages/project-build/src/runtime/mdx-template-resolution.tsindex bd2fb83b2e..94ace5257c 100644--- a/packages/project-build/src/runtime/mdx-template-resolution.ts+++ b/packages/project-build/src/runtime/mdx-template-resolution.ts@@ -10,7 +10,6 @@ import type {import {findContentBlockTemplateContainers,getContentBlockTemplateName,- getComponentByJsxName,getHtmlTagsFromProps,type ContentBlockDiagnostic,type ContentBlockExternalContentIdentity,@@ -268,16 +267,6 @@ export const resolveMdxTemplates = ({if (standard?.key.startsWith("component:") === true) {continue;}- if (- node.syntax === "jsx" &&- getComponentByJsxName({- name: node.name,- components: metas.keys(),- }) !== undefined- ) {- visit(node.children, path);- continue;- }references.push({type: "unresolved-template",path,diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.tsindex 5de30f235e..8bb42bc181 100644--- a/packages/project/src/db/build-patch.test.ts+++ b/packages/project/src/db/build-patch.test.ts@@ -257,6 +257,11 @@ describe("patchBuild", () => {buildId: "build-1",projectId: "project-1",clientVersion: 3,+ assetStore: {+ readFile: async () => {+ throw new Error("Unexpected asset content read");+ },+ },transactions: [transaction({payload: [diff --git a/packages/project/src/db/build-patch.ts b/packages/project/src/db/build-patch.tsindex 5583a4ff20..6de3508ebf 100644--- a/packages/project/src/db/build-patch.ts+++ b/packages/project/src/db/build-patch.ts@@ -2,6 +2,7 @@ import {deleteAssetFoldersWithClient,patchAssetFoldersWithClient,patchAssets,+ type AssetObjectReader,} from "@webstudio-is/asset-uploader/server";import type { Build } from "@webstudio-is/project-build";import { loadRawBuildById } from "@webstudio-is/project-build/server";@@ -39,12 +40,14 @@ export const patchLoadedBuild = async (projectId,transactions,clientVersion,+ assetStore,}: {build: Database["public"]["Tables"]["Build"]["Row"];buildId: Build["id"];projectId: Project["id"];transactions: BuildPatchTransaction[];clientVersion: number;+ assetStore?: AssetObjectReader;},context: AppContext): Promise<PatchLoadedBuildResult> => {@@ -62,7 +65,9 @@ export const patchLoadedBuild = async (return { status: "ok", version: result.nextVersion, build };}const buildUpdate = result.update;-+ if (result.assetPatches.length > 0 && assetStore === undefined) {+ throw new Error("Asset object storage is required to patch assets");+ }// build.patch does not have the worker's atomic Build+asset commit path.// Apply app-side asset mutations before marking the Build with// lastTransactionId so a failed asset mutation is not later treated as an@@ -76,7 +81,11 @@ export const patchLoadedBuild = async ({ deferDeletes: true });if (result.assetPatches.length > 0) {- await patchAssets({ projectId }, result.assetPatches.flat(), context);+ await patchAssets(+ { projectId, assetStore: assetStore! },+ result.assetPatches.flat(),+ context+ );}await deleteAssetFoldersWithClient({ projectId, ids: deletedAssetFolderIds },@@ -125,17 +134,19 @@ export const patchBuild = async (projectId,transactions,clientVersion,+ assetStore,}: {buildId: Build["id"];projectId: Project["id"];transactions: BuildPatchTransaction[];clientVersion: number;+ assetStore?: AssetObjectReader;},context: AppContext): Promise<PatchBuildResult> => {const build = await loadRawBuildById(context, buildId);const result = await patchLoadedBuild(- { build, buildId, projectId, transactions, clientVersion },+ { build, buildId, projectId, transactions, clientVersion, assetStore },context);diff --git a/packages/query-builder-react/src/index.browser.test.tsx b/packages/query-builder-react/src/index.browser.test.tsxindex b009fdb8ac..75f468aab4 100644--- a/packages/query-builder-react/src/index.browser.test.tsx+++ b/packages/query-builder-react/src/index.browser.test.tsx@@ -1,6 +1,7 @@import { useState } from "react";import { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, describe, expect, test } from "vitest";+import { userEvent } from "@vitest/browser/context";import {createStructuredQuery,type QueryDefinition,@@ -481,4 +482,38 @@ describe("structured query builder", () => {expect(screen.getByText("File content")).toBeTruthy();expect(screen.getByRole("separator")).toBeTruthy();});++ test("keeps a long Output menu within the viewport and scrolls to its last option", async () => {+ const capabilities = {+ ...selectionCapabilities,+ fields: Array.from({ length: 100 }, (_, index) => ({+ path: [`field${index}`],+ label: `Field ${index}`,+ types: ["string" as const],+ })),+ };+ render(+ <StructuredQueryBuilder+ value={createStructuredQuery(capabilities)}+ capabilities={capabilities}+ onChange={() => {}}+ />+ );+ await userEvent.click(screen.getByLabelText("Add output"));+ const menu = screen.getByRole("menu");+ await expect+ .poll(() => menu.getBoundingClientRect().top)+ .toBeGreaterThanOrEqual(0);+ expect(menu.getBoundingClientRect().bottom).toBeLessThanOrEqual(+ window.innerHeight+ );+ expect(menu.scrollHeight).toBeGreaterThan(menu.clientHeight);+ await userEvent.keyboard("{End}");+ const lastOption = screen.getByRole("menuitem", { name: "Field 99" });+ expect(document.activeElement).toBe(lastOption);+ await expect.poll(() => menu.scrollTop).toBeGreaterThan(0);+ expect(lastOption.getBoundingClientRect().bottom).toBeLessThanOrEqual(+ menu.getBoundingClientRect().bottom+ );+ });});diff --git a/packages/query-builder-react/src/index.tsx b/packages/query-builder-react/src/index.tsxindex ec3ebbd3cf..da23c3def7 100644--- a/packages/query-builder-react/src/index.tsx+++ b/packages/query-builder-react/src/index.tsx@@ -833,7 +833,15 @@ const QueryParameters = ({icon={<PlusIcon />}/></DropdownMenuTrigger>- <DropdownMenuContent align="end" sideOffset={4}>+ <DropdownMenuContent+ align="end"+ sideOffset={4}+ css={{+ maxHeight:+ "var(--radix-dropdown-menu-content-available-height)",+ overflowY: "auto",+ }}+ >{selectionParameters.map((parameter, index) => (<Fragment key={parameter.key}>{index > 0 && <DropdownMenuSeparator />}diff --git a/packages/sdk-components-react/src/time.ws.ts b/packages/sdk-components-react/src/time.ws.tsindex f09b5d97dd..158a2e4644 100644--- a/packages/sdk-components-react/src/time.ws.ts+++ b/packages/sdk-components-react/src/time.ws.ts@@ -26,7 +26,7 @@ export const meta: WsComponentMeta = {...props,datetime: {type: "string",- control: "text",+ control: "date",required: false,contentMode: true,},diff --git a/packages/sdk-components-registry/src/core-templates.test.tsx b/packages/sdk-components-registry/src/core-templates.test.tsxindex 6b31cd2456..04c215d8b4 100644--- a/packages/sdk-components-registry/src/core-templates.test.tsx+++ b/packages/sdk-components-registry/src/core-templates.test.tsx@@ -2,6 +2,7 @@import { expect, test } from "vitest";import {blockComponent,+ blockBodyComponent,blockTemplateComponent,contentBlockMdxTemplateDescriptors,getContentBlockMdxTemplateDescriptor,@@ -33,6 +34,24 @@ const expectCodeTextDefaultsToStayImplicit = ().toEqual([]);};+test("creates unconnected Content Blocks with direct content and no MDX Body wrapper", () => {+ const fragment = renderCoreTemplate(coreTemplates[blockComponent]);+ expect(+ fragment.instances.some(({ component }) => component === blockBodyComponent)+ ).toBe(false);+ const block = fragment.instances.find(+ ({ component }) => component === blockComponent+ )!;+ const children = block.children.map((child) =>+ fragment.instances.find(({ id }) => id === child.value)+ );+ expect(children[0]?.component).toBe(blockTemplateComponent);+ expect(children.slice(1).map((instance) => instance?.tag)).toEqual([+ "p",+ "ul",+ ]);+});+test("keeps Code Text defaults out of standalone and Content Block props", () => {expectCodeTextDefaultsToStayImplicit(coreTemplates.code_text);expectCodeTextDefaultsToStayImplicit(coreTemplates[blockComponent]);diff --git a/packages/sdk-components-registry/src/core-templates.tsx b/packages/sdk-components-registry/src/core-templates.tsxindex 60350b29ff..4a8bbad43d 100644--- a/packages/sdk-components-registry/src/core-templates.tsx+++ b/packages/sdk-components-registry/src/core-templates.tsx@@ -26,7 +26,6 @@ import {import { componentsById } from "./components";const BlockTemplate = ws.blockTemplate;-const BlockBody = ws.contentBlockBody;const blockDocument = new Parameter(contentBlockDocumentProp);const listItemMdxTemplateDescriptor = contentBlockMdxTemplateDescriptors.find(@@ -105,29 +104,27 @@ const blockMeta: TemplateMeta = {{ label: "Templates" },<BlockTemplate>{contentBlockDefaultTemplates}</BlockTemplate>)}- <BlockBody>- <p>- The Content Block component designates regions on the page where- pre-styled instances can be inserted in{" "}- <a href="https://wstd.us/content-block">Content mode</a>.- </p>- <ul>- <li>- In Content mode, you can edit content inside this Content Block and- add new instances predefined in templates. Content outside Content- Blocks is read-only.- </li>- <li>- To predefine instances for insertion in Content mode, switch to- Design mode and add them to the Templates container.- </li>- <li>- To insert predefined instances in Content mode, click the + button- while hovering over the Content Block on the canvas and choose an- instance from the list.- </li>- </ul>- </BlockBody>+ <p>+ The Content Block component designates regions on the page where+ pre-styled instances can be inserted in{" "}+ <a href="https://wstd.us/content-block">Content mode</a>.+ </p>+ <ul>+ <li>+ In Content mode, you can edit content inside this Content Block and+ add new instances predefined in templates. Content outside Content+ Blocks is read-only.+ </li>+ <li>+ To predefine instances for insertion in Content mode, switch to Design+ mode and add them to the Templates container.+ </li>+ <li>+ To insert predefined instances in Content mode, click the + button+ while hovering over the Content Block on the canvas and choose an+ instance from the list.+ </li>+ </ul></ws.block>),};diff --git a/packages/sdk/src/content-block.test.ts b/packages/sdk/src/content-block.test.tsindex 893e66c750..41336d4385 100644--- a/packages/sdk/src/content-block.test.ts+++ b/packages/sdk/src/content-block.test.ts@@ -185,56 +185,59 @@ describe("Content Block source", () => {).toEqual([[shell, body]]);});- test("recognizes only direct document frontmatter bindings", () => {- const document = encodeDataSourceVariable("document-id");- expect(- getWritableContentBlockDocumentBinding({- binding: {- type: "expression",- value: `${document}.frontmatter.author.name`,- mode: "readwrite",- },- documentDataSourceId: "document-id",- })- ).toEqual({- type: "writable-content-block-document-binding",- expression: {- type: "direct-path",- expression: `${document}.frontmatter.author.name`,- path: [document, "frontmatter", "author", "name"],- },- frontmatterPath: ["author", "name"],- });- expect(- getWritableContentBlockDocumentBinding({- binding: {- type: "expression",- value: `${document}.frontmatter.title ?? "Untitled"`,- mode: "readwrite",- },- documentDataSourceId: "document-id",- })- ).toBeUndefined();- expect(- getWritableContentBlockDocumentBinding({- binding: {- type: "expression",- value: `${document}.frontmatter.title`,- },- documentDataSourceId: "document-id",- })- ).toBeUndefined();- expect(- getWritableContentBlockDocumentBinding({- binding: {- type: "expression",- value: `${document}.frontmatter["__proto__"].polluted`,- mode: "readwrite",+ test.each([".author.name", ".author?.name"])(+ "recognizes direct document frontmatter binding %s",+ (suffix) => {+ const document = encodeDataSourceVariable("document-id");+ expect(+ getWritableContentBlockDocumentBinding({+ binding: {+ type: "expression",+ value: `${document}.frontmatter${suffix}`,+ mode: "readwrite",+ },+ documentDataSourceId: "document-id",+ })+ ).toEqual({+ type: "writable-content-block-document-binding",+ expression: {+ type: "direct-path",+ expression: `${document}.frontmatter${suffix}`,+ path: [document, "frontmatter", "author", "name"],},- documentDataSourceId: "document-id",- })- ).toBeUndefined();- });+ frontmatterPath: ["author", "name"],+ });+ expect(+ getWritableContentBlockDocumentBinding({+ binding: {+ type: "expression",+ value: `${document}.frontmatter.title ?? "Untitled"`,+ mode: "readwrite",+ },+ documentDataSourceId: "document-id",+ })+ ).toBeUndefined();+ expect(+ getWritableContentBlockDocumentBinding({+ binding: {+ type: "expression",+ value: `${document}.frontmatter.title`,+ },+ documentDataSourceId: "document-id",+ })+ ).toBeUndefined();+ expect(+ getWritableContentBlockDocumentBinding({+ binding: {+ type: "expression",+ value: `${document}.frontmatter["__proto__"].polluted`,+ mode: "readwrite",+ },+ documentDataSourceId: "document-id",+ })+ ).toBeUndefined();+ }+ );test("finds direct document bindings inside a connected Content Block", () => {const document = encodeDataSourceVariable("document-id");diff --git a/packages/sdk/src/schema/expression.test.ts b/packages/sdk/src/schema/expression.test.tsindex 1c78dac287..30864a822b 100644--- a/packages/sdk/src/schema/expression.test.ts+++ b/packages/sdk/src/schema/expression.test.ts@@ -54,6 +54,6 @@ describe("expression binding mode", () => {value: "document?.frontmatter.title",mode: "readwrite",}).success- ).toBe(false);+ ).toBe(true);});});diff --git a/packages/sdk/src/schema/prop-meta.ts b/packages/sdk/src/schema/prop-meta.tsindex fde2b9b5f0..5bd0b0f926 100644--- a/packages/sdk/src/schema/prop-meta.ts+++ b/packages/sdk/src/schema/prop-meta.ts@@ -179,13 +179,11 @@ const json = z.object({defaultValue: z.unknown().optional(),});-// we neither generate date nor support it in props panel, listed here for completenessconst date = z.object({...common,control: z.literal("date"),- // @todo not sure what type should be here- // (we don't support Date yet, added for completeness)+ // Dates are stored as strings, not JavaScript Date objects.type: z.literal("string"),defaultValue: z.string().optional(),});diff --git a/packages/sync-client/src/transaction-completion.test.ts b/packages/sync-client/src/transaction-completion.test.tsindex 124d4f2f5a..8893a36bb8 100644--- a/packages/sync-client/src/transaction-completion.test.ts+++ b/packages/sync-client/src/transaction-completion.test.ts@@ -32,6 +32,21 @@ describe("createTransactionCompletionStore", () => {expect(callback).toHaveBeenCalledOnce();});+ test("subscribes only to the current transaction when one exists", () => {+ const store = createTransactionCompletionStore();+ const callback = vi.fn();++ store.$lastTransactionId.set("tx-current");+ store.onNextTransactionComplete(callback);+ store.$lastTransactionId.set("tx-next");++ store.completeTransaction("tx-current", true);+ expect(callback).toHaveBeenCalledOnce();++ store.completeTransaction("tx-next", true);+ expect(callback).toHaveBeenCalledOnce();+ });+test("removes stale callbacks after timeout", () => {vi.useFakeTimers();const store = createTransactionCompletionStore();diff --git a/packages/sync-client/src/transaction-completion.ts b/packages/sync-client/src/transaction-completion.tsindex b6d9f876c1..ed3b387837 100644--- a/packages/sync-client/src/transaction-completion.ts+++ b/packages/sync-client/src/transaction-completion.ts@@ -24,38 +24,73 @@ export const createTransactionCompletionStore = ({callbacks.set(transactionId, transactionCallbacks);scheduleTimeout(() => {- callbacks.delete(transactionId);+ const currentCallbacks = callbacks.get(transactionId);+ if (currentCallbacks === undefined) {+ return;+ }+ const callbackIndex = currentCallbacks.indexOf(callback);+ if (callbackIndex === -1) {+ return;+ }+ const remainingCallbacks = [...currentCallbacks];+ remainingCallbacks.splice(callbackIndex, 1);+ if (remainingCallbacks.length === 0) {+ callbacks.delete(transactionId);+ } else {+ callbacks.set(transactionId, remainingCallbacks);+ }});};const onNextTransactionComplete = (callback: () => void) => {- let unsubscribe: (() => void) | undefined;- unsubscribe = $lastTransactionId.subscribe((transactionId) => {- if (transactionId === undefined) {+ let settled = false;+ let unsubscribe = () => {};+ const settle = (success: boolean) => {+ if (settled) {return;}- onTransactionComplete(transactionId, (success) => {- if (success) {- callback();+ settled = true;+ unsubscribe();+ if (success) {+ callback();+ }+ };+ const register = (transactionId: string) => {+ onTransactionComplete(transactionId, settle);+ };+ const currentTransactionId = $lastTransactionId.get();+ if (currentTransactionId !== undefined) {+ register(currentTransactionId);+ } else {+ unsubscribe = $lastTransactionId.listen((transactionId) => {+ if (transactionId === undefined) {+ return;}+ register(transactionId);+ unsubscribe();});- unsubscribe?.();- });+ }scheduleTimeout(() => {- unsubscribe?.();+ settle(false);});+ return () => {+ settled = true;+ unsubscribe();+ };};const completeTransaction = (transactionId: string, success: boolean) => {const transactionCallbacks = callbacks.get(transactionId);- if (transactionCallbacks === undefined) {- return;+ callbacks.delete(transactionId);+ if ($lastTransactionId.get() === transactionId) {+ $lastTransactionId.set(undefined);}- for (const callback of transactionCallbacks) {- callback(success);+ if (transactionCallbacks !== undefined) {+ for (const callback of transactionCallbacks) {+ callback(success);+ }}- callbacks.delete(transactionId);};const clear = () => {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d2d4672510..df2c0274dd 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1531,6 +1531,9 @@ importers:'@webstudio-is/query-builder':specifier: workspace:*version: link:../query-builder+ ajv:+ specifier: 8.20.0+ version: 8.20.0canonicalize:specifier: 3.0.0version: 3.0.0@@ -1588,6 +1591,9 @@ importers:unified:specifier: 10.1.2version: 10.1.2+ urlpattern-polyfill:+ specifier: ^10.1.0+ version: 10.1.0yaml:specifier: 2.9.0version: 2.9.0