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: Make Content Block templates the MDX authoring interface (#6307)
Oleg Isonen05706b54255d
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 600d146bae..2f2a8e1a24 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -482,9 +482,6 @@ export const Builder = (props: BuilderProps) => {><Inspector navigatorLayout={navigatorLayout} /></SidePanel>- <Main css={{ pointerEvents: "none" }}>- <CanvasToolsContainer />- </Main>{project ? (<Topbarproject={project}diff --git a/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx b/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsxindex c71bb140cd..f0ae5ae96a 100644--- a/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx@@ -3,7 +3,10 @@ import { coreMetas, elementComponent } from "@webstudio-is/sdk";import * as baseMetas from "@webstudio-is/sdk-components-react/metas";import * as animationMetas from "@webstudio-is/sdk-components-animation/metas";import { createDefaultPages } from "@webstudio-is/project-build";-import { $, renderData } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+} from "@webstudio-is/template";import { $registeredComponentMetas } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import { $pages, $props } from "~/shared/sync/data-stores";@@ -12,6 +15,11 @@ import { $selectedPageId } from "~/shared/nano-states";import { selectInstance } from "~/shared/nano-states";import { canWrapInstance } from "@webstudio-is/project-build/runtime";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const ListItem = createTemplateComponentFixture("ListItem");+const Text = createTemplateComponentFixture("Text");+registerContainers();const metas = new Map(@@ -28,9 +36,9 @@ describe("canWrapInstance for components", () => {test("should allow wrapping text in a Link", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Text ws:id="text">Hello</$.Text>- </$.Body>+ <Body ws:id="body">+ <Text ws:id="text">Hello</Text>+ </Body>).instances);selectInstance(["text", "body"]);@@ -51,9 +59,9 @@ describe("canWrapInstance for components", () => {test("should allow wrapping text in a Heading", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Text ws:id="text">Hello</$.Text>- </$.Body>+ <Body ws:id="body">+ <Text ws:id="text">Hello</Text>+ </Body>).instances);selectInstance(["text", "body"]);@@ -74,9 +82,9 @@ describe("canWrapInstance for components", () => {test("should allow wrapping box in a Form", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>).instances);selectInstance(["box", "body"]);@@ -97,9 +105,9 @@ describe("canWrapInstance for components", () => {test("should prevent wrapping an instance in CodeText", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Text ws:id="text">Hello</$.Text>- </$.Body>+ <Body ws:id="body">+ <Text ws:id="text">Hello</Text>+ </Body>).instances);selectInstance(["text", "body"]);@@ -122,9 +130,9 @@ describe("canWrapInstance for HTML elements", () => {test("should allow wrapping text in a span", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Text ws:id="text">Hello</$.Text>- </$.Body>+ <Body ws:id="body">+ <Text ws:id="text">Hello</Text>+ </Body>).instances);selectInstance(["text", "body"]);@@ -145,9 +153,9 @@ describe("canWrapInstance for HTML elements", () => {test("should allow wrapping box in a div", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>).instances);selectInstance(["box", "body"]);@@ -168,9 +176,9 @@ describe("canWrapInstance for HTML elements", () => {test("should allow wrapping box in span (content model allows it)", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>).instances);selectInstance(["box", "body"]);@@ -193,9 +201,9 @@ describe("canWrapInstance for HTML elements", () => {test("should allow wrapping list item in ul", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.ListItem ws:id="li">Item</$.ListItem>- </$.Body>+ <Body ws:id="body">+ <ListItem ws:id="li">Item</ListItem>+ </Body>).instances);selectInstance(["li", "body"]);@@ -216,9 +224,9 @@ describe("canWrapInstance for HTML elements", () => {test("should reject wrapping box in ul (ul requires li children)", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>).instances);selectInstance(["box", "body"]);@@ -242,9 +250,9 @@ describe("canWrapInstance edge cases", () => {test("should handle wrapping with Slot", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>).instances);selectInstance(["box", "body"]);@@ -265,9 +273,9 @@ describe("canWrapInstance edge cases", () => {test("should allow wrapping with Collection", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>).instances);selectInstance(["box", "body"]);@@ -288,9 +296,9 @@ describe("canWrapInstance edge cases", () => {test("should allow wrapping with AnimateChildren", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>).instances);selectInstance(["box", "body"]);@@ -311,9 +319,9 @@ describe("canWrapInstance edge cases", () => {test("should allow wrapping with AnimateText", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>).instances);selectInstance(["box", "body"]);@@ -334,9 +342,9 @@ describe("canWrapInstance edge cases", () => {test("should allow wrapping with StaggerAnimation", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>).instances);selectInstance(["box", "body"]);@@ -357,9 +365,9 @@ describe("canWrapInstance edge cases", () => {test("should allow wrapping with VideoAnimation", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>).instances);selectInstance(["box", "body"]);@@ -380,12 +388,12 @@ describe("canWrapInstance edge cases", () => {test("should handle wrapping multiple elements", () => {$instances.set(renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child1"></$.Box>- <$.Box ws:id="child2"></$.Box>- </$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="parent">+ <Box ws:id="child1"></Box>+ <Box ws:id="child2"></Box>+ </Box>+ </Body>).instances);selectInstance(["child1", "parent", "body"]);diff --git a/apps/builder/app/builder/features/settings-panel/settings-section.test.tsx b/apps/builder/app/builder/features/settings-panel/settings-section.test.tsxnew file mode 100644index 0000000000..d8b8da0e7e--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/settings-section.test.tsx@@ -0,0 +1,126 @@+// Verifies that Content Block template identity is exposed separately from the+// editable canvas label without changing settings for ordinary instances.+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, test } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import {+ blockTemplateComponent,+ elementComponent,+ type Instance,+} from "@webstudio-is/sdk";+import { selectInstance } from "~/shared/nano-states";+import { $instances } from "~/shared/sync/data-stores";+import { $externalContentRoots } from "~/shared/external-content-mutations";+import { SettingsSection } from "./settings-section";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ $externalContentRoots.set(new Map());+});++afterEach(() => {+ act(() => root.unmount());+ document.body.innerHTML = "";+ selectInstance(undefined);+ $instances.set(new Map());+ $externalContentRoots.set(new Map());+});++const renderSettings = (instances: Instance[], selectedId: string) => {+ $instances.set(new Map(instances.map((instance) => [instance.id, instance])));+ selectInstance([selectedId]);+ act(() => {+ root.render(+ <TooltipProvider>+ <SettingsSection />+ </TooltipProvider>+ );+ });+};++test("shows stable template name separately from its display label", () => {+ renderSettings(+ [+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "card" }],+ },+ {+ type: "instance",+ id: "card",+ component: "Box",+ name: "PromotionCard",+ label: "Promotion card for launches",+ children: [],+ },+ ],+ "card"+ );++ expect(container.querySelectorAll("input")).toHaveLength(2);+ expect(container.textContent).toContain("Name");+ expect(container.textContent).toContain("Label");+ expect(+ Array.from(container.querySelectorAll<HTMLInputElement>("input")).map(+ ({ value }) => value+ )+ ).toEqual(["PromotionCard", "Promotion card for launches"]);+});++test("humanizes the template name as the default label", () => {+ renderSettings(+ [+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "div" }],+ },+ {+ type: "instance",+ id: "div",+ component: elementComponent,+ tag: "div",+ name: "Div",+ children: [],+ },+ ],+ "div"+ );++ const [name, label] = container.querySelectorAll<HTMLInputElement>("input");+ expect(name?.value).toBe("Div");+ expect(label?.value).toBe("");+ expect(label?.placeholder).toBe("Div");+});++test("keeps ordinary instances on the label-only settings", () => {+ renderSettings(+ [+ {+ type: "instance",+ id: "box",+ component: "Box",+ label: "Regular box",+ children: [],+ },+ ],+ "box"+ );++ expect(container.querySelectorAll("input")).toHaveLength(1);+ expect(container.textContent).not.toContain("Name");+ expect(container.textContent).toContain("Label");+});diff --git a/apps/builder/app/builder/features/settings-panel/settings-section.tsx b/apps/builder/app/builder/features/settings-panel/settings-section.tsxindex d2ffb9e463..9df0025dc9 100644--- a/apps/builder/app/builder/features/settings-panel/settings-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/settings-section.tsx@@ -5,6 +5,11 @@ import { useDraftValue } from "~/builder/shared/use-draft-value";import { HorizontalLayout, Label, Row } from "./shared";import { $selectedInstance } from "~/shared/nano-states";import { getInstanceLabel } from "~/builder/shared/instance-label";+import {+ blockTemplateComponent,+ findParentInstanceReference,+ getContentBlockTemplateName,+} from "@webstudio-is/sdk";import {executeRuntimeMutation,getDuplicateTemplateNameMessage,@@ -14,14 +19,21 @@ import {externalContentInstanceNameMessage,isExternalContentInstance,} from "~/shared/external-content-mutations";+import { $instances } from "~/shared/sync/data-stores";export const SettingsSection = () => {const selectedInstance = useStore($selectedInstance);+ const instances = useStore($instances);const externalContentRoots = useStore($externalContentRoots);- const id = useId();- const [error, setError] = useState<string>();- useEffect(() => setError(undefined), [selectedInstance?.id]);- const localValue = useDraftValue(+ const labelId = useId();+ const nameId = useId();+ const [labelError, setLabelError] = useState<string>();+ const [nameError, setNameError] = useState<string>();+ useEffect(() => {+ setLabelError(undefined);+ setNameError(undefined);+ }, [selectedInstance?.id]);+ const labelValue = useDraftValue(selectedInstance?.label ?? "",(value) => {if (selectedInstance === undefined) {@@ -40,13 +52,35 @@ export const SettingsSection = () => {id: "instances.setLabel",input: { instanceId: selectedInstance.id, label: value },});- setError(undefined);+ setLabelError(undefined);} catch (error) {const message = getDuplicateTemplateNameMessage(error);if (message === undefined) {throw error;}- setError(message);+ setLabelError(message);+ }+ },+ { autoSave: false }+ );+ const templateName =+ selectedInstance === undefined+ ? ""+ : getContentBlockTemplateName(selectedInstance);+ const nameValue = useDraftValue(+ templateName,+ (value) => {+ if (selectedInstance === undefined) {+ return;+ }+ try {+ executeRuntimeMutation({+ id: "instances.setName",+ input: { instanceId: selectedInstance.id, name: value },+ });+ setNameError(undefined);+ } catch (error) {+ setNameError(error instanceof Error ? error.message : String(error));}},{ autoSave: false }@@ -57,31 +91,57 @@ export const SettingsSection = () => {}const placeholder = getInstanceLabel(selectedInstance);+ const parent = findParentInstanceReference(+ instances,+ selectedInstance.id+ )?.instance;+ const isTemplate = parent?.component === blockTemplateComponent;const isNameEditable =isExternalContentInstance(externalContentRoots, selectedInstance.id) ===false;return (<Row>- <HorizontalLayout label={<Label htmlFor={id}>Name</Label>}>+ {isTemplate && (+ <HorizontalLayout label={<Label htmlFor={nameId}>Name</Label>}>+ <Tooltip content={nameError} delayDuration={0}>+ <InputField+ id={nameId}+ key={`${selectedInstance.id}:name`}+ value={nameValue.value}+ color={nameError === undefined ? undefined : "error"}+ aria-invalid={nameError === undefined ? undefined : true}+ disabled={isNameEditable === false}+ onChange={(event) => {+ setNameError(undefined);+ nameValue.set(event.target.value);+ }}+ onBlur={nameValue.save}+ />+ </Tooltip>+ </HorizontalLayout>+ )}+ <HorizontalLayout label={<Label htmlFor={labelId}>Label</Label>}><Tooltip- content={isNameEditable ? error : externalContentInstanceNameMessage}+ content={+ isNameEditable ? labelError : externalContentInstanceNameMessage+ }delayDuration={0}><InputField- id={id}+ id={labelId}/* Key is required, otherwise when label is undefined, previous value stayed */key={selectedInstance.id}placeholder={placeholder}- value={localValue.value}- color={error === undefined ? undefined : "error"}- aria-invalid={error === undefined ? undefined : true}+ value={labelValue.value}+ color={labelError === undefined ? undefined : "error"}+ aria-invalid={labelError === undefined ? undefined : true}disabled={isNameEditable === false}onChange={(event) => {- setError(undefined);- localValue.set(event.target.value);+ setLabelError(undefined);+ labelValue.set(event.target.value);}}- onBlur={localValue.save}+ onBlur={labelValue.save}/></Tooltip></HorizontalLayout>diff --git a/apps/builder/app/builder/features/style-panel/shared/model.test.ts b/apps/builder/app/builder/features/style-panel/shared/model.test.tsnew file mode 100644index 0000000000..0381816bfa--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/shared/model.test.ts@@ -0,0 +1,81 @@+// Verifies that style-panel tag lookup uses component metadata when a prop+// selects the element rendered by a polymorphic component.+import { afterEach, expect, test } from "vitest";+import { createDefaultPages } from "@webstudio-is/project-build";+import type { WsComponentMeta } from "@webstudio-is/sdk";+import {+ $registeredComponentMetas,+ $selectedPageId,+ selectInstance,+} from "~/shared/nano-states";+import {+ $instances,+ $pages,+ $props,+ resetDataStores,+} from "~/shared/sync/data-stores";+import { $instanceTags } from "./model";++afterEach(() => {+ resetDataStores();+ $selectedPageId.set(undefined);+ $registeredComponentMetas.set(new Map());+ selectInstance(undefined);+});++test("resolves prop-selected component tags for the style panel", () => {+ const pages = createDefaultPages({ rootInstanceId: "list" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $instances.set(+ new Map([+ [+ "list",+ {+ type: "instance" as const,+ id: "list",+ component: "List",+ children: [],+ },+ ],+ ])+ );+ $props.set(+ new Map([+ [+ "ordered",+ {+ id: "ordered",+ instanceId: "list",+ name: "ordered",+ type: "boolean" as const,+ value: true,+ },+ ],+ ])+ );+ $registeredComponentMetas.set(+ new Map<string, WsComponentMeta>([+ [+ "List",+ {+ props: {+ ordered: {+ type: "boolean",+ control: "boolean",+ required: false,+ },+ },+ renderedTag: {+ prop: "ordered",+ values: { true: "ol", false: "ul" },+ default: "ul",+ },+ },+ ],+ ])+ );+ selectInstance(["list"]);++ expect($instanceTags.get().get("list")).toBe("ol");+});diff --git a/apps/builder/app/builder/features/style-panel/shared/model.tsx b/apps/builder/app/builder/features/style-panel/shared/model.tsxindex f708b1ca1c..d1e9d487fa 100644--- a/apps/builder/app/builder/features/style-panel/shared/model.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/model.tsx@@ -30,7 +30,11 @@ import {$selectedOrLastStyleSourceSelector,} from "~/shared/nano-states";import { $breakpoints } from "~/shared/sync/data-stores";-import { $styles, $styleSourceSelections } from "~/shared/sync/data-stores";+import {+ $props,+ $styles,+ $styleSourceSelections,+} from "~/shared/sync/data-stores";import {getComputedStyleDecl,getPresetStyleDeclKey,@@ -62,8 +66,13 @@ const $presetStyles = computed($registeredComponentMetas, (metas) => {});export const $instanceTags = computed(- [$registeredComponentMetas, $propsIndex, $selectedInstancePathWithRoot],- (metas, propsIndex, instancePath) => {+ [+ $registeredComponentMetas,+ $propsIndex,+ $props,+ $selectedInstancePathWithRoot,+ ],+ (metas, propsIndex, props, instancePath) => {const instanceTags = new Map<Instance["id"], HtmlTags>();if (instancePath === undefined) {return instanceTags;@@ -72,6 +81,7 @@ export const $instanceTags = computed(const tag = getHtmlTagFromInstance({instance,metas,+ props,htmlTagsByInstanceId: propsIndex.htmlTagsByInstanceId,});if (tag !== undefined) {diff --git a/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsx b/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsxindex 479117280d..21b4826179 100644--- a/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsx+++ b/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsx@@ -26,8 +26,8 @@ const markdown: Asset = {createdAt: "2026-01-01T00:00:00.000Z",};-test("resolves asset IDs and relative paths in Markdown images and links", () => {- const html = renderMarkdownPreview({+test("resolves asset IDs and relative paths in Markdown images and links", async () => {+ const html = await renderMarkdownPreview({markdown:"\n\n[Relative image](./image.png)\n\n[Download image](image-id)\n\n",sourceAsset: markdown,@@ -45,8 +45,8 @@ test("resolves asset IDs and relative paths in Markdown images and links", () =>expect(html).toContain('src="https://example.com/image.png"');});-test("uses an object URL while an inserted image is uploading", () => {- const html = renderMarkdownPreview({+test("uses an object URL while an inserted image is uploading", async () => {+ const html = await renderMarkdownPreview({markdown: "",sourceAsset: markdown,folders: new Map(),@@ -62,3 +62,35 @@ test("uses an object URL while an inserted image is uploading", () => {expect(html).toContain('src="blob:https://builder.example/upload"');});++test("renders named MDX heading components with their authored tag", async () => {+ const html = await renderMarkdownPreview({+ markdown: '<Heading tag="h1">h1</Heading>',+ sourceAsset: markdown,+ folders: new Map(),+ assetContainers: [],+ origin: "https://builder.example",+ });++ expect(html).toBe("<h1>h1</h1>\n");+});++test("shows a placeholder for an empty component without a visible preview", async () => {+ const html = await renderMarkdownPreview({+ markdown:+ '<YouTube src="https://youtu.be/KI5JHpzBK1s" />\n\n<Image src="https://example.com/image.png" alt="Example" />',+ sourceAsset: markdown,+ folders: new Map(),+ assetContainers: [],+ origin: "https://builder.example",+ });++ const container = document.createElement("div");+ container.innerHTML = html;+ const placeholder = container.querySelector(+ "[data-ws-mdx-component-placeholder]"+ );+ expect(placeholder?.tagName).toBe("DIV");+ expect(placeholder?.textContent?.trim()).toBe("YouTube");+ expect(container.querySelector("img")?.getAttribute("alt")).toBe("Example");+});diff --git a/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsx b/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsxindex 1d8d6be392..c4c63a49ab 100644--- a/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsx+++ b/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsx@@ -1,15 +1,25 @@-import { useMemo, type ReactNode } from "react";+import { useEffect, useState, type ReactNode } from "react";import { css, cssVar, SplitView, theme } from "@webstudio-is/design-system";import { renderMarkdownHtml } from "@webstudio-is/sdk-components-react/markdown";+import {+ parseMdxDocument,+ serializeMdxDocument,+ type MdxAuthoredNode,+} from "@webstudio-is/content-engine/mdx";import { discoverNamedMarkdownAssetReferenceRanges } from "@webstudio-is/content-engine/markdown-assets";import { rewriteMarkdownAssetReferenceRanges } from "@webstudio-is/content-engine/markdown-references";import {createAssetFolderHierarchy,formatAssetName,+ getComponentByJsxName,+ getHtmlTagFromInstance,getAssetUrl,type Asset,type AssetFolders,+ type Instance,+ type Prop,} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import type { AssetContainer } from "~/builder/shared/assets";const previewStyle = css({@@ -67,9 +77,117 @@ const previewStyle = css({},"& img": { maxWidth: "100%" },"& a": { color: cssVar("--foreground-accent") },+ "& [data-ws-mdx-component-placeholder]": {+ display: "grid",+ placeItems: "center",+ minHeight: theme.spacing[20],+ border: `1px dotted ${cssVar("--border-default")}`,+ },});-const renderMarkdownPreview = ({+// A file can feed multiple Content Blocks, so this preview cannot choose one+// block's custom templates. It can still preserve the semantic HTML tag of a+// registered component fallback such as <Heading tag="h1">.+const getRegisteredComponentPreviewTag = (+ node: Extract<MdxAuthoredNode, { type: "template" }>+) => {+ const component = getComponentByJsxName({+ name: node.name,+ components: componentMetas.keys(),+ });+ const meta =+ component === undefined ? undefined : componentMetas.get(component);+ if (component === undefined || meta === undefined) {+ return;+ }+ const instanceId = "markdown-preview-component";+ const instance: Instance = {+ type: "instance",+ id: instanceId,+ component,+ children: [],+ };+ const selectorNames = new Set(["tag", meta.renderedTag?.prop]);+ const props = new Map<string, Prop>();+ for (const [index, prop] of node.props.entries()) {+ if (+ selectorNames.has(prop.name) === false ||+ typeof prop.value !== "string"+ ) {+ continue;+ }+ props.set(`${instanceId}-${index}`, {+ id: `${instanceId}-${index}`,+ instanceId,+ name: prop.name,+ type: "string",+ value: prop.value,+ });+ }+ return {+ tag: getHtmlTagFromInstance({ instance, metas: componentMetas, props }),+ selectorNames,+ };+};++const materializeRegisteredComponentTags = (+ nodes: readonly MdxAuthoredNode[]+): readonly MdxAuthoredNode[] =>+ nodes.map((node) => {+ if (+ node.type === "text" ||+ node.type === "comment" ||+ node.type === "opaque"+ ) {+ return node;+ }+ const children = materializeRegisteredComponentTags(node.children);+ if (node.type !== "template" || node.syntax !== "jsx") {+ return { ...node, children };+ }+ const preview = getRegisteredComponentPreviewTag(node);+ if (+ children.length === 0 &&+ (preview === undefined || preview.tag === "div")+ ) {+ return {+ type: "element",+ syntax: "mdx",+ tag: "div",+ props: [+ {+ name: "data-ws-mdx-component-placeholder",+ value: "",+ },+ ],+ children: [+ {+ type: "text",+ value: node.name,+ sourceRange: node.sourceRange,+ },+ ],+ mdxMode: "flow",+ sourceRange: node.sourceRange,+ };+ }+ if (preview?.tag === undefined) {+ return { ...node, children };+ }+ return {+ type: "element",+ syntax: "mdx",+ tag: preview.tag,+ props: node.props.filter(+ ({ name }) => preview.selectorNames.has(name) === false+ ),+ children,+ mdxMode: node.mdxMode,+ sourceRange: node.sourceRange,+ };+ });++const renderMarkdownPreview = async ({markdown,sourceAsset,folders,@@ -101,10 +219,23 @@ const renderMarkdownPreview = ({: getAssetUrl(container.asset, origin).href,]));- return renderMarkdownHtml(- rewriteMarkdownAssetReferenceRanges({ markdown, references, assetUrls }),- { allowBlobImages: true }- );+ const rewritten = rewriteMarkdownAssetReferenceRanges({+ markdown,+ references,+ assetUrls,+ });+ try {+ const document = await parseMdxDocument({ source: rewritten });+ return renderMarkdownHtml(+ serializeMdxDocument({+ ...document,+ children: materializeRegisteredComponentTags(document.children),+ }),+ { allowBlobImages: true }+ );+ } catch {+ return renderMarkdownHtml(rewritten, { allowBlobImages: true });+ }};export const __testing__ = { renderMarkdownPreview };@@ -124,17 +255,27 @@ export const MarkdownSplitView = ({assetContainers: AssetContainer[];children: ReactNode;}) => {- const html = useMemo(() => {+ const [html, setHtml] = useState("");+ useEffect(() => {+ let active = true;if (open === false) {- return "";+ setHtml("");+ return;}- return renderMarkdownPreview({+ void renderMarkdownPreview({markdown: source,sourceAsset,folders,assetContainers,origin: window.location.origin,+ }).then((nextHtml) => {+ if (active) {+ setHtml(nextHtml);+ }});+ return () => {+ active = false;+ };}, [assetContainers, folders, open, source, sourceAsset]);return (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.tsxnew file mode 100644index 0000000000..05298d0f7a--- /dev/null+++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor.test.tsx@@ -0,0 +1,91 @@+// Verifies that MDX completions use the live Content Block template contract,+// including stable JSX names and template-authored properties.+import { afterEach, expect, test } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ contentBlockSourceProp,+ coreMetas,+ elementComponent,+ type Instance,+ type Prop,+} from "@webstudio-is/sdk";+import { $instances, $props } from "~/shared/sync/data-stores";+import { __testing__ } from "./text-file-editor";++const { getMdxCompletionComponents } = __testing__;++afterEach(() => {+ $instances.set(new Map());+ $props.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",+ {+ 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);++ 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);+});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 bb38f73b6d..369df9029e 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@@ -41,27 +41,35 @@ import {TextStrikethroughIcon,} from "@webstudio-is/icons";import {+ findBlockTemplates,formatAssetName,+ getMdxAssetSourceBlockInstanceIds,inspectMdxAssetSource,MdxAuthoredContentConflictError,} from "@webstudio-is/project-build/runtime";-import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { getJsxPropName } from "@webstudio-is/content-engine/jsx-attributes";import {getAssetUrl,+ getComponentJsxName,+ getContentBlockTemplateName,+ getHtmlTagFromInstance,getPagePath,isMdxFileAsset,type Asset,+ type WsComponentMeta,} from "@webstudio-is/sdk";import { CodeEditor } from "~/shared/code-editor";import { EditorDialog, type EditorApi } from "~/shared/code-editor-base";import {$assetFolders,$assets,+ $dataSources,+ $instances,$pages,$props,readBuilderStateStores,} from "~/shared/sync/data-stores";-import { $authPermit } from "~/shared/nano-states";+import { $authPermit, $registeredComponentMetas } from "~/shared/nano-states";import { AssetManager } from "~/builder/shared/asset-manager";import {AssetUpload,@@ -76,6 +84,7 @@ import {getTextFileEditorExtensions,getMdxPersistenceFeedback,isMarkdownAsset,+ type MdxCompletionComponent,type MdxPersistenceFeedback,normalizeTextFileContent,} from "./text-file-utils";@@ -93,6 +102,123 @@ type TextFileState =| { status: "loaded"; content: string }| { status: "error" };+const getStaticMdxCompletionProps = (+ meta: WsComponentMeta | undefined,+ contentModeOnly = false+): MdxCompletionComponent["props"] =>+ Object.entries(meta?.props ?? {}).flatMap(([name, prop]) => {+ if (+ (contentModeOnly && prop.contentMode !== true) ||+ (prop.type !== "string" &&+ prop.type !== "number" &&+ prop.type !== "boolean")+ ) {+ return [];+ }+ const values = "options" in prop ? prop.options : undefined;+ return [+ {+ name,+ ...(Array.isArray(values) ? { values } : {}),+ },+ ];+ });++const getMdxCompletionComponents = ({+ assetId,+ metas,+}: {+ assetId: string;+ metas: Map<string, WsComponentMeta>;+}): MdxCompletionComponent[] => {+ const components = new Map<string, MdxCompletionComponent>();+ const componentIds = Array.from(metas.keys());+ for (const [component, meta] of metas) {+ const name = getComponentJsxName({+ component,+ components: componentIds,+ });+ if (name !== undefined) {+ components.set(name, {+ name,+ props: getStaticMdxCompletionProps(meta),+ });+ }+ }++ const state = readBuilderStateStores();+ const instances = state.instances ?? new Map();+ const propsByInstanceId = new Map<+ string,+ Array<{ name: string; type: "string" | "number" | "boolean" }>+ >();+ for (const prop of state.props?.values() ?? []) {+ if (+ prop.type !== "string" &&+ prop.type !== "number" &&+ prop.type !== "boolean"+ ) {+ continue;+ }+ const props = propsByInstanceId.get(prop.instanceId) ?? [];+ props.push({ name: prop.name, type: prop.type });+ propsByInstanceId.set(prop.instanceId, props);+ }+ const templates = new Map<string, MdxCompletionComponent>();+ for (const blockInstanceId of getMdxAssetSourceBlockInstanceIds({+ assetId,+ state,+ })) {+ for (const [template] of findBlockTemplates({+ anchor: [blockInstanceId],+ instances,+ }) ?? []) {+ const name = getContentBlockTemplateName(template);+ const existing = templates.get(name);+ const meta = metas.get(template.component);+ const componentPropNames = new Set(Object.keys(meta?.props ?? {}));+ const acceptsHtmlAttributes =+ getHtmlTagFromInstance({+ instance: template,+ metas,+ props: state.props,+ }) !== undefined;+ const existingProps = (propsByInstanceId.get(template.id) ?? []).flatMap(+ (prop) => {+ const propMeta = meta?.props?.[prop.name];+ if (+ propMeta !== undefined &&+ (propMeta.contentMode !== true || propMeta.type !== prop.type)+ ) {+ return [];+ }+ return [+ {+ name: getJsxPropName({+ instancePropName: prop.name,+ acceptsHtmlAttributes,+ componentPropNames,+ }),+ },+ ];+ }+ );+ const props = new Map(+ [+ ...(existing?.props ?? []),+ ...getStaticMdxCompletionProps(meta, true),+ ...existingProps,+ ].map((prop) => [prop.name, prop] as const)+ );+ templates.set(name, { name, props: Array.from(props.values()) });+ }+ }+ for (const [name, template] of templates) {+ components.set(name, template);+ }+ return Array.from(components.values());+};+const markdownActions = [{label: "Bold",@@ -267,6 +393,10 @@ const MarkdownImagePicker = ({);};+export const __testing__ = {+ getMdxCompletionComponents,+};+const getMarkdownHref = (value: UrlInputValue) => {if (value.type === "string" || value.type === "asset") {return value.value;@@ -453,6 +583,10 @@ export const TextFileEditor = ({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";@@ -476,8 +610,11 @@ export const TextFileEditor = ({const languageExtensions = useMemo(() => {// The state reader below is intentionally refreshed when its external- // Content Block context changes.+ // Content Block context or template definitions change.void externalContentRoots;+ void instances;+ void props;+ void dataSources;if (asset === undefined) {return [];}@@ -485,19 +622,34 @@ export const TextFileEditor = ({return getTextFileEditorExtensions(asset);}const projectId = asset.projectId;- return getTextFileEditorExtensions(asset, [], async ({ source }) =>- inspectMdxAssetSource({- source,+ return getTextFileEditorExtensions(+ asset,+ [],+ async ({ source }) =>+ inspectMdxAssetSource({+ source,+ assetId,+ state: readBuilderStateStores(),+ metas: registeredComponentMetas,+ projectId,+ }),+ getMdxCompletionComponents({assetId,- state: readBuilderStateStores(),- metas: componentMetas,- projectId,+ metas: registeredComponentMetas,}));},// Recreate the linter after a Content Block is materialized or refreshed so// contextual template and content-model diagnostics are recalculated.- [asset, assetId, externalContentRoots]+ [+ asset,+ assetId,+ dataSources,+ externalContentRoots,+ instances,+ props,+ registeredComponentMetas,+ ]);useEffect(() => {@@ -694,9 +846,6 @@ export const TextFileEditor = ({readOnly={canEdit === false}onChange={(content) => {setState({ status: "loaded", content });- if (isMdxFileAsset(asset)) {- save(content);- }}}onChangeComplete={save}/>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 091af28cc4..d258a88679 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@@ -1,4 +1,7 @@import { describe, expect, test } from "vitest";+import { CompletionContext } from "@codemirror/autocomplete";+import { EditorState, type Extension } from "@codemirror/state";+import { markdown } from "@codemirror/lang-markdown";import {ALLOWED_FILE_TYPES,getAssetTextEditorLanguage,@@ -8,12 +11,82 @@ import {getTextFileEditorExtensions,getTextFileEditorDiagnostics,getMdxPersistenceFeedback,+ createMdxCompletionSource,isMarkdownAsset,normalizeTextFileContent,normalizeTextFileConversion,} from "./text-file-utils";+const getCompletionLabels = async (+ source: ReturnType<typeof createMdxCompletionSource>,+ value: string,+ position = value.length,+ extensions: Extension[] = []+) => {+ const state = EditorState.create({ doc: value, extensions });+ const result = await source(new CompletionContext(state, position, true));+ return result?.options.map(({ label }) => label) ?? [];+};+describe("text file assets", () => {+ test("completes available MDX components, props, and prop values", async () => {+ const source = createMdxCompletionSource([+ {+ name: "Heading",+ props: [{ name: "tag", values: ["h1", "h2"] }, { name: "title" }],+ },+ ]);++ await expect(getCompletionLabels(source, "<He")).resolves.toContain(+ "Heading"+ );+ await expect(getCompletionLabels(source, "<Heading ta")).resolves.toContain(+ "tag"+ );+ await expect(+ getCompletionLabels(source, '<Heading tag="')+ ).resolves.toEqual(expect.arrayContaining(["h1", "h2"]));+ await expect(getCompletionLabels(source, "<Heading cl")).resolves.toEqual(+ expect.arrayContaining(["className"])+ );+ await expect(+ getCompletionLabels(source, "<Heading cl")+ ).resolves.not.toContain("class");+ });++ test("does not offer display labels that are invalid JSX identifiers", async () => {+ const source = createMdxCompletionSource([+ { name: "Heading 1", props: [] },+ { name: "Heading", props: [] },+ ]);++ await expect(getCompletionLabels(source, "<He")).resolves.toEqual(+ expect.arrayContaining(["Heading"])+ );+ await expect(getCompletionLabels(source, "<He")).resolves.not.toContain(+ "Heading 1"+ );+ });++ test("does not complete JSX inside Markdown code", async () => {+ const source = createMdxCompletionSource([+ { name: "Heading", props: [{ name: "tag" }] },+ ]);++ const inlineCode = "`<He`";+ await expect(+ getCompletionLabels(source, inlineCode, inlineCode.length - 1, [+ markdown(),+ ])+ ).resolves.toEqual([]);+ const fencedCode = "```mdx\n<He\n```";+ await expect(+ getCompletionLabels(source, fencedCode, fencedCode.indexOf("\n```"), [+ markdown(),+ ])+ ).resolves.toEqual([]);+ });+test("detects formats case-insensitively", () => {expect(isTextFileAsset({ format: "JSON" })).toBe(true);expect(getTextFileEditorExtensions({ format: "JSON" })).toHaveLength(1);@@ -39,12 +112,8 @@ describe("text file assets", () => {(format) => {const language = getAssetTextEditorLanguage({ format });expect(isTextFileAsset({ format })).toBe(language !== undefined);- expect(getTextFileEditorExtensions({ format })).toHaveLength(- language === undefined || language === "plain"- ? 0- : format === "md" || format === "mdx"- ? 4- : 1+ expect(getTextFileEditorExtensions({ format }).length > 0).toBe(+ language !== undefined && language !== "plain");});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 ee163ab928..b7dd86cf46 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@@ -1,5 +1,12 @@-import type { Extension } from "@codemirror/state";-import { keymap } from "@codemirror/view";+import { EditorState, type Extension } from "@codemirror/state";+import { syntaxTree } from "@codemirror/language";+import { keymap, tooltips } from "@codemirror/view";+import {+ autocompletion,+ CompletionContext,+ completionKeymap,+ type CompletionSource,+} from "@codemirror/autocomplete";import {linter,lintGutter,@@ -7,11 +14,17 @@ import {type Diagnostic,} from "@codemirror/lint";import { css } from "@codemirror/lang-css";-import { html } from "@codemirror/lang-html";+import {+ html as htmlLanguage,+ htmlCompletionSourceWith,+ type TagSpec,+} from "@codemirror/lang-html";import { javascript } from "@codemirror/lang-javascript";import { markdown } from "@codemirror/lang-markdown";import { parseJsonExpression } from "@webstudio-is/expression";+import { standardAttributesToReactProps } from "@webstudio-is/content-engine/jsx-attributes";import {+ isMdxTemplateComponentName,type MdxSourcePoint,type TextAssetSourceDiagnostic,validateTextAssetSource,@@ -42,6 +55,127 @@ export type ValidateTextFileSource = (input: {const validateTextFileSource: ValidateTextFileSource = async (input) =>(await validateTextAssetSource(input)).diagnostics;+export type MdxCompletionComponent = Readonly<{+ name: string;+ props: readonly Readonly<{+ name: string;+ values?: readonly string[];+ }>[];+}>;++const mdxCompletionExcludedSyntax = new Set([+ "CodeBlock",+ "FencedCode",+ "InlineCode",+ "ProcessingInstructionBlock",+ "CommentBlock",+ "Link",+ "Image",+]);++/** Uses CodeMirror's HTML parser to complete constrained JSX inside MDX. */+export const createMdxCompletionSource = (+ components: readonly MdxCompletionComponent[]+): CompletionSource => {+ const validComponents = components.filter(({ name }) =>+ isMdxTemplateComponentName(name)+ );+ const componentsByName = new Map(+ validComponents.map((component) => [component.name, component] as const)+ );+ const extraTags = Object.fromEntries(+ validComponents.map(({ name, props }) => [+ name,+ {+ attrs: Object.fromEntries(+ props.map((prop) => [prop.name, prop.values ?? null])+ ),+ } satisfies TagSpec,+ ])+ );+ const htmlSupport = htmlLanguage({+ matchClosingTags: false,+ autoCloseTags: false,+ extraTags,+ });+ const completeHtml = htmlCompletionSourceWith({ extraTags });+ return async (context) => {+ let node = syntaxTree(context.state).resolveInner(context.pos, -1);+ while (node.type.isTop === false) {+ if (mdxCompletionExcludedSyntax.has(node.name)) {+ return null;+ }+ const parent = node.parent;+ if (parent === null) {+ break;+ }+ node = parent;+ }+ const htmlState = EditorState.create({+ doc: context.state.doc,+ selection: { anchor: context.pos },+ extensions: [htmlSupport],+ });+ const htmlContext = new CompletionContext(+ htmlState,+ context.pos,+ context.explicit+ );+ const result = await completeHtml(htmlContext);+ if (result === null) {+ return null;+ }+ let htmlNode = syntaxTree(htmlState).resolveInner(context.pos, -1);+ if (htmlNode.name === "AttributeValue") {+ return result;+ }+ while (htmlNode.type.isTop === false && htmlNode.name !== "OpenTag") {+ const parent = htmlNode.parent;+ if (parent === null) {+ break;+ }+ htmlNode = parent;+ }+ if (htmlNode.name !== "OpenTag") {+ return result;+ }+ const tagNameNode = htmlNode.getChild("TagName");+ if (+ tagNameNode === null ||+ context.pos <= tagNameNode.to ||+ context.pos < tagNameNode.from+ ) {+ return result;+ }+ const tagName = htmlState.doc.sliceString(tagNameNode.from, tagNameNode.to);+ const componentPropNames = new Set(+ componentsByName.get(tagName)?.props.map(({ name }) => name) ?? []+ );+ const options = new Map(+ result.options.map((option) => {+ const label =+ option.label === "class"+ ? "className"+ : componentPropNames.has(option.label)+ ? option.label+ : (standardAttributesToReactProps[option.label] ?? option.label);+ return [+ label,+ {+ ...option,+ label,+ ...(option.apply === option.label ? { apply: label } : {}),+ },+ ] as const;+ })+ );+ return {+ ...result,+ options: Array.from(options.values()),+ };+ };+};+export const getMdxPersistenceFeedback = (state: Pick<AssetContentSessionState, "status" | "error">): MdxPersistenceFeedback | undefined => {@@ -126,36 +260,51 @@ export const getTextFileEditorDiagnostics = async ({const getMarkdownExtensions = (format: "md" | "mdx",semanticDiagnostics: readonly ContentBlockDiagnostic[],- validateSource: ValidateTextFileSource-): Extension[] => [- linter(- (view) =>- getTextFileEditorDiagnostics({- source: view.state.doc.toString(),- format,- semanticDiagnostics,- validateSource,+ validateSource: ValidateTextFileSource,+ completionComponents: readonly MdxCompletionComponent[]+): Extension[] => {+ const extensions: Extension[] = [+ linter(+ (view) =>+ getTextFileEditorDiagnostics({+ source: view.state.doc.toString(),+ format,+ semanticDiagnostics,+ validateSource,+ }),+ { delay: 300 }+ ),+ lintGutter(),+ keymap.of(lintKeymap),+ ];+ if (format === "mdx") {+ extensions.push(+ tooltips({ parent: document.body }),+ autocompletion({+ override: [createMdxCompletionSource(completionComponents)],+ icons: false,}),- { delay: 300 }- ),- lintGutter(),- keymap.of(lintKeymap),-];+ keymap.of(completionKeymap)+ );+ }+ return extensions;+};const languageExtensions = {plain: [],css: [css()],- html: [html()],+ html: [htmlLanguage()],javascript: [javascript()],json: [javascript()],markdown: [markdown()],- xml: [html()],+ xml: [htmlLanguage()],} satisfies Record<AssetTextEditorLanguage, Extension[]>;export const getTextFileEditorExtensions = (asset: Pick<Asset, "format">,semanticDiagnostics: readonly ContentBlockDiagnostic[] = [],- validateSource: ValidateTextFileSource = validateTextFileSource+ validateSource: ValidateTextFileSource = validateTextFileSource,+ completionComponents: readonly MdxCompletionComponent[] = []): Extension[] => {const language = getAssetTextEditorLanguage(asset);if (language === undefined) {@@ -166,7 +315,12 @@ export const getTextFileEditorExtensions = (return format === "md" || format === "mdx"? [...extensions,- ...getMarkdownExtensions(format, semanticDiagnostics, validateSource),+ ...getMarkdownExtensions(+ format,+ semanticDiagnostics,+ validateSource,+ completionComponents+ ),]: extensions;};diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.test.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.test.tsxnew file mode 100644index 0000000000..746680ea49--- /dev/null+++ b/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.test.tsx@@ -0,0 +1,84 @@+// Verifies that the slash menu does not retain invisible editor state when no+// Content Block template can be inserted at the current position.+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, expect, test } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type Instance,+} from "@webstudio-is/sdk";+import {+ $registeredComponentMetas,+ $textEditorContextMenu,+ $textEditingInstanceSelector,+} from "~/shared/nano-states";+import { $instances, $props } from "~/shared/sync/data-stores";+import { TextEditorContextMenu } from "./block-editor-context-menu";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | undefined;++afterEach(() => {+ act(() => root?.unmount());+ root = undefined;+ document.body.innerHTML = "";+ $textEditorContextMenu.set(undefined);+ $textEditingInstanceSelector.set(undefined);+ $instances.set(new Map());+ $props.set(new Map());+ $registeredComponentMetas.set(new Map());+});++test("closes the editor menu when every template is structural-only", async () => {+ const createInstance = (+ id: string,+ component: string,+ children: Instance["children"] = []+ ): Instance => ({ type: "instance", id, component, children });+ const instances = new Map<Instance["id"], Instance>([+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ { type: "id", value: "current" },+ ]),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "list-item" },+ ]),+ ],+ [+ "list-item",+ {+ ...createInstance("list-item", elementComponent),+ tag: "li",+ },+ ],+ ["current", { ...createInstance("current", elementComponent), tag: "p" }],+ ]);+ $instances.set(instances);+ $textEditingInstanceSelector.set({+ selector: ["current", "block"],+ reason: "left",+ });+ $textEditorContextMenu.set({+ cursorRect: new DOMRect(),+ replaceAnchor: false,+ });+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);++ await act(async () => {+ root?.render(<TextEditorContextMenu />);+ });++ expect($textEditorContextMenu.get()).toBeUndefined();+});diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsxindex b2df6edcfa..2f2309dd5e 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsx@@ -3,16 +3,20 @@ import { styled } from "@webstudio-is/design-system";import {$modifierKeys,+ $registeredComponentMetas,$textEditingInstanceSelector,$textEditorContextMenu,$textEditorContextMenuCommand,execTextEditorContextMenuCommand,} from "~/shared/nano-states";-import { $instances } from "~/shared/sync/data-stores";+import { $instances, $props } from "~/shared/sync/data-stores";import { applyScale } from "./outline";import { $scale } from "~/builder/shared/nano-states";import { TemplatesMenu } from "./outline/block-instance-outline";-import { insertTemplateAt } from "./outline/block-utils";+import {+ filterInsertableContentBlockTemplates,+ insertTemplateAt,+} from "./outline/block-utils";import { useCallback, useEffect, useState } from "react";import { useEffectEvent } from "~/shared/hook-utils/effect-event";import type { InstanceSelector } from "@webstudio-is/project-build/runtime";@@ -61,10 +65,12 @@ const Menu = ({cursorRect,anchor,templates,+ replaceAnchor,}: {cursorRect: DOMRect;anchor: InstanceSelector;templates: [instance: Instance, instanceSelector: InstanceSelector][];+ replaceAnchor: boolean;}) => {const [inert, setInert] = useState(true);const modifierKeys = useStore($modifierKeys);@@ -84,7 +90,12 @@ const Menu = ({(templateSelector: InstanceSelector) => {const insertBefore = modifierKeys.altKey;execTextEditorContextMenuCommand({ type: "templateInsertionStarted" });- void insertTemplateAt(templateSelector, anchor, insertBefore).then(+ void insertTemplateAt({+ templateSelector,+ anchor,+ insertBefore,+ replaceAnchor,+ }).then((didInsert) => {if (didInsert === false) {execTextEditorContextMenuCommand({@@ -99,7 +110,7 @@ const Menu = ({});},- [anchor, modifierKeys.altKey]+ [anchor, modifierKeys.altKey, replaceAnchor]);const currentValue = intermediateValue ?? value;@@ -158,7 +169,8 @@ const Menu = ({}case "templateInsertionStarted":- case "templateInsertionCancelled": {+ case "templateInsertionCancelled":+ case "close": {break;}@@ -204,10 +216,20 @@ const Menu = ({);};+const CloseTextEditorContextMenu = () => {+ useEffect(() => {+ $textEditorContextMenu.set(undefined);+ execTextEditorContextMenuCommand({ type: "close" });+ }, []);+ return null;+};+export const TextEditorContextMenu = () => {const textEditingInstanceSelector = useStore($textEditingInstanceSelector);const textEditorContextMenu = useStore($textEditorContextMenu);const instances = useStore($instances);+ const props = useStore($props);+ const metas = useStore($registeredComponentMetas);if (textEditorContextMenu === undefined) {return;@@ -223,7 +245,17 @@ export const TextEditorContextMenu = () => {});if (templates === undefined) {- return;+ return <CloseTextEditorContextMenu />;+ }++ const insertableTemplates = filterInsertableContentBlockTemplates({+ templates,+ props,+ metas,+ });++ if (insertableTemplates.length === 0) {+ return <CloseTextEditorContextMenu />;}return (@@ -231,7 +263,8 @@ export const TextEditorContextMenu = () => {key={JSON.stringify(textEditingInstanceSelector.selector)}cursorRect={textEditorContextMenu.cursorRect}anchor={textEditingInstanceSelector.selector}- templates={templates}+ templates={insertableTemplates}+ replaceAnchor={textEditorContextMenu.replaceAnchor}/>);};diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.test.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.test.tsxnew file mode 100644index 0000000000..5821bd8682--- /dev/null+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.test.tsx@@ -0,0 +1,148 @@+// Verifies pointer interaction for the Content Block template menu while the+// canvas editor deliberately retains DOM focus.+import { useEffect, useState } from "react";+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { userEvent } from "@vitest/browser/context";+import { afterEach, expect, test, vi } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type Instance,+} from "@webstudio-is/sdk";+import { TooltipProvider } from "@webstudio-is/design-system";+import { $instances } from "~/shared/sync/data-stores";+import { TemplatesMenu } from "./block-instance-outline";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | undefined;++afterEach(() => {+ act(() => root?.unmount());+ root = undefined;+ document.body.innerHTML = "";+ $instances.set(new Map());+});++test("supports mouse hover and selection while preserving editor focus", async () => {+ const createInstance = (+ id: string,+ component: string,+ children: Instance["children"] = []+ ): Instance => ({ type: "instance", id, component, children });+ const first = createInstance("first", elementComponent);+ const second = createInstance("second", elementComponent);+ $instances.set(+ new Map([+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ { type: "id", value: "current" },+ ]),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: first.id },+ { type: "id", value: second.id },+ ]),+ ],+ [first.id, first],+ [second.id, second],+ ["current", createInstance("current", elementComponent)],+ ])+ );+ const firstSelector = [first.id, "templates", "block"];+ const secondSelector = [second.id, "templates", "block"];+ const onValueChangeComplete = vi.fn();+ const onOpenChange = vi.fn();+ const canvas = document.createElement("iframe");+ document.body.appendChild(canvas);+ const canvasDocument = canvas.contentDocument;+ if (canvasDocument === null) {+ throw new Error("Expected the canvas document");+ }+ const editor = canvasDocument.createElement("input");+ editor.setAttribute("aria-label", "Editor");+ canvasDocument.body.appendChild(editor);+ editor.focus();+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);++ const Harness = () => {+ const [open, setOpen] = useState(true);+ const [inert, setInert] = useState(true);+ const [value, setValue] = useState<string[] | undefined>(firstSelector);+ useEffect(() => {+ const timeout = setTimeout(() => setInert(false), 0);+ return () => clearTimeout(timeout);+ }, []);+ return (+ <TooltipProvider>+ <TemplatesMenu+ open={open}+ onOpenChange={(nextOpen) => {+ onOpenChange(nextOpen);+ setOpen(nextOpen);+ }}+ anchor={["current", "block"]}+ triggerTooltipContent={<>Templates</>}+ templates={[+ [first, firstSelector],+ [second, secondSelector],+ ]}+ value={value}+ onValueChange={setValue}+ onValueChangeComplete={onValueChangeComplete}+ modal={false}+ inert={inert}+ preventFocusOnHover={true}+ >+ <button>Templates</button>+ </TemplatesMenu>+ </TooltipProvider>+ );+ };++ await act(async () => {+ root?.render(<Harness />);+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ });++ let items = document.querySelectorAll<HTMLElement>('[role="menuitemradio"]');+ expect(items).toHaveLength(2);+ expect(document.activeElement).toBe(canvas);+ expect(canvasDocument.activeElement).toBe(editor);++ await act(async () => {+ items[1]?.dispatchEvent(+ new PointerEvent("pointerover", {+ bubbles: true,+ pointerType: "mouse",+ })+ );+ });+ items = document.querySelectorAll<HTMLElement>('[role="menuitemradio"]');+ expect(items[1]?.hasAttribute("data-highlighted")).toBe(true);+ expect(document.activeElement).toBe(canvas);+ expect(canvasDocument.activeElement).toBe(editor);++ if (items[1] === undefined) {+ throw new Error("Expected the second menu item");+ }+ await act(async () => {+ await userEvent.click(items[1]);+ });++ expect(onValueChangeComplete).toHaveBeenCalledExactlyOnceWith(secondSelector);+ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(document.querySelectorAll('[role="menuitemradio"]')).toHaveLength(0);+ expect(document.activeElement).toBe(canvas);+ expect(canvasDocument.activeElement).toBe(editor);+});diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsxindex b3fc938ad3..45d1c85145 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx@@ -19,7 +19,11 @@ import {DropdownMenuSeparator,menuItemCss,} from "@webstudio-is/design-system";-import type { Instance } from "@webstudio-is/sdk";+import {+ blockTemplateComponent,+ type Instance,+ type Instances,+} from "@webstudio-is/sdk";import { PlusIcon, TrashIcon } from "@webstudio-is/icons";import {$blockChildOutline,@@ -27,19 +31,24 @@ import {$hoveredInstanceSelector,$isContentMode,$modifierKeys,+ $registeredComponentMetas,type BlockChildOutline,} from "~/shared/nano-states";-import { $instances } from "~/shared/sync/data-stores";+import { $instances, $props } from "~/shared/sync/data-stores";import { $clampingRect, $scale } from "~/builder/shared/nano-states";import type { InstanceSelector } from "@webstudio-is/project-build/runtime";import {canDeleteInstanceInContentMode,+ findBlockContentSelector,findBlockSelector,findBlockTemplates,} from "@webstudio-is/project-build/runtime";import { skipInertHandlersAttribute } from "~/builder/shared/inert-handlers";import { useEffectEvent } from "~/shared/hook-utils/effect-event";-import { insertTemplateAt } from "./block-utils";+import {+ filterInsertableContentBlockTemplates,+ insertTemplateAt,+} from "./block-utils";import { Outline } from "./outline";import { applyScale } from "../apply-scale";import { canvasToolColors } from "../color-recipes";@@ -49,6 +58,27 @@ import {} from "~/builder/shared/instance-label";import { useOutlineControlPosition } from "./use-outline-control-position";+const hasBlockContent = ({+ anchor,+ instances,+}: {+ anchor: InstanceSelector;+ instances: Instances;+}) => {+ const contentSelector = findBlockContentSelector({ anchor, instances });+ const content =+ contentSelector === undefined+ ? undefined+ : instances.get(contentSelector[0]);+ return (+ content?.children.some(+ (child) =>+ child.type !== "id" ||+ instances.get(child.value)?.component !== blockTemplateComponent+ ) ?? false+ );+};+export const TemplatesMenu = ({onOpenChange,open,@@ -104,10 +134,9 @@ export const TemplatesMenu = ({return;}- // 1 child is Templates instance- const hasChildren = blockInstance.children.length > 1;+ const hasChildren = hasBlockContent({ anchor, instances });- const menuItems = templates?.map(([template, templateSelector]) => ({+ const menuItems = templates.map(([template, templateSelector]) => ({id: template.id,icon: <InstanceIcon instance={{ component: template.component }} />,title: getInstanceLabel(template),@@ -146,48 +175,124 @@ export const TemplatesMenu = ({// oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callbackonValueChange={handleValueChangeComplete}>- {menuItems?.map((item) => (- <DropdownMenuRadioItem- aria-selected={- JSON.stringify(item.value) === JSON.stringify(value)- }- onPointerEnter={() => {- // oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callback- handleValueChange(value);- }}- onPointerMove={- preventFocusOnHover- ? (e) => {- e.preventDefault();- }- : undefined- }- onPointerLeave={- preventFocusOnHover- ? (e) => {- // oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callback- handleValueChange(undefined);- e.preventDefault();- }- : undefined- }- onPointerDown={- preventFocusOnHover- ? (event) => {- event.preventDefault();- }- : undefined- }- key={item.id}- value={JSON.stringify(item.value)}- {...{ [skipInertHandlersAttribute]: true }}- >- <Flex css={{ px: theme.spacing[3] }} gap={2} data-xxx>- {item.icon}- <Box css={{ textTransform: "none" }}>{item.title}</Box>- </Flex>- </DropdownMenuRadioItem>- ))}+ {menuItems?.map((item) => {+ const isSelected = shallowEqual(item.value, value);+ return (+ <DropdownMenuRadioItem+ aria-selected={isSelected}+ {...(preventFocusOnHover && isSelected+ ? { "data-highlighted": "" }+ : {})}+ onPointerEnter={() => {+ // oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callback+ handleValueChange(item.value);+ }}+ onPointerMove={+ preventFocusOnHover+ ? (e) => {+ e.preventDefault();+ }+ : undefined+ }+ onPointerLeave={+ preventFocusOnHover+ ? (e) => {+ // oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callback+ handleValueChange(undefined);+ e.preventDefault();+ }+ : undefined+ }+ onPointerDown={+ preventFocusOnHover+ ? (event) => {+ if (event.button !== 0) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ const pointerId = event.pointerId;+ const ownerDocument =+ event.currentTarget.ownerDocument;+ const captureTarget = ownerDocument.body;+ const preventClick = (clickEvent: MouseEvent) => {+ clickEvent.preventDefault();+ clickEvent.stopImmediatePropagation();+ };+ const releasePointer = (+ pointerEvent: PointerEvent+ ) => {+ pointerEvent.preventDefault();+ pointerEvent.stopImmediatePropagation();+ ownerDocument.removeEventListener(+ "pointerup",+ releasePointer,+ true+ );+ ownerDocument.removeEventListener(+ "pointercancel",+ releasePointer,+ true+ );+ if (pointerEvent.type === "pointercancel") {+ ownerDocument.removeEventListener(+ "click",+ preventClick,+ true+ );+ } else {+ ownerDocument.defaultView?.setTimeout(() => {+ ownerDocument.removeEventListener(+ "click",+ preventClick,+ true+ );+ }, 100);+ }+ if (captureTarget.hasPointerCapture(pointerId)) {+ captureTarget.releasePointerCapture(pointerId);+ }+ onOpenChange(false);+ };+ // Inserting replaces the canvas editor and unmounts+ // this menu before a normal click can fire. Activate+ // on pointer down and keep the remaining pointer+ // events in the Builder document so they do not+ // click the canvas underneath.+ ownerDocument.addEventListener(+ "click",+ preventClick,+ { capture: true, once: true }+ );+ captureTarget.setPointerCapture(pointerId);+ ownerDocument.addEventListener(+ "pointerup",+ releasePointer,+ { capture: true, once: true }+ );+ ownerDocument.addEventListener(+ "pointercancel",+ releasePointer,+ { capture: true, once: true }+ );+ // oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callback+ handleValueChangeComplete(+ JSON.stringify(item.value)+ );+ }+ : undefined+ }+ key={item.id}+ value={JSON.stringify(item.value)}+ {...{ [skipInertHandlersAttribute]: true }}+ >+ <Flex css={{ px: theme.spacing[3] }} gap={2}>+ {item.icon}+ <Box css={{ textTransform: "none" }}>{item.title}</Box>+ </Flex>+ </DropdownMenuRadioItem>+ );+ })}</DropdownMenuRadioGroup><DropdownMenuSeparator /><div className={menuItemCss({ hint: true })}>@@ -240,6 +345,8 @@ export const BlockChildHoveredInstanceOutline = () => {const isContentMode = useStore($isContentMode);const modifierKeys = useStore($modifierKeys);const instances = useStore($instances);+ const props = useStore($props);+ const metas = useStore($registeredComponentMetas);const clampingRect = useStore($clampingRect);const timeoutRef = useRef<undefined | ReturnType<typeof setTimeout>>(@@ -293,12 +400,20 @@ export const BlockChildHoveredInstanceOutline = () => {return;}- if (templates.length === 0) {+ const insertableTemplates = filterInsertableContentBlockTemplates({+ templates,+ props,+ metas,+ });++ if (insertableTemplates.length === 0) {return;}- // 1 child is Templates instance- const hasChildren = blockInstance.children.length > 1;+ const hasChildren = hasBlockContent({+ anchor: outline.selector,+ instances,+ });const canDeleteHoveredInstance =shallowEqual(outline.selector, outline.hoveredSelector) &&@@ -381,10 +496,14 @@ export const BlockChildHoveredInstanceOutline = () => {}}anchor={outline.selector}triggerTooltipContent={tooltipContent}- templates={templates}+ templates={insertableTemplates}onValueChangeComplete={(templateSelector) => {const insertBefore = modifierKeys.altKey;- insertTemplateAt(templateSelector, outline.selector, insertBefore);+ insertTemplateAt({+ templateSelector,+ anchor: outline.selector,+ insertBefore,+ });}}value={undefined}modal={true}diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.tsindex 0cc14cb76f..ef9756f237 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts@@ -5,12 +5,19 @@ import {coreMetas,elementComponent,type Instance,+ type Prop,type WebstudioFragment,} from "@webstudio-is/sdk";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";import type { Project } from "@webstudio-is/project";import { createDefaultPages } from "@webstudio-is/project-build";-import { __testing__, insertListItemAt, insertTemplateAt } from "./block-utils";+import type { InstanceSelector } from "@webstudio-is/project-build/runtime";+import {+ __testing__,+ filterInsertableContentBlockTemplates,+ insertListItemAt,+ insertTemplateAt,+} from "./block-utils";import { registerContainers } from "~/shared/sync/sync-stores";import {$instances,@@ -26,6 +33,7 @@ import {selectPage,selectInstance,} from "~/shared/nano-states";+import { $externalContentRoots } from "~/shared/external-content-mutations";const { getTemplateTokenConflicts } = __testing__;registerContainers();@@ -88,6 +96,36 @@ describe("getTemplateTokenConflicts", () => {});});+test("keeps structural MDX templates out of insertion menus", () => {+ const templates: [Instance, InstanceSelector][] = [+ [+ { ...createInstance("cell", elementComponent), tag: "td" },+ ["cell", "templates", "block"],+ ],+ [createInstance("heading", "Heading"), ["heading", "templates", "block"]],+ [createInstance("card", "Card"), ["card", "templates", "block"]],+ ];+ const props = new Map<string, Prop>([+ [+ "heading-tag",+ {+ id: "heading-tag",+ instanceId: "heading",+ name: "tag",+ type: "string",+ value: "h2",+ },+ ],+ ]);+ const metas = new Map(Object.entries({ ...defaultMetas, ...coreMetas }));++ expect(+ filterInsertableContentBlockTemplates({ templates, props, metas }).map(+ ([template]) => template.id+ )+ ).toEqual(["heading", "card"]);+});+describe("insertListItemAt", () => {beforeEach(() => {$project.set({ id: "projectId" } as Project);@@ -149,6 +187,7 @@ describe("insertTemplateAt", () => {afterEach(() => {$builderMode.set("design");+ $externalContentRoots.set(new Map());});test("inserts synchronously when content mode has no token conflicts", async () => {@@ -176,6 +215,7 @@ describe("insertTemplateAt", () => {{...createInstance("template", elementComponent),tag: "p",+ label: "Card",},],[@@ -187,17 +227,104 @@ describe("insertTemplateAt", () => {],]));-- const insertion = insertTemplateAt(- ["template", "templates", "block", "body"],- ["current", "block", "body"],- false+ $externalContentRoots.set(+ new Map([+ [+ "scope",+ {+ blockInstanceId: "block",+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ },+ ],+ ]));+ const insertion = insertTemplateAt({+ templateSelector: ["template", "templates", "block", "body"],+ anchor: ["current", "block", "body"],+ insertBefore: false,+ });+const insertedSelector = $selectedInstanceSelector.get();expect(insertedSelector?.[0]).not.toBe("current");expect(insertedSelector?.slice(1)).toEqual(["block", "body"]);+ const insertedId = insertedSelector?.[0];+ const recordedInsertion =+ insertedId === undefined+ ? undefined+ : $externalContentRoots+ .get()+ .get("scope")+ ?.insertedTemplates?.get(insertedId);+ expect(recordedInsertion).toMatchObject({ templateName: "Card" });+ expect(recordedInsertion?.pristineFragment.children).toEqual([+ { type: "id", value: insertedId },+ ]);+ expect(recordedInsertion?.htmlTags).toEqual([+ { instanceId: insertedId, tag: "p" },+ ]);++ await expect(insertion).resolves.toBe(true);+ });++ test("replaces the current block when slash replaces all of its text", async () => {+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "block" }]),+ ],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ { type: "id", value: "current" },+ ]),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "template" },+ ]),+ ],+ [+ "template",+ {+ ...createInstance("template", elementComponent, [+ { type: "text", value: "Template content" },+ ]),+ tag: "p",+ label: "Paragraph",+ },+ ],+ [+ "current",+ {+ ...createInstance("current", elementComponent, [+ { type: "text", value: "Replaced content" },+ ]),+ tag: "p",+ },+ ],+ ])+ );++ const insertion = insertTemplateAt({+ templateSelector: ["template", "templates", "block", "body"],+ anchor: ["current", "block", "body"],+ insertBefore: false,+ replaceAnchor: true,+ });await expect(insertion).resolves.toBe(true);+ const children = $instances.get().get("block")?.children ?? [];+ expect(children).toHaveLength(2);+ expect(children[0]).toEqual({ type: "id", value: "templates" });+ expect(children).not.toContainEqual({ type: "id", value: "current" });+ const insertedId = children[1]?.type === "id" ? children[1].value : "";+ expect($instances.get().get(insertedId)?.children).toEqual([+ { type: "text", value: "Template content" },+ ]);});});diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.tsindex ca2823211c..81acbe3af0 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts@@ -1,4 +1,12 @@-import type { WebstudioFragment } from "@webstudio-is/sdk";+import {+ getHtmlTagFromInstance,+ getContentBlockTemplateName,+ isContentBlockMdxTemplateInsertable,+ type Instance,+ type Props,+ type WebstudioFragment,+ type WsComponentMeta,+} from "@webstudio-is/sdk";import { findTextEditorTarget } from "@webstudio-is/project-build/runtime";import {executeRuntimeMutationAsync,@@ -29,6 +37,7 @@ import {findBlockContentSelector,getBlockTemplateInsertionIndex,} from "@webstudio-is/project-build/runtime";+import { recordExternalContentTemplateInsertion } from "~/shared/external-content-mutations";const getTemplateTokenConflicts = ({fragment,@@ -47,6 +56,22 @@ const getTemplateTokenConflicts = ({return detect({ fragment, targetData });};+export const filterInsertableContentBlockTemplates = ({+ templates,+ props,+ metas,+}: {+ templates: [instance: Instance, selector: InstanceSelector][];+ props: Props;+ metas: Map<Instance["component"], WsComponentMeta>;+}) =>+ templates.filter(([instance]) =>+ isContentBlockMdxTemplateInsertable({+ component: instance.component,+ tag: getHtmlTagFromInstance({ instance, props, metas }),+ })+ );+export const __testing__ = {getTemplateTokenConflicts,};@@ -118,12 +143,22 @@ export const insertListItemAt = async (listItemSelector: InstanceSelector) => {selectInstance(selectedInstanceSelector);};-export const insertTemplateAt = async (- templateSelector: InstanceSelector,- anchor: InstanceSelector,- insertBefore: boolean-) => {+export const insertTemplateAt = async ({+ templateSelector,+ anchor,+ insertBefore,+ replaceAnchor = false,+}: {+ templateSelector: InstanceSelector;+ anchor: InstanceSelector;+ insertBefore: boolean;+ replaceAnchor?: boolean;+}) => {const instances = $instances.get();+ const template = instances.get(templateSelector[0]);+ if (template === undefined) {+ return false;+ }const fragment = extractWebstudioFragment(getWebstudioData(),@@ -170,7 +205,10 @@ export const insertTemplateAt = async (fragment,target,conflictResolution,- { contentMode }+ {+ contentMode,+ replaceInstanceSelector: replaceAnchor ? anchor : undefined,+ });if (didInsert === false) {return false;@@ -180,11 +218,33 @@ export const insertTemplateAt = async (return false;}const data = getWebstudioData();+ const metas = $registeredComponentMetas.get();+ const pristineFragment = structuredClone(+ extractWebstudioFragment(data, selectedInstanceSelector[0])+ );+ const pristineProps = new Map(+ pristineFragment.props.map((prop) => [prop.id, prop])+ );+ recordExternalContentTemplateInsertion({+ instanceSelector: selectedInstanceSelector,+ insertion: {+ templateName: getContentBlockTemplateName(template),+ pristineFragment,+ htmlTags: pristineFragment.instances.flatMap((instance) => {+ const tag = getHtmlTagFromInstance({+ instance,+ metas,+ props: pristineProps,+ });+ return tag === undefined ? [] : [{ instanceId: instance.id, tag }];+ }),+ },+ });const editableInstanceSelector = findTextEditorTarget({instanceSelector: selectedInstanceSelector,instances: data.instances,props: data.props,- metas: $registeredComponentMetas.get(),+ metas,});$textEditingInstanceSelector.set(editableInstanceSelectordiff --git a/apps/builder/app/builder/inspector.test.tsx b/apps/builder/app/builder/inspector.test.tsxnew file mode 100644index 0000000000..6613b16d64--- /dev/null+++ b/apps/builder/app/builder/inspector.test.tsx@@ -0,0 +1,135 @@+import { act } from "react-dom/test-utils";+import { createRoot } from "react-dom/client";+import { afterEach, expect, test } from "vitest";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { elementComponent } from "@webstudio-is/sdk";+import { $registeredComponentMetas } from "~/shared/nano-states";+import { __testing__ } from "./inspector";++const { InstanceInfo } = __testing__;++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(() => {+ document.body.innerHTML = "";+ $registeredComponentMetas.set(new Map());+});++test("shows and truncates the instance label and JSX component name", () => {+ const headingMeta = componentMetas.get("Heading");+ if (headingMeta === undefined) {+ throw new Error("Expected Heading component metadata");+ }+ $registeredComponentMetas.set(+ new Map([+ ["Heading", headingMeta],+ ["HeadingBlaBlubbWithALongComponentName", headingMeta],+ ["@webstudio-is/sdk-components-animation:AnimateChildren", headingMeta],+ ])+ );+ const container = document.createElement("div");+ container.style.width = "120px";+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <InstanceInfo+ instance={{+ type: "instance",+ id: "heading",+ component: "Heading",+ label: "Heading",+ children: [],+ }}+ />+ );+ });+ expect(container.textContent).toContain("Heading<Heading>");+ const shortLabel = container.querySelector<HTMLElement>('[title="Heading"]');+ expect(shortLabel).not.toBeNull();+ expect(shortLabel!.scrollWidth).toBeLessThanOrEqual(shortLabel!.clientWidth);+ expect(container.querySelector("svg")).toBeNull();++ act(() => {+ root.render(+ <InstanceInfo+ instance={{+ type: "instance",+ id: "promotion-card",+ component: elementComponent,+ tag: "div",+ name: "PromotionCard",+ children: [],+ }}+ />+ );+ });+ expect(container.textContent).toContain("Promotion Card<PromotionCard>");++ act(() => {+ root.render(+ <InstanceInfo+ instance={{+ type: "instance",+ id: "div",+ component: elementComponent,+ tag: "div",+ name: "Div",+ children: [],+ }}+ />+ );+ });+ expect(container.textContent).toContain("Div<Div>");++ act(() => {+ root.render(+ <InstanceInfo+ instance={{+ type: "instance",+ id: "heading",+ component: "HeadingBlaBlubbWithALongComponentName",+ label: "Heading bla blubb with a long label",+ children: [],+ }}+ />+ );+ });++ const label = container.querySelector<HTMLElement>(+ '[title="Heading bla blubb with a long label"]'+ );+ const component = container.querySelector<HTMLElement>(+ '[title="<HeadingBlaBlubbWithALongComponentName>"]'+ );+ expect(container.textContent).toContain(+ "Heading bla blubb with a long label<HeadingBlaBlubbWithALongComponentName>"+ );+ expect(label).not.toBeNull();+ expect(component).not.toBeNull();+ expect(getComputedStyle(label!).textOverflow).toBe("ellipsis");+ expect(getComputedStyle(label!).maxWidth).toBe("50%");+ expect(getComputedStyle(label!).flexShrink).toBe("0");+ expect(getComputedStyle(component!).textOverflow).toBe("ellipsis");+ expect(label!.scrollWidth).toBeGreaterThan(label!.clientWidth);+ expect(component!.scrollWidth).toBeGreaterThan(component!.clientWidth);++ act(() => {+ root.render(+ <InstanceInfo+ instance={{+ type: "instance",+ id: "animate-children",+ component: "@webstudio-is/sdk-components-animation:AnimateChildren",+ children: [],+ }}+ />+ );+ });+ expect(container.textContent).toContain("Animate Children<AnimateChildren>");++ act(() => root.unmount());+});diff --git a/apps/builder/app/builder/inspector.tsx b/apps/builder/app/builder/inspector.tsxindex 12ed5ee61b..47203401eb 100644--- a/apps/builder/app/builder/inspector.tsx+++ b/apps/builder/app/builder/inspector.tsx@@ -1,7 +1,11 @@import { useRef } from "react";import { computed } from "nanostores";import { useStore } from "@nanostores/react";-import type { Instance } from "@webstudio-is/sdk";+import {+ elementComponent,+ getComponentJsxName,+ type Instance,+} from "@webstudio-is/sdk";import {theme,PanelTabs,@@ -33,16 +37,38 @@ import {$selectedInstanceKey,$selectedPage,} from "~/shared/nano-states";-import { InstanceIcon, getInstanceLabel } from "./shared/instance-label";+import { getInstanceLabel } from "./shared/instance-label";const InstanceInfo = ({ instance }: { instance: Instance }) => {+ const metas = useStore($registeredComponentMetas);+ const label = getInstanceLabel(instance);+ const componentName =+ instance.name ??+ (instance.component === elementComponent+ ? (instance.tag ?? "div")+ : getComponentJsxName({+ component: instance.component,+ components: new Set([...metas.keys(), instance.component]),+ }));+ const componentTag = `<${componentName}>`;return (- <Flex gap="1" align="center">- <Flex shrink={false}>- <InstanceIcon instance={instance} />- </Flex>- <Text truncate variant="labels">- {getInstanceLabel(instance)}+ <Flex gap="1" align="center" grow css={{ minWidth: 0, overflow: "hidden" }}>+ <Text+ truncate+ variant="labels"+ title={label}+ css={{ minWidth: 0, maxWidth: "50%", flexShrink: 0 }}+ >+ {label}+ </Text>+ <Text+ truncate+ variant="labels"+ color="subtle"+ title={componentTag}+ css={{ minWidth: 0, flexShrink: 1 }}+ >+ {componentTag}</Text></Flex>);@@ -208,4 +234,5 @@ export const Inspector = ({ navigatorLayout }: InspectorProps) => {export const __testing__ = {getInspectorEmptyStateMessage,+ InstanceInfo,};diff --git a/apps/builder/app/builder/shared/instance-label.tsx b/apps/builder/app/builder/shared/instance-label.tsxindex bf314577ef..33928248af 100644--- a/apps/builder/app/builder/shared/instance-label.tsx+++ b/apps/builder/app/builder/shared/instance-label.tsx@@ -75,6 +75,7 @@ const htmlIcons: Record<string, undefined | string> = {type InstanceLike = {component: string;label?: string;+ name?: string;tag?: string;};@@ -123,6 +124,9 @@ export const getInstanceLabel = (if (instanceOrInstanceId.label) {return instanceOrInstanceId.label;}+ if (instanceOrInstanceId.name) {+ return humanizeString(instanceOrInstanceId.name);+ }if (instanceOrInstanceId.component === elementComponent &&instanceOrInstanceId.tagdiff --git a/apps/builder/app/canvas/features/build-mode/block.tsx b/apps/builder/app/canvas/features/build-mode/block.tsxindex 2c4f0a655d..13d139b5d0 100644--- a/apps/builder/app/canvas/features/build-mode/block.tsx+++ b/apps/builder/app/canvas/features/build-mode/block.tsx@@ -31,13 +31,14 @@ export const Block = React.forwardRef<return <div>Content Block instance is undefined</div>;}- const templateInstance = findContentBlockTemplateContainers({+ const templateInstances = findContentBlockTemplateContainers({blockInstance: instance,instances,- })[0];- if (templateInstance === undefined) {- return <div>Content Block template child is not found</div>;+ });+ if (templateInstances.length !== 1) {+ return <div>Content Block must contain exactly one Templates list</div>;}+ const [templateInstance] = templateInstances;const templateInstanceId = templateInstance.id;if (isDesignMode) {diff --git a/apps/builder/app/canvas/features/text-editor/interop.test.tsx b/apps/builder/app/canvas/features/text-editor/interop.test.tsxindex 52ff11da04..a9ba5e3520 100644--- a/apps/builder/app/canvas/features/text-editor/interop.test.tsx+++ b/apps/builder/app/canvas/features/text-editor/interop.test.tsx@@ -2,7 +2,12 @@ import { test, expect } from "vitest";import { createHeadlessEditor } from "@lexical/headless";import { LinkNode } from "@lexical/link";import { $createParagraphNode, $createTextNode, $getRoot } from "lexical";-import { $, renderData, renderTemplate, ws } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+ renderTemplate,+ ws,+} from "@webstudio-is/template";import {$convertToLexical,$convertToPlainTextUpdate,@@ -10,21 +15,28 @@ import {type Refs,} from "./interop";+const Body = createTemplateComponentFixture("Body");+const Bold = createTemplateComponentFixture("Bold");+const Box = createTemplateComponentFixture("Box");+const Italic = createTemplateComponentFixture("Italic");+const RichTextLink = createTemplateComponentFixture("RichTextLink");+const Span = createTemplateComponentFixture("Span");+const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="emptyBoxId"></$.Box>- <$.Box ws:id="textBoxId">+ <Body ws:id="bodyId">+ <Box ws:id="emptyBoxId"></Box>+ <Box ws:id="textBoxId">Hello{"\n"}- <$.Bold ws:id="boldId">- <$.Italic ws:id="italicId">world</$.Italic>- </$.Bold>+ <Bold ws:id="boldId">+ <Italic ws:id="italicId">world</Italic>+ </Bold>{"\n"}- <$.Span ws:id="spanId">and</$.Span>+ <Span ws:id="spanId">and</Span>{"\n"}- <$.RichTextLink ws:id="linkId" href="/my-url">+ <RichTextLink ws:id="linkId" href="/my-url">other realms- </$.RichTextLink>- </$.Box>+ </RichTextLink>+ </Box><ws.element ws:tag="div" ws:id="textElementId">Hello{"\n"}<ws.element ws:tag="b" ws:id="boldElementId">@@ -41,7 +53,7 @@ const { instances } = renderData(other realms</ws.element></ws.element>- </$.Body>+ </Body>);const expectedState = {@@ -219,11 +231,11 @@ test("convert lexical to instances uses supplied id generator for new formattingexpect(updates).toEqual(renderTemplate(- <$.Box ws:id="emptyBoxId">+ <Box ws:id="emptyBoxId"><ws.element ws:tag="b" ws:id="generated-bold">Generated</ws.element>- </$.Box>+ </Box>).instances);});diff --git a/apps/builder/app/canvas/features/text-editor/interop.ts b/apps/builder/app/canvas/features/text-editor/interop.tsindex 9a10295c62..214036d9d2 100644--- a/apps/builder/app/canvas/features/text-editor/interop.ts+++ b/apps/builder/app/canvas/features/text-editor/interop.ts@@ -42,7 +42,8 @@ const $writeUpdates = (instancesList: Instance[],refs: Refs,newLinkKeyToInstanceId: Refs,- createId: CreateId+ createId: CreateId,+ transientTextNodeKeys: ReadonlySet<string>) => {const children = node.getChildren();for (const child of children) {@@ -53,7 +54,8 @@ const $writeUpdates = (instancesList,refs,newLinkKeyToInstanceId,- createId+ createId,+ transientTextNodeKeys);}if ($isLineBreakNode(child)) {@@ -74,7 +76,8 @@ const $writeUpdates = (instancesList,refs,newLinkKeyToInstanceId,- createId+ createId,+ transientTextNodeKeys);instancesList.push({type: "instance",@@ -85,6 +88,9 @@ const $writeUpdates = (});}if ($isTextNode(child)) {+ if (transientTextNodeKeys.has(child.getKey())) {+ continue;+ }// support nesting bold into italic and vice versa// considering lexical represents both as single node// and add ref suffix to distinct styling on one node key@@ -133,7 +139,8 @@ export const $convertToUpdates = (treeRootInstance: Instance,refs: Refs,newLinkKeyToInstanceId: Refs,- createId: CreateId+ createId: CreateId,+ transientTextNodeKeys: ReadonlySet<string> = new Set()) => {const treeRootInstanceChildren: Instance["children"] = [];const instancesList: Instance[] = [@@ -149,7 +156,8 @@ export const $convertToUpdates = (instancesList,refs,newLinkKeyToInstanceId,- createId+ createId,+ transientTextNodeKeys);return instancesList;};diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsxindex 98ee6e9974..14b06d33ab 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx@@ -3,10 +3,17 @@ import { useStore } from "@nanostores/react";import { ContentEditable } from "@lexical/react/LexicalContentEditable";import type { StoryFn, Meta } from "@storybook/react";import { action } from "@storybook/addon-actions";-import { Box, Button, Flex, StorySection } from "@webstudio-is/design-system";+import {+ Box as DesignSystemBox,+ Button,+ Flex,+ StorySection,+} from "@webstudio-is/design-system";import { theme } from "@webstudio-is/design-system";import type { Instance, Instances, Props } from "@webstudio-is/sdk";-import { $, renderData } from "@webstudio-is/template";+import { Body, Bold, Box } from "@webstudio-is/sdk-components-react/components";+import { componentIds } from "@webstudio-is/sdk-components-registry/components";+import { renderData } from "@webstudio-is/template";import {$registeredComponentMetas,$textEditingInstanceSelector,@@ -120,7 +127,7 @@ export const Basic: StoryFn<typeof TextEditor> = () => {>Clear</button>- <Box+ <DesignSystemBoxcss={{"& > div": {padding: `0 ${theme.spacing[5]}`,@@ -139,7 +146,7 @@ export const Basic: StoryFn<typeof TextEditor> = () => {console.info("select instance", instanceId)}/>- </Box>+ </DesignSystemBox></div></StorySection>);@@ -150,7 +157,7 @@ export const CursorPositioning: StoryFn<typeof TextEditor> = () => {return (<StorySection title="Cursor Positioning">- <Box+ <DesignSystemBoxcss={{width: 300,"& > div": {@@ -200,7 +207,7 @@ export const CursorPositioning: StoryFn<typeof TextEditor> = () => {<strong> la la la subtext</strong></div>)}- </Box>+ </DesignSystemBox><br /><div><i>Click on text above, see cursor position and start editing text</i>@@ -271,17 +278,19 @@ export const CursorPositioningUpDown: StoryFn<typeof TextEditor> = () => {);return renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxAId">- Hello world <$.Bold ws:id="boldA">Hello world</$.Bold> Hello world- world Hello worldsdsdj skdk ls dk jslkdjklsjdkl sdk jskdj ksjd lksdj- dsj- </$.Box>- <$.Box ws:id="boxBId">- Let it be Let it be <$.Bold ws:id="boldB">Let it be Let</$.Bold> Let- it be Let it be Let it be Let it be Let it be Let it be- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxAId">+ Hello world <Bold ws:id="boldA">Hello world</Bold> Hello world world+ Hello worldsdsdj skdk ls dk jslkdjklsjdkl sdk jskdj ksjd lksdj dsj+ </Box>+ <Box ws:id="boxBId">+ Let it be Let it be <Bold ws:id="boldB">Let it be Let</Bold> Let it be+ Let it be Let it be Let it be Let it be Let it be+ </Box>+ </Body>,+ undefined,+ [],+ { componentIds });});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 6b0101881f..4fa631817a 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@@ -1,9 +1,21 @@import { act } from "react-dom/test-utils";import { createRoot, type Root } from "react-dom/client";-import { afterEach, describe, expect, test } from "vitest";+import { afterEach, describe, expect, test, vi } from "vitest";import { ContentEditable } from "@lexical/react/LexicalContentEditable";-import { elementComponent, type Instance } from "@webstudio-is/sdk";-import { $textEditingInstanceSelector } from "~/shared/nano-states";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type Instance,+} from "@webstudio-is/sdk";+import {+ $textEditorContextMenu,+ $textEditorContextMenuCommand,+ $textEditingInstanceSelector,+ execTextEditorContextMenuCommand,+ selectInstance,+} from "~/shared/nano-states";+import { $instances, $props } from "~/shared/sync/data-stores";import { TextEditor } from "./text-editor";(@@ -12,6 +24,51 @@ import { TextEditor } from "./text-editor";let root: Root | undefined;+const createContentBlockInstances = () =>+ new Map<Instance["id"], Instance>([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "templates" },+ { type: "id", value: "current" },+ ],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "template" }],+ },+ ],+ [+ "template",+ {+ type: "instance",+ id: "template",+ component: elementComponent,+ tag: "p",+ children: [],+ },+ ],+ [+ "current",+ {+ type: "instance",+ id: "current",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Before" }],+ },+ ],+ ]);+afterEach(() => {act(() => {root?.unmount();@@ -19,6 +76,10 @@ afterEach(() => {root = undefined;document.body.innerHTML = "";$textEditingInstanceSelector.set(undefined);+ $textEditorContextMenu.set(undefined);+ selectInstance(undefined);+ $instances.set(new Map());+ $props.set(new Map());});describe("TextEditor", () => {@@ -60,4 +121,285 @@ describe("TextEditor", () => {true);});++ 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);++ 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 })+ );+ });+ expect(editable?.textContent).toBe("Before/");+ expect($textEditorContextMenu.get()).toMatchObject({+ replaceAnchor: false,+ });++ await act(async () => {+ 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" }],+ })+ );+ });++ test("does not save an editor after its instance was replaced", async () => {+ const instances = createContentBlockInstances();+ $instances.set(instances);+ $textEditingInstanceSelector.set({+ selector: ["current", "block"],+ reason: "new",+ });+ 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={() => {}}+ />+ );+ });++ const editable = container.querySelector<HTMLElement>(+ "[data-lexical-editor]"+ );+ await act(async () => {+ editable?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "/", bubbles: true })+ );+ });+ await act(async () => {+ $instances.set(new Map());+ editable?.dispatchEvent(new FocusEvent("blur"));+ });++ expect(onChange).not.toHaveBeenCalled();+ });++ test("marks slash insertion as a replacement when it replaces all text", async () => {+ const instances = createContentBlockInstances();+ $instances.set(instances);+ selectInstance(["current", "block"]);+ $textEditingInstanceSelector.set({+ selector: ["current", "block"],+ reason: "new",+ });+ 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={() => {}}+ onSelectInstance={() => {}}+ />+ );+ });++ const editable = container.querySelector<HTMLElement>(+ "[data-lexical-editor]"+ );+ await act(async () => {+ editable?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "/", bubbles: true })+ );+ });++ expect(editable?.textContent).toBe("/");+ expect($textEditorContextMenu.get()).toMatchObject({+ replaceAnchor: true,+ });+ });++ test("restores normal keyboard handling when template insertion is cancelled", async () => {+ const instances = createContentBlockInstances();+ $instances.set(instances);+ selectInstance(["current", "block"]);+ $textEditingInstanceSelector.set({+ selector: ["current", "block"],+ reason: "left",+ });+ 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={() => {}}+ onSelectInstance={() => {}}+ />+ );+ });++ const editable = container.querySelector<HTMLElement>(+ "[data-lexical-editor]"+ );+ await act(async () => {+ editable?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "/", bubbles: true })+ );+ });+ expect($textEditorContextMenu.get()).toBeDefined();++ await act(async () => {+ execTextEditorContextMenuCommand({+ type: "templateInsertionStarted",+ });+ execTextEditorContextMenuCommand({ type: "templateInsertionCancelled" });+ await Promise.resolve();+ });+ expect($textEditorContextMenu.get()).toBeUndefined();++ const commands: string[] = [];+ const unsubscribe = $textEditorContextMenuCommand.listen((command) => {+ if (command !== undefined) {+ commands.push(command.type);+ }+ });+ commands.length = 0;+ editable?.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ bubbles: true,+ cancelable: true,+ })+ );+ unsubscribe();+ expect(commands).not.toContain("selectNext");+ });++ test("enables the slash menu when a template is added while editing", async () => {+ const current: Instance = {+ type: "instance",+ id: "current",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Before" }],+ };+ const block: Instance = {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "templates" },+ { type: "id", value: current.id },+ ],+ };+ const templates: Instance = {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ };+ const instances = new Map(+ [block, templates, current].map((instance) => [instance.id, instance])+ );+ $instances.set(instances);+ selectInstance([current.id, block.id]);+ $textEditingInstanceSelector.set({+ selector: [current.id, block.id],+ reason: "left",+ });+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);++ await act(async () => {+ root?.render(+ <TextEditor+ rootInstanceSelector={[current.id, block.id]}+ instances={instances}+ props={new Map()}+ contentEditable={<ContentEditable />}+ onChange={() => {}}+ onSelectInstance={() => {}}+ />+ );+ });++ const template: Instance = {+ type: "instance",+ id: "paragraph-template",+ component: elementComponent,+ tag: "p",+ label: "Paragraph",+ children: [],+ };+ await act(async () => {+ $instances.set(+ new Map([+ ...instances,+ [+ templates.id,+ { ...templates, children: [{ type: "id", value: template.id }] },+ ],+ [template.id, template],+ ])+ );+ });++ const editable = container.querySelector<HTMLElement>(+ "[data-lexical-editor]"+ );+ await act(async () => {+ editable?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "/", bubbles: true })+ );+ });+ expect($textEditorContextMenu.get()).toBeDefined();++ await act(async () => {+ $instances.set(new Map($instances.get()));+ });+ expect($textEditorContextMenu.get()).toBeDefined();+ });});diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsxindex 67ca8d57a0..f7fb147f5a 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx@@ -49,10 +49,12 @@ import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";import { LinkPlugin } from "@lexical/react/LexicalLinkPlugin";+import { useStore } from "@nanostores/react";import { createRegularStyleSheet } from "@webstudio-is/css-engine";import {createId,+ getHtmlTagFromInstance,type Instance,type Instances,type Props,@@ -87,7 +89,7 @@ import {execTextEditorContextMenuCommand,} from "~/shared/nano-states";-import { $instances } from "~/shared/sync/data-stores";+import { $instances, $props } from "~/shared/sync/data-stores";import {findBlockChildSelector,findBlockTemplates,@@ -106,6 +108,7 @@ import {import { selectInstance } from "~/shared/nano-states";import { shallowEqual } from "shallow-equal";import {+ filterInsertableContentBlockTemplates,insertListItemAt,insertTemplateAt,} from "~/builder/features/workspace/canvas-tools/outline/block-utils";@@ -1029,10 +1032,12 @@ const SwitchBlockPlugin = ({ onNext }: SwitchBlockPluginProps) => {type ContextMenuParams = {cursorRect: DOMRect;+ replaceAnchor: boolean;};type RichTextContentPluginProps = {rootInstanceSelector: InstanceSelector;+ transientTextNodeKeys: Set<NodeKey>;onOpen: (editorState: EditorState,params: undefined | ContextMenuParams@@ -1041,22 +1046,30 @@ type RichTextContentPluginProps = {};const RichTextContentPlugin = (props: RichTextContentPluginProps) => {- const [templates] = useState(() =>- findBlockTemplates({- anchor: props.rootInstanceSelector,- instances: $instances.get(),- })- );+ const instances = useStore($instances);+ const instanceProps = useStore($props);+ const metas = useStore($registeredComponentMetas);+ const templates = findBlockTemplates({+ anchor: props.rootInstanceSelector,+ instances,+ });if (templates === undefined) {return;}- if (templates.length === 0) {+ const insertableTemplates = filterInsertableContentBlockTemplates({+ templates,+ props: instanceProps,+ metas,+ });+ if (insertableTemplates.length === 0) {return;}- return <RichTextContentPluginInternal {...props} templates={templates} />;+ return (+ <RichTextContentPluginInternal {...props} templates={insertableTemplates} />+ );};const getTag = (instanceId: Instance["id"]) => {@@ -1066,13 +1079,16 @@ const getTag = (instanceId: Instance["id"]) => {if (instance === undefined) {return;}- const meta = metas.get(instance.component);- const tags = Object.keys(meta?.presetStyle ?? {});- return instance.tag ?? tags[0];+ return getHtmlTagFromInstance({+ instance,+ metas,+ props: $props.get(),+ });};const RichTextContentPluginInternal = ({rootInstanceSelector,+ transientTextNodeKeys,onOpen,templates,onNext,@@ -1083,6 +1099,7 @@ const RichTextContentPluginInternal = ({const [preservedSelection] = useState(rootInstanceSelector);const handleOpen = useEffectEvent(onOpen);+ const getTemplates = useEffectEvent(() => templates);useEffect(() => {if (!editor.isEditable()) {@@ -1092,9 +1109,14 @@ const RichTextContentPluginInternal = ({let menuState: "closed" | "opening" | "opened" = "closed";let slashNodeKey: NodeKey | undefined = undefined;+ let replaceAnchor = false;let removeSlashWhenSelectionChanges = false;- const closeMenu = () => {+ const closeMenu = ({+ deferSlashNormalization = false,+ }: {+ deferSlashNormalization?: boolean;+ } = {}) => {if (menuState === "closed" && removeSlashWhenSelectionChanges === false) {return;}@@ -1110,10 +1132,7 @@ const RichTextContentPluginInternal = ({}const node = $getNodeByKey(slashNodeKey);-- if ($isTextNode(node)) {- node.setStyle("");- }+ const currentSlashNodeKey = slashNodeKey;const selectedInstanceSelector = $selectedInstanceSelector.get();@@ -1123,6 +1142,7 @@ const RichTextContentPluginInternal = ({if (!isSelectionInSameComponent) {node?.remove();+ transientTextNodeKeys.delete(currentSlashNodeKey);slashNodeKey = undefined;removeSlashWhenSelectionChanges = false;@@ -1137,6 +1157,27 @@ const RichTextContentPluginInternal = ({deleteInstanceBySelector(rootInstanceSelector);}}+ } else if (deferSlashNormalization) {+ queueMicrotask(() => {+ editor.update(() => {+ const currentNode = $getNodeByKey(currentSlashNodeKey);+ if ($isTextNode(currentNode)) {+ currentNode.setStyle("");+ }+ transientTextNodeKeys.delete(currentSlashNodeKey);+ const currentSelection = $getSelection();+ if ($isRangeSelection(currentSelection)) {+ currentSelection.setStyle("");+ }+ });+ });+ return;+ } else {+ transientTextNodeKeys.delete(currentSlashNodeKey);+ }++ if ($isTextNode(node)) {+ node.setStyle("");}// if selection changed, remove the slash node@@ -1157,6 +1198,11 @@ const RichTextContentPluginInternal = ({}if (command?.type === "templateInsertionCancelled") {removeSlashWhenSelectionChanges = false;+ editor.update(() => closeMenu());+ }+ if (command?.type === "close") {+ removeSlashWhenSelectionChanges = false;+ editor.update(() => closeMenu());}});@@ -1243,7 +1289,7 @@ const RichTextContentPluginInternal = ({const allowedTags = ["p", "h1", "h2", "h3", "h4", "h5", "h6"];for (const tag of allowedTags) {- const templateSelector = templates.find(+ const templateSelector = getTemplates().find(([instance]) => getTag(instance.id) === tag)?.[1];@@ -1285,7 +1331,11 @@ const RichTextContentPluginInternal = ({*/- insertTemplateAt(templateSelector, rootInstanceSelector, false);+ insertTemplateAt({+ templateSelector,+ anchor: rootInstanceSelector,+ insertBefore: false,+ });if (tag === "li" && $getRoot().getTextContentSize() === 0) {const parentInstanceSelector = rootInstanceSelector.slice(1);@@ -1356,7 +1406,13 @@ const RichTextContentPluginInternal = ({}const slashNode = $createTextNode("/");+ const rootText = $getRoot().getTextContent();+ replaceAnchor =+ rootText.length === 0 ||+ (selection.isCollapsed() === false &&+ selection.getTextContent() === rootText);slashNodeKey = slashNode.getKey();+ transientTextNodeKeys.add(slashNodeKey);menuState = "opening";slashNode.setStyle(@@ -1376,13 +1432,13 @@ const RichTextContentPluginInternal = ({COMMAND_PRIORITY_EDITOR);- const closeMenuWithUpdate = () => {+ const closeMenuWithUpdate = (deferSlashNormalization = false) => {if (menuState === "closed" && removeSlashWhenSelectionChanges === false) {return;}editor.update(() => {- closeMenu();+ closeMenu({ deferSlashNormalization });});};@@ -1431,16 +1487,18 @@ const RichTextContentPluginInternal = ({handleOpen(editor.getEditorState(), {cursorRect: rect,+ replaceAnchor,});});}});+ const handleBlur = () => closeMenuWithUpdate(true);const unsubscribeBlurListener = editor.registerRootListener((rootElement, prevRootElement) => {- rootElement?.addEventListener("blur", closeMenuWithUpdate);- prevRootElement?.removeEventListener("blur", closeMenuWithUpdate);+ rootElement?.addEventListener("blur", handleBlur);+ prevRootElement?.removeEventListener("blur", handleBlur);});@@ -1451,9 +1509,15 @@ const RichTextContentPluginInternal = ({unsubscribeBlurListener();unsubscribeContextMenuCommand();// Safari and FF support as no blur event is triggered in some cases- closeMenuWithUpdate();+ closeMenuWithUpdate(true);};- }, [editor, onNext, preservedSelection, rootInstanceSelector, templates]);+ }, [+ editor,+ onNext,+ preservedSelection,+ rootInstanceSelector,+ transientTextNodeKeys,+ ]);return null;};@@ -1563,32 +1627,39 @@ export const TextEditor = ({const handleChange = useEffectEvent((editorState: EditorState, reason: "blur" | "unmount" | "next") => {+ const currentInstances = $instances.get();+ const treeRootInstance = currentInstances.get(rootInstanceSelector[0]);+ // Replacing a content block child unmounts its editor after the instance+ // was deleted. Do not write the detached editor state back over the+ // replacement.+ if (treeRootInstance === undefined) {+ return;+ }+editorState.read(() => {- const treeRootInstance = instances.get(rootInstanceSelector[0]);- if (treeRootInstance) {- const jsonState = editorState.toJSON();- if (deepEqual(jsonState, lastSavedStateJsonRef.current)) {- inflateInstance(rootInstanceSelector[0], false);- return;- }+ const jsonState = editorState.toJSON();+ if (deepEqual(jsonState, lastSavedStateJsonRef.current)) {+ inflateInstance(rootInstanceSelector[0], false);+ return;+ }- const updates = plainText- ? $convertToPlainTextUpdate(treeRootInstance)- : $convertToUpdates(- treeRootInstance,- refs,- newLinkKeyToInstanceId,- builderRuntimeContext.createId- );- const idMap = onChange(updates);- if (idMap !== undefined) {- for (const [key, instanceId] of refs) {- refs.set(key, idMap[instanceId] ?? instanceId);- }+ const updates = plainText+ ? $convertToPlainTextUpdate(treeRootInstance)+ : $convertToUpdates(+ treeRootInstance,+ refs,+ newLinkKeyToInstanceId,+ builderRuntimeContext.createId,+ transientTextNodeKeys+ );+ const idMap = onChange(updates);+ if (idMap !== undefined) {+ for (const [key, instanceId] of refs) {+ refs.set(key, idMap[instanceId] ?? instanceId);}- newLinkKeyToInstanceId.clear();- lastSavedStateJsonRef.current = jsonState;}+ newLinkKeyToInstanceId.clear();+ lastSavedStateJsonRef.current = jsonState;inflateInstance(rootInstanceSelector[0], false);});@@ -1633,6 +1704,7 @@ export const TextEditor = ({// cannot store custom data// Map<nodeKey, Instance>const [refs] = useState<Refs>(() => new Map());+ const [transientTextNodeKeys] = useState(() => new Set<NodeKey>());const initialConfig = {namespace: "WsTextEditor",theme: {@@ -1700,9 +1772,7 @@ export const TextEditor = ({if (instance === undefined) {continue;}- const meta = metas.get(instance.component);- const tags = Object.keys(meta?.presetStyle ?? {});- const tag = instance.tag ?? tags[0];+ const tag = getHtmlTagFromInstance({ instance, metas, props });// opinionated: Non-collapsed elements without children can act as spacers (they have size for some reason).if (@@ -1799,6 +1869,7 @@ export const TextEditor = ({<RichTextContentPluginonOpen={handleContextMenuOpen}rootInstanceSelector={rootInstanceSelector}+ transientTextNodeKeys={transientTextNodeKeys}// oxlint-disable-next-line react-hooks/rules-of-hooks -- our useEffectEvent is a stable callbackonNext={handleNext}/>diff --git a/apps/builder/app/canvas/shared/use-drag-drop.test.tsx b/apps/builder/app/canvas/shared/use-drag-drop.test.tsxindex add714bda6..465990120c 100644--- a/apps/builder/app/canvas/shared/use-drag-drop.test.tsx+++ b/apps/builder/app/canvas/shared/use-drag-drop.test.tsx@@ -12,7 +12,10 @@ import { coreMetas } from "@webstudio-is/sdk";import type { Project } from "@webstudio-is/project";import { createDefaultPages } from "@webstudio-is/project-build";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";-import { $, renderData } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+} from "@webstudio-is/template";import {$registeredComponentMetas,$registeredTemplates,@@ -36,6 +39,10 @@ import {import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";import { commitCanvasDragDrop } from "./use-drag-drop";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Text = createTemplateComponentFixture("Text");+enableMapSet();registerContainers();@@ -83,12 +90,12 @@ describe("commitCanvasDragDrop", () => {test("reparents existing subtree through runtime bridge and preserves related data", () => {const data = renderData(- <$.Body ws:id="body">- <$.Box ws:id="source">- <$.Text ws:id="child">Dynamic card</$.Text>- </$.Box>- <$.Box ws:id="target"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="source">+ <Text ws:id="child">Dynamic card</Text>+ </Box>+ <Box ws:id="target"></Box>+ </Body>);const prop = {id: "child-prop",@@ -206,7 +213,7 @@ describe("commitCanvasDragDrop", () => {});test("inserts dragged component through runtime bridge", () => {- const data = renderData(<$.Body ws:id="body"></$.Body>);+ const data = renderData(<Body ws:id="body"></Body>);$instances.set(data.instances);serverSyncStore.popAll();@@ -241,7 +248,7 @@ describe("commitCanvasDragDrop", () => {});test("inserts an Image with its source bound to the dragged asset", () => {- const data = renderData(<$.Body ws:id="body"></$.Body>);+ const data = renderData(<Body ws:id="body"></Body>);$instances.set(data.instances);serverSyncStore.popAll();@@ -272,7 +279,7 @@ describe("commitCanvasDragDrop", () => {});test("does not commit incomplete drag state", () => {- const data = renderData(<$.Body ws:id="body"></$.Body>);+ const data = renderData(<Body ws:id="body"></Body>);$instances.set(data.instances);expect(diff --git a/apps/builder/app/services/build-router.server.test.ts b/apps/builder/app/services/build-router.server.test.tsindex 9588bdd523..e1560eeb92 100644--- a/apps/builder/app/services/build-router.server.test.ts+++ b/apps/builder/app/services/build-router.server.test.ts@@ -115,7 +115,7 @@ describe("build router jsx fragment conversion", () => {await expect(caller.createJsxFragment({projectId: "project-id",- source: `<$.Box><$.Heading>Title</$.Heading></$.Box>`,+ source: `<Box><Heading>Title</Heading></Box>`,})).resolves.toEqual(expect.objectContaining({@@ -134,7 +134,7 @@ describe("build router jsx fragment conversion", () => {await expect(caller.createJsxFragment({projectId: "project-id",- source: `<$.Box {...{"ws:id": "0"}} />`,+ source: `<Box {...{"ws:id": "0"}} />`,})).rejects.toThrow("Do not set ws:id in JSX fragments");});@@ -146,7 +146,7 @@ describe("build router jsx fragment conversion", () => {await expect(caller.createJsxFragment({projectId: "project-id",- source: `<$.Box />`,+ source: `<Box />`,})).rejects.toThrow("You don't have access to this project");});diff --git a/apps/builder/app/shared/awareness.test.tsx b/apps/builder/app/shared/awareness.test.tsxindex c1633d4d9e..d580f3bafd 100644--- a/apps/builder/app/shared/awareness.test.tsx+++ b/apps/builder/app/shared/awareness.test.tsx@@ -7,7 +7,16 @@ import { selectInstance, selectInstances } from "./nano-states/instances";import { $selectedPageId } from "./nano-states";import { $user } from "./nano-states/misc";import { createDefaultPages } from "@webstudio-is/project-build";-import { $, renderData } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+} from "@webstudio-is/template";++const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Fragment = createTemplateComponentFixture("Fragment");+const Slot = createTemplateComponentFixture("Slot");+const Text = createTemplateComponentFixture("Text");test("find awareness by instance", () => {const pages = createDefaultPages({@@ -15,11 +24,11 @@ test("find awareness by instance", () => {rootInstanceId: "bodyId",});const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Text ws:id="textId"></$.Text>- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <Text ws:id="textId"></Text>+ </Box>+ </Body>);expect(findPageAndSelectorByInstanceId(pages, instances, "textId")).toEqual({pageId: "homePageId",@@ -33,18 +42,18 @@ test("find awareness by instance inside of slot", () => {rootInstanceId: "bodyId",});const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slotOneId">- <$.Fragment ws:id="fragmentId">- <$.Box ws:id="boxId"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slotTwoId">- <$.Fragment ws:id="fragmentId">- <$.Box ws:id="boxId"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="bodyId">+ <Slot ws:id="slotOneId">+ <Fragment ws:id="fragmentId">+ <Box ws:id="boxId"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slotTwoId">+ <Fragment ws:id="fragmentId">+ <Box ws:id="boxId"></Box>+ </Fragment>+ </Slot>+ </Body>);expect(findPageAndSelectorByInstanceId(pages, instances, "boxId")).toEqual({pageId: "homePageId",diff --git a/apps/builder/app/shared/content-block-diagnostics.test.ts b/apps/builder/app/shared/content-block-diagnostics.test.tsindex a73522d200..88a148d01c 100644--- a/apps/builder/app/shared/content-block-diagnostics.test.ts+++ b/apps/builder/app/shared/content-block-diagnostics.test.ts@@ -37,3 +37,17 @@ test("formats and deduplicates diagnostics by revision without losing detail", (diagnostic,]);});++test("formats ambiguous semantic template diagnostics", () => {+ expect(+ formatContentBlockDiagnostic({+ code: "ambiguous-template",+ severity: "warning",+ blockInstanceId: "block",+ semanticKey: "element:h1",+ templateNames: ["Primary Heading", "Alternate Heading"],+ })+ ).toBe(+ "Multiple templates match element:h1: Primary Heading, Alternate Heading. The semantic fallback without Content Block template styles was used."+ );+});diff --git a/apps/builder/app/shared/content-block-diagnostics.ts b/apps/builder/app/shared/content-block-diagnostics.tsindex bbea4f1697..b4125a19df 100644--- a/apps/builder/app/shared/content-block-diagnostics.ts+++ b/apps/builder/app/shared/content-block-diagnostics.ts@@ -17,6 +17,8 @@ export const formatContentBlockDiagnostic = (message = diagnostic.reason;} else if (diagnostic.code === "unresolved-template") {message = `Template "${diagnostic.templateName}" is not available and was skipped.`;+ } else if (diagnostic.code === "ambiguous-template") {+ message = `Multiple templates match ${diagnostic.semanticKey}: ${diagnostic.templateNames.join(", ")}. The semantic fallback without Content Block template styles was used.`;} else if (diagnostic.code === "ignored-template-prop") {message = `Property "${diagnostic.propName}" on template "${diagnostic.templateNamediff --git a/apps/builder/app/shared/copy-paste/asset-upload.test.tsx b/apps/builder/app/shared/copy-paste/asset-upload.test.tsxindex ca53588f45..0955d3ef96 100644--- a/apps/builder/app/shared/copy-paste/asset-upload.test.tsx+++ b/apps/builder/app/shared/copy-paste/asset-upload.test.tsx@@ -1,17 +1,25 @@import { expect, test, vi } from "vitest";-import { $, AssetValue, renderTemplate } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ AssetValue,+ renderTemplate,+} from "@webstudio-is/template";import type { StyleDecl, WebstudioFragment } from "@webstudio-is/sdk";import { denormalizeSrcProps } from "./asset-upload";import { builderRuntimeContext } from "@webstudio-is/project-build/runtime";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Image = createTemplateComponentFixture("Image");+test("extractSrcProps works well", async () => {const data = renderTemplate(- <$.Body ws:id="boxA">- <$.Image ws:id="imageA" src="https://src-a/"></$.Image>- <$.Box ws:id="boxB">- <$.Image ws:id="imageB" src="https://src-b/"></$.Image>- </$.Box>- </$.Body>+ <Body ws:id="boxA">+ <Image ws:id="imageA" src="https://src-a/"></Image>+ <Box ws:id="boxB">+ <Image ws:id="imageB" src="https://src-b/"></Image>+ </Box>+ </Body>);const src2AssetId = (src: string) => `${src}asset-id`;@@ -30,22 +38,17 @@ test("extractSrcProps works well", async () => {const assetB = new AssetValue(src2AssetId("https://src-b/"));const desiredOutcome = renderTemplate(- <$.Body ws:id="boxA">- <$.Image- ws:id="imageA"- src={assetA}- width={assetA}- height={assetA}- ></$.Image>- <$.Box ws:id="boxB">- <$.Image+ <Body ws:id="boxA">+ <Image ws:id="imageA" src={assetA} width={assetA} height={assetA}></Image>+ <Box ws:id="boxB">+ <Imagews:id="imageB"src={assetB}width={assetB}height={assetB}- ></$.Image>- </$.Box>- </$.Body>+ ></Image>+ </Box>+ </Body>);expect(denormalizedData.instances).toEqual(desiredOutcome.instances);@@ -132,12 +135,12 @@ test("it works well with no background-images", async () => {test("upload raw inception images", async () => {const data = renderTemplate(- <$.Body ws:id="boxA">- <$.Image+ <Body ws:id="boxA">+ <Imagews:id="imageA"src="https://preview.webstudio.ai/cgi/image/dev/5036ed5c3dfce99eaac566a06bc3729620354a364357907a523f1feb2d6fb819.png?width=1024&height=1024&format=auto"- ></$.Image>- </$.Body>+ ></Image>+ </Body>);const uploadImages = vi.fn(async (srcs: string[]) => {return new Map(srcs.map((src) => [src, src]));@@ -154,9 +157,9 @@ test("upload raw inception images", async () => {test("uses runtime id generator for generated asset size props by default", async () => {const data = renderTemplate(- <$.Body ws:id="box">- <$.Image ws:id="image" src="https://src/"></$.Image>- </$.Body>+ <Body ws:id="box">+ <Image ws:id="image" src="https://src/"></Image>+ </Body>);const uploadImages = async (srcs: string[]) => {return new Map(srcs.map((src) => [src, "asset-id"]));diff --git a/apps/builder/app/shared/copy-paste/plugin-jsx.test.ts b/apps/builder/app/shared/copy-paste/plugin-jsx.test.tsindex 3b61481e4e..ca2c628a05 100644--- a/apps/builder/app/shared/copy-paste/plugin-jsx.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-jsx.test.ts@@ -44,23 +44,19 @@ describe("jsx paste plugin", () => {});test("detects only Webstudio JSX", () => {- expect(isLikelyWebstudioJsx("<$.Box />")).toBe(true);- expect(isLikelyWebstudioJsx("\n < $ .Box />")).toBe(true);- expect(isLikelyWebstudioJsx("< $ . Box />")).toBe(true);+ expect(isLikelyWebstudioJsx("<Box />")).toBe(true);expect(isLikelyWebstudioJsx('<ws.element ws:tag="section" />')).toBe(true);- expect(isLikelyWebstudioJsx("<radix.Switch />")).toBe(true);- expect(isLikelyWebstudioJsx("<animation.VideoAnimation />")).toBe(true);- expect(isLikelyWebstudioJsx("<$. />")).toBe(false);- expect(isLikelyWebstudioJsx("<$.>")).toBe(false);- expect(isLikelyWebstudioJsx("</$.Box>")).toBe(false);+ expect(isLikelyWebstudioJsx("<Switch />")).toBe(true);+ expect(isLikelyWebstudioJsx("<VideoAnimation />")).toBe(true);+ expect(isLikelyWebstudioJsx("</Box>")).toBe(false);expect(isLikelyWebstudioJsx("<section>HTML</section>")).toBe(false);expect(isLikelyWebstudioJsx("## Markdown")).toBe(false);});test("can import JSX syntax inspection without the Node evaluator", () => {- expect(() => inspectWebstudioJsxFragmentSyntax("<$.Box />")).not.toThrow();+ expect(() => inspectWebstudioJsxFragmentSyntax("<Box />")).not.toThrow();expect(() =>- inspectWebstudioJsxFragmentSyntax("<$.Box data-secret={process.env} />")+ inspectWebstudioJsxFragmentSyntax("<Box data-secret={process.env} />")).toThrow('Do not access "process" in JSX fragments');});@@ -69,11 +65,11 @@ describe("jsx paste plugin", () => {mocks.createJsxFragment.mockResolvedValue(fragment);mocks.insertWebstudioFragmentAt.mockReturnValue(true);- await expect(jsx.onPaste?.("<$.Box />")).resolves.toEqual(pasteHandled);+ await expect(jsx.onPaste?.("<Box />")).resolves.toEqual(pasteHandled);expect(mocks.createJsxFragment).toHaveBeenCalledWith({projectId: "project-id",- source: "<$.Box />",+ source: "<Box />",});expect(mocks.insertWebstudioFragmentAt).toHaveBeenCalledWith(fragment,@@ -97,7 +93,7 @@ describe("jsx paste plugin", () => {test("does not claim JSX without a current project", async () => {$project.set(undefined);- await expect(jsx.onPaste?.("<$.Box />")).resolves.toEqual(pasteIgnored);+ await expect(jsx.onPaste?.("<Box />")).resolves.toEqual(pasteIgnored);expect(mocks.createJsxFragment).not.toHaveBeenCalled();expect(mocks.insertWebstudioFragmentAt).not.toHaveBeenCalled();@@ -106,7 +102,7 @@ describe("jsx paste plugin", () => {test("reports conversion errors and stops paste fallback", async () => {mocks.createJsxFragment.mockRejectedValue(new Error("Invalid JSX"));- await expect(jsx.onPaste?.('<$.Box ws:id="0" />')).resolves.toEqual({+ await expect(jsx.onPaste?.('<Box ws:id="0" />')).resolves.toEqual({success: false,error: "Invalid JSX",});diff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.test.tsx b/apps/builder/app/shared/copy-paste/plugin-markdown.test.tsxindex 6a56db80f2..f189cac7ef 100644--- a/apps/builder/app/shared/copy-paste/plugin-markdown.test.tsx+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.test.tsx@@ -1,7 +1,13 @@import { test, expect } from "vitest";-import { $, renderTemplate, ws } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderTemplate,+ ws,+} from "@webstudio-is/template";import { __testing__ } from "./plugin-markdown";+const Image = createTemplateComponentFixture("Image");+const { parse } = __testing__;test("paragraph", () => {@@ -90,7 +96,7 @@ test("image", () => {expect(parse('')).toEqual(renderTemplate(<ws.element ws:tag="p">- <$.Image src="/url" alt="foo" title="title" />+ <Image src="/url" alt="foo" title="title" /></ws.element>));diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsxindex d34e080496..39d3be3bf3 100644--- a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx@@ -10,7 +10,10 @@ import {type WebstudioFragment,type Instance,} from "@webstudio-is/sdk";-import { $, renderData } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+} from "@webstudio-is/template";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";import { __testing__, webflow } from "./plugin-webflow";import { $registeredComponentMetas } from "../../nano-states";@@ -20,6 +23,28 @@ import invariant from "tiny-invariant";import { wfData } from "@webstudio-is/project-build/transfer";import { pasteIgnored } from "../copy-paste";+const Blockquote = createTemplateComponentFixture("Blockquote");+const Bold = createTemplateComponentFixture("Bold");+const Box = createTemplateComponentFixture("Box");+const Button = createTemplateComponentFixture("Button");+const Checkbox = createTemplateComponentFixture("Checkbox");+const CodeText = createTemplateComponentFixture("CodeText");+const Heading = createTemplateComponentFixture("Heading");+const HtmlEmbed = createTemplateComponentFixture("HtmlEmbed");+const Image = createTemplateComponentFixture("Image");+const Input = createTemplateComponentFixture("Input");+const Italic = createTemplateComponentFixture("Italic");+const Label = createTemplateComponentFixture("Label");+const Link = createTemplateComponentFixture("Link");+const List = createTemplateComponentFixture("List");+const ListItem = createTemplateComponentFixture("ListItem");+const Paragraph = createTemplateComponentFixture("Paragraph");+const RadioButton = createTemplateComponentFixture("RadioButton");+const Subscript = createTemplateComponentFixture("Subscript");+const Superscript = createTemplateComponentFixture("Superscript");+const Text = createTemplateComponentFixture("Text");+const Textarea = createTemplateComponentFixture("Textarea");+const { toWebstudioFragment } = __testing__;const equalFragment = (fragment: WebstudioFragment, jsx: JSX.Element) => {@@ -154,7 +179,7 @@ test("Heading", async () => {},});- equalFragment(fragment, <$.Heading ws:tag="h1">Turtle in the sea</$.Heading>);+ equalFragment(fragment, <Heading ws:tag="h1">Turtle in the sea</Heading>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {h1 {@@ -248,10 +273,7 @@ test("Link Block, Button, Text Link", async () => {},});- equalFragment(- fragment,- <$.Link href="https://webstudio.is" target="_blank" />- );+ equalFragment(fragment, <Link href="https://webstudio.is" target="_blank" />);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {a {@@ -312,11 +334,11 @@ test("List and ListItem", async () => {equalFragment(fragment,- <$.List>- <$.ListItem />- <$.ListItem />- <$.ListItem />- </$.List>+ <List>+ <ListItem />+ <ListItem />+ <ListItem />+ </List>);expect(toCss(fragment)).toMatchInlineSnapshot(`@@ -353,7 +375,7 @@ test("Paragraph", async () => {},});- equalFragment(fragment, <$.Paragraph>Text in a paragraph</$.Paragraph>);+ equalFragment(fragment, <Paragraph>Text in a paragraph</Paragraph>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {@@ -393,7 +415,7 @@ test("Text", async () => {equalFragment(fragment,- <$.Text ws:tag="div">This is some text inside of a div block.</$.Text>+ <Text ws:tag="div">This is some text inside of a div block.</Text>);expect(toCss(fragment)).toMatchInlineSnapshot(`""`);@@ -422,7 +444,7 @@ test("Blockquote", async () => {},});- equalFragment(fragment, <$.Blockquote>Block Quote</$.Blockquote>);+ equalFragment(fragment, <Blockquote>Block Quote</Blockquote>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {blockquote {@@ -465,7 +487,7 @@ test("Strong", async () => {},});- equalFragment(fragment, <$.Bold>Bold Text</$.Bold>);+ equalFragment(fragment, <Bold>Bold Text</Bold>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {strong {@@ -497,7 +519,7 @@ test("Emphasized", async () => {assets: [],},});- equalFragment(fragment, <$.Italic>Emphasis</$.Italic>);+ equalFragment(fragment, <Italic>Emphasis</Italic>);expect(toCss(fragment)).toMatchInlineSnapshot(`""`);});@@ -524,7 +546,7 @@ test("Superscript", async () => {},});- equalFragment(fragment, <$.Superscript>Superscript</$.Superscript>);+ equalFragment(fragment, <Superscript>Superscript</Superscript>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {sup {@@ -561,7 +583,7 @@ test("Subscript", async () => {},});- equalFragment(fragment, <$.Subscript>Subscript</$.Subscript>);+ equalFragment(fragment, <Subscript>Subscript</Subscript>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {sub {@@ -593,7 +615,7 @@ test("Section", async () => {},});- equalFragment(fragment, <$.Box ws:tag="section" />);+ equalFragment(fragment, <Box ws:tag="section" />);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {section {@@ -621,7 +643,7 @@ test("Figure", async () => {},});- equalFragment(fragment, <$.Box ws:tag="figure" />);+ equalFragment(fragment, <Box ws:tag="figure" />);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {figure {@@ -652,7 +674,7 @@ test("BlockContainer", async () => {assets: [],},});- equalFragment(fragment, <$.Box />);+ equalFragment(fragment, <Box />);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {w-layout-blockcontainer {@@ -723,7 +745,7 @@ test("Block", async () => {},});- equalFragment(fragment, <$.Box ws:tag="div" />);+ equalFragment(fragment, <Box ws:tag="div" />);expect(toCss(fragment)).toMatchInlineSnapshot(`""`);});@@ -744,7 +766,7 @@ test("V Flex", async () => {assets: [],},});- equalFragment(fragment, <$.Box />);+ equalFragment(fragment, <Box />);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {w-layout-vflex {@@ -773,7 +795,7 @@ test("H Flex", async () => {assets: [],},});- equalFragment(fragment, <$.Box />);+ equalFragment(fragment, <Box />);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {w-layout-hflex {@@ -834,10 +856,10 @@ test("QuickStack with instance styles", async () => {});equalFragment(fragment,- <$.Box>- <$.Box />- <$.Box />- </$.Box>+ <Box>+ <Box />+ <Box />+ </Box>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {@@ -884,7 +906,7 @@ test("Grid", async () => {},});- equalFragment(fragment, <$.Box />);+ equalFragment(fragment, <Box />);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {w-layout-grid {@@ -936,10 +958,10 @@ test("Columns", async () => {equalFragment(fragment,- <$.Box>- <$.Box />- <$.Box />- </$.Box>+ <Box>+ <Box />+ <Box />+ </Box>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {@@ -1017,7 +1039,7 @@ test("Image", async () => {equalFragment(fragment,- <$.Image+ <Imagealt="Test"loading="eager"width="200"@@ -1054,7 +1076,7 @@ test("HtmlEmbed", async () => {assets: [],},});- equalFragment(fragment, <$.HtmlEmbed code="some html" clientOnly={true} />);+ equalFragment(fragment, <HtmlEmbed code="some html" clientOnly={true} />);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {w-embed {@@ -1103,7 +1125,7 @@ test("CodeBlock", async () => {},});- equalFragment(fragment, <$.CodeText lang="javascript">test</$.CodeText>);+ equalFragment(fragment, <CodeText lang="javascript">test</CodeText>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {w-code-block {@@ -1470,51 +1492,51 @@ test("RichText", async () => {equalFragment(fragment,- <$.Box>- <$.Heading ws:tag="h1">Heading 1</$.Heading>- <$.Heading ws:tag="h2">Heading 2</$.Heading>- <$.Heading ws:tag="h3">Heading 3</$.Heading>- <$.Heading ws:tag="h4">Heading 4</$.Heading>- <$.Heading ws:tag="h5">Heading 5</$.Heading>- <$.Heading ws:tag="h6">Heading 6</$.Heading>- <$.Paragraph>+ <Box>+ <Heading ws:tag="h1">Heading 1</Heading>+ <Heading ws:tag="h2">Heading 2</Heading>+ <Heading ws:tag="h3">Heading 3</Heading>+ <Heading ws:tag="h4">Heading 4</Heading>+ <Heading ws:tag="h5">Heading 5</Heading>+ <Heading ws:tag="h6">Heading 6</Heading>+ <Paragraph>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minimveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex eacommodo consequat. Duis aute irure dolor in reprehenderit in voluptatevelit esse cillum dolore eu fugiat nulla pariatur.- </$.Paragraph>- <$.Blockquote>Block quote</$.Blockquote>- <$.Paragraph>Ordered list</$.Paragraph>- <$.List ordered={true}>- <$.ListItem>Item 1</$.ListItem>- <$.ListItem>Item 2</$.ListItem>- <$.ListItem>Item 3</$.ListItem>- </$.List>- <$.Paragraph>Unordered list</$.Paragraph>- <$.List>- <$.ListItem>Item A</$.ListItem>- <$.ListItem>Item B</$.ListItem>- <$.ListItem>Item C</$.ListItem>- </$.List>- <$.Paragraph>- <$.Link href="https://university.webflow.com/lesson/add-and-nest-text-links-in-webflow">+ </Paragraph>+ <Blockquote>Block quote</Blockquote>+ <Paragraph>Ordered list</Paragraph>+ <List ordered={true}>+ <ListItem>Item 1</ListItem>+ <ListItem>Item 2</ListItem>+ <ListItem>Item 3</ListItem>+ </List>+ <Paragraph>Unordered list</Paragraph>+ <List>+ <ListItem>Item A</ListItem>+ <ListItem>Item B</ListItem>+ <ListItem>Item C</ListItem>+ </List>+ <Paragraph>+ <Link href="https://university.webflow.com/lesson/add-and-nest-text-links-in-webflow">Text link- </$.Link>- </$.Paragraph>- <$.Paragraph>- <$.Bold>Bold text</$.Bold>- </$.Paragraph>- <$.Paragraph>- <$.Italic>Emphasis</$.Italic>- </$.Paragraph>- <$.Paragraph>- <$.Superscript>Superscript</$.Superscript>- </$.Paragraph>- <$.Paragraph>- <$.Subscript>Subscript</$.Subscript>- </$.Paragraph>- </$.Box>+ </Link>+ </Paragraph>+ <Paragraph>+ <Bold>Bold text</Bold>+ </Paragraph>+ <Paragraph>+ <Italic>Emphasis</Italic>+ </Paragraph>+ <Paragraph>+ <Superscript>Superscript</Superscript>+ </Paragraph>+ <Paragraph>+ <Subscript>Subscript</Subscript>+ </Paragraph>+ </Box>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {@@ -1707,9 +1729,9 @@ test("Form", async () => {equalFragment(fragment,- <$.Box>- <$.Box>- <$.Input+ <Box>+ <Box>+ <Inputid="name"name="name"maxLength={256}@@ -1719,8 +1741,8 @@ test("Form", async () => {required={false}autoFocus={false}/>- </$.Box>- </$.Box>+ </Box>+ </Box>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {@@ -1811,7 +1833,7 @@ test("FormButton", async () => {},});- equalFragment(fragment, <$.Button>Submit</$.Button>);+ equalFragment(fragment, <Button>Submit</Button>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {input {@@ -1889,7 +1911,7 @@ test("FormTextInput", async () => {equalFragment(fragment,- <$.Input+ <Inputid="email"name="email"maxLength={256}@@ -1988,10 +2010,7 @@ test("FormBlockLabel", async () => {},});- equalFragment(- fragment,- <$.Label {...{ for: "email" }}>Email Address</$.Label>- );+ equalFragment(fragment, <Label {...{ for: "email" }}>Email Address</Label>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {label {@@ -2033,7 +2052,7 @@ test("FormTextarea", async () => {equalFragment(fragment,- <$.Textarea+ <Textareaid="field"name="field"maxLength={5000}@@ -2125,10 +2144,7 @@ test("FormBlockLabel", async () => {},});- equalFragment(- fragment,- <$.Label {...{ for: "email" }}>Email Address</$.Label>- );+ equalFragment(fragment, <Label {...{ for: "email" }}>Email Address</Label>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {label {@@ -2191,17 +2207,17 @@ test("FormCheckboxWrapper, FormCheckboxInput, FormInlineLabel", async () => {equalFragment(fragment,- <$.Label ws:label="Checkbox Field">- <$.Checkbox+ <Label ws:label="Checkbox Field">+ <Checkboxid="checkbox"name="checkbox"required={false}defaultChecked={false}/>- <$.Text ws:tag="span" ws:label="Label">+ <Text ws:tag="span" ws:label="Label">Checkbox- </$.Text>- </$.Label>+ </Text>+ </Label>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {@@ -2321,12 +2337,12 @@ test("FormRadioWrapper, FormRadioInput, FormInlineLabel", async () => {equalFragment(fragment,- <$.Label ws:label="Radio Field">- <$.RadioButton id="radio" name="radio" required={false} value="Radio" />- <$.Text ws:tag="span" ws:label="Label">+ <Label ws:label="Radio Field">+ <RadioButton id="radio" name="radio" required={false} value="Radio" />+ <Text ws:tag="span" ws:label="Label">Radio- </$.Text>- </$.Label>+ </Text>+ </Label>);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {@@ -2443,7 +2459,7 @@ test("FormSelect", async () => {equalFragment(fragment,- <$.Input id="field-3" name="field-3" required={false} multiple={false} />+ <Input id="field-3" name="field-3" required={false} multiple={false} />);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {@@ -2504,11 +2520,11 @@ test("Multiline text", async () => {equalFragment(fragment,- <$.Box ws:tag="div">+ <Box ws:tag="div">{"a"}{"\n"}{"b"}- </$.Box>+ </Box>);expect(toCss(fragment)).toMatchInlineSnapshot(`""`);@@ -2540,7 +2556,7 @@ describe("Custom attributes", () => {assets: [],},});- equalFragment(fragment, <$.Heading ws:tag="h1" at="b" />);+ equalFragment(fragment, <Heading ws:tag="h1" at="b" />);expect(toCss(fragment)).toMatchInlineSnapshot(`"@media all {h1 {@@ -2579,7 +2595,7 @@ test("Set show false when visibility's only condition is false", async () => {assets: [],},});- equalFragment(fragment, <$.Box data-ws-show={false} ws:tag="div" />);+ equalFragment(fragment, <Box data-ws-show={false} ws:tag="div" />);expect(toCss(fragment)).toMatchInlineSnapshot(`""`);});diff --git a/apps/builder/app/shared/external-content-mutations.test.ts b/apps/builder/app/shared/external-content-mutations.test.tsindex 93157fb7cd..aa2aac2b70 100644--- a/apps/builder/app/shared/external-content-mutations.test.ts+++ b/apps/builder/app/shared/external-content-mutations.test.ts@@ -1,11 +1,26 @@-import { describe, expect, test } from "vitest";+import { afterEach, describe, expect, test, vi } from "vitest";import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";-import { elementComponent, type Instance, type Prop } from "@webstudio-is/sdk";import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type Instance,+ type Prop,+} from "@webstudio-is/sdk";+import {+ $externalContentRoots,+ getAffectedExternalContentTemplateRootKeys,isExternalContentInstance,isExternalContentMutation,+ publishExternalContentTemplateMutation,+ registerExternalContentRoot,+ subscribeExternalContentTemplateMutations,} from "./external-content-mutations";+afterEach(() => {+ $externalContentRoots.set(new Map());+});+const instance = (id: string,children: Instance["children"] = []@@ -39,8 +54,11 @@ const state = {const change = (namespace: BuilderPatchChange["namespace"],- patches: BuilderPatchChange["patches"]-): BuilderPatchChange => ({ namespace, patches });+ patches: BuilderPatchChange["patches"],+ revisePatches?: BuilderPatchChange["patches"]+): BuilderPatchChange & {+ revisePatches?: BuilderPatchChange["patches"];+} => ({ namespace, patches, revisePatches });describe("external content mutation detection", () => {const roots = new Map([@@ -150,6 +168,364 @@ describe("external content mutation detection", () => {})).toBe(false);});++ test("identifies template changes separately from authored content", () => {+ const templateState = {+ ...state,+ instances: new Map([+ ...state.instances,+ [+ "templates",+ {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ] as const,+ ["heading-template", instance("heading-template")] as const,+ ]),+ };+ const templateRoots = new Map([+ [+ "scope",+ {+ ...roots.get("scope")!,+ templateOwnership: {+ instances: new Set(["templates", "heading-template"]),+ styleSources: new Set(["heading-template-style"]),+ styles: new Set(["heading-template:base:color"]),+ },+ },+ ],+ ]);+ const payload = [+ change("instances", [+ {+ op: "replace" as const,+ path: ["templates", "children"],+ value: [{ type: "id", value: "heading-template" }],+ },+ ]),+ ];++ expect(+ getAffectedExternalContentTemplateRootKeys({+ state: templateState,+ roots: templateRoots,+ payload,+ })+ ).toEqual(["scope"]);+ expect(+ isExternalContentMutation({ state, roots: templateRoots, payload })+ ).toBe(false);++ expect(+ getAffectedExternalContentTemplateRootKeys({+ state: templateState,+ roots: templateRoots,+ payload: [+ change("instances", [+ {+ op: "replace",+ path: ["block", "children"],+ value: [{ type: "id", value: "inserted" }],+ },+ ]),+ ],+ })+ ).toEqual([]);++ expect(+ getAffectedExternalContentTemplateRootKeys({+ state: templateState,+ roots: templateRoots,+ payload: [+ change("styleSourceSelections", [+ {+ op: "add",+ path: ["heading-template"],+ value: {+ instanceId: "heading-template",+ values: ["heading-template-style"],+ },+ },+ ]),+ ],+ })+ ).toEqual(["scope"]);+ expect(+ getAffectedExternalContentTemplateRootKeys({+ state: templateState,+ roots: templateRoots,+ payload: [+ change("styles", [+ {+ op: "add",+ path: ["heading-template-style:base:background-color"],+ value: {+ breakpointId: "base",+ styleSourceId: "heading-template-style",+ property: "background-color",+ value: { type: "keyword", value: "red" },+ },+ },+ ]),+ ],+ })+ ).toEqual(["scope"]);+ });++ test("detects removal of template records added before ownership refresh", () => {+ const templateState = {+ instances: new Map([+ [+ "block",+ {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [{ type: "id" as const, value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id" as const, value: "heading-template" }],+ },+ ],+ ["heading-template", instance("heading-template")],+ ]),+ props: new Map<string, Prop>(),+ };+ const templateRoots = new Map([+ [+ "scope",+ {+ blockInstanceId: "block",+ instanceIds: new Set<string>(),+ templateOwnership: {+ instances: new Set(["templates", "heading-template"]),+ props: new Set<string>(),+ styleSources: new Set(["heading-template-style"]),+ styles: new Set<string>(),+ },+ mutationRevision: 0,+ },+ ],+ ]);+ const removedProp: Prop = {+ id: "new-template-prop",+ instanceId: "heading-template",+ name: "title",+ type: "string",+ value: "Temporary",+ };++ expect(+ getAffectedExternalContentTemplateRootKeys({+ state: templateState,+ roots: templateRoots,+ payload: [+ change(+ "props",+ [{ op: "remove", path: [removedProp.id] }],+ [{ op: "add", path: [removedProp.id], value: removedProp }]+ ),+ ],+ })+ ).toEqual(["scope"]);+ expect(+ getAffectedExternalContentTemplateRootKeys({+ state: templateState,+ roots: templateRoots,+ payload: [+ change(+ "styles",+ [{ op: "remove", path: ["new-template-style"] }],+ [+ {+ op: "add",+ path: ["new-template-style"],+ value: {+ breakpointId: "base",+ styleSourceId: "heading-template-style",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ },+ ]+ ),+ ],+ })+ ).toEqual(["scope"]);+ });++ test("detects adding and removing the Templates container", () => {+ const block = {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [{ type: "id" as const, value: "templates" }],+ };+ const templates = {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ };+ const roots = new Map([+ [+ "scope",+ {+ sourceBlockInstanceId: "block",+ blockInstanceId: "block",+ instanceIds: new Set<string>(),+ templateOwnership: { instances: new Set(["templates"]) },+ mutationRevision: 0,+ },+ ],+ ]);++ expect(+ getAffectedExternalContentTemplateRootKeys({+ state: {+ instances: new Map([+ [block.id, block],+ [templates.id, templates],+ ]),+ },+ roots,+ payload: [+ change("instances", [+ { op: "replace", path: ["block", "children"], value: [] },+ ]),+ ],+ })+ ).toEqual(["scope"]);++ const rootsWithoutTemplates = new Map([+ [+ "scope",+ {+ ...roots.get("scope")!,+ templateOwnership: { instances: new Set<string>() },+ },+ ],+ ]);+ expect(+ getAffectedExternalContentTemplateRootKeys({+ state: { instances: new Map([[block.id, { ...block, children: [] }]]) },+ roots: rootsWithoutTemplates,+ payload: [+ change("instances", [+ { op: "add", path: ["templates"], value: templates },+ {+ op: "replace",+ path: ["block", "children"],+ value: [{ type: "id", value: "templates" }],+ },+ ]),+ ],+ })+ ).toEqual(["scope"]);+ });++ test("detects remotely applied Templates container changes", () => {+ const template = {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ };+ const removalRoots = new Map([+ [+ "scope",+ {+ sourceBlockInstanceId: "block",+ blockInstanceId: "block",+ instanceIds: new Set<string>(),+ templateContainerIds: [template.id],+ templateOwnership: { instances: new Set([template.id]) },+ mutationRevision: 0,+ },+ ],+ ]);+ const removalPayload = [+ change("instances", [+ { op: "replace" as const, path: ["block", "children"], value: [] },+ { op: "remove" as const, path: [template.id] },+ ]),+ ];++ expect(+ getAffectedExternalContentTemplateRootKeys({+ state: {+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ },+ ],+ ]),+ },+ roots: removalRoots,+ payload: removalPayload,+ })+ ).toEqual(["scope"]);++ const additionRoots = new Map([+ [+ "scope",+ {+ sourceBlockInstanceId: "block",+ blockInstanceId: "block",+ instanceIds: new Set<string>(),+ templateContainerIds: [],+ templateOwnership: { instances: new Set<string>() },+ mutationRevision: 0,+ },+ ],+ ]);+ const additionPayload = [+ change("instances", [+ { op: "add" as const, path: [template.id], value: template },+ {+ op: "replace" as const,+ path: ["block", "children"],+ value: [{ type: "id", value: template.id }],+ },+ ]),+ ];++ expect(+ getAffectedExternalContentTemplateRootKeys({+ state: {+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: template.id }],+ },+ ],+ [template.id, template],+ ]),+ },+ roots: additionRoots,+ payload: additionPayload,+ })+ ).toEqual(["scope"]);+ });});test("identifies only instances authored by external content", () => {@@ -168,3 +544,96 @@ test("identifies only instances authored by external content", () => {expect(isExternalContentInstance(roots, "block")).toBe(false);expect(isExternalContentInstance(roots, "ordinary")).toBe(false);});++test("routes template invalidation through the synchronized root revision", () => {+ const root = {+ blockInstanceId: "block",+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ templateMutationRevision: 0,+ };+ $externalContentRoots.set(new Map([["scope", root]]));+ const listener = vi.fn();+ const unsubscribe = subscribeExternalContentTemplateMutations(listener);++ try {+ $externalContentRoots.set(+ new Map([+ [+ "scope",+ {+ ...root,+ templateMutationRevision: 1,+ },+ ],+ ])+ );+ } finally {+ unsubscribe();+ }++ expect(listener).toHaveBeenCalledExactlyOnceWith(["scope"]);+});++test("publishing a template mutation advances only matching roots", () => {+ $externalContentRoots.set(+ new Map([+ [+ "current",+ {+ blockInstanceId: "current-block",+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ templateMutationRevision: 2,+ },+ ],+ [+ "other",+ {+ blockInstanceId: "other-block",+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ templateMutationRevision: 4,+ },+ ],+ ])+ );++ publishExternalContentTemplateMutation(["current", "missing"]);++ expect(+ $externalContentRoots.get().get("current")?.templateMutationRevision+ ).toBe(3);+ expect(+ $externalContentRoots.get().get("other")?.templateMutationRevision+ ).toBe(4);+});++test("unregisters the current root after synchronized revisions replace it", () => {+ const unregister = registerExternalContentRoot("scope", {+ blockInstanceId: "block",+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ });++ publishExternalContentTemplateMutation(["scope"]);+ unregister();++ expect($externalContentRoots.get().has("scope")).toBe(false);+});++test("does not let an older disposer unregister a replacement root", () => {+ const root = {+ blockInstanceId: "block",+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ };+ const unregisterPrevious = registerExternalContentRoot("scope", root);+ const unregisterCurrent = registerExternalContentRoot("scope", root);++ unregisterPrevious();+ expect($externalContentRoots.get().has("scope")).toBe(true);++ unregisterCurrent();+ expect($externalContentRoots.get().has("scope")).toBe(false);+});diff --git a/apps/builder/app/shared/external-content-mutations.ts b/apps/builder/app/shared/external-content-mutations.tsindex 1257509e7f..86d6520451 100644--- a/apps/builder/app/shared/external-content-mutations.ts+++ b/apps/builder/app/shared/external-content-mutations.ts@@ -1,5 +1,12 @@+/**+ * Owns the synchronized registry of mounted external-content roots and routes+ * Builder patches to authored-content saves or live-template invalidations.+ */import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";-import type { BuilderState } from "@webstudio-is/project-build/state";+import {+ applyBuilderNamespacePatches,+ type BuilderState,+} from "@webstudio-is/project-build/state";import type {ContentBlockExternalContentIdentity,ContentBlockDiagnostic,@@ -7,10 +14,18 @@ import type {Instances,Prop,} from "@webstudio-is/sdk";-import { blockBodyComponent, blockComponent } from "@webstudio-is/sdk";-import type { InstanceSelector } from "@webstudio-is/project-build/runtime";+import {+ blockBodyComponent,+ blockComponent,+ findContentBlockTemplateContainers,+ findTreeInstanceIds,+} from "@webstudio-is/sdk";+import type {+ InstanceSelector,+ MdxTemplateInsertion,+} from "@webstudio-is/project-build/runtime";import type { MdxDocument } from "@webstudio-is/content-engine/mdx";-import { atom } from "nanostores";+import { atom, type ReadableAtom } from "nanostores";import type { ExternalContentOwnership } from "./external-content-persistence";export type ExternalContentRoot = {@@ -24,8 +39,19 @@ export type ExternalContentRoot = {instanceIds: ReadonlySet<Instance["id"]>;propIds?: ReadonlySet<Prop["id"]>;ownership?: ExternalContentOwnership;+ /** Latest template tree observed in the project stores for mutation routing. */+ templateContainerIds?: readonly Instance["id"][];+ /** Latest template ownership observed in the project stores. */+ templateOwnership?: ExternalContentOwnership;mutationRevision: 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;+ /** Unsaved clones that retain the exact template selected by the user. */+ insertedTemplates?: ReadonlyMap<Instance["id"], MdxTemplateInsertion>;identity?: ContentBlockExternalContentIdentity;diagnostics?: readonly ContentBlockDiagnostic[];document?: MdxDocument;@@ -145,30 +171,76 @@ export const $externalContentRoots = atom(new Map<string, ExternalContentRoot>());const mutationListeners = new Set<(rootKeys: readonly string[]) => void>();-const observedMutationRevisions = new Map<string, number>();+const templateMutationListeners = new Set<+ (rootKeys: readonly string[]) => void+>();+const rootRegistrationGenerations = new Map<string, number>();-$externalContentRoots.listen((roots) => {- const changedRootKeys: string[] = [];- for (const [key, root] of roots) {- const previousRevision = observedMutationRevisions.get(key);- observedMutationRevisions.set(key, root.mutationRevision);- if (- previousRevision !== undefined &&- root.mutationRevision > previousRevision- ) {- changedRootKeys.push(key);+const observeExternalContentRootMutations = ({+ store,+ onMutation,+ onTemplateMutation,+}: {+ store: ReadableAtom<Map<string, ExternalContentRoot>>;+ onMutation: (rootKeys: readonly string[]) => void;+ onTemplateMutation: (rootKeys: readonly string[]) => void;+}) => {+ const observedMutationRevisions = new Map<string, number>();+ const observedTemplateMutationRevisions = new Map<string, number>();+ return store.listen((roots) => {+ const changedRootKeys: string[] = [];+ const changedTemplateRootKeys: string[] = [];+ for (const [key, root] of roots) {+ const previousRevision = observedMutationRevisions.get(key);+ observedMutationRevisions.set(key, root.mutationRevision);+ if (+ previousRevision !== undefined &&+ root.mutationRevision > previousRevision+ ) {+ changedRootKeys.push(key);+ }+ const templateMutationRevision = root.templateMutationRevision ?? 0;+ const previousTemplateMutationRevision =+ observedTemplateMutationRevisions.get(key);+ observedTemplateMutationRevisions.set(key, templateMutationRevision);+ if (+ previousTemplateMutationRevision !== undefined &&+ templateMutationRevision > previousTemplateMutationRevision+ ) {+ changedTemplateRootKeys.push(key);+ }}- }- for (const key of observedMutationRevisions.keys()) {- if (roots.has(key) === false) {- observedMutationRevisions.delete(key);+ for (const key of observedMutationRevisions.keys()) {+ if (roots.has(key) === false) {+ observedMutationRevisions.delete(key);+ }}- }- if (changedRootKeys.length > 0) {+ for (const key of observedTemplateMutationRevisions.keys()) {+ if (roots.has(key) === false) {+ observedTemplateMutationRevisions.delete(key);+ }+ }+ if (changedRootKeys.length > 0) {+ onMutation(changedRootKeys);+ }+ if (changedTemplateRootKeys.length > 0) {+ onTemplateMutation(changedTemplateRootKeys);+ }+ });+};++observeExternalContentRootMutations({+ store: $externalContentRoots,+ onMutation(rootKeys) {for (const listener of mutationListeners) {- listener(changedRootKeys);+ listener(rootKeys);}- }+ },+ onTemplateMutation(rootKeys) {+ for (const listener of templateMutationListeners) {+ listener(rootKeys);+ }+ },});export const registerExternalContentRoot = (@@ -176,18 +248,31 @@ export const registerExternalContentRoot = (root: ExternalContentRoot) => {const current = $externalContentRoots.get();+ const registrationGeneration =+ (rootRegistrationGenerations.get(key) ?? 0) + 1;+ rootRegistrationGenerations.set(key, registrationGeneration);const registeredRoot = {...root,mutationRevision: current.get(key)?.mutationRevision ?? 0,+ templateMutationRevision:+ current.get(key)?.templateMutationRevision ??+ root.templateMutationRevision ??+ 0,+ templateMaterializationError:+ current.get(key)?.templateMaterializationError,+ insertedTemplates:+ current.get(key)?.insertedTemplates ?? root.insertedTemplates,};$externalContentRoots.set(new Map(current).set(key, registeredRoot));return () => {- const roots = $externalContentRoots.get();- if (roots.get(key) === registeredRoot) {- const nextRoots = new Map(roots);- nextRoots.delete(key);- $externalContentRoots.set(nextRoots);+ if (rootRegistrationGenerations.get(key) !== registrationGeneration) {+ return;}+ rootRegistrationGenerations.delete(key);+ const roots = $externalContentRoots.get();+ const nextRoots = new Map(roots);+ nextRoots.delete(key);+ $externalContentRoots.set(nextRoots);};};@@ -215,6 +300,103 @@ export const subscribeExternalContentMutations = (return () => mutationListeners.delete(listener);};+export const subscribeExternalContentTemplateMutations = (+ listener: (rootKeys: readonly string[]) => void+) => {+ templateMutationListeners.add(listener);+ return () => templateMutationListeners.delete(listener);+};++export const publishExternalContentTemplateMutation = (+ rootKeys: readonly string[]+) => {+ if (rootKeys.length === 0) {+ return;+ }+ const roots = $externalContentRoots.get();+ const nextRoots = new Map(roots);+ let changed = false;+ for (const key of rootKeys) {+ const root = roots.get(key);+ if (root === undefined) {+ continue;+ }+ nextRoots.set(key, {+ ...root,+ templateMutationRevision: (root.templateMutationRevision ?? 0) + 1,+ });+ changed = true;+ }+ if (changed) {+ $externalContentRoots.set(nextRoots);+ }+};++export const recordExternalContentTemplateInsertion = ({+ instanceSelector,+ insertion,+}: {+ instanceSelector: InstanceSelector;+ insertion: MdxTemplateInsertion;+}) => {+ const roots = $externalContentRoots.get();+ const entry = findExternalContentRootEntryBySelector(roots, instanceSelector);+ if (entry === undefined) {+ return;+ }+ const [key, root] = entry;+ const insertedTemplates = new Map(root.insertedTemplates);+ insertedTemplates.set(instanceSelector[0], insertion);+ $externalContentRoots.set(+ new Map(roots).set(key, { ...root, insertedTemplates })+ );+};++export const clearExternalContentTemplateInsertions = ({+ key,+ instanceIds,+}: {+ key: string;+ instanceIds: Iterable<Instance["id"]>;+}) => {+ const roots = $externalContentRoots.get();+ const root = roots.get(key);+ if (root?.insertedTemplates === undefined) {+ return;+ }+ const insertedTemplates = new Map(root.insertedTemplates);+ for (const instanceId of instanceIds) {+ insertedTemplates.delete(instanceId);+ }+ $externalContentRoots.set(+ new Map(roots).set(key, {+ ...root,+ insertedTemplates:+ insertedTemplates.size === 0 ? undefined : insertedTemplates,+ })+ );+};++export const updateExternalContentTemplateMaterializationError = ({+ key,+ error,+}: {+ key: string;+ error: string | undefined;+}) => {+ const roots = $externalContentRoots.get();+ const root = roots.get(key);+ if (root === undefined || root.templateMaterializationError === error) {+ return;+ }+ $externalContentRoots.set(+ new Map(roots).set(key, {+ ...root,+ templateMaterializationError: error,+ })+ );+};+export const publishExternalContentMutation = (rootKeys: readonly string[]) => {if (rootKeys.length === 0) {return;@@ -247,9 +429,145 @@ export const getAffectedExternalContentRootKeys = ({.filter(([, root]) => doesMutationAffectRoot({ state, root, payload })).map(([key]) => key);+const getTemplateContainerIds = (+ instances: Instances,+ blockInstanceId: Instance["id"]+) => {+ const block = instances.get(blockInstanceId);+ return block === undefined+ ? []+ : findContentBlockTemplateContainers({+ blockInstance: block,+ instances,+ }).map(({ id }) => id);+};++export const getAffectedExternalContentTemplateRootKeys = ({+ state,+ roots,+ payload,+}: {+ state: ExternalContentMutationState;+ roots: ReadonlyMap<string, ExternalContentRoot>;+ payload: readonly BuilderPatchChange[];+}) => {+ const instancePatches = payload.flatMap((change) =>+ change.namespace === "instances" ? change.patches : []+ );+ let nextInstances: Instances | undefined;+ if (instancePatches.length > 0) {+ const relevantInstanceIds = new Set<string>();+ for (const root of roots.values()) {+ const sourceBlockInstanceId =+ root.sourceBlockInstanceId ?? root.blockInstanceId;+ relevantInstanceIds.add(sourceBlockInstanceId);+ for (const child of state.instances.get(sourceBlockInstanceId)+ ?.children ?? []) {+ if (child.type === "id") {+ relevantInstanceIds.add(child.value);+ }+ }+ }+ for (const patch of instancePatches) {+ const id = getPatchId(patch);+ if (id !== undefined) {+ relevantInstanceIds.add(id);+ }+ }+ const relevantInstances = new Map(+ Array.from(relevantInstanceIds).flatMap((id) => {+ const instance = state.instances.get(id);+ return instance === undefined ? [] : ([[id, instance]] as const);+ })+ );+ nextInstances = applyBuilderNamespacePatches(+ relevantInstances,+ instancePatches+ );+ for (const root of roots.values()) {+ const sourceBlockInstanceId =+ root.sourceBlockInstanceId ?? root.blockInstanceId;+ for (const child of nextInstances.get(sourceBlockInstanceId)?.children ??+ []) {+ if (child.type !== "id" || nextInstances.has(child.value)) {+ continue;+ }+ const instance = state.instances.get(child.value);+ if (instance !== undefined) {+ nextInstances.set(child.value, instance);+ }+ }+ }+ }+ return Array.from(roots)+ .filter(([, root]) => {+ const sourceBlockInstanceId =+ root.sourceBlockInstanceId ?? root.blockInstanceId;+ const currentTemplateContainerIds = getTemplateContainerIds(+ state.instances,+ sourceBlockInstanceId+ );+ if (+ root.templateContainerIds !== undefined &&+ (root.templateContainerIds.length !==+ currentTemplateContainerIds.length ||+ root.templateContainerIds.some(+ (id, index) => id !== currentTemplateContainerIds[index]+ ))+ ) {+ return true;+ }+ if (nextInstances !== undefined) {+ const nextTemplateContainerIds = getTemplateContainerIds(+ nextInstances,+ sourceBlockInstanceId+ );+ if (+ currentTemplateContainerIds.length !==+ nextTemplateContainerIds.length ||+ currentTemplateContainerIds.some(+ (id, index) => id !== nextTemplateContainerIds[index]+ )+ ) {+ return true;+ }+ }+ const ownership = root.templateOwnership;+ if (ownership === undefined) {+ return false;+ }+ const liveTemplateInstanceIds = new Set(+ currentTemplateContainerIds.flatMap((containerId) =>+ Array.from(findTreeInstanceIds(state.instances, containerId))+ )+ );+ return doesMutationAffectRoot({+ state,+ root: {+ ...root,+ instanceIds: new Set([+ ...(ownership.instances ?? []),+ ...liveTemplateInstanceIds,+ ]),+ propIds: ownership.props,+ ownership,+ },+ payload,+ includeContentContainer: false,+ });+ })+ .map(([key]) => key);+};+type ExternalContentMutationState = {instances: NonNullable<BuilderState["instances"]>;props?: BuilderState["props"];+ styleSourceSelections?: BuilderState["styleSourceSelections"];+};++type ExternalContentPatchChange = BuilderPatchChange & {+ /** Immerhin includes inverse record values for removals. */+ revisePatches?: BuilderPatchChange["patches"];};const getPatchId = (patch: BuilderPatchChange["patches"][number]) => {@@ -257,12 +575,32 @@ const getPatchId = (patch: BuilderPatchChange["patches"][number]) => {return typeof id === "string" ? id : undefined;};+const getRemovedRecord = (change: ExternalContentPatchChange, id: string) => {+ const patch = change.revisePatches?.find(+ (candidate) =>+ candidate.op !== "remove" &&+ candidate.path.length === 1 &&+ getPatchId(candidate) === id+ );+ if (+ patch === undefined ||+ patch.op === "remove" ||+ typeof patch.value !== "object" ||+ patch.value === null+ ) {+ return;+ }+ return patch.value;+};+const affectsRootInstances = ({root,change,+ includeContentContainer,}: {root: ExternalContentRoot;- change: BuilderPatchChange;+ change: ExternalContentPatchChange;+ includeContentContainer: boolean;}) => {for (const patch of change.patches) {const id = getPatchId(patch);@@ -273,6 +611,7 @@ const affectsRootInstances = ({return true;}if (+ includeContentContainer &&id === (root.contentInstanceId ?? root.blockInstanceId) &&patch.path[1] === "children") {@@ -299,7 +638,7 @@ const affectsRootProps = ({}: {state: ExternalContentMutationState;root: ExternalContentRoot;- change: BuilderPatchChange;+ change: ExternalContentPatchChange;}) => {for (const patch of change.patches) {const id = getPatchId(patch);@@ -307,6 +646,8 @@ const affectsRootProps = ({continue;}const existing = state.props?.get(id);+ const removed =+ patch.op === "remove" ? getRemovedRecord(change, id) : undefined;const added =patch.op !== "remove" &&patch.path.length === 1 &&@@ -318,6 +659,9 @@ const affectsRootProps = ({if (root.propIds?.has(id) ||(existing !== undefined && root.instanceIds.has(existing.instanceId)) ||+ (removed !== undefined &&+ "instanceId" in removed &&+ root.instanceIds.has(String(removed.instanceId))) ||(added !== undefined && root.instanceIds.has(String(added.instanceId)))) {return true;@@ -330,14 +674,16 @@ const doesMutationAffectRoot = ({state,root,payload,+ includeContentContainer = true,}: {state: ExternalContentMutationState;root: ExternalContentRoot;- payload: readonly BuilderPatchChange[];+ payload: readonly ExternalContentPatchChange[];+ includeContentContainer?: boolean;}) =>payload.some((change) => {if (change.namespace === "instances") {- return affectsRootInstances({ root, change });+ return affectsRootInstances({ root, change, includeContentContainer });}if (change.namespace === "props") {return affectsRootProps({ state, root, change });@@ -346,7 +692,41 @@ const doesMutationAffectRoot = ({root.ownership?.[change.namespace as keyof ExternalContentOwnership];return change.patches.some((patch) => {const id = getPatchId(patch);- return id !== undefined && ownedIds?.has(id) === true;+ if (id !== undefined && ownedIds?.has(id) === true) {+ return true;+ }+ if (includeContentContainer || id === undefined) {+ return false;+ }+ if (+ change.namespace === "styleSourceSelections" &&+ root.instanceIds.has(id)+ ) {+ return true;+ }+ const record =+ patch.op === "remove"+ ? getRemovedRecord(change, id)+ : patch.path.length === 1 &&+ typeof patch.value === "object" &&+ patch.value !== null+ ? patch.value+ : undefined;+ if (record === undefined) {+ return false;+ }+ if (change.namespace === "styles" && "styleSourceId" in record) {+ const styleSourceId = String(record.styleSourceId);+ if (root.ownership?.styleSources?.has(styleSourceId) === true) {+ return true;+ }+ return Array.from(state.styleSourceSelections?.values() ?? []).some(+ (selection) =>+ root.instanceIds.has(selection.instanceId) &&+ selection.values.includes(styleSourceId)+ );+ }+ return false;});});@@ -357,8 +737,10 @@ export const isExternalContentMutation = ({}: {state: ExternalContentMutationState;roots: ReadonlyMap<string, ExternalContentRoot>;- payload: readonly BuilderPatchChange[];+ payload: readonly ExternalContentPatchChange[];}) =>Array.from(roots.values()).some((root) =>doesMutationAffectRoot({ state, root, payload }));++export const __testing__ = { observeExternalContentRootMutations };diff --git a/apps/builder/app/shared/external-content-roots.test.ts b/apps/builder/app/shared/external-content-roots.test.tsindex 917af1dd2f..8d2e6797dd 100644--- a/apps/builder/app/shared/external-content-roots.test.ts+++ b/apps/builder/app/shared/external-content-roots.test.ts@@ -1,12 +1,16 @@import { afterEach, expect, test, vi } from "vitest";import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";import { createDefaultPages } from "@webstudio-is/project-build";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";import {blockBodyComponent,blockComponent,blockTemplateComponent,+ coreMetas,+ elementComponent,type Asset,type Instance,+ type Prop,} from "@webstudio-is/sdk";import {__testing__ as assetContentBridgeTesting,@@ -26,8 +30,16 @@ import {updateExternalContentAssetSource,updateExternalContentFrontmatter,} from "./external-content-roots";-import { executeRuntimeMutation } from "./instance-utils/data";-import { selectInstance } from "./nano-states";+import {+ executeRuntimeMutation,+ getWebstudioData,+} from "./instance-utils/data";+import {+ $builderMode,+ $registeredComponentMetas,+ selectInstance,+ selectPage,+} from "./nano-states";import {findExternalContentRoot,getExternalContentRoots,@@ -48,16 +60,799 @@ import {$styles,} from "./sync/data-stores";import {+ createObjectPool,externalContentSyncStore,registerContainers,serverSyncStore,} from "./sync/sync-stores";+import { createSyncChangesFromBuilderPatchPayload } from "./sync/builder-patch";+import { insertTemplateAt } from "~/builder/features/workspace/canvas-tools/outline/block-utils";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>';+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>';+ const sourceAsset = {+ ...asset,+ size: new TextEncoder().encode(source).byteLength,+ };+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: sourceAsset,+ data: (async function* () {+ yield new TextEncoder().encode(source);+ })(),+ }),+ updateContent: async () => sourceAsset,+ },+ authorize: () => true,+ });+ sessions.push(session);+ assetContentBridgeTesting.initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(+ new Map([+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ ["templates", instance("templates", blockTemplateComponent, [])],+ ])+ );+ $props.set(new Map());+ $assets.set(new Map([[sourceAsset.id, sourceAsset]]));+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });++ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: sourceAsset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ );++ const section = Array.from($instances.get().values()).find(+ (candidate) => candidate.tag === "section"+ );+ const missing = Array.from($instances.get().values()).find(+ (candidate) => candidate.label === "Missing template: Missing"+ );+ expect(missing).toMatchObject({+ component: "ws:element",+ tag: "div",+ children: [{ type: "text", value: "Missing template: Missing" }],+ });+ if (section === undefined || missing === undefined) {+ throw new Error("Expected the section and missing-template placeholder");+ }+ expect(section.children).toEqual([+ { type: "text", value: "Before" },+ { type: "id", value: missing.id },+ { type: "text", value: "After" },+ ]);+ expect(+ getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ ).toEqual([{ type: "id", value: section.id }]);+});++test("re-resolves existing Markdown when a matching template is added", async () => {+ const source = "# Existing heading\n";+ const sourceAsset = {+ ...asset,+ size: new TextEncoder().encode(source).byteLength,+ };+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: sourceAsset,+ data: (async function* () {+ yield new TextEncoder().encode(source);+ })(),+ }),+ updateContent: async () => sourceAsset,+ },+ authorize: () => true,+ });+ sessions.push(session);+ assetContentBridgeTesting.initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(+ new Map([+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ ["templates", instance("templates", blockTemplateComponent, [])],+ ])+ );+ $props.set(new Map());+ $assets.set(new Map([[sourceAsset.id, sourceAsset]]));+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });++ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: sourceAsset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ );++ const initialHeading = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[0];+ if (initialHeading?.type !== "id") {+ throw new Error("Expected the initial materialized heading");+ }+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: initialHeading.value,+ mode: "text",+ text: "Edited heading",+ },+ });++ const insertion = executeRuntimeMutation({+ id: "instances.insertComponent",+ input: {+ parentInstanceId: "templates",+ component: "ws:element",+ tag: "h1",+ },+ });+ const templateId = insertion?.result.rootInstanceIds[0];+ if (templateId === undefined) {+ throw new Error("Expected an inserted heading template");+ }+ executeRuntimeMutation({+ id: "instances.updateProps",+ input: {+ updates: [+ {+ instanceId: templateId,+ name: "title",+ type: "string",+ value: "Template applied",+ },+ ],+ },+ });++ await vi.waitFor(() => {+ const heading = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[0];+ if (heading?.type !== "id") {+ throw new Error("Expected the materialized heading");+ }+ expect($instances.get().get(heading.value)?.children).toEqual([+ { type: "text", value: "Edited heading" },+ ]);+ expect(+ Array.from($props.get().values()).find(+ (prop) => prop.instanceId === heading.value && prop.name === "title"+ )+ ).toMatchObject({ type: "string", value: "Template applied" });+ });++ const templateRevisionBeforeRemoteChange =+ getExternalContentRoots().values().next().value?.templateMutationRevision ??+ 0;+ serverSyncStore.addTransaction(+ "remote-template-style",+ createSyncChangesFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: [+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["remote-template-style"],+ value: { type: "local", id: "remote-template-style" },+ },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: [templateId],+ value: {+ instanceId: templateId,+ values: ["remote-template-style"],+ },+ },+ ],+ },+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["remote-template-style:base:color"],+ value: {+ breakpointId: "base",+ styleSourceId: "remote-template-style",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ },+ ],+ },+ ] satisfies BuilderPatchChange[],+ }),+ "remote"+ );+ expect(+ getExternalContentRoots().values().next().value?.templateMutationRevision+ ).toBe(templateRevisionBeforeRemoteChange + 1);++ serverSyncStore.undo();+ expect(+ getExternalContentRoots().values().next().value?.templateMutationRevision+ ).toBe(templateRevisionBeforeRemoteChange + 2);+ serverSyncStore.redo();+ expect(+ getExternalContentRoots().values().next().value?.templateMutationRevision+ ).toBe(templateRevisionBeforeRemoteChange + 3);++ const rejectedPayload = createSyncChangesFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: [+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["remote-template-style:base:background-color"],+ value: {+ breakpointId: "base",+ styleSourceId: "remote-template-style",+ property: "background-color",+ value: { type: "keyword", value: "black" },+ },+ },+ ],+ },+ ] satisfies BuilderPatchChange[],+ });+ const objectPool = createObjectPool();+ objectPool.applyTransaction({+ id: "rejected-template-style",+ object: "server",+ payload: rejectedPayload,+ });+ expect(+ getExternalContentRoots().values().next().value?.templateMutationRevision+ ).toBe(templateRevisionBeforeRemoteChange + 4);+ objectPool.revertTransaction({+ id: "rejected-template-style",+ object: "server",+ });+ expect(+ getExternalContentRoots().values().next().value?.templateMutationRevision+ ).toBe(templateRevisionBeforeRemoteChange + 5);++ await vi.waitFor(() => {+ const heading = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[0];+ if (heading?.type !== "id") {+ throw new Error("Expected the remotely restyled heading");+ }+ const selection = $styleSourceSelections.get().get(heading.value);+ expect(selection?.values).toHaveLength(1);+ expect(+ Array.from($styles.get().values()).find(+ (style) =>+ style.styleSourceId === selection?.values[0] &&+ style.property === "color"+ )+ ).toMatchObject({ value: { type: "keyword", value: "red" } });+ });+});++test("preserves the last valid materialization while the Templates structure is invalid", async () => {+ const source = "# Heading\n";+ const sourceAsset = {+ ...asset,+ size: new TextEncoder().encode(source).byteLength,+ };+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: sourceAsset,+ data: (async function* () {+ yield new TextEncoder().encode(source);+ })(),+ }),+ updateContent: async () => sourceAsset,+ },+ authorize: () => true,+ });+ sessions.push(session);+ assetContentBridgeTesting.initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(+ new Map([+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ [+ "templates",+ instance("templates", blockTemplateComponent, [+ { type: "id", value: "heading-template" },+ ]),+ ],+ [+ "heading-template",+ {+ ...instance("heading-template", "ws:element", []),+ tag: "h1",+ label: "Styled heading",+ },+ ],+ ])+ );+ $props.set(new Map());+ $assets.set(new Map([[sourceAsset.id, sourceAsset]]));+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });+ serverSyncStore.popAll();+ externalContentSyncStore.popAll();++ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: sourceAsset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ );+ const headingChild = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[0];+ if (headingChild?.type !== "id") {+ throw new Error("Expected the materialized heading");+ }+ expect($instances.get().get(headingChild.value)?.label).toBe(+ "Styled heading"+ );++ const duplicateTemplates = instance(+ "duplicate-templates",+ blockTemplateComponent,+ []+ );+ const blockBeforeDuplicate = $instances.get().get("block");+ if (blockBeforeDuplicate === undefined) {+ throw new Error("Expected the Content Block");+ }+ serverSyncStore.addTransaction(+ "add-duplicate-templates",+ createSyncChangesFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: [duplicateTemplates.id],+ value: duplicateTemplates,+ },+ {+ op: "replace",+ path: [blockBeforeDuplicate.id, "children"],+ value: [+ { type: "id", value: duplicateTemplates.id },+ ...blockBeforeDuplicate.children,+ ],+ },+ ],+ },+ ] satisfies BuilderPatchChange[],+ }),+ "remote"+ );++ await vi.waitFor(() =>+ expect(+ getExternalContentRoots().values().next().value+ ?.templateMaterializationError+ ).toBe("Content Block has 2 Templates containers; exactly one is required")+ );+ expect(+ getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ ).toEqual([headingChild]);+ expect($instances.get().get(headingChild.value)?.label).toBe(+ "Styled heading"+ );++ const blockBeforeRepair = $instances.get().get("block");+ if (blockBeforeRepair === undefined) {+ throw new Error("Expected the invalid Content Block");+ }+ serverSyncStore.addTransaction(+ "remove-duplicate-templates",+ createSyncChangesFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [blockBeforeRepair.id, "children"],+ value: blockBeforeRepair.children.filter(+ (child) =>+ child.type !== "id" || child.value !== duplicateTemplates.id+ ),+ },+ { op: "remove", path: [duplicateTemplates.id] },+ ],+ },+ ] satisfies BuilderPatchChange[],+ }),+ "remote"+ );++ await vi.waitFor(() => {+ const root = getExternalContentRoots().values().next().value;+ expect(root?.templateMaterializationError).toBeUndefined();+ expect(root?.templateContainerIds).toEqual(["templates"]);+ });+ expect(+ getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ ).toEqual([headingChild]);+ expect($instances.get().get(headingChild.value)?.label).toBe(+ "Styled heading"+ );+});++test.each([+ ["no Templates container", []],+ ["multiple Templates containers", ["templates-1", "templates-2"]],+] as const)(+ "rejects initial acquisition with %s without registering a root",+ async (_case, templateIds) => {+ const source = "# Heading\n";+ const sourceAsset = {+ ...asset,+ size: new TextEncoder().encode(source).byteLength,+ };+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: sourceAsset,+ data: (async function* () {+ yield new TextEncoder().encode(source);+ })(),+ }),+ updateContent: async () => sourceAsset,+ },+ authorize: () => true,+ });+ sessions.push(session);+ assetContentBridgeTesting.initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(+ new Map([+ [+ "block",+ instance(+ "block",+ blockComponent,+ templateIds.map((id) => ({ type: "id" as const, value: id }))+ ),+ ],+ ...templateIds.map(+ (id) => [id, instance(id, blockTemplateComponent, [])] as const+ ),+ ])+ );+ $props.set(new Map());+ $assets.set(new Map([[sourceAsset.id, sourceAsset]]));+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });++ let release: (() => void) | undefined;+ let acquisitionError: unknown;+ try {+ release = await acquireExternalContentRoot({+ projectId: "project",+ assetId: sourceAsset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ });+ } catch (error) {+ acquisitionError = error;+ }++ try {+ expect(acquisitionError).toMatchObject({+ name: "InvalidMdxTemplateStructureError",+ message: expect.stringContaining("exactly one"),+ });+ expect(getExternalContentRoots()).toHaveLength(0);+ } finally {+ release?.();+ if (getExternalContentRoots().size > 0) {+ await disposeExternalContentProject({+ projectId: "project",+ session,+ });+ }+ }+ }+);++test("surfaces a failed template refresh and retries it", async () => {+ const source = "# Heading\n";+ const sourceAsset = {+ ...asset,+ size: new TextEncoder().encode(source).byteLength,+ };+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: sourceAsset,+ data: (async function* () {+ yield new TextEncoder().encode(source);+ })(),+ }),+ updateContent: async () => sourceAsset,+ },+ authorize: () => true,+ });+ sessions.push(session);+ const bridge = createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ });+ assetContentBridgeTesting.initBridge(bridge);+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(createDefaultPages({ rootInstanceId: "block" }));+ $instances.set(+ new Map([+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ ["templates", instance("templates", blockTemplateComponent, [])],+ ])+ );+ $props.set(new Map());+ $assets.set(new Map([[sourceAsset.id, sourceAsset]]));+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });++ const insertion = executeRuntimeMutation({+ id: "instances.insertComponent",+ input: {+ parentInstanceId: "templates",+ component: "ws:element",+ tag: "h1",+ },+ });+ const templateId = insertion?.result.rootInstanceIds[0];+ if (templateId === undefined) {+ throw new Error("Expected an inserted heading template");+ }++ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: sourceAsset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ );+ const states: Array<{ status: string; error?: Error }> = [];+ const unsubscribe = subscribeExternalContentAsset({+ projectId: "project",+ assetId: sourceAsset.id,+ listener: (state) => states.push(state),+ });++ assetContentBridgeTesting.clearBridge();+ executeRuntimeMutation({+ id: "instances.updateProps",+ input: {+ updates: [+ {+ instanceId: templateId,+ name: "title",+ type: "string",+ value: "After",+ },+ ],+ },+ });+ const templatePropId = Array.from($props.get().values()).find(+ (prop) => prop.instanceId === templateId && prop.name === "title"+ )?.id;+ if (templatePropId === undefined) {+ throw new Error("Expected the template prop");+ }++ await vi.waitFor(() => {+ expect(states.at(-1)?.status).toBe("failed");+ expect(states.at(-1)?.error?.message).toBeTruthy();+ });+ expect(+ getExternalContentRoots()+ .values()+ .next()+ .value?.templateOwnership?.props?.has(templatePropId)+ ).toBe(false);++ await expect(+ retryExternalContentAsset({+ projectId: "project",+ assetId: sourceAsset.id,+ })+ ).rejects.toThrow("bridge");+ expect(states.at(-1)?.status).toBe("failed");++ assetContentBridgeTesting.initBridge(bridge);+ await retryExternalContentAsset({+ projectId: "project",+ assetId: sourceAsset.id,+ });++ const heading = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[0];+ if (heading?.type !== "id") {+ throw new Error("Expected the materialized heading");+ }+ expect(+ Array.from($props.get().values()).find(+ (prop) => prop.instanceId === heading.value && prop.name === "title"+ )+ ).toMatchObject({ type: "string", value: "After" });+ expect(states.at(-1)?.status).not.toBe("failed");+ expect(+ getExternalContentRoots()+ .values()+ .next()+ .value?.templateOwnership?.props?.has(templatePropId)+ ).toBe(true);++ unsubscribe();+});++const asset: Asset = {+ id: "asset",+ projectId: "project",+ name: "article_v1.mdx",+ type: "file",+ format: "mdx",+ size: 7,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+};++const instance = (+ id: string,+ component: string,+ children: Instance["children"]+): Instance => ({ type: "instance", id, component, children });++const releases: Array<() => void> = [];+const sessions: Array<ReturnType<typeof createAssetContentSession>> = [];++afterEach(() => {+ assetContentBridgeTesting.clearBridge();+ $builderMode.set("design");+ for (const release of releases.splice(0)) {+ release();+ }+ for (const session of sessions.splice(0)) {+ session.dispose();+ }+});++test("does not let initial materialization overwrite a newer template refresh", async () => {+ const source = "# Heading\n";const sourceAsset = {...asset,size: new TextEncoder().encode(source).byteLength,@@ -86,8 +881,41 @@ test("places unresolved-template placeholders at their authored nesting point",);$project.set({ id: "project", title: "Project", domain: "" } as never);$pages.set(createDefaultPages({ rootInstanceId: "block" }));- $instances.set(new Map([["block", instance("block", blockComponent, [])]]));- $props.set(new Map());+ $instances.set(+ new Map([+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ [+ "templates",+ instance("templates", blockTemplateComponent, [+ { type: "id", value: "heading-template" },+ ]),+ ],+ [+ "heading-template",+ {+ ...instance("heading-template", elementComponent, []),+ tag: "h1",+ },+ ],+ ])+ );+ $props.set(+ new Map([+ [+ "heading-title",+ {+ id: "heading-title",+ instanceId: "heading-template",+ name: "title",+ type: "string" as const,+ value: "Old",+ },+ ],+ ])+ );$assets.set(new Map([[sourceAsset.id, sourceAsset]]));$breakpoints.set(new Map());$dataSources.set(new Map());@@ -96,73 +924,340 @@ test("places unresolved-template placeholders at their authored nesting point",$styleSourceSelections.set(new Map());$styles.set(new Map());$projectSettings.set({ meta: {}, compiler: {} });+ serverSyncStore.popAll();+ externalContentSyncStore.popAll();- releases.push(- await acquireExternalContentRoot({+ let releaseFirstDigest: (() => void) | undefined;+ const firstDigestGate = new Promise<void>((resolve) => {+ releaseFirstDigest = resolve;+ });+ let notifyFirstDigest: (() => void) | undefined;+ const firstDigestStarted = new Promise<void>((resolve) => {+ notifyFirstDigest = resolve;+ });+ const digest = crypto.subtle.digest.bind(crypto.subtle);+ let digestCalls = 0;+ const digestSpy = vi+ .spyOn(crypto.subtle, "digest")+ .mockImplementation(async (...args) => {+ digestCalls += 1;+ if (digestCalls === 1) {+ notifyFirstDigest?.();+ await firstDigestGate;+ }+ return digest(...args);+ });++ try {+ const opening = acquireExternalContentRoot({projectId: "project",assetId: sourceAsset.id,blockInstanceId: "block",renderScope: '["block"]',- })- );+ });+ await firstDigestStarted;- const section = Array.from($instances.get().values()).find(- (candidate) => candidate.tag === "section"- );- const missing = Array.from($instances.get().values()).find(- (candidate) => candidate.label === "Missing template: Missing"- );- expect(missing).toMatchObject({- component: "ws:element",- tag: "div",- children: [{ type: "text", value: "Missing template: Missing" }],- });- if (section === undefined || missing === undefined) {- throw new Error("Expected the section and missing-template placeholder");- }- expect(section.children).toEqual([- { type: "text", value: "Before" },- { type: "id", value: missing.id },- { type: "text", value: "After" },- ]);- expect(- getExternalContentRootChildren({+ executeRuntimeMutation({+ id: "instances.updateProps",+ input: {+ updates: [+ {+ instanceId: "heading-template",+ name: "title",+ type: "string",+ value: "New",+ },+ ],+ },+ });++ await vi.waitFor(() => {+ const child = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[0];+ if (child?.type !== "id") {+ throw new Error("Expected the refreshed heading");+ }+ expect(+ Array.from($props.get().values()).find(+ (prop) => prop.instanceId === child.value && prop.name === "title"+ )+ ).toMatchObject({ value: "New" });+ });++ releaseFirstDigest?.();+ releases.push(await opening);++ const child = getExternalContentRootChildren({projectId: "project",blockInstanceId: "block",renderScope: '["block"]',- })- ).toEqual([{ type: "id", value: section.id }]);+ })?.[0];+ if (child?.type !== "id") {+ throw new Error("Expected the materialized heading");+ }+ expect(+ Array.from($props.get().values()).find(+ (prop) => prop.instanceId === child.value && prop.name === "title"+ )+ ).toMatchObject({ value: "New" });+ } finally {+ releaseFirstDigest?.();+ digestSpy.mockRestore();+ }});-const asset: Asset = {- id: "asset",- projectId: "project",- name: "article_v1.mdx",- type: "file",- format: "mdx",- size: 7,- createdAt: "2026-01-01T00:00:00.000Z",- description: null,- meta: {},-};+test.each([+ {+ name: "keeps the selected JSX template when editing immediately after insertion",+ verifyFirstSaveCleanup: false,+ },+ {+ name: "clears insertion metadata after the first queued save",+ verifyFirstSaveCleanup: true,+ },+])("$name", async ({ verifyFirstSaveCleanup }) => {+ const initialSource = "# Existing\n";+ const sourceAsset = {+ ...asset,+ size: new TextEncoder().encode(initialSource).byteLength,+ };+ let storedSource = initialSource;+ const writes: string[] = [];+ const session = createAssetContentSession({+ repository: {+ readContent: async () => ({+ asset: sourceAsset,+ data: (async function* () {+ yield new TextEncoder().encode(storedSource);+ })(),+ }),+ updateContent: async ({ data }) => {+ storedSource = await new Response(data).text();+ writes.push(storedSource);+ return {+ ...sourceAsset,+ size: new TextEncoder().encode(storedSource).byteLength,+ };+ },+ },+ authorize: () => true,+ debounceMilliseconds: 60_000,+ });+ sessions.push(session);+ assetContentBridgeTesting.initBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: fetch,+ authorize: () => true,+ requireReload: vi.fn(),+ getContentSession: () => session,+ })+ );+ $project.set({ id: "project", title: "Project", domain: "" } as never);+ $pages.set(+ createDefaultPages({ homePageId: "home", rootInstanceId: "block" })+ );+ selectPage("home");+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ [+ "templates",+ instance("templates", blockTemplateComponent, [+ { type: "id", value: "card" },+ { type: "id", value: "note" },+ ]),+ ],+ [+ "card",+ {+ ...instance("card", elementComponent, [+ { type: "text", value: "Card default" },+ ]),+ tag: "p",+ label: "Card",+ },+ ],+ [+ "note",+ {+ ...instance("note", elementComponent, [+ { type: "text", value: "Note default" },+ ]),+ tag: "p",+ label: "Note",+ },+ ],+ ])+ );+ $props.set(+ new Map<Prop["id"], Prop>([+ [+ "card-kind",+ {+ id: "card-kind",+ instanceId: "card",+ name: "data-kind",+ type: "string",+ value: "card",+ },+ ],+ ])+ );+ $assets.set(new Map([[sourceAsset.id, sourceAsset]]));+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styles.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });+ $registeredComponentMetas.set(new Map(Object.entries(coreMetas)));+ $builderMode.set("content");-const instance = (- id: string,- component: string,- children: Instance["children"]-): Instance => ({ type: "instance", id, component, children });+ const release = await acquireExternalContentRoot({+ projectId: "project",+ assetId: sourceAsset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ });+ releases.push(release);+ const heading = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[0];+ if (heading?.type !== "id") {+ throw new Error("Expected the initial heading");+ }+ selectInstance([heading.value, "block"]);-const releases: Array<() => void> = [];-const sessions: Array<ReturnType<typeof createAssetContentSession>> = [];+ await expect(+ insertTemplateAt({+ templateSelector: ["card", "templates", "block"],+ anchor: [heading.value, "block"],+ insertBefore: false,+ })+ ).resolves.toBe(true);+ const inserted = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[1];+ if (inserted?.type !== "id") {+ throw new Error("Expected the inserted Card");+ }-afterEach(() => {- assetContentBridgeTesting.clearBridge();- for (const release of releases.splice(0)) {- release();+ if (verifyFirstSaveCleanup) {+ await vi.waitFor(() =>+ expect(+ getExternalContentRoots().values().next().value?.insertedTemplates+ ).toBeUndefined()+ );+ return;}- for (const session of sessions.splice(0)) {- session.dispose();++ await expect(+ insertTemplateAt({+ templateSelector: ["note", "templates", "block"],+ anchor: [inserted.value, "block"],+ insertBefore: false,+ })+ ).resolves.toBe(true);+ const removedBeforeSave = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[2];+ if (removedBeforeSave?.type !== "id") {+ throw new Error("Expected the inserted Note");}+ executeRuntimeMutation({+ id: "instances.deleteBySelector",+ input: { instanceSelector: [removedBeforeSave.value, "block"] },+ });++ await Promise.resolve();+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: inserted.value,+ mode: "text",+ text: "Edited text",+ },+ });+ executeRuntimeMutation({+ id: "instances.updateProps",+ input: {+ updates: [+ {+ instanceId: inserted.value,+ name: "title",+ type: "string",+ value: "Edited",+ },+ ],+ },+ });++ await flushExternalContentAsset({+ projectId: "project",+ assetId: sourceAsset.id,+ });+ expect(writes.at(-1)).toBe(+ '# Existing\n\n<Card title="Edited">Edited text</Card>\n'+ );+ expect(+ getExternalContentRoots().values().next().value?.insertedTemplates+ ).toBeUndefined();++ release();+ releases.splice(releases.indexOf(release), 1);+ releases.push(+ await acquireExternalContentRoot({+ projectId: "project",+ assetId: sourceAsset.id,+ blockInstanceId: "block",+ renderScope: '["block"]',+ })+ );+ executeRuntimeMutation({+ id: "instances.updateProps",+ input: {+ updates: [+ {+ instanceId: "card",+ name: "data-template-version",+ type: "string",+ value: "two",+ },+ ],+ },+ });+ await vi.waitFor(() => {+ const reloaded = getExternalContentRootChildren({+ projectId: "project",+ blockInstanceId: "block",+ renderScope: '["block"]',+ })?.[1];+ if (reloaded?.type !== "id") {+ throw new Error("Expected the reloaded Card");+ }+ expect(+ Array.from($props.get().values()).find(+ (prop) =>+ prop.instanceId === reloaded.value &&+ prop.name === "data-template-version"+ )+ ).toMatchObject({ type: "string", value: "two" });+ });});test("rejects a stale raw editor replacement behind a newer queued edit", async () => {@@ -260,8 +1355,18 @@ test("rebases frontmatter edits from Content Blocks sharing one Asset", async ()$pages.set(createDefaultPages({ rootInstanceId: "block" }));$instances.set(new Map([- ["block", instance("block", blockComponent, [])],- ["block-2", instance("block-2", blockComponent, [])],+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ ["templates", instance("templates", blockTemplateComponent, [])],+ [+ "block-2",+ instance("block-2", blockComponent, [+ { type: "id", value: "templates-2" },+ ]),+ ],+ ["templates-2", instance("templates-2", blockTemplateComponent, [])],]));$props.set(new Map());@@ -353,7 +1458,15 @@ test("does not install an Asset load after its Content Block unmounts", async ());$project.set({ id: "project", title: "Project", domain: "" } as never);$pages.set(createDefaultPages({ rootInstanceId: "block" }));- $instances.set(new Map([["block", instance("block", blockComponent, [])]]));+ $instances.set(+ new Map([+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ ["templates", instance("templates", blockTemplateComponent, [])],+ ])+ );$props.set(new Map());$dataSources.set(new Map());$resources.set(new Map());@@ -417,7 +1530,15 @@ test("replaces a mounted root when its source Asset changes", async () => {);$project.set({ id: "project", title: "Project", domain: "" } as never);$pages.set(createDefaultPages({ rootInstanceId: "block" }));- $instances.set(new Map([["block", instance("block", blockComponent, [])]]));+ $instances.set(+ new Map([+ [+ "block",+ instance("block", blockComponent, [{ type: "id", value: "templates" }]),+ ],+ ["templates", instance("templates", blockTemplateComponent, [])],+ ])+ );$props.set(new Map());$assets.set(new Map<Asset["id"], Asset>([diff --git a/apps/builder/app/shared/external-content-roots.ts b/apps/builder/app/shared/external-content-roots.tsindex 7831c7d68d..568771dcfe 100644--- a/apps/builder/app/shared/external-content-roots.ts+++ b/apps/builder/app/shared/external-content-roots.ts@@ -1,3 +1,7 @@+/**+ * Manages the live lifecycle between connected Asset documents and canvas+ * instances: materialization, persistence, template refresh, and cleanup.+ */import {createCanonicalAssetPath,createMarkdownFrontmatterDiagnostics,@@ -22,6 +26,7 @@ import {extractWebstudioFragment,adoptMdxAuthoredContentFragment,createEmptyWebstudioFragment,+ assertMdxTemplateContainerCount,materializeMdxSource,mergeWebstudioFragments,MdxAuthoredContentConflictError,@@ -29,6 +34,7 @@ import {rebaseMdxAuthoredContent,createMdxScopeIdGenerator,type MaterializedMdxAuthoredContentRoot,+ type MdxTemplateInsertion,} from "@webstudio-is/project-build/runtime";import {blockTemplateComponent,@@ -37,10 +43,10 @@ import {formatAssetName,findContentBlockBodyContainerPaths,findContentBlockTemplateContainers,- getInstanceName,createContentBlockExternalContentIdentity,toAssetReferenceRuntimeData,type ContentBlockDiagnostic,+ type Instance,type WebstudioFragment,} from "@webstudio-is/sdk";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";@@ -50,9 +56,15 @@ import type {} from "@webstudio-is/content-engine/asset-content-session";import { getAssetContentBridge } from "./asset-content-bridge.client";import {+ $externalContentRoots,+ clearExternalContentTemplateInsertions,+ getAffectedExternalContentTemplateRootKeys,getExternalContentRoots,+ publishExternalContentTemplateMutation,registerExternalContentRoot,subscribeExternalContentMutations,+ subscribeExternalContentTemplateMutations,+ updateExternalContentTemplateMaterializationError,} from "./external-content-mutations";import {getExternalContentFragmentOwnership,@@ -60,7 +72,11 @@ import {} from "./external-content-persistence";import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";import { getWebstudioData } from "./instance-utils/data";-import { externalContentSyncStore } from "./sync/sync-stores";+import {+ externalContentSyncStore,+ serverSyncStore,+ subscribeServerSyncReverts,+} from "./sync/sync-stores";import { createSyncChangesFromBuilderPatchPayload } from "./sync/builder-patch";import { $project } from "./sync/data-stores";import {@@ -86,6 +102,8 @@ type RootEntry = {unregisterMutationRoot: () => void;references: number;openVersion: number;+ templateVersion: number;+ templateRematerialization?: Promise<void>;saveRevision: number;dependencyAssetIds: ReadonlySet<string>;};@@ -108,7 +126,11 @@ type AssetQueue = {type PreparedAssetUpdate =| string- | Readonly<{ source: string; document: MdxDocument }>+ | Readonly<{+ source: string;+ document: MdxDocument;+ afterSave?: () => void;+ }>| undefined;type AssetUpdate = (state: AssetContentSessionState,@@ -175,6 +197,7 @@ const settleProjectAssetQueues = async (projectId: string) => {);const serializations = queues.map((queue) => queue.serialization);await Promise.all(serializations);+ await waitForTemplateRematerialization(projectId);const currentQueues = Array.from(assetQueues.values()).filter((queue) => queue.projectId === projectId);@@ -190,6 +213,11 @@ const settleProjectAssetQueues = async (projectId: string) => {if (failed?.error !== undefined) {throw failed.error;}+ const templateMaterializationError =+ getTemplateMaterializationError(projectId);+ if (templateMaterializationError !== undefined) {+ throw templateMaterializationError;+ }return currentQueues;}}@@ -230,6 +258,34 @@ const publishAssetQueueError = (queue: AssetQueue) => {}};+const getTemplateMaterializationError = (+ projectId: string,+ assetId?: string+) => {+ for (const root of getExternalContentRoots().values()) {+ if (+ root.projectId === projectId &&+ (assetId === undefined || root.assetId === assetId) &&+ root.templateMaterializationError !== undefined+ ) {+ return new Error(root.templateMaterializationError);+ }+ }+};++const getTemplateMaterializationRootKeys = (+ projectId: string,+ assetId: string+) =>+ Array.from(getExternalContentRoots())+ .filter(+ ([, root]) =>+ root.projectId === projectId &&+ root.assetId === assetId &&+ root.templateMaterializationError !== undefined+ )+ .map(([key]) => key);+const getPreservedRootKey = (queue: AssetQueue | undefined,state: AssetContentSessionState@@ -280,11 +336,32 @@ const getMutationRootChildren = (return [...templateChildren, ...authoredChildren];};+const getTemplateSnapshot = (entry: RootEntry) => {+ const data = getWebstudioData();+ const sourceBlock = data.instances.get(entry.sourceBlockInstanceId);+ const templateContainers =+ sourceBlock === undefined+ ? []+ : findContentBlockTemplateContainers({+ blockInstance: sourceBlock,+ instances: data.instances,+ });+ const templateFragment = mergeWebstudioFragments(+ templateContainers.map(({ id }) => id),+ templateContainers.map(({ id }) => extractWebstudioFragment(data, id))+ );+ return {+ containerIds: templateContainers.map(({ id }) => id),+ ownership: getExternalContentFragmentOwnership(templateFragment),+ };+};+const registerMutationRoot = (entry: RootEntry,fragment: WebstudioFragment) => {const owned = getExternalContentFragmentOwnership(fragment);+ const templateSnapshot = getTemplateSnapshot(entry);const instanceSelector = parseContentBlockRenderScope(entry.renderScope);entry.unregisterMutationRoot = registerExternalContentRoot(entry.key, {sourceBlockInstanceId: entry.sourceBlockInstanceId,@@ -300,8 +377,11 @@ const registerMutationRoot = (instanceIds: owned.instances,propIds: owned.props,ownership: owned,+ templateContainerIds: templateSnapshot.containerIds,+ templateOwnership: templateSnapshot.ownership,mutationRevision: 0,projectId: entry.projectId,+ assetId: entry.assetId,identity: entry.root.identity,diagnostics: entry.diagnostics,document: entry.root.document,@@ -324,7 +404,7 @@ const installRoot = ({const data = getWebstudioData();const sourceBlock = data.instances.get(entry.sourceBlockInstanceId);if (sourceBlock === undefined) {- return;+ return false;}const installedFragment = root.fragment;const transientInstanceIds = new Set(@@ -357,7 +437,7 @@ const installRoot = ({if (entry.contentInstanceId !== entry.blockInstanceId) {const sourceContent = data.instances.get(entry.sourceContentInstanceId);if (sourceContent === undefined) {- return;+ return false;}payload.push({namespace: "instances",@@ -421,6 +501,11 @@ const installRoot = ({entry.transientInstanceIds = transientInstanceIds;entry.diagnostics = diagnostics;registerMutationRoot(entry, installedFragment);+ updateExternalContentTemplateMaterializationError({+ key: entry.key,+ error: undefined,+ });+ return true;};const uninstallRoot = (entry: RootEntry) => {@@ -899,42 +984,28 @@ const captureInstalledFragment = (};};-const getInsertedTemplateNames = (+const getInsertedTemplates = (entry: RootEntry,fragment: WebstudioFragment) => {- const data = getWebstudioData();- const block = data.instances.get(entry.blockInstanceId);- const templates =- block === undefined- ? undefined- : findContentBlockTemplateContainers({- blockInstance: block,- instances: data.instances,- })[0];- const availableNames = new Set(- templates?.children.flatMap((child) => {- const instance =- child.type === "id" ? data.instances.get(child.value) : undefined;- return instance === undefined- ? []- : [getInstanceName({ instance, metas: componentMetas })];- }) ?? []- );+ const insertions = getExternalContentRoots().get(+ entry.key+ )?.insertedTemplates;+ if (insertions === undefined) {+ return new Map<Instance["id"], MdxTemplateInsertion>();+ }const authoredIds = new Set(entry.root.fragment.instances.map(({ id }) => id));return new Map(fragment.children.flatMap((child) => {- const instance =- child.type === "id" && authoredIds.has(child.value) === false- ? data.instances.get(child.value)- : undefined;- if (instance === undefined) {+ if (child.type !== "id" || authoredIds.has(child.value)) {return [];}- const name = getInstanceName({ instance, metas: componentMetas });- return availableNames.has(name) ? [[instance.id, name] as const] : [];+ const insertion = insertions.get(child.value);+ return insertion === undefined+ ? []+ : ([[child.value, insertion]] as const);}));};@@ -976,6 +1047,9 @@ const enqueueAssetUpdate = ({? undefined: { source, document: prepared.document };session.save(assetId, source);+ if (typeof prepared !== "string") {+ prepared.afterSave?.();+ }});let succeeded = false;const tracked = saving.then(@@ -1034,7 +1108,7 @@ subscribeExternalContentMutations((rootKeys) => {root: entry.root,fragment,});- const insertedTemplateNames = getInsertedTemplateNames(entry, fragment);+ const insertedTemplates = getInsertedTemplates(entry, fragment);const authoredRoot = entry.root;const saveRevision = ++entry.saveRevision;entry.installedFragment = captureInstalledFragment(entry, fragment);@@ -1067,7 +1141,7 @@ subscribeExternalContentMutations((rootKeys) => {}let saveRoot = authoredRoot;let saveFragment = persistedFragment;- let saveInsertedTemplateNames = insertedTemplateNames;+ let saveInsertedTemplates = insertedTemplates;if (roots.get(entry.key) === entry) {const currentFragment = extractCurrentFragment(entry);saveRoot = entry.root;@@ -1075,10 +1149,7 @@ subscribeExternalContentMutations((rootKeys) => {root: saveRoot,fragment: currentFragment,});- saveInsertedTemplateNames = getInsertedTemplateNames(- entry,- currentFragment- );+ saveInsertedTemplates = getInsertedTemplates(entry, currentFragment);} else if (entry.saveRevision !== saveRevision) {return;}@@ -1088,8 +1159,14 @@ subscribeExternalContentMutations((rootKeys) => {latest: latestDocument,latestRevision: createExternalContentIdentity(entry, state).revision,latestIsLocal,- insertedTemplateNames: saveInsertedTemplateNames,+ insertedTemplates: saveInsertedTemplates,});+ if (+ roots.get(entry.key) === entry &&+ entry.saveRevision !== saveRevision+ ) {+ return;+ }const source = serializeMdxDocument(document);if (roots.get(entry.key) !== entry) {return { source, document };@@ -1099,6 +1176,9 @@ subscribeExternalContentMutations((rootKeys) => {sourceState: { ...state, source },});if (roots.get(entry.key) !== entry) {+ return { source, document };+ }+ if (entry.saveRevision !== saveRevision) {return;}try {@@ -1112,12 +1192,164 @@ subscribeExternalContentMutations((rootKeys) => {// a recovery write never replaces the user's local IDs or selection.// Other occurrences still rematerialize from the merged source.}- return { source, document };+ const insertionIdsToClear = Array.from(+ getExternalContentRoots().get(entry.key)?.insertedTemplates?.keys() ??+ []+ );+ return {+ source,+ document,+ afterSave: () =>+ clearExternalContentTemplateInsertions({+ key: entry.key,+ instanceIds: insertionIdsToClear,+ }),+ };},}).catch(() => {});}});+const rematerializeTemplateRoot = async (entry: RootEntry) => {+ const key = entry.key;+ updateExternalContentTemplateMaterializationError({+ key,+ error: undefined,+ });+ const templateVersion = ++entry.templateVersion;+ const queue = getAssetQueue(entry.projectId, entry.assetId);+ try {+ while (+ roots.get(key) === entry &&+ entry.templateVersion === templateVersion+ ) {+ const serialization = queue.serialization;+ await serialization;+ if (queue.serialization !== serialization) {+ continue;+ }+ if (queue.error !== undefined) {+ return;+ }+ const sourceState = getSession(entry.projectId).get(entry.assetId);+ if (sourceState === undefined) {+ throw new Error(`Asset content session "${entry.assetId}" is not open`);+ }+ const data = getWebstudioData();+ const sourceBlock = data.instances.get(entry.sourceBlockInstanceId);+ if (sourceBlock === undefined) {+ throw new Error("Connected Content Block no longer exists");+ }+ const templateContainers = findContentBlockTemplateContainers({+ blockInstance: sourceBlock,+ instances: data.instances,+ });+ if (templateContainers.length !== 1) {+ // Keep observing the invalid structure so removing the extra container+ // triggers recovery without replacing the last valid materialization.+ registerMutationRoot(entry, entry.installedFragment);+ }+ assertMdxTemplateContainerCount(templateContainers.length);+ const openVersion = ++entry.openVersion;+ const result = await materialize({ entry, sourceState });+ if (+ roots.get(key) !== entry ||+ entry.templateVersion !== templateVersion+ ) {+ return;+ }+ if (entry.openVersion !== openVersion) {+ continue;+ }+ if (installRoot({ entry, ...result }) === false) {+ throw new Error("Connected Content Block no longer exists");+ }+ return;+ }+ } catch (error) {+ if (roots.get(key) === entry && entry.templateVersion === templateVersion) {+ updateExternalContentTemplateMaterializationError({+ key,+ error:+ error instanceof Error+ ? error.message+ : "Unable to apply Content Block templates",+ });+ }+ }+};++const startTemplateRematerialization = (entry: RootEntry) => {+ const rematerialization = rematerializeTemplateRoot(entry);+ entry.templateRematerialization = rematerialization;+ void rematerialization.finally(() => {+ if (entry.templateRematerialization === rematerialization) {+ entry.templateRematerialization = undefined;+ }+ });+ return rematerialization;+};++const waitForTemplateRematerialization = async (+ projectId: string,+ assetId?: string+) => {+ while (true) {+ const pending = Array.from(roots.values()).flatMap((entry) =>+ entry.projectId === projectId &&+ (assetId === undefined || entry.assetId === assetId) &&+ entry.templateRematerialization !== undefined+ ? [entry.templateRematerialization]+ : []+ );+ if (pending.length === 0) {+ return;+ }+ await Promise.all(pending);+ await Promise.resolve();+ }+};++subscribeExternalContentTemplateMutations((rootKeys) => {+ for (const key of rootKeys) {+ const entry = roots.get(key);+ if (entry !== undefined) {+ void startTemplateRematerialization(entry);+ }+ }+});++const publishAffectedExternalContentTemplateMutations = (+ payload: readonly BuilderPatchChange[]+) => {+ // The canvas owns materialized roots. Builder-side copies receive the+ // resulting revision through the shared Nanostore and must not publish a+ // duplicate invalidation for the same server transaction.+ if (roots.size === 0) {+ return;+ }+ const registeredRoots = getExternalContentRoots();+ publishExternalContentTemplateMutation(+ getAffectedExternalContentTemplateRootKeys({+ state: getWebstudioData(),+ roots: registeredRoots,+ payload,+ })+ );+};++serverSyncStore.subscribe((_transactionId, payload) => {+ publishAffectedExternalContentTemplateMutations(+ payload as BuilderPatchChange[]+ );+});++subscribeServerSyncReverts((payload) => {+ publishAffectedExternalContentTemplateMutations([+ ...payload,+ ] as BuilderPatchChange[]);+});+export const updateExternalContentAssetSource = ({projectId,assetId,@@ -1292,12 +1524,19 @@ export const acquireExternalContentRoot = async ({fragment: createEmptyWebstudioFragment(),document: { frontmatter: { properties: {} }, children: [] },provenance: { nodes: [], unresolvedTemplates: [] },+ diagnostics: [],};const instanceSelector = parseContentBlockRenderScope(renderScope);const sourceBlock = getWebstudioData().instances.get(blockInstanceId);if (sourceBlock === undefined) {throw new Error("Connected Content Block no longer exists");}+ assertMdxTemplateContainerCount(+ findContentBlockTemplateContainers({+ blockInstance: sourceBlock,+ instances: getWebstudioData().instances,+ }).length+ );const bodyPaths = findContentBlockBodyContainerPaths({blockInstance: sourceBlock,instances: getWebstudioData().instances,@@ -1344,13 +1583,15 @@ export const acquireExternalContentRoot = async ({unregisterMutationRoot: () => {},references: 1,openVersion: 0,+ templateVersion: 0,saveRevision: 0,dependencyAssetIds: new Set([assetId]),};roots.set(key, entry);registerMutationRoot(entry, placeholderRoot.fragment);+ const openVersion = ++entry.openVersion;const result = await materialize({ entry, sourceState });- if (roots.get(key) === entry) {+ if (roots.get(key) === entry && entry.openVersion === openVersion) {installRoot({ entry, ...result });}return () => releaseExternalContentRoot(key, entry);@@ -1374,6 +1615,14 @@ export const flushExternalContentAsset = async ({state));+ await waitForTemplateRematerialization(projectId, assetId);+ const templateMaterializationError = getTemplateMaterializationError(+ projectId,+ assetId+ );+ if (templateMaterializationError !== undefined) {+ throw templateMaterializationError;+ }return state;};@@ -1422,7 +1671,7 @@ export const reloadExternalContentAsset = ({expectedName: string;}) => getSession(projectId).reload(assetId, { expectedName });-export const retryExternalContentAsset = ({+export const retryExternalContentAsset = async ({projectId,assetId,}: {@@ -1431,14 +1680,34 @@ export const retryExternalContentAsset = ({}) => {const queue = getAssetQueue(projectId, assetId);if (queue.failedUpdate !== undefined) {- return enqueueAssetUpdate({+ await enqueueAssetUpdate({projectId,assetId,update: queue.failedUpdate,preservedRootKey: queue.failedPreservedRootKey,- }).then(() => getSession(projectId).get(assetId));+ });+ return getSession(projectId).get(assetId);}- return getSession(projectId).retry(assetId);+ const templateRootKeys = getTemplateMaterializationRootKeys(+ projectId,+ assetId+ );+ if (templateRootKeys.length > 0) {+ for (const key of templateRootKeys) {+ updateExternalContentTemplateMaterializationError({+ key,+ error: undefined,+ });+ }+ publishExternalContentTemplateMutation(templateRootKeys);+ await waitForTemplateRematerialization(projectId, assetId);+ const error = getTemplateMaterializationError(projectId, assetId);+ if (error !== undefined) {+ throw error;+ }+ return getSession(projectId).get(assetId);+ }+ return await getSession(projectId).retry(assetId);};export const subscribeExternalContentAsset = ({@@ -1452,12 +1721,13 @@ export const subscribeExternalContentAsset = ({}) => {const session = getSession(projectId);const queue = getAssetQueue(projectId, assetId);- const publish = (state: AssetContentSessionState) =>+ const publish = (state: AssetContentSessionState) => {+ const error =+ queue.error ?? getTemplateMaterializationError(projectId, assetId);listener(- queue.error === undefined- ? state- : { ...state, status: "failed", error: queue.error }+ error === undefined ? state : { ...state, status: "failed", error });+ };const current = session.get(assetId);if (current !== undefined) {publish(current);@@ -1474,8 +1744,15 @@ export const subscribeExternalContentAsset = ({}};queue.listeners.add(queueListener);+ const unsubscribeRoots = $externalContentRoots.listen(() => {+ const state = session.get(assetId);+ if (state !== undefined) {+ publish(state);+ }+ });return () => {unsubscribe();+ unsubscribeRoots();queue.listeners.delete(queueListener);};};diff --git a/apps/builder/app/shared/instance-utils/data.ts b/apps/builder/app/shared/instance-utils/data.tsindex 8ad74920da..7209da10a6 100644--- a/apps/builder/app/shared/instance-utils/data.ts+++ b/apps/builder/app/shared/instance-utils/data.ts@@ -42,9 +42,20 @@ export type RuntimeMutationOperation = {[Id in BuilderRuntimeMutationOperationId]: {id: Id;input: BuilderRuntimeOperationInput<Id>;+ context?: RuntimeMutationContext;};}[BuilderRuntimeMutationOperationId];+type RuntimeMutationSequenceResults<+ Operations extends readonly RuntimeMutationOperation[],+> = {+ [Index in keyof Operations]: Operations[Index] extends {+ id: infer Id extends BuilderRuntimeMutationOperationId;+ }+ ? RuntimeMutationResult<Id>["result"]+ : never;+};+type TemplateNameConfirmation = ReturnType<typeof blockTemplateNameConfirmationInput.parse>;@@ -301,15 +312,17 @@ export const confirmPendingTemplateNameChange = () => {}};-export const executeRuntimeMutationSequence = (- operations: readonly RuntimeMutationOperation[]-): void => {+export const executeRuntimeMutationSequence = <+ const Operations extends readonly RuntimeMutationOperation[],+>(+ operations: Operations+): RuntimeMutationSequenceResults<Operations> | undefined => {if (canCommitWebstudioData() === false) {return;}const accumulator = createRuntimeMutationAccumulator(getWebstudioData());const results: Record<string, unknown>[] = [];- for (const [operationIndex, { id, input }] of operations.entries()) {+ for (const [operationIndex, { id, input, context }] of operations.entries()) {try {results.push(accumulator.stage(@@ -319,7 +332,7 @@ export const executeRuntimeMutationSequence = (id,state: accumulator.state,input,- context: getRuntimeMutationContext(),+ context: { ...getRuntimeMutationContext(), ...context },})))@@ -338,6 +351,7 @@ export const executeRuntimeMutationSequence = (}}commitRuntimeMutation(accumulator.complete({ results }));+ return results as RuntimeMutationSequenceResults<Operations>;};export const executeRuntimeMutationAsync = async <diff --git a/apps/builder/app/shared/instance-utils/fragment.test.tsx b/apps/builder/app/shared/instance-utils/fragment.test.tsxindex 381481a4fb..1a6bc06c09 100644--- a/apps/builder/app/shared/instance-utils/fragment.test.tsx+++ b/apps/builder/app/shared/instance-utils/fragment.test.tsx@@ -10,7 +10,13 @@ import { enableMapSet } from "immer";import { describe, test, expect, beforeEach } from "vitest";import type { Project } from "@webstudio-is/project";import { createDefaultPages } from "@webstudio-is/project-build";-import { $, ws, css, renderData, token } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ ws,+ css,+ renderData,+ token,+} from "@webstudio-is/template";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";import type {Asset,@@ -49,6 +55,11 @@ import { registerContainers } from "../sync/sync-stores";import { getInstancePath } from "@webstudio-is/project-build/runtime";import { isFragmentContentModeCopyableProp } from "@webstudio-is/project-build/runtime";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Fragment = createTemplateComponentFixture("Fragment");+const Slot = createTemplateComponentFixture("Slot");+const {getFragmentInstancesData,insertFragmentAssetsMutable,@@ -506,19 +517,19 @@ describe("insert webstudio fragment copy", () => {test("duplicate shared slot child in shared slot content", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);const instancePath =@@ -557,19 +568,19 @@ describe("insert webstudio fragment copy", () => {test("copy shared slot child outside keeps copy independent from slot content", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);const fragment = extractWebstudioFragment(data, "div");@@ -617,23 +628,23 @@ describe("insert webstudio fragment copy", () => {test("copy nested shared slot child outside keeps copy independent from slot content", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);const fragment = extractWebstudioFragment(data, "box");@@ -2231,8 +2242,8 @@ describe("detectPageTokenConflicts", () => {test("detectFragmentTokenConflicts returns token style conflicts", () => {const targetData = renderData(- <$.Body ws:id="body">- <$.Box+ <Body ws:id="body">+ <Boxws:id="existing-box"ws:tokens={[token(@@ -2242,15 +2253,15 @@ describe("detectPageTokenConflicts", () => {`),]}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);setDataStores(targetData);$pages.set(createDefaultPages({ rootInstanceId: "body" }));const sourceData = renderData(- <$.Body ws:id="source-body">- <$.Box+ <Body ws:id="source-body">+ <Boxws:id="source-box"ws:tokens={[token(@@ -2260,8 +2271,8 @@ describe("detectPageTokenConflicts", () => {`),]}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);const conflicts = detectFragmentTokenConflicts({@@ -2280,9 +2291,9 @@ describe("detectPageTokenConflicts", () => {test("returns empty array when no conflicts exist", () => {// Set up target project data (no tokens)const targetData = renderData(- <$.Body ws:id="body">- <$.Box ws:id="existing-box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="existing-box"></Box>+ </Body>);setDataStores(targetData);const pages = createDefaultPages({ rootInstanceId: "body" });@@ -2290,8 +2301,8 @@ describe("detectPageTokenConflicts", () => {// Create source data with a tokenconst sourceData = renderData(- <$.Body ws:id="source-body">- <$.Box+ <Body ws:id="source-body">+ <Boxws:id="source-box"ws:tokens={[token(@@ -2301,8 +2312,8 @@ describe("detectPageTokenConflicts", () => {`),]}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });const sourceWebstudioData: WebstudioData = {@@ -2323,8 +2334,8 @@ describe("detectPageTokenConflicts", () => {test("returns conflicts when token conflicts exist", () => {// Set up target project with a "primary" tokenconst targetData = renderData(- <$.Body ws:id="body">- <$.Box+ <Body ws:id="body">+ <Boxws:id="existing-box"ws:tokens={[token(@@ -2334,8 +2345,8 @@ describe("detectPageTokenConflicts", () => {`),]}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);setDataStores(targetData);const pages = createDefaultPages({ rootInstanceId: "body" });@@ -2343,8 +2354,8 @@ describe("detectPageTokenConflicts", () => {// Create source data with same "primary" token but different stylesconst sourceData = renderData(- <$.Body ws:id="source-body">- <$.Box+ <Body ws:id="source-body">+ <Boxws:id="source-box"ws:tokens={[token(@@ -2354,8 +2365,8 @@ describe("detectPageTokenConflicts", () => {`),]}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });const sourceWebstudioData: WebstudioData = {@@ -2377,8 +2388,8 @@ describe("detectPageTokenConflicts", () => {test("detects conflicts from ROOT_INSTANCE tokens", () => {// Set up target project with a "header" tokenconst targetData = renderData(- <$.Body ws:id="body">- <$.Box+ <Body ws:id="body">+ <Boxws:id="existing-box"ws:tokens={[token(@@ -2388,8 +2399,8 @@ describe("detectPageTokenConflicts", () => {`),]}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);setDataStores(targetData);const pages = createDefaultPages({ rootInstanceId: "body" });@@ -2397,9 +2408,9 @@ describe("detectPageTokenConflicts", () => {// Create source data with a ROOT_INSTANCE that has conflicting "header" tokenconst sourceBodyData = renderData(- <$.Body ws:id="source-body">- <$.Box ws:id="source-box"></$.Box>- </$.Body>+ <Body ws:id="source-body">+ <Box ws:id="source-box"></Box>+ </Body>);// Add a global "header" token with different styles (simulating ROOT_INSTANCE content)const headerTokenId = "header-token-id";@@ -2449,12 +2460,12 @@ describe("detectPageTokenConflicts", () => {});test("throws error when page not found", () => {- const targetData = renderData(<$.Body ws:id="body"></$.Body>);+ const targetData = renderData(<Body ws:id="body"></Body>);setDataStores(targetData);const pages = createDefaultPages({ rootInstanceId: "body" });$pages.set(pages);- const sourceData = renderData(<$.Body ws:id="source-body"></$.Body>);+ const sourceData = renderData(<Body ws:id="source-body"></Body>);const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });const sourceWebstudioData: WebstudioData = {...sourceData,diff --git a/apps/builder/app/shared/instance-utils/insert.test.tsx b/apps/builder/app/shared/instance-utils/insert.test.tsxindex 397190b9d8..62b7bae07c 100644--- a/apps/builder/app/shared/instance-utils/insert.test.tsx+++ b/apps/builder/app/shared/instance-utils/insert.test.tsx@@ -12,7 +12,7 @@ import { toast } from "@webstudio-is/design-system";import type { Project } from "@webstudio-is/project";import { createDefaultPages } from "@webstudio-is/project-build";import {- $,+ createTemplateComponentFixture,ws,css,expression,@@ -47,6 +47,15 @@ import { selectInstance } from "../nano-states";import { $selectedPageId } from "../nano-states/pages";import { expectSlotsShareFragment } from "../slot-test-utils";+const Body = createTemplateComponentFixture("Body");+const Bold = createTemplateComponentFixture("Bold");+const Box = createTemplateComponentFixture("Box");+const Fragment = createTemplateComponentFixture("Fragment");+const Image = createTemplateComponentFixture("Image");+const ListItem = createTemplateComponentFixture("ListItem");+const Paragraph = createTemplateComponentFixture("Paragraph");+const Slot = createTemplateComponentFixture("Slot");+enableMapSet();registerContainers();@@ -102,7 +111,7 @@ describe("insert webstudio element at", () => {});test("insert element with div tag into body", async () => {- $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);+ $instances.set(renderData(<Body ws:id="bodyId"></Body>).instances);await insertWebstudioElementAt({parentSelector: ["bodyId"],position: "end",@@ -110,9 +119,9 @@ describe("insert webstudio element at", () => {const [_bodyId, newInstanceId] = $instances.get().keys();expect($instances.get()).toEqual(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id={newInstanceId} ws:tag="div" />- </$.Body>+ </Body>).instances);});@@ -120,9 +129,9 @@ describe("insert webstudio element at", () => {test("insert element with li tag into ul", async () => {$instances.set(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id="listId" ws:tag="ul"></ws.element>- </$.Body>+ </Body>).instances);await insertWebstudioElementAt({@@ -132,11 +141,11 @@ describe("insert webstudio element at", () => {const [_bodyId, _listId, newInstanceId] = $instances.get().keys();expect($instances.get()).toEqual(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id="listId" ws:tag="ul"><ws.element ws:id={newInstanceId} ws:tag="li" /></ws.element>- </$.Body>+ </Body>).instances);});@@ -147,9 +156,9 @@ describe("insert webstudio element at", () => {);$instances.set(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id="divId" ws:tag="div"></ws.element>- </$.Body>+ </Body>).instances);selectPage("homePageId");@@ -158,11 +167,11 @@ describe("insert webstudio element at", () => {const [_bodyId, _divId, newInstanceId] = $instances.get().keys();expect($instances.get()).toEqual(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id="divId" ws:tag="div"><ws.element ws:id={newInstanceId} ws:tag="div" /></ws.element>- </$.Body>+ </Body>).instances);});@@ -173,11 +182,11 @@ describe("insert webstudio element at", () => {);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slotId">- <$.Box ws:id="boxId"></$.Box>- </$.Slot>- </$.Body>+ <Body ws:id="bodyId">+ <Slot ws:id="slotId">+ <Box ws:id="boxId"></Box>+ </Slot>+ </Body>).instances);selectPage("homePageId");@@ -196,14 +205,14 @@ describe("insert webstudio element at", () => {);expect(instances).toEqual(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slotId">- <$.Fragment ws:id={fragmentId}>- <$.Box ws:id="boxId"></$.Box>+ <Body ws:id="bodyId">+ <Slot ws:id="slotId">+ <Fragment ws:id={fragmentId}>+ <Box ws:id="boxId"></Box><ws.element ws:id={newInstanceId} ws:tag="div" />- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>).instances);});@@ -214,19 +223,19 @@ describe("insert webstudio element at", () => {);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>).instances);selectPage("homePageId");@@ -253,19 +262,19 @@ describe("insert webstudio element at", () => {test("insert element at start of shared slot content", async () => {$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>).instances);@@ -296,19 +305,19 @@ describe("insert webstudio element at", () => {);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:id="div" ws:tag="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:id="div" ws:tag="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>).instances);selectPage("homePageId");@@ -340,12 +349,12 @@ describe("insert webstudio element at", () => {);$instances.set(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id="divId" ws:tag="div">text</ws.element><ws.element ws:id="spanId" ws:tag="span"></ws.element>- </$.Body>+ </Body>).instances);selectPage("homePageId");@@ -354,13 +363,13 @@ describe("insert webstudio element at", () => {const [_bodyId, _divId, _spanId, newInstanceId] = $instances.get().keys();expect($instances.get()).toEqual(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id="divId" ws:tag="div">text</ws.element><ws.element ws:id={newInstanceId} ws:tag="div" /><ws.element ws:id="spanId" ws:tag="span"></ws.element>- </$.Body>+ </Body>).instances);});@@ -371,10 +380,10 @@ describe("insert webstudio element at", () => {);$instances.set(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id="imgId" ws:tag="img"></ws.element><ws.element ws:id="spanId" ws:tag="span"></ws.element>- </$.Body>+ </Body>).instances);selectPage("homePageId");@@ -383,18 +392,18 @@ describe("insert webstudio element at", () => {const [_bodyId, _imgId, _spanId, newInstanceId] = $instances.get().keys();expect($instances.get()).toEqual(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id="imgId" ws:tag="img"></ws.element><ws.element ws:id={newInstanceId} ws:tag="div" /><ws.element ws:id="spanId" ws:tag="span"></ws.element>- </$.Body>+ </Body>).instances);});test("reports unresolved explicit element insert target", async () => {const toastError = vi.spyOn(toast, "error").mockImplementation(() => "");- $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);+ $instances.set(renderData(<Body ws:id="bodyId"></Body>).instances);expect(await insertWebstudioElementAt({@@ -407,7 +416,7 @@ describe("insert webstudio element at", () => {"Cannot insert: the target no longer exists.");expect($instances.get()).toEqual(- renderData(<$.Body ws:id="bodyId"></$.Body>).instances+ renderData(<Body ws:id="bodyId"></Body>).instances);toastError.mockRestore();});@@ -427,7 +436,7 @@ describe("insert webstudio fragment at", () => {});test("insert multiple instances", async () => {- $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);+ $instances.set(renderData(<Body ws:id="bodyId"></Body>).instances);await insertWebstudioFragmentAt(renderTemplate(<>@@ -442,10 +451,10 @@ describe("insert webstudio fragment at", () => {);expect($instances.get()).toEqual(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id={expect.any(String)} ws:tag="h1"></ws.element><ws.element ws:id={expect.any(String)} ws:tag="p"></ws.element>- </$.Body>+ </Body>).instances);});@@ -455,7 +464,7 @@ describe("insert webstudio fragment at", () => {createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" }));selectPage("homePageId");- $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);+ $instances.set(renderData(<Body ws:id="bodyId"></Body>).instances);const onContentModelWarnings = vi.fn();const inserted = insertWebstudioFragmentAt(@@ -526,9 +535,9 @@ describe("insert webstudio fragment at", () => {test("insert fragment after insertable", async () => {$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId"></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId"></Box>+ </Body>).instances);await insertWebstudioFragmentAt(@@ -540,16 +549,16 @@ describe("insert webstudio fragment at", () => {);expect($instances.get()).toEqual(renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId"></$.Box>+ <Body ws:id="bodyId">+ <Box ws:id="boxId"></Box><ws.element ws:id={expect.any(String)} ws:tag="h1"></ws.element>- </$.Body>+ </Body>).instances);});test("insert fragment inside of body when configured to place after insertable", async () => {- $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);+ $instances.set(renderData(<Body ws:id="bodyId"></Body>).instances);await insertWebstudioFragmentAt(renderTemplate(<ws.element ws:id="headingId" ws:tag="h1"></ws.element>),{@@ -559,16 +568,16 @@ describe("insert webstudio fragment at", () => {);expect($instances.get()).toEqual(renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:id={expect.any(String)} ws:tag="h1"></ws.element>- </$.Body>+ </Body>).instances);});test("reports unresolved explicit insert target", async () => {const toastError = vi.spyOn(toast, "error").mockImplementation(() => "");- $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);+ $instances.set(renderData(<Body ws:id="bodyId"></Body>).instances);expect(await insertWebstudioFragmentAt(@@ -584,7 +593,7 @@ describe("insert webstudio fragment at", () => {"Cannot insert: the target no longer exists.");expect($instances.get()).toEqual(- renderData(<$.Body ws:id="bodyId"></$.Body>).instances+ renderData(<Body ws:id="bodyId"></Body>).instances);toastError.mockRestore();});@@ -593,19 +602,19 @@ describe("insert webstudio fragment at", () => {$project.set({ id: "current_project" } as Project);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>).instances);@@ -633,15 +642,15 @@ describe("insert webstudio fragment at", () => {$project.set({ id: "current_project" } as Project);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Box ws:id="box"></$.Box>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Box ws:id="box"></Box>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Box ws:id="box"></$.Box>- </$.Slot>- </$.Body>+ <Box ws:id="box"></Box>+ </Slot>+ </Body>).instances);@@ -673,19 +682,19 @@ describe("insert webstudio fragment at", () => {$project.set({ id: "current_project" } as Project);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>).instances);@@ -713,23 +722,23 @@ describe("insert webstudio fragment at", () => {$project.set({ id: "current_project" } as Project);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:id="div" ws:tag="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:id="div" ws:tag="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>).instances);@@ -764,7 +773,7 @@ describe("insert webstudio component at", () => {createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" }));selectPage("homePageId");- $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);+ $instances.set(renderData(<Body ws:id="bodyId"></Body>).instances);$styleSourceSelections.set(new Map());$styleSources.set(new Map());$breakpoints.set(new Map());@@ -824,13 +833,13 @@ describe("find closest insertable", () => {test("puts in the end if closest instance is container", () => {const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Paragraph ws:id="paragraphId">- <$.Bold ws:id="boldId"></$.Bold>- </$.Paragraph>- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <Paragraph ws:id="paragraphId">+ <Bold ws:id="boldId"></Bold>+ </Paragraph>+ </Box>+ </Body>);$instances.set(instances);selectInstance(["boxId", "bodyId"]);@@ -842,9 +851,9 @@ describe("find closest insertable", () => {test("puts in the end of root instance", () => {const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Paragraph ws:id="paragraphId"></$.Paragraph>- </$.Body>+ <Body ws:id="bodyId">+ <Paragraph ws:id="paragraphId"></Paragraph>+ </Body>);$instances.set(instances);selectInstance(["bodyId"]);@@ -855,7 +864,7 @@ describe("find closest insertable", () => {});test("puts in the end of root instance when page root only has text", () => {- const { instances } = renderData(<$.Body ws:id="bodyId">text</$.Body>);+ const { instances } = renderData(<Body ws:id="bodyId">text</Body>);$instances.set(instances);selectInstance(["bodyId"]);expect(findClosestInsertable(newBoxFragment)).toEqual({@@ -866,11 +875,11 @@ describe("find closest insertable", () => {test("finds closest container and puts after its child within selection", () => {const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Paragraph ws:id="paragraphId">- <$.Bold ws:id="boldId"></$.Bold>- </$.Paragraph>- </$.Body>+ <Body ws:id="bodyId">+ <Paragraph ws:id="paragraphId">+ <Bold ws:id="boldId"></Bold>+ </Paragraph>+ </Body>);$instances.set(instances);selectInstance(["boldId", "paragraphId", "bodyId"]);@@ -882,11 +891,11 @@ describe("find closest insertable", () => {test("finds closest container that doesn't have an expression as a child", () => {const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="box1Id"></$.Box>- <$.Paragraph ws:id="paragraphId">{expression`"bla"`}</$.Paragraph>- <$.Box ws:id="box2Id"></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="box1Id"></Box>+ <Paragraph ws:id="paragraphId">{expression`"bla"`}</Paragraph>+ <Box ws:id="box2Id"></Box>+ </Body>);$instances.set(instances);selectInstance(["paragraphId", "bodyId"]);@@ -898,9 +907,9 @@ describe("find closest insertable", () => {test("finds closest container without textual placeholder", () => {const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Paragraph ws:id="paragraphId"></$.Paragraph>- </$.Body>+ <Body ws:id="bodyId">+ <Paragraph ws:id="paragraphId"></Paragraph>+ </Body>);$instances.set(instances);selectInstance(["paragraphId", "bodyId"]);@@ -912,16 +921,16 @@ describe("find closest insertable", () => {test("finds closest container even with when parent has placeholder", () => {const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Paragraph ws:id="paragraphId">- <$.Image ws:id="imageId"></$.Image>- </$.Paragraph>- </$.Body>+ <Body ws:id="bodyId">+ <Paragraph ws:id="paragraphId">+ <Image ws:id="imageId"></Image>+ </Paragraph>+ </Body>);$instances.set(instances);selectInstance(["imageId", "paragraphId", "bodyId"]);expect(- findClosestInsertable(renderTemplate(<$.Box ws:tag="span"></$.Box>))+ findClosestInsertable(renderTemplate(<Box ws:tag="span"></Box>))).toEqual({parentSelector: ["paragraphId", "bodyId"],position: 1,@@ -929,7 +938,7 @@ describe("find closest insertable", () => {});test("forbids inserting into :root", () => {- const { instances } = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const { instances } = renderData(<Body ws:id="bodyId"></Body>);$instances.set(instances);selectInstance([":root"]);expect(findClosestInsertable(newBoxFragment)).toEqual(undefined);@@ -937,11 +946,11 @@ describe("find closest insertable", () => {test("allow inserting into collection item", () => {const { instances } = renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.collection ws:id="collectionId">- <$.Box ws:id="boxId"></$.Box>+ <Box ws:id="boxId"></Box></ws.collection>- </$.Body>+ </Body>);$instances.set(instances);selectInstance(["collectionId[1]", "collectionId", "bodyId"]);@@ -952,11 +961,11 @@ describe("find closest insertable", () => {});test("prevents inserting list item in body when validation fails", () => {- const { instances } = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const { instances } = renderData(<Body ws:id="bodyId"></Body>);$instances.set(instances);selectInstance(["bodyId"]);const newListItemFragment = renderTemplate(- <$.ListItem ws:id="newListItemId"></$.ListItem>+ <ListItem ws:id="newListItemId"></ListItem>);expect(findClosestInsertable(newListItemFragment)).toBeUndefined();});@@ -1066,8 +1075,8 @@ describe("insertWebstudioFragmentAt with conflictResolution", () => {test("uses conflictResolution='theirs' by default (creates new token with suffix)", async () => {// Existing project with a "primary" token (used by existing-box)const data = renderData(- <$.Body ws:id="body">- <$.Box+ <Body ws:id="body">+ <Boxws:id="existing-box"ws:tokens={[token(@@ -1077,8 +1086,8 @@ describe("insertWebstudioFragmentAt with conflictResolution", () => {`),]}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);// Create fragment with token that has same name but different styles@@ -1143,8 +1152,8 @@ describe("insertWebstudioFragmentAt with conflictResolution", () => {test("uses conflictResolution='ours' to keep existing token styles", async () => {// Existing project with a "primary" token (used by existing-box)const data = renderData(- <$.Body ws:id="body">- <$.Box+ <Body ws:id="body">+ <Boxws:id="existing-box"ws:tokens={[token(@@ -1154,8 +1163,8 @@ describe("insertWebstudioFragmentAt with conflictResolution", () => {`),]}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);const fragment = renderTemplate(@@ -1216,8 +1225,8 @@ describe("insertWebstudioFragmentAt with conflictResolution", () => {test("uses conflictResolution='merge' to merge styles (theirs overrides)", async () => {// Existing project with a "primary" token that has color and fontSizeconst data = renderData(- <$.Body ws:id="body">- <$.Box+ <Body ws:id="body">+ <Boxws:id="existing-box"ws:tokens={[token(@@ -1228,8 +1237,8 @@ describe("insertWebstudioFragmentAt with conflictResolution", () => {`),]}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);// Fragment with same "primary" token but different color and new propertydiff --git a/apps/builder/app/shared/instance-utils/insert.ts b/apps/builder/app/shared/instance-utils/insert.tsindex e65cdb4a7c..067440eb8b 100644--- a/apps/builder/app/shared/instance-utils/insert.ts+++ b/apps/builder/app/shared/instance-utils/insert.ts@@ -17,6 +17,7 @@ import {type ConflictResolution,resolveComponentInsertTarget,resolveFragmentInsertTarget,+ type InstanceSelector,type InsertTarget,} from "@webstudio-is/project-build/runtime";import {@@ -28,7 +29,7 @@ import {} from "../nano-states";import { $instances, $project, $props } from "../sync/data-stores";import { getInstanceLabel } from "~/builder/shared/instance-label";-import { executeRuntimeMutation } from "./data";+import { executeRuntimeMutation, executeRuntimeMutationSequence } from "./data";const getRootInstanceId = () => $selectedPage.get()?.rootInstanceId;@@ -167,6 +168,7 @@ export const insertWebstudioFragmentAt = (conflictResolution?: ConflictResolution,options?: {contentMode?: boolean;+ replaceInstanceSelector?: InstanceSelector;onBreakpointLimitMerge?: () => void;allowContentModelWarnings?: boolean;onContentModelWarnings?: (warnings: FragmentContentModelWarning[]) => void;@@ -200,7 +202,7 @@ export const insertWebstudioFragmentAt = (if ($project.get() === undefined || target === undefined) {return false;}- const result = executeRuntimeMutation({+ const insertOperation = {id: "instances.insertFragment",input: {parentInstanceId: target.parentInstanceId,@@ -212,12 +214,22 @@ export const insertWebstudioFragmentAt = (context: {allowLegacyContentModelWarnings: options?.allowContentModelWarnings,},- });- const newInstanceId = result?.result.rootInstanceIds[0];- if (result !== undefined && newInstanceId !== undefined) {+ } as const;+ const insertionResult =+ options?.replaceInstanceSelector === undefined+ ? executeRuntimeMutation(insertOperation)?.result+ : executeRuntimeMutationSequence([+ insertOperation,+ {+ id: "instances.deleteBySelector",+ input: { instanceSelector: options.replaceInstanceSelector },+ },+ ] as const)?.[0];+ const newInstanceId = insertionResult?.rootInstanceIds[0];+ if (insertionResult !== undefined && newInstanceId !== undefined) {const resultParentInstanceId =- "parentInstanceId" in result.result- ? result.result.parentInstanceId+ "parentInstanceId" in insertionResult+ ? insertionResult.parentInstanceId: undefined;const nextParentSelector =resultParentInstanceId === undefined ||@@ -226,10 +238,13 @@ export const insertWebstudioFragmentAt = (: [resultParentInstanceId, ...target.parentSelector];selectInstance([newInstanceId, ...nextParentSelector]);}- if (result?.result.didMergeBreakpointsDueToLimit === true) {+ if (insertionResult?.didMergeBreakpointsDueToLimit === true) {options?.onBreakpointLimitMerge?.();}- if (result !== undefined && options?.allowContentModelWarnings === true) {+ if (+ insertionResult !== undefined &&+ options?.allowContentModelWarnings === true+ ) {const warnings = getFragmentContentModelWarnings({fragment,metas: $registeredComponentMetas.get(),@@ -238,7 +253,7 @@ export const insertWebstudioFragmentAt = (options.onContentModelWarnings?.(warnings);}}- return result !== undefined;+ return insertionResult !== undefined;};export const getComponentTemplateData = (diff --git a/apps/builder/app/shared/instance-utils/lookup.test.tsx b/apps/builder/app/shared/instance-utils/lookup.test.tsxindex 5aa66166d1..4bc8816506 100644--- a/apps/builder/app/shared/instance-utils/lookup.test.tsx+++ b/apps/builder/app/shared/instance-utils/lookup.test.tsx@@ -1,8 +1,17 @@import { describe, expect, test } from "vitest";import { createDefaultPages } from "@webstudio-is/project-build";-import { $, renderData } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+} from "@webstudio-is/template";import { buildInstancePath } from "./lookup";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Heading = createTemplateComponentFixture("Heading");+const Link = createTemplateComponentFixture("Link");+const Text = createTemplateComponentFixture("Text");+describe("buildInstancePath", () => {const createPages = () =>createDefaultPages({@@ -21,9 +30,9 @@ describe("buildInstancePath", () => {test("returns empty array for root instance (no ancestors)", () => {const { instances } = renderData(- <$.Body ws:id="rootId">- <$.Box ws:id="boxId"></$.Box>- </$.Body>+ <Body ws:id="rootId">+ <Box ws:id="boxId"></Box>+ </Body>);const pages = createPages();@@ -33,9 +42,9 @@ describe("buildInstancePath", () => {test("builds path for single-level nesting", () => {const { instances } = renderData(- <$.Body ws:id="rootId">- <$.Box ws:id="boxId"></$.Box>- </$.Body>+ <Body ws:id="rootId">+ <Box ws:id="boxId"></Box>+ </Body>);const pages = createPages();@@ -45,11 +54,11 @@ describe("buildInstancePath", () => {test("builds path for multi-level nesting", () => {const { instances } = renderData(- <$.Body ws:id="rootId">- <$.Box ws:id="containerId">- <$.Heading ws:id="headingId"></$.Heading>- </$.Box>- </$.Body>+ <Body ws:id="rootId">+ <Box ws:id="containerId">+ <Heading ws:id="headingId"></Heading>+ </Box>+ </Body>);const pages = createPages();@@ -59,15 +68,15 @@ describe("buildInstancePath", () => {test("builds path for deeply nested instance", () => {const { instances } = renderData(- <$.Body ws:id="rootId">- <$.Box ws:id="sectionId">- <$.Box ws:id="articleId">- <$.Box ws:id="divId">- <$.Text ws:id="textId"></$.Text>- </$.Box>- </$.Box>- </$.Box>- </$.Body>+ <Body ws:id="rootId">+ <Box ws:id="sectionId">+ <Box ws:id="articleId">+ <Box ws:id="divId">+ <Text ws:id="textId"></Text>+ </Box>+ </Box>+ </Box>+ </Body>);const pages = createPages();@@ -77,11 +86,11 @@ describe("buildInstancePath", () => {test("handles instances with custom labels", () => {const { instances } = renderData(- <$.Body ws:id="rootId" ws:label="Main Body">- <$.Box ws:id="navId" ws:label="Navigation">- <$.Link ws:id="linkId" ws:label="Home Link"></$.Link>- </$.Box>- </$.Body>+ <Body ws:id="rootId" ws:label="Main Body">+ <Box ws:id="navId" ws:label="Navigation">+ <Link ws:id="linkId" ws:label="Home Link"></Link>+ </Box>+ </Body>);const pages = createPages();diff --git a/apps/builder/app/shared/instance-utils/mutation.test.tsx b/apps/builder/app/shared/instance-utils/mutation.test.tsxindex 350861e442..ed55680b68 100644--- a/apps/builder/app/shared/instance-utils/mutation.test.tsx+++ b/apps/builder/app/shared/instance-utils/mutation.test.tsx@@ -16,7 +16,12 @@ import {canConvertInstance,reparentInstanceMutable,} from "@webstudio-is/project-build/runtime";-import { $, ws, expression, renderData } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ ws,+ expression,+ renderData,+} from "@webstudio-is/template";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";import * as radixMetas from "@webstudio-is/sdk-components-react-radix/metas";import type {@@ -57,6 +62,19 @@ import type {InstanceSelector,} from "@webstudio-is/project-build/runtime";+const Body = createTemplateComponentFixture("Body");+const Bold = createTemplateComponentFixture("Bold");+const Box = createTemplateComponentFixture("Box");+const Button = createTemplateComponentFixture("Button");+const Fragment = createTemplateComponentFixture("Fragment");+const Heading = createTemplateComponentFixture("Heading");+const Paragraph = createTemplateComponentFixture("Paragraph");+const Slot = createTemplateComponentFixture("Slot");+const Text = createTemplateComponentFixture("Text");+const Tooltip = createTemplateComponentFixture("Tooltip");+const TooltipContent = createTemplateComponentFixture("TooltipContent");+const TooltipTrigger = createTemplateComponentFixture("TooltipTrigger");+enableMapSet();registerContainers();@@ -127,12 +145,12 @@ describe("reparent instance", () => {test("between instances", () => {const data = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box">- <$.Text ws:id="text"></$.Text>- </$.Box>- <$.Button ws:id="button"></$.Button>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box">+ <Text ws:id="text"></Text>+ </Box>+ <Button ws:id="button"></Button>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));reparentTestInstanceMutable(data, ["text", "box", "body"], {@@ -142,22 +160,22 @@ describe("reparent instance", () => {const newTextId = data.instances.get("body")?.children[1].value as string;expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- <$.Text ws:id={newTextId}></$.Text>- <$.Button ws:id="button"></$.Button>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ <Text ws:id={newTextId}></Text>+ <Button ws:id="button"></Button>+ </Body>).instances);});test("to the end", () => {const data = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box">- <$.Text ws:id="text"></$.Text>- </$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box">+ <Text ws:id="text"></Text>+ </Box>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));reparentTestInstanceMutable(data, ["text", "box", "body"], {@@ -167,20 +185,20 @@ describe("reparent instance", () => {const newTextId = data.instances.get("body")?.children[1].value as string;expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- <$.Text ws:id={newTextId}></$.Text>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ <Text ws:id={newTextId}></Text>+ </Body>).instances);});test("reparentInstance wrapper updates stores and selection", () => {const data = renderData(- <$.Body ws:id="body">- <$.Box ws:id="source"></$.Box>- <$.Box ws:id="target"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="source"></Box>+ <Box ws:id="target"></Box>+ </Body>);$project.set({ id: "projectId" } as Project);$pages.set(createDefaultPages({ rootInstanceId: "body" }));@@ -207,11 +225,11 @@ describe("reparent instance", () => {test("before itself", () => {const data = renderData(- <$.Body ws:id="body">- <$.Text ws:id="text"></$.Text>- <$.Box ws:id="box"></$.Box>- <$.Button ws:id="button"></$.Button>- </$.Body>+ <Body ws:id="body">+ <Text ws:id="text"></Text>+ <Box ws:id="box"></Box>+ <Button ws:id="button"></Button>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));reparentTestInstanceMutable(data, ["box", "body"], {@@ -220,22 +238,22 @@ describe("reparent instance", () => {});expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">- <$.Text ws:id="text"></$.Text>- <$.Box ws:id="box"></$.Box>- <$.Button ws:id="button"></$.Button>- </$.Body>+ <Body ws:id="body">+ <Text ws:id="text"></Text>+ <Box ws:id="box"></Box>+ <Button ws:id="button"></Button>+ </Body>).instances);});test("after itself", () => {const data = renderData(- <$.Body ws:id="body">- <$.Text ws:id="text"></$.Text>- <$.Box ws:id="box"></$.Box>- <$.Button ws:id="button"></$.Button>- </$.Body>+ <Body ws:id="body">+ <Text ws:id="text"></Text>+ <Box ws:id="box"></Box>+ <Button ws:id="button"></Button>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));reparentTestInstanceMutable(data, ["box", "body"], {@@ -244,21 +262,21 @@ describe("reparent instance", () => {});expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">- <$.Text ws:id="text"></$.Text>- <$.Box ws:id="box"></$.Box>- <$.Button ws:id="button"></$.Button>- </$.Body>+ <Body ws:id="body">+ <Text ws:id="text"></Text>+ <Box ws:id="box"></Box>+ <Button ws:id="button"></Button>+ </Body>).instances);});test("wrap with fragment when reparent into empty slot", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot"></$.Slot>- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot"></Slot>+ <Box ws:id="box"></Box>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));reparentTestInstanceMutable(data, ["box", "body"], {@@ -269,25 +287,25 @@ describe("reparent instance", () => {.value as string;expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id={newFragmentId}>- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot">+ <Fragment ws:id={newFragmentId}>+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>).instances);});test("reuse existing fragment when reparent into slot", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id="fragment"></$.Fragment>- </$.Slot>- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot">+ <Fragment ws:id="fragment"></Fragment>+ </Slot>+ <Box ws:id="box"></Box>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));reparentTestInstanceMutable(data, ["box", "body"], {@@ -296,25 +314,25 @@ describe("reparent instance", () => {});expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>).instances);});test("reparent into legacy slot with direct children wraps content in fragment", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot">+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Box ws:id="box"></Box>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -327,30 +345,30 @@ describe("reparent instance", () => {expect(fragmentId).toEqual(expect.any(String));expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id={fragmentId}>- <$.Heading ws:id="heading"></$.Heading>- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot">+ <Fragment ws:id={fragmentId}>+ <Heading ws:id="heading"></Heading>+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>).instances);});test("reparent into legacy shared slot content normalizes all occurrences", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Box ws:id="box"></Box>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -377,11 +395,11 @@ describe("reparent instance", () => {test("reparent into empty legacy shared slot content normalizes all occurrences", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1"></$.Slot>- <$.Slot ws:id="slot2"></$.Slot>- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot1"></Slot>+ <Slot ws:id="slot2"></Slot>+ <Box ws:id="box"></Box>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -401,11 +419,11 @@ describe("reparent instance", () => {test("reparent into legacy shared slot content preserves text and expression children", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1"></$.Slot>- <$.Slot ws:id="slot2"></$.Slot>- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot1"></Slot>+ <Slot ws:id="slot2"></Slot>+ <Box ws:id="box"></Box>+ </Body>);data.instances.set("slot1",@@ -450,16 +468,16 @@ describe("reparent instance", () => {test("reparent into legacy slot does not normalize unrelated overlapping slot", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Slot ws:id="slot2">- <$.Box ws:id="box"></$.Box>- </$.Slot>- <$.Text ws:id="text"></$.Text>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Slot ws:id="slot2">+ <Box ws:id="box"></Box>+ </Slot>+ <Text ws:id="text"></Text>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -484,19 +502,19 @@ describe("reparent instance", () => {test("sort legacy shared slot content through visible slot drop target", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Box ws:id="box1"></Box>+ <Box ws:id="box2"></Box>+ <Box ws:id="box3"></Box>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Slot>- </$.Body>+ <Box ws:id="box1"></Box>+ <Box ws:id="box2"></Box>+ <Box ws:id="box3"></Box>+ </Slot>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -524,17 +542,17 @@ describe("reparent instance", () => {test("reparent legacy shared slot child outside removes it from all slot occurrences", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- </$.Body>+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -557,24 +575,24 @@ describe("reparent instance", () => {test("reparent legacy shared slot child into another slot updates both shared slots", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="sourceSlot1">- <$.Box ws:id="box"></$.Box>- <$.Text ws:id="text"></$.Text>- </$.Slot>- <$.Slot ws:id="sourceSlot2">+ <Body ws:id="body">+ <Slot ws:id="sourceSlot1">+ <Box ws:id="box"></Box>+ <Text ws:id="text"></Text>+ </Slot>+ <Slot ws:id="sourceSlot2">{/* same ids */}- <$.Box ws:id="box"></$.Box>- <$.Text ws:id="text"></$.Text>- </$.Slot>- <$.Slot ws:id="targetSlot1">- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Slot ws:id="targetSlot2">+ <Box ws:id="box"></Box>+ <Text ws:id="text"></Text>+ </Slot>+ <Slot ws:id="targetSlot1">+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Slot ws:id="targetSlot2">{/* same ids */}- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- </$.Body>+ <Heading ws:id="heading"></Heading>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -611,19 +629,19 @@ describe("reparent instance", () => {test("reparent slot child from one instance of this slot into another", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));reparentTestInstanceMutable(data, ["box", "fragment", "slot1", "body"], {@@ -632,42 +650,42 @@ describe("reparent instance", () => {});expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>).instances);});test("sort shared slot content through visible slot drop target", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box1"></Box>+ <Box ws:id="box2"></Box>+ <Box ws:id="box3"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box1"></Box>+ <Box ws:id="box2"></Box>+ <Box ws:id="box3"></Box>+ </Fragment>+ </Slot>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -691,21 +709,21 @@ describe("reparent instance", () => {test("reparent shared slot child into sibling in shared slot content", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -735,23 +753,23 @@ describe("reparent instance", () => {test("reparent nested shared slot child within shared slot content", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Heading ws:id="heading"></$.Heading>+ <Heading ws:id="heading"></Heading></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Heading ws:id="heading"></$.Heading>+ <Heading ws:id="heading"></Heading></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -780,20 +798,20 @@ describe("reparent instance", () => {test("reparent normal child into slot makes it shared slot content", () => {const data = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -821,20 +839,20 @@ describe("reparent instance", () => {test("reparent normal child into nested shared slot container makes it shared", () => {const data = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -864,30 +882,30 @@ describe("reparent instance", () => {test("reparent child from one slot into another updates both shared slot contents", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="sourceSlot1">- <$.Fragment ws:id="sourceFragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="sourceSlot2">+ <Body ws:id="body">+ <Slot ws:id="sourceSlot1">+ <Fragment ws:id="sourceFragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="sourceSlot2">{/* same ids */}- <$.Fragment ws:id="sourceFragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="targetSlot1">- <$.Fragment ws:id="targetFragment">- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="targetSlot2">+ <Fragment ws:id="sourceFragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="targetSlot1">+ <Fragment ws:id="targetFragment">+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="targetSlot2">{/* same ids */}- <$.Fragment ws:id="targetFragment">- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="targetFragment">+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -922,30 +940,30 @@ describe("reparent instance", () => {test("reparent child from one slot into nested container in another slot", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="sourceSlot1">- <$.Fragment ws:id="sourceFragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="sourceSlot2">+ <Body ws:id="body">+ <Slot ws:id="sourceSlot1">+ <Fragment ws:id="sourceFragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="sourceSlot2">{/* same ids */}- <$.Fragment ws:id="sourceFragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="targetSlot1">- <$.Fragment ws:id="targetFragment">+ <Fragment ws:id="sourceFragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="targetSlot1">+ <Fragment ws:id="targetFragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="targetSlot2">+ </Fragment>+ </Slot>+ <Slot ws:id="targetSlot2">{/* same ids */}- <$.Fragment ws:id="targetFragment">+ <Fragment ws:id="targetFragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -981,32 +999,32 @@ describe("reparent instance", () => {test("reparent child from one slot into another preserves source siblings", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="sourceSlot1">- <$.Fragment ws:id="sourceFragment">- <$.Box ws:id="box"></$.Box>- <$.Text ws:id="text"></$.Text>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="sourceSlot2">+ <Body ws:id="body">+ <Slot ws:id="sourceSlot1">+ <Fragment ws:id="sourceFragment">+ <Box ws:id="box"></Box>+ <Text ws:id="text"></Text>+ </Fragment>+ </Slot>+ <Slot ws:id="sourceSlot2">{/* same ids */}- <$.Fragment ws:id="sourceFragment">- <$.Box ws:id="box"></$.Box>- <$.Text ws:id="text"></$.Text>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="targetSlot1">- <$.Fragment ws:id="targetFragment">- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="targetSlot2">+ <Fragment ws:id="sourceFragment">+ <Box ws:id="box"></Box>+ <Text ws:id="text"></Text>+ </Fragment>+ </Slot>+ <Slot ws:id="targetSlot1">+ <Fragment ws:id="targetFragment">+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="targetSlot2">{/* same ids */}- <$.Fragment ws:id="targetFragment">- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="targetFragment">+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -1062,23 +1080,23 @@ describe("reparent instance", () => {> = [() => ({data: renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box1"></Box>+ <Box ws:id="box2"></Box>+ <Box ws:id="box3"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box1"></Box>+ <Box ws:id="box2"></Box>+ <Box ws:id="box3"></Box>+ </Fragment>+ </Slot>+ </Body>),sourceSelector: ["box1", "fragment", "slot1", "body"],dropTarget: {@@ -1099,19 +1117,19 @@ describe("reparent instance", () => {}),() => ({data: renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Box ws:id="box1"></Box>+ <Box ws:id="box2"></Box>+ <Box ws:id="box3"></Box>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Slot>- </$.Body>+ <Box ws:id="box1"></Box>+ <Box ws:id="box2"></Box>+ <Box ws:id="box3"></Box>+ </Slot>+ </Body>),sourceSelector: ["box1", "slot1", "body"],dropTarget: {@@ -1132,20 +1150,20 @@ describe("reparent instance", () => {}),() => ({data: renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>),sourceSelector: ["box", "body"],dropTarget: {@@ -1161,21 +1179,21 @@ describe("reparent instance", () => {}),() => ({data: renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>),sourceSelector: ["box", "fragment", "slot1", "body"],dropTarget: {@@ -1212,20 +1230,20 @@ describe("reparent instance", () => {test("slot operation sequence preserves integrity after normalize, reparent out, and delete", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same visible content in legacy direct-child shape */}- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Box ws:id="outside"></$.Box>- </$.Body>+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Box ws:id="outside"></Box>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -1272,23 +1290,23 @@ describe("reparent instance", () => {test("reparent nested shared slot child outside removes it from all slot occurrences", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -1320,25 +1338,25 @@ describe("reparent instance", () => {test("reparent shared slot child outside preserves moved scoped data and resources", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="card">- <$.Box ws:id="label"></$.Box>+ <Box ws:id="label"></Box></ws.element>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="card">- <$.Box ws:id="label"></$.Box>+ <Box ws:id="label"></Box></ws.element>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>);data.dataSources.set("cardVariable", {id: "cardVariable",@@ -1450,21 +1468,21 @@ describe("reparent instance", () => {test("reparent shared slot child outside removes it from all slots and preserves siblings", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -1489,19 +1507,19 @@ describe("reparent instance", () => {test("reparent direct slot child outside updates all linked slot occurrences", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$project.set({ id: "projectId" } as Project);$registeredComponentMetas.set(createFakeComponentMetas({}));@@ -1522,11 +1540,11 @@ describe("reparent instance", () => {test("prevent slot reparenting into own children to avoid infinite loop", () => {const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id="fragment"></$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot">+ <Fragment ws:id="fragment"></Fragment>+ </Slot>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));reparentTestInstanceMutable(data, ["slot", "body"], {@@ -1535,22 +1553,22 @@ describe("reparent instance", () => {});expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id="fragment"></$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot">+ <Fragment ws:id="fragment"></Fragment>+ </Slot>+ </Body>).instances);});test("from collection item", () => {const data = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.collection ws:id="collection">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.collection>- </$.Body>+ </Body>);$registeredComponentMetas.set(createFakeComponentMetas({}));reparentTestInstanceMutable(@@ -1560,10 +1578,10 @@ describe("reparent instance", () => {);expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.collection ws:id="collection"></ws.collection>- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Box ws:id="box"></Box>+ </Body>).instances);});@@ -1779,12 +1797,12 @@ describe("reparent instance", () => {test("move required child within same instance", () => {const data = renderData(- <$.Body ws:id="body">- <$.Tooltip ws:id="tooltip">- <$.TooltipTrigger ws:id="trigger"></$.TooltipTrigger>- <$.TooltipContent ws:id="content"></$.TooltipContent>- </$.Tooltip>- </$.Body>+ <Body ws:id="body">+ <Tooltip ws:id="tooltip">+ <TooltipTrigger ws:id="trigger"></TooltipTrigger>+ <TooltipContent ws:id="content"></TooltipContent>+ </Tooltip>+ </Body>);$registeredComponentMetas.set(new Map(Object.entries({ ...defaultMetas, ...radixMetas }))@@ -1795,12 +1813,12 @@ describe("reparent instance", () => {});expect(data.instances).toEqual(renderData(- <$.Body ws:id="body">- <$.Tooltip ws:id="tooltip">- <$.TooltipContent ws:id="content"></$.TooltipContent>- <$.TooltipTrigger ws:id={expect.any(String)}></$.TooltipTrigger>- </$.Tooltip>- </$.Body>+ <Body ws:id="body">+ <Tooltip ws:id="tooltip">+ <TooltipContent ws:id="content"></TooltipContent>+ <TooltipTrigger ws:id={expect.any(String)}></TooltipTrigger>+ </Tooltip>+ </Body>).instances);});@@ -1908,19 +1926,19 @@ describe("wrap in", () => {$registeredComponentMetas.set(defaultMetasMap);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>).instances);selectInstance(["div", "fragment", "slot1", "bodyId"]);@@ -1946,17 +1964,17 @@ describe("wrap in", () => {$registeredComponentMetas.set(defaultMetasMap);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1"><ws.element ws:tag="div" ws:id="div"></ws.element>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Slot ws:id="slot2">+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}<ws.element ws:tag="div" ws:id="div"></ws.element>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- </$.Body>+ <Heading ws:id="heading"></Heading>+ </Slot>+ </Body>).instances);selectInstance(["div", "slot1", "bodyId"]);@@ -1988,21 +2006,21 @@ describe("wrap in", () => {$registeredComponentMetas.set(defaultMetasMap);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>).instances);selectInstance(["div", "fragment", "slot1", "bodyId"]);@@ -2040,21 +2058,21 @@ describe("wrap in", () => {$registeredComponentMetas.set(defaultMetasMap);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>).instances);selectInstance([selectedId, "fragment", "slot1", "bodyId"]);@@ -2090,23 +2108,23 @@ describe("wrap in", () => {$registeredComponentMetas.set(defaultMetasMap);$instances.set(renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="bodyId">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>).instances);selectInstance(["box", "div", "fragment", "slot1", "bodyId"]);@@ -2180,9 +2198,9 @@ describe("wrap in", () => {describe("toggleInstanceShow", () => {test("creates show prop with false value when it doesn't exist", () => {const { instances } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>);$instances.set(instances);$props.set(new Map());@@ -2205,9 +2223,9 @@ describe("toggleInstanceShow", () => {test("toggles show prop from true to false", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box" ws:show={true}></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box" ws:show={true}></Box>+ </Body>);$instances.set(instances);$props.set(props);@@ -2227,9 +2245,9 @@ describe("toggleInstanceShow", () => {test("toggles show prop from false to true", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box" ws:show={false}></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box" ws:show={false}></Box>+ </Body>);$instances.set(instances);$props.set(props);@@ -2249,9 +2267,9 @@ describe("toggleInstanceShow", () => {test("preserves non-boolean show prop", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box" ws:show={expression`isVisible`}></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box" ws:show={expression`isVisible`}></Box>+ </Body>);$instances.set(instances);$props.set(props);@@ -2266,13 +2284,13 @@ describe("toggleInstanceShow", () => {describe("unwrap instance", () => {test("unwrap command skips hidden slot fragment", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2293,19 +2311,19 @@ describe("unwrap instance", () => {test("unwrap command moves only shared slot child out of all slot occurrences", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2331,21 +2349,21 @@ describe("unwrap instance", () => {test("unwrap command moves direct shared slot child out of all slots and preserves siblings", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2387,17 +2405,17 @@ describe("unwrap instance", () => {test("unwrap command moves direct legacy shared slot child out of all slots and preserves siblings", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- </$.Body>+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2449,23 +2467,23 @@ describe("unwrap instance", () => {"unwrap command moves direct shared slot child in $selectedId position out of all slots",({ selectedId, remainingIds }) => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box1"></Box>+ <Box ws:id="box2"></Box>+ <Box ws:id="box3"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box1"></Box>+ <Box ws:id="box2"></Box>+ <Box ws:id="box3"></Box>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2497,23 +2515,23 @@ describe("unwrap instance", () => {test("unwrap command keeps nested shared slot child in shared slot content", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2544,25 +2562,25 @@ describe("unwrap instance", () => {test("unwrap command keeps nested shared slot child with siblings in shared slot content", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2603,13 +2621,13 @@ describe("canUnwrapInstance", () => {test("returns true for unwrappable instance", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="wrapper">- <$.Box ws:id="child"></$.Box>- </$.Box>- </$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="parent">+ <Box ws:id="wrapper">+ <Box ws:id="child"></Box>+ </Box>+ </Box>+ </Body>);$instances.set(instances);@@ -2638,9 +2656,9 @@ describe("canUnwrapInstance", () => {test("returns false if parent is root instance", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>);$instances.set(instances);@@ -2666,11 +2684,11 @@ describe("canUnwrapInstance", () => {test("returns false for textual instance", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Paragraph ws:id="paragraph">- <$.Bold ws:id="bold">text</$.Bold>- </$.Paragraph>- </$.Body>+ <Body ws:id="body">+ <Paragraph ws:id="paragraph">+ <Bold ws:id="bold">text</Bold>+ </Paragraph>+ </Body>);$instances.set(instances);@@ -2696,13 +2714,13 @@ describe("canUnwrapInstance", () => {test("returns true for Body > div > a scenario", () => {const { instances, props } = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.element ws:tag="div" ws:id="div"><ws.element ws:tag="a" ws:id="link">Link text</ws.element></ws.element>- </$.Body>+ </Body>);$instances.set(instances);@@ -2736,7 +2754,7 @@ describe("canConvertInstance", () => {test("returns true for valid conversion", () => {const { instances, props } = renderData(<ws.element ws:tag="body" ws:id="body">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>);@@ -2774,7 +2792,7 @@ describe("canConvertInstance", () => {test("returns true when converting Box to Heading", () => {const { instances, props } = renderData(<ws.element ws:tag="body" ws:id="body">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>);@@ -2793,7 +2811,7 @@ describe("canConvertInstance", () => {test("uses preset tag when available", () => {const { instances, props } = renderData(<ws.element ws:tag="body" ws:id="body">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>);@@ -2817,19 +2835,19 @@ describe("convertInstance", () => {test("detach shared slot children when converting slot", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2853,21 +2871,21 @@ describe("convertInstance", () => {test("detach shared slot children with siblings when converting slot", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2896,17 +2914,17 @@ describe("convertInstance", () => {test("detach legacy shared slot children when converting slot", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- </$.Body>+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2937,19 +2955,19 @@ describe("convertInstance", () => {test("converts shared slot child in shared slot content", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -2972,17 +2990,17 @@ describe("convertInstance", () => {test("converts legacy shared slot child in shared slot content", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- </$.Body>+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -3010,23 +3028,23 @@ describe("convertInstance", () => {test("converts nested shared slot child in shared slot content", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>+ <Box ws:id="box"></Box></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -3052,25 +3070,25 @@ describe("convertInstance", () => {test("converts nested shared slot child and preserves siblings", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">+ <Fragment ws:id="fragment"><ws.element ws:tag="div" ws:id="div">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -3097,21 +3115,21 @@ describe("convertInstance", () => {test("command sequence preserves shared slot content through wrap, convert, and unwrap", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);$props.set(props);@@ -3168,7 +3186,7 @@ describe("convertInstance", () => {test("converts legacy tag to element", () => {const { instances, props } = renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.Box tag="article" ws:id="articleId"></$.Box>+ <Box tag="article" ws:id="articleId"></Box></ws.element>);$instances.set(instances);@@ -3189,12 +3207,12 @@ describe("convertInstance", () => {test("migrates legacy properties", () => {const { instances, props } = renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.Box+ <Boxws:tag="div"ws:id="divId"className="my-class"htmlFor="my-id"- ></$.Box>+ ></Box></ws.element>);$instances.set(instances);@@ -3221,7 +3239,7 @@ describe("convertInstance", () => {$instances.set(renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:tag="article" ws:id="articleId"></$.Box>+ <Box ws:tag="article" ws:id="articleId"></Box></ws.element>).instances);@@ -3240,7 +3258,7 @@ describe("convertInstance", () => {$instances.set(renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.Heading ws:id="headingId"></$.Heading>+ <Heading ws:id="headingId"></Heading></ws.element>).instances);@@ -3259,7 +3277,7 @@ describe("convertInstance", () => {$instances.set(renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:id="divId"></$.Box>+ <Box ws:id="divId"></Box></ws.element>).instances);@@ -3278,7 +3296,7 @@ describe("convertInstance", () => {$instances.set(renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:id="divId"></$.Box>+ <Box ws:id="divId"></Box></ws.element>).instances);@@ -3297,7 +3315,7 @@ describe("convertInstance", () => {$instances.set(renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:id="boxId"></$.Box>+ <Box ws:id="boxId"></Box></ws.element>).instances);@@ -3331,7 +3349,7 @@ describe("convertInstance", () => {const initialInstances = renderData(<ws.element ws:tag="html" ws:id="rootId"><ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:id="boxId"></$.Box>+ <Box ws:id="boxId"></Box></ws.element></ws.element>).instances;@@ -3346,13 +3364,13 @@ describe("convertInstance", () => {describe("deleteSelectedInstance", () => {test("delete selected instance and select next one", () => {const { instances } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child1"></$.Box>- <$.Box ws:id="child2"></$.Box>- <$.Box ws:id="child3"></$.Box>- </$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="parent">+ <Box ws:id="child1"></Box>+ <Box ws:id="child2"></Box>+ <Box ws:id="child3"></Box>+ </Box>+ </Body>);$instances.set(instances);const pages = createDefaultPages({ rootInstanceId: "body" });@@ -3369,13 +3387,13 @@ describe("deleteSelectedInstance", () => {test("delete selected instance and select previous one", () => {const { instances } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child1"></$.Box>- <$.Box ws:id="child2"></$.Box>- <$.Box ws:id="child3"></$.Box>- </$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="parent">+ <Box ws:id="child1"></Box>+ <Box ws:id="child2"></Box>+ <Box ws:id="child3"></Box>+ </Box>+ </Body>);$instances.set(instances);const pages = createDefaultPages({ rootInstanceId: "body" });@@ -3392,11 +3410,11 @@ describe("deleteSelectedInstance", () => {test("delete selected instance and select parent one", () => {const { instances } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child1"></$.Box>- </$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="parent">+ <Box ws:id="child1"></Box>+ </Box>+ </Body>);$instances.set(instances);const pages = createDefaultPages({ rootInstanceId: "body" });@@ -3409,17 +3427,17 @@ describe("deleteSelectedInstance", () => {test("delete selected legacy shared slot child and select next normalized sibling", () => {const { instances } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Box ws:id="box"></$.Box>- <$.Heading ws:id="heading"></$.Heading>- </$.Slot>- </$.Body>+ <Box ws:id="box"></Box>+ <Heading ws:id="heading"></Heading>+ </Slot>+ </Body>);$instances.set(instances);const pages = createDefaultPages({ rootInstanceId: "body" });@@ -3446,19 +3464,19 @@ describe("deleteSelectedInstance", () => {test("delete last selected shared slot child and select visible slot occurrence", () => {const { instances } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>);$instances.set(instances);const pages = createDefaultPages({ rootInstanceId: "body" });@@ -3475,15 +3493,15 @@ describe("deleteSelectedInstance", () => {test("delete last selected legacy shared slot child and select visible slot occurrence", () => {const { instances } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Box ws:id="box"></$.Box>- </$.Slot>- <$.Slot ws:id="slot2">+ <Body ws:id="body">+ <Slot ws:id="slot1">+ <Box ws:id="box"></Box>+ </Slot>+ <Slot ws:id="slot2">{/* same ids */}- <$.Box ws:id="box"></$.Box>- </$.Slot>- </$.Body>+ <Box ws:id="box"></Box>+ </Slot>+ </Body>);$instances.set(instances);const pages = createDefaultPages({ rootInstanceId: "body" });diff --git a/apps/builder/app/shared/nano-states/components.test.tsx b/apps/builder/app/shared/nano-states/components.test.tsxnew file mode 100644index 0000000000..f032bcc351--- /dev/null+++ b/apps/builder/app/shared/nano-states/components.test.tsx@@ -0,0 +1,35 @@+/** Verifies that Builder template registration resolves imported component objects. */+import { afterEach, expect, test } from "vitest";+import { CodeText } from "@webstudio-is/sdk-components-react/components";+import { componentIds } from "@webstudio-is/sdk-components-registry/components";+import {+ $registeredComponentHooks,+ $registeredComponentMetas,+ $registeredComponents,+ $registeredTemplates,+ registerComponentLibrary,+} from "./components";++afterEach(() => {+ $registeredComponents.set(new Map());+ $registeredComponentMetas.set(new Map());+ $registeredTemplates.set(new Map());+ $registeredComponentHooks.set([]);+});++test("renders templates that import an alternate registered implementation", () => {+ registerComponentLibrary({+ components: {},+ componentIds,+ metas: {},+ templates: {+ code_text: {+ category: "typography",+ template: <CodeText>const status = "ready";</CodeText>,+ },+ },+ });++ const template = $registeredTemplates.get().get("code_text")?.template;+ expect(template?.instances[0]?.component).toBe("CodeText");+});diff --git a/apps/builder/app/shared/nano-states/components.ts b/apps/builder/app/shared/nano-states/components.tsindex f435f04ad5..c920798dec 100644--- a/apps/builder/app/shared/nano-states/components.ts+++ b/apps/builder/app/shared/nano-states/components.ts@@ -178,6 +178,7 @@ export const registerComponentLibrary = ({metas,hooks,templates,+ componentIds = new Map(),}: {namespace?: string;// simplify adding component libraries@@ -186,6 +187,7 @@ export const registerComponentLibrary = ({metas: Record<Instance["component"], WsComponentMeta>;hooks?: Hook[];templates: Record<Instance["component"], TemplateMeta>;+ componentIds?: ReadonlyMap<object, Instance["component"]>;}) => {const prefix = namespace === undefined ? "" : `${namespace}:`;@@ -203,13 +205,21 @@ export const registerComponentLibrary = ({}$registeredComponentMetas.set(nextMetas);+ const resolvedComponentIds = new Map(componentIds);+ for (const [componentId, component] of nextComponents) {+ resolvedComponentIds.set(component, componentId);+ }+const prevTemplates = $registeredTemplates.get();const nextTemplates = new Map(prevTemplates);for (const [componentName, meta] of Object.entries(templates)) {const { template, ...generatedMeta } = meta;nextTemplates.set(`${prefix}${componentName}`, {...generatedMeta,- template: renderTemplate(template),+ template: renderTemplate(template, undefined, [], {+ componentIds: resolvedComponentIds,+ componentMetas: nextMetas,+ }),});}$registeredTemplates.set(nextTemplates);diff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.tsindex b042015220..83947ec031 100644--- a/apps/builder/app/shared/nano-states/instances.ts+++ b/apps/builder/app/shared/nano-states/instances.ts@@ -51,6 +51,7 @@ export const $textEditingInstanceSelector = atom<export const $textEditorContextMenu = atom<| {cursorRect: DOMRect;+ replaceAnchor: boolean;}| undefined>(undefined);@@ -63,6 +64,7 @@ type ContextMenuCommand =| { type: "selectNext" }| { type: "selectPrevious" }| { type: "enter" }+ | { type: "close" }| { type: "templateInsertionStarted" }| { type: "templateInsertionCancelled" };diff --git a/apps/builder/app/shared/nano-states/misc.test.ts b/apps/builder/app/shared/nano-states/misc.test.tsindex 11f875448d..b1e3d3144e 100644--- a/apps/builder/app/shared/nano-states/misc.test.ts+++ b/apps/builder/app/shared/nano-states/misc.test.ts@@ -3,12 +3,57 @@ import {$authPermit,$builderMode,$canOpenPageTemplates,+ $propsIndex,type BuilderMode,} from "./misc";+import { $props } from "../sync/data-stores";afterEach(() => {$builderMode.set("design");$authPermit.set("view");+ $props.set(new Map());+});++test("keeps the public tag index limited to static string values", () => {+ $props.set(+ new Map([+ [+ "dynamic-tag",+ {+ id: "dynamic-tag",+ instanceId: "box",+ name: "tag",+ type: "expression" as const,+ value: '"article"',+ mode: "read" as const,+ },+ ],+ [+ "first-static-tag",+ {+ id: "first-static-tag",+ instanceId: "duplicate-box",+ name: "tag",+ type: "string" as const,+ value: "article",+ },+ ],+ [+ "second-static-tag",+ {+ id: "second-static-tag",+ instanceId: "duplicate-box",+ name: "tag",+ type: "string" as const,+ value: "aside",+ },+ ],+ ])+ );++ expect($propsIndex.get().htmlTagsByInstanceId).toEqual(+ new Map([["duplicate-box", "aside"]])+ );});describe("$canOpenPageTemplates", () => {diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.tsindex e37bdf6795..a413e7542e 100644--- a/apps/builder/app/shared/nano-states/misc.ts+++ b/apps/builder/app/shared/nano-states/misc.ts@@ -15,6 +15,7 @@ import type { User } from "~/shared/db/user.server";import { toast, type Placement } from "@webstudio-is/design-system";import {createId,+ getHtmlTagsFromProps,type AssetType,type Instance,type Prop,@@ -47,7 +48,6 @@ export const $memoryProps = atom<Map<string, Props>>(new Map());export const $propsIndex = computed($props, (props) => {const propsByInstanceId = new Map<Instance["id"], Prop[]>();- const htmlTagsByInstanceId = new Map<Instance["id"], string>();for (const prop of props.values()) {const { instanceId } = prop;let instanceProps = propsByInstanceId.get(instanceId);@@ -56,13 +56,10 @@ export const $propsIndex = computed($props, (props) => {propsByInstanceId.set(instanceId, instanceProps);}instanceProps.push(prop);- if (prop.type === "string" && prop.name === "tag") {- htmlTagsByInstanceId.set(instanceId, prop.value);- }}return {propsByInstanceId,- htmlTagsByInstanceId,+ htmlTagsByInstanceId: getHtmlTagsFromProps(props),};});diff --git a/apps/builder/app/shared/nano-states/props.test.tsx b/apps/builder/app/shared/nano-states/props.test.tsxindex dc25a78b6e..40b3618211 100644--- a/apps/builder/app/shared/nano-states/props.test.tsx+++ b/apps/builder/app/shared/nano-states/props.test.tsx@@ -30,7 +30,7 @@ import { $dataSourceVariables } from "./variables";import { $selectedPageId } from "./pages";import { getInstanceKey } from "../nano-states";import {- $,+ createTemplateComponentFixture,expression,Parameter,renderData,@@ -43,6 +43,12 @@ import { registerContainers } from "../sync/sync-stores";import { $resourcesCache, getResourceKey } from "../resources";import { $externalContentRoots } from "../external-content-mutations";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Fragment = createTemplateComponentFixture("Fragment");+const Slot = createTemplateComponentFixture("Slot");+const Text = createTemplateComponentFixture("Text");+const { $computedResourceRequests } = __testing__;const initialSystem = {@@ -152,20 +158,20 @@ test("does not reuse frontmatter from a previous Collection occurrence", () => {const collectionItem = new Parameter("Collection Item");const document = new Parameter(contentBlockDocumentProp);const data = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.collectionws:id="collection"data={expression`${collectionData}`}item={collectionItem}><ws.block ws:id="block" document={document}>- <$.Box+ <Boxws:id="title"ariaLabel={expression`${document}.frontmatter.title`}/></ws.block></ws.collection>- </$.Body>+ </Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -601,15 +607,15 @@ test("compute expression from object collection items", () => {});const collectionItem = new Parameter("Collection Item");const data = renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.collectionws:id="collectionId"data={expression`${dataVariable}`}item={collectionItem}>- <$.Box ws:id="boxId" ariaLabel={expression`${collectionItem}`}></$.Box>+ <Box ws:id="boxId" ariaLabel={expression`${collectionItem}`}></Box></ws.collection>- </$.Body>+ </Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -921,10 +927,10 @@ test("compute instance text content bound to expression", () => {test("use page system values in props", () => {const systemParameter = new Parameter("system");const data = renderData(- <$.Body+ <Bodyws:id="bodyId"data-origin={expression`${systemParameter}.origin`}- ></$.Body>+ ></Body>);expect(data.dataSources.size).toEqual(1);const [systemParameterId] = data.dataSources.keys();@@ -948,9 +954,9 @@ test("compute props with global variables", () => {const rootVariable = new Variable("rootVariable", "root value");const data = renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${rootVariable}`}>- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId" data-value={expression`${rootVariable}`}></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId" data-value={expression`${rootVariable}`}></Box>+ </Body></ws.root>);data.instances.delete(ROOT_INSTANCE_ID);@@ -971,7 +977,7 @@ test("compute props with global variables", () => {test("use global system values in props", () => {const data = renderData(- <$.Body ws:id="bodyId" data-origin={expression`$ws$system.origin`}></$.Body>+ <Body ws:id="bodyId" data-origin={expression`$ws$system.origin`}></Body>);expect(data.dataSources.size).toEqual(0);$instances.set(data.instances);@@ -993,7 +999,7 @@ test("use global system values in props", () => {test("compute variable values for page root", () => {const bodyVariable = new Variable("bodyVariable", "initial");const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}></$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}></Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1018,10 +1024,10 @@ test("nest variable values from global root to current instance", () => {const boxVariable = new Variable("boxVariable", "");const textVariable = new Variable("textVariable", "");const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" ars={expression`${boxVariable}`}></$.Box>- <$.Text ws:id="textId" ars={expression`${textVariable}`}></$.Text>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" ars={expression`${boxVariable}`}></Box>+ <Text ws:id="textId" ars={expression`${textVariable}`}></Text>+ </Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1077,15 +1083,15 @@ test("compute item values for collection", () => {]);const collectionItem = new Parameter("Collection Item");const data = renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.collectionws:id="collectionId"data={expression`${dataVariable}`}item={collectionItem}>- <$.Box ws:id="boxId"></$.Box>+ <Box ws:id="boxId"></Box></ws.collection>- </$.Body>+ </Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1143,15 +1149,15 @@ test("compute item values for collection with object data", () => {});const collectionItem = new Parameter("Collection Item");const data = renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.collectionws:id="collectionId"data={expression`${dataVariable}`}item={collectionItem}>- <$.Box ws:id="boxId"></$.Box>+ <Box ws:id="boxId"></Box></ws.collection>- </$.Body>+ </Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1208,15 +1214,15 @@ test("compute item values for collection with nested object data", () => {});const collectionItem = new Parameter("Collection Item");const data = renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.collectionws:id="collectionId"data={expression`${dataVariable}`}item={collectionItem}>- <$.Box ws:id="boxId"></$.Box>+ <Box ws:id="boxId"></Box></ws.collection>- </$.Body>+ </Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1259,7 +1265,7 @@ test("compute inherited item values inside collection without item parameter", (]);const outerItem = new Parameter("Outer Item");const data = renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.collectionws:id="outerCollectionId"data={expression`${dataVariable}`}@@ -1269,10 +1275,10 @@ test("compute inherited item values inside collection without item parameter", (ws:id="innerCollectionId"data={expression`${outerItem}.items`}>- <$.Box ws:id="boxId"></$.Box>+ <Box ws:id="boxId"></Box></ws.collection></ws.collection>- </$.Body>+ </Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1310,7 +1316,7 @@ test("compute resource variable values", () => {headers: [],});const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${resourceVariable}`}></$.Body>+ <Body ws:id="bodyId" vars={expression`${resourceVariable}`}></Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1339,13 +1345,13 @@ test("stop variables lookup outside of slots", () => {const slotVariable = new Variable("slotVariable", "slot");const boxVariable = new Variable("boxVariable", "box");const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Slot ws:id="slotId" vars={expression`${slotVariable}`}>- <$.Fragment ws:id="fragmentId">- <$.Box ws:id="boxId" vars={expression`${boxVariable}`}></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Slot ws:id="slotId" vars={expression`${slotVariable}`}>+ <Fragment ws:id="fragmentId">+ <Box ws:id="boxId" vars={expression`${boxVariable}`}></Box>+ </Fragment>+ </Slot>+ </Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1383,10 +1389,10 @@ test("compute parameter and resource variables without values to make it availab});const parameterVariable = new Parameter("parameterVariable");const data = renderData(- <$.Body+ <Bodyws:id="bodyId"vars={expression`${resourceVariable} + ${parameterVariable}`}- ></$.Body>+ ></Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1403,7 +1409,7 @@ test("compute parameter and resource variables without values to make it availabtest("provide page system variable value", () => {const system = new Parameter("system");const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${system}`}></$.Body>+ <Body ws:id="bodyId" vars={expression`${system}`}></Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1434,7 +1440,7 @@ test("provide page system variable value", () => {test("provide global system variable value", () => {const data = renderData(- <$.Body ws:id="bodyId" vars={expression`$ws$system`}></$.Body>+ <Body ws:id="bodyId" vars={expression`$ws$system`}></Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1480,9 +1486,9 @@ test("mask variables with the same name in nested scope", () => {const bodyVariable = new Variable("myVariable", "body");const boxVariable = new Variable("myVariable", "box");const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" vars={expression`${boxVariable}`}></$.Box>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" vars={expression`${boxVariable}`}></Box>+ </Body>);$instances.set(data.instances);$dataSources.set(data.dataSources);@@ -1519,9 +1525,9 @@ test("inherit variables from global root", () => {const boxVariable = new Variable("myVariable", "box");const data = renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${rootVariable}`}>- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId" vars={expression`${boxVariable}`}></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId" vars={expression`${boxVariable}`}></Box>+ </Body></ws.root>);data.instances.delete(ROOT_INSTANCE_ID);@@ -1564,13 +1570,13 @@ test("inherit variables from global root inside slots", () => {const boxVariable = new Variable("myVariable", "box");const data = renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${rootVariable}`}>- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Slot ws:id="slotId">- <$.Fragment ws:id="fragmentId">- <$.Box ws:id="boxId" vars={expression`${boxVariable}`}></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Slot ws:id="slotId">+ <Fragment ws:id="fragmentId">+ <Box ws:id="boxId" vars={expression`${boxVariable}`}></Box>+ </Fragment>+ </Slot>+ </Body></ws.root>);data.instances.delete(ROOT_INSTANCE_ID);diff --git a/apps/builder/app/shared/pages/use-switch-page.test.tsx b/apps/builder/app/shared/pages/use-switch-page.test.tsxindex 17559625b9..c5c2634bfe 100644--- a/apps/builder/app/shared/pages/use-switch-page.test.tsx+++ b/apps/builder/app/shared/pages/use-switch-page.test.tsx@@ -1,8 +1,17 @@import { expect, test } from "vitest";import { createDefaultPages } from "@webstudio-is/project-build";-import { $, renderData } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+} from "@webstudio-is/template";import { __testing__ } from "./use-switch-page";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Fragment = createTemplateComponentFixture("Fragment");+const Heading = createTemplateComponentFixture("Heading");+const Slot = createTemplateComponentFixture("Slot");+const { getDeepLinkedInstanceSelection, shouldNavigateToPageState } =__testing__;@@ -43,11 +52,11 @@ test("resolves a deep-linked instance to its page and full selector", () => {rootInstanceId: "body",});const { instances } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box">- <$.Heading ws:id="heading">Heading</$.Heading>- </$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box">+ <Heading ws:id="heading">Heading</Heading>+ </Box>+ </Body>);expect(getDeepLinkedInstanceSelection({@@ -68,18 +77,18 @@ test("restores the selected shared slot occurrence from its full selector", () =rootInstanceId: "body",});const { instances } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot-one">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot-two">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="body">+ <Slot ws:id="slot-one">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ <Slot ws:id="slot-two">+ <Fragment ws:id="fragment">+ <Box ws:id="box"></Box>+ </Fragment>+ </Slot>+ </Body>);expect(@@ -100,7 +109,7 @@ test("ignores missing deep-linked instances", () => {homePageId: "home-page",rootInstanceId: "body",});- const { instances } = renderData(<$.Body ws:id="body"></$.Body>);+ const { instances } = renderData(<Body ws:id="body"></Body>);expect(getDeepLinkedInstanceSelection({diff --git a/apps/builder/app/shared/style-object-model.test.tsx b/apps/builder/app/shared/style-object-model.test.tsxindex 154953c686..603f9e08b9 100644--- a/apps/builder/app/shared/style-object-model.test.tsx+++ b/apps/builder/app/shared/style-object-model.test.tsx@@ -9,7 +9,10 @@ import {type StyleDecl,getStyleDeclKey,} from "@webstudio-is/sdk";-import { $, renderData } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+} from "@webstudio-is/template";import { camelCaseProperty, parseCss } from "@webstudio-is/css-data";import type {ColorValue,@@ -24,6 +27,12 @@ import {getPresetStyleDeclKey,} from "./style-object-model";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Heading = createTemplateComponentFixture("Heading");+const Input = createTemplateComponentFixture("Input");+const Span = createTemplateComponentFixture("Span");+/*** Create model fixture with a few features*@@ -111,7 +120,7 @@ test("use cascaded style when specified and fallback to initial value", () => {width: 10px;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});const instanceSelector = ["body"];// cascaded property@@ -138,7 +147,7 @@ test("support initial keyword", () => {width: initial;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});const instanceSelector = ["body"];expect(@@ -162,11 +171,11 @@ test("support inherit keyword", () => {}`,jsx: (- <$.Box ws:id="level1" class="level1Local">- <$.Box ws:id="level2" class="level2Local">- <$.Box ws:id="level3" class="level3Local"></$.Box>- </$.Box>- </$.Box>+ <Box ws:id="level1" class="level1Local">+ <Box ws:id="level2" class="level2Local">+ <Box ws:id="level3" class="level3Local"></Box>+ </Box>+ </Box>),});const instanceSelector = ["level3", "level2", "level1"];@@ -195,9 +204,9 @@ test("support unset keyword", () => {}`,jsx: (- <$.Box ws:id="level1" class="level1Local">- <$.Box ws:id="level2" class="level2Local"></$.Box>- </$.Box>+ <Box ws:id="level1" class="level1Local">+ <Box ws:id="level2" class="level2Local"></Box>+ </Box>),});const instanceSelector = ["level2", "level1"];@@ -222,11 +231,11 @@ test("inherit style from ancestors", () => {}`,jsx: (- <$.Box ws:id="level1" class="level1Local">- <$.Box ws:id="level2" class="level2Local">- <$.Box ws:id="level3" class="level3Local"></$.Box>- </$.Box>- </$.Box>+ <Box ws:id="level1" class="level1Local">+ <Box ws:id="level2" class="level2Local">+ <Box ws:id="level3" class="level3Local"></Box>+ </Box>+ </Box>),});const instanceSelector = ["level3", "level2", "level1"];@@ -256,9 +265,9 @@ test("support currentcolor keyword", () => {}`,jsx: (- <$.Box ws:id="level1" class="level1Local">- <$.Box ws:id="level2" class="level2Local"></$.Box>- </$.Box>+ <Box ws:id="level1" class="level1Local">+ <Box ws:id="level2" class="level2Local"></Box>+ </Box>),});const instanceSelector = ["level2", "level1"];@@ -292,9 +301,9 @@ test("in color property currentcolor is inherited", () => {}`,jsx: (- <$.Box ws:id="level1" class="level1Local">- <$.Box ws:id="level2" class="level2Local"></$.Box>- </$.Box>+ <Box ws:id="level1" class="level1Local">+ <Box ws:id="level2" class="level2Local"></Box>+ </Box>),});const instanceSelector = ["level3", "level2", "level1"];@@ -311,7 +320,7 @@ test("in root color property currentcolor is initial", () => {color: currentcolor;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});const instanceSelector = ["body"];expect(@@ -328,7 +337,7 @@ test("support custom properties", () => {color: var(--my-property);}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});const instanceSelector = ["body"];expect(@@ -349,7 +358,7 @@ test("compute single custom property without layers", () => {background-image: var(--gradient);}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});expect(getComputedStyleDecl({@@ -372,7 +381,7 @@ test("support custom properties in layers", () => {background-image: var(--gradient-1), var(--gradient-2);}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});expect(getComputedStyleDecl({@@ -397,7 +406,7 @@ test("parse single custom property without tuples", () => {filter: var(--noise);}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});expect(getComputedStyleDecl({@@ -417,7 +426,7 @@ test("compute custom properties in shadows", () => {box-shadow: 10px 20px;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});const layers = model.styles.get("bodyLocal:base:boxShadow:")?.value as LayersValue;@@ -458,7 +467,7 @@ test("resolve custom property in color alpha channel", () => {color: #ff0000;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});// Mutate the color value to have a VarValue alpha, simulating parsed// Tailwind output like `rgb(28 25 23 / var(--tw-opacity))`@@ -492,7 +501,7 @@ test("support custom properties in tuples", () => {filter: var(--noise-1) var(--noise-2);}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});expect(getComputedStyleDecl({@@ -519,7 +528,7 @@ test("support custom properties in unparsed values", () => {box-shadow: var(--size) red, var(--size) blue;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});expect(getComputedStyleDecl({@@ -564,7 +573,7 @@ test("support empty custom properties", () => {box-shadow: var(--inset) red;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});expect(getComputedStyleDecl({@@ -592,7 +601,7 @@ test("use fallback value when custom property does not exist", () => {color: var(--my-property, red);}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});const instanceSelector = ["body"];expect(@@ -608,7 +617,7 @@ test("use initial value when custom property does not exist", () => {color: var(--my-property);}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});const instanceSelector = ["body"];expect(@@ -630,9 +639,9 @@ test("use inherited value when custom property does not exist", () => {}`,jsx: (- <$.Body ws:id="body" class="bodyLocal">- <$.Box ws:id="box" class="boxLocal"></$.Box>- </$.Body>+ <Body ws:id="body" class="bodyLocal">+ <Box ws:id="box" class="boxLocal"></Box>+ </Body>),});const instanceSelector = ["box", "body"];@@ -659,11 +668,11 @@ test("inherit custom property", () => {}`,jsx: (- <$.Box ws:id="level1" class="level1Local">- <$.Box ws:id="level2" class="level2Local">- <$.Box ws:id="level3" class="level3Local"></$.Box>- </$.Box>- </$.Box>+ <Box ws:id="level1" class="level1Local">+ <Box ws:id="level2" class="level2Local">+ <Box ws:id="level3" class="level3Local"></Box>+ </Box>+ </Box>),});const instanceSelector = ["level3", "level2", "level1"];@@ -690,9 +699,9 @@ test("resolve dependency cycles in custom properties", () => {}`,jsx: (- <$.Body ws:id="body" class="bodyLocal">- <$.Box ws:id="box" class="boxLocal"></$.Box>- </$.Body>+ <Body ws:id="body" class="bodyLocal">+ <Box ws:id="box" class="boxLocal"></Box>+ </Body>),});const instanceSelector = ["box", "body"];@@ -719,9 +728,9 @@ test("resolve non-cyclic references in custom properties", () => {}`,jsx: (- <$.Body ws:id="body" class="bodyLocal">- <$.Box ws:id="box" class="boxLocal"></$.Box>- </$.Body>+ <Body ws:id="body" class="bodyLocal">+ <Box ws:id="box" class="boxLocal"></Box>+ </Body>),});const instanceSelector = ["box", "body"];@@ -746,9 +755,9 @@ test("allow multiple usages of the same custom property", () => {}`,jsx: (- <$.Body ws:id="body" class="bodyLocal">- <$.Box ws:id="box" class="boxLocal"></$.Box>- </$.Body>+ <Body ws:id="body" class="bodyLocal">+ <Box ws:id="box" class="boxLocal"></Box>+ </Body>),});expect(@@ -783,7 +792,7 @@ test("cascade value from matching breakpoints", () => {width: 10px;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,matchingBreakpoints: ["base", "small", "large"],});const instanceSelector = ["body"];@@ -810,7 +819,7 @@ test("ignore values from not matching breakpoints", () => {}}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,// large is not matching breakpointmatchingBreakpoints: ["base", "small"],});@@ -831,7 +840,7 @@ test("cascade value from matching style sources", () => {width: 10px;}`,- jsx: <$.Body ws:id="body" class="bodyToken bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyToken bodyLocal"></Body>,});const instanceSelector = ["body"];// the latest token value wins@@ -848,7 +857,7 @@ test("cascade values with matching states", () => {width: 20px;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,matchingStates: new Set([":hover"]),});const instanceSelector = ["body"];@@ -869,7 +878,7 @@ test("prefer stateless values over matching states", () => {width: 20px;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,matchingStates: new Set([":hover"]),});const instanceSelector = ["body"];@@ -890,7 +899,7 @@ test("ignore values from not matching states", () => {width: 30px;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,matchingStates: new Set([":hover"]),});const instanceSelector = ["body"];@@ -906,10 +915,10 @@ test("support html styles", () => {const model = createModel({css: "",jsx: (- <$.Body ws:id="bodyId" ws:tag="body">- <$.Span ws:id="spanId" ws:tag="span"></$.Span>- <$.Heading ws:id="headingId" ws:tag="h1"></$.Heading>- </$.Body>+ <Body ws:id="bodyId" ws:tag="body">+ <Span ws:id="spanId" ws:tag="span"></Span>+ <Heading ws:id="headingId" ws:tag="h1"></Heading>+ </Body>),});// tag with browser styles@@ -948,7 +957,7 @@ test("support preset styles", () => {`,},css: ``,- jsx: <$.Body ws:id="body" ws:tag="body"></$.Body>,+ jsx: <Body ws:id="body" ws:tag="body"></Body>,});expect(getComputedStyleDecl({@@ -976,7 +985,7 @@ test("ignore values from not matching states in preset styles", () => {`,},css: ``,- jsx: <$.Body ws:id="body" ws:tag="body"></$.Body>,+ jsx: <Body ws:id="body" ws:tag="body"></Body>,});expect(getComputedStyleDecl({@@ -999,7 +1008,7 @@ test("breakpoints are more specific than style sources", () => {width: 10px;}`,- jsx: <$.Body ws:id="body" class="bodyToken bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyToken bodyLocal"></Body>,matchingBreakpoints: ["base", "small"],});// bigger breakpoint on current style source should overide@@ -1025,7 +1034,7 @@ test("breakpoints are more specific than matching states", () => {width: 20px;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,matchingBreakpoints: ["base", "small"],matchingStates: new Set([":hover"]),});@@ -1056,7 +1065,7 @@ test("user styles are more specific than preset styles", () => {color: red;}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,matchingStates: new Set([":hover"]),});expect(@@ -1080,7 +1089,7 @@ test("preset styles are more specific than browser styles", () => {`,},css: ``,- jsx: <$.Body ws:id="body" ws:tag="body"></$.Body>,+ jsx: <Body ws:id="body" ws:tag="body"></Body>,});expect(getComputedStyleDecl({@@ -1098,7 +1107,7 @@ test("access cascaded value without resolving", () => {color: initial;}`,- jsx: <$.Body ws:id="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" class="local"></Body>,});expect(getComputedStyleDecl({@@ -1117,9 +1126,9 @@ test("fallback cascaded value to initial value", () => {}`,jsx: (- <$.Body ws:id="body" class="body">- <$.Box ws:id="box" class="box"></$.Box>- </$.Body>+ <Body ws:id="body" class="body">+ <Box ws:id="box" class="box"></Box>+ </Body>),});expect(@@ -1140,9 +1149,9 @@ test("fallback cascaded value to inherited unresolved value", () => {}`,jsx: (- <$.Body ws:id="body" class="body">- <$.Box ws:id="box" class="box"></$.Box>- </$.Body>+ <Body ws:id="body" class="body">+ <Box ws:id="box" class="box"></Box>+ </Body>),});expect(@@ -1161,7 +1170,7 @@ test("work with unknown or invalid properties", () => {unknown-property: [object Object];}`,- jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ jsx: <Body ws:id="body" class="bodyLocal"></Body>,});const instanceSelector = ["body"];expect(@@ -1191,7 +1200,7 @@ describe("selected style", () => {color: blue;}`,- jsx: <$.Body ws:id="body" class="token local"></$.Body>,+ jsx: <Body ws:id="body" class="token local"></Body>,});expect(getComputedStyleDecl({@@ -1210,7 +1219,7 @@ describe("selected style", () => {color: red;}`,- jsx: <$.Body ws:id="body" class="token local"></$.Body>,+ jsx: <Body ws:id="body" class="token local"></Body>,});expect(getComputedStyleDecl({@@ -1232,7 +1241,7 @@ describe("selected style", () => {color: blue;}`,- jsx: <$.Body ws:id="body" class="first second local"></$.Body>,+ jsx: <Body ws:id="body" class="first second local"></Body>,});expect(getComputedStyleDecl({@@ -1254,7 +1263,7 @@ describe("selected style", () => {color: green;}`,- jsx: <$.Body ws:id="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" class="local"></Body>,});expect(getComputedStyleDecl({@@ -1280,7 +1289,7 @@ describe("selected style", () => {color: red;}`,- jsx: <$.Body ws:id="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" class="local"></Body>,});expect(getComputedStyleDecl({@@ -1302,7 +1311,7 @@ describe("selected style", () => {color: blue;}`,- jsx: <$.Body ws:id="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" class="local"></Body>,matchingStates: new Set([":hover"]),});expect(@@ -1324,7 +1333,7 @@ describe("selected style", () => {color: blue;}`,- jsx: <$.Body ws:id="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" class="local"></Body>,matchingStates: new Set([":hover", ":focus"]),});expect(@@ -1349,7 +1358,7 @@ describe("selected style", () => {}}`,- jsx: <$.Body ws:id="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" class="local"></Body>,matchingBreakpoints: ["base", "small"],});expect(@@ -1375,7 +1384,7 @@ describe("selected style", () => {`,},css: "",- jsx: <$.Body ws:id="body" ws:tag="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" ws:tag="body" class="local"></Body>,});expect(getComputedStyleDecl({@@ -1399,7 +1408,7 @@ describe("style value source", () => {test("default", () => {const model = createModel({css: "",- jsx: <$.Body ws:id="body" ws:tag="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" ws:tag="body" class="local"></Body>,});expect(getComputedStyleDecl({@@ -1420,7 +1429,7 @@ describe("style value source", () => {`,},css: "",- jsx: <$.Body ws:id="body" ws:tag="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" ws:tag="body" class="local"></Body>,});expect(getComputedStyleDecl({@@ -1446,9 +1455,7 @@ describe("style value source", () => {color: red;}`,- jsx: (- <$.Body ws:id="body" ws:tag="body" class="first second third"></$.Body>- ),+ jsx: <Body ws:id="body" ws:tag="body" class="first second third"></Body>,});expect(getComputedStyleDecl({@@ -1512,9 +1519,7 @@ describe("style value source", () => {color: blue;}`,- jsx: (- <$.Body ws:id="body" ws:tag="body" class="first second third"></$.Body>- ),+ jsx: <Body ws:id="body" ws:tag="body" class="first second third"></Body>,});expect(getComputedStyleDecl({@@ -1564,7 +1569,7 @@ describe("style value source", () => {color: red;}`,- jsx: <$.Body ws:id="body" ws:tag="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" ws:tag="body" class="local"></Body>,matchingStates: new Set([":hover"]),});expect(@@ -1606,7 +1611,7 @@ describe("style value source", () => {color: blue;}`,- jsx: <$.Body ws:id="body" ws:tag="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" ws:tag="body" class="local"></Body>,matchingStates: new Set([":hover"]),});expect(@@ -1650,7 +1655,7 @@ describe("style value source", () => {}}`,- jsx: <$.Body ws:id="body" ws:tag="body" class="local"></$.Body>,+ jsx: <Body ws:id="body" ws:tag="body" class="local"></Body>,matchingBreakpoints: ["base", "small"],});expect(@@ -1691,13 +1696,13 @@ describe("style value source", () => {}`,jsx: (- <$.Body ws:id="body" ws:tag="body" class="bodyLocal">- <$.Box ws:id="outer" ws:tag="div" class="outerLocal">- <$.Box ws:id="box" ws:tag="div" class="boxLocal">- <$.Box ws:id="inner" ws:tag="div" class="innerLocal"></$.Box>- </$.Box>- </$.Box>- </$.Body>+ <Body ws:id="body" ws:tag="body" class="bodyLocal">+ <Box ws:id="outer" ws:tag="div" class="outerLocal">+ <Box ws:id="box" ws:tag="div" class="boxLocal">+ <Box ws:id="inner" ws:tag="div" class="innerLocal"></Box>+ </Box>+ </Box>+ </Body>),});expect(@@ -1744,9 +1749,9 @@ describe("style value source", () => {}`,jsx: (- <$.Body ws:id="body" ws:tag="body" class="bodyLocal">- <$.Box ws:id="box" ws:tag="div" class="boxLocal"></$.Box>- </$.Body>+ <Body ws:id="body" ws:tag="body" class="bodyLocal">+ <Box ws:id="box" ws:tag="div" class="boxLocal"></Box>+ </Body>),});expect(@@ -1777,7 +1782,7 @@ describe("pseudo-element inheritance", () => {content: "test";}`,- jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,+ jsx: <Box ws:id="box" class="boxLocal"></Box>,});const instanceSelector = ["box"];@@ -1832,7 +1837,7 @@ describe("pseudo-element inheritance", () => {content: "test";}`,- jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,+ jsx: <Box ws:id="box" class="boxLocal"></Box>,});const instanceSelector = ["box"];@@ -1877,7 +1882,7 @@ describe("pseudo-element inheritance", () => {font-size: 20px;}`,- jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,+ jsx: <Box ws:id="box" class="boxLocal"></Box>,});const instanceSelector = ["box"];@@ -1913,7 +1918,7 @@ describe("pseudo-element inheritance", () => {color: inherit;}`,- jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,+ jsx: <Box ws:id="box" class="boxLocal"></Box>,});const instanceSelector = ["box"];@@ -1948,7 +1953,7 @@ describe("pseudo-element inheritance", () => {color: initial;}`,- jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,+ jsx: <Box ws:id="box" class="boxLocal"></Box>,});const instanceSelector = ["box"];@@ -1975,7 +1980,7 @@ describe("pseudo-element inheritance", () => {width: unset;}`,- jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,+ jsx: <Box ws:id="box" class="boxLocal"></Box>,});const instanceSelector = ["box"];@@ -2016,7 +2021,7 @@ describe("pseudo-element inheritance", () => {color: green;}`,- jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,+ jsx: <Box ws:id="box" class="boxLocal"></Box>,});const instanceSelector = ["box"];@@ -2074,7 +2079,7 @@ describe("pseudo-element inheritance", () => {width: var(--my-size);}`,- jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,+ jsx: <Box ws:id="box" class="boxLocal"></Box>,});const instanceSelector = ["box"];@@ -2128,7 +2133,7 @@ describe("pseudo-element inheritance", () => {color: blue;}`,- jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,+ jsx: <Box ws:id="box" class="boxLocal"></Box>,matchingStates: new Set([":hover"]),});const instanceSelector = ["box"];@@ -2165,7 +2170,7 @@ describe("pseudo-element inheritance", () => {color: gray;}`,- jsx: <$.Input ws:id="input" ws:tag="input" class="inputLocal"></$.Input>,+ jsx: <Input ws:id="input" ws:tag="input" class="inputLocal"></Input>,});const instanceSelector = ["input"];diff --git a/apps/builder/app/shared/sync-client.test.ts b/apps/builder/app/shared/sync-client.test.tsindex 5f9c23e6a7..f91fbf58e0 100644--- a/apps/builder/app/shared/sync-client.test.ts+++ b/apps/builder/app/shared/sync-client.test.ts@@ -180,6 +180,34 @@ test("recreates transaction values in the receiving realm", () => {expect(Object.getPrototypeOf(receivedValue)).toBe(Object.prototype);});+test("reports the rejected changes when a transaction is reverted", () => {+ const store = createFollowerStore();+ const onRevert = vi.fn();+ const object = new ImmerhinSyncObject("my-data", store, { onRevert });+ object.applyTransaction({+ id: "transaction-id",+ object: "my-data",+ payload: [+ {+ namespace: "users",+ patches: [{ op: "add", path: ["james"], value: "James Jameson" }],+ revisePatches: [{ op: "remove", path: ["james"] }],+ },+ ],+ });++ object.revertTransaction({ id: "transaction-id", object: "my-data" });++ expect(store.containers.get("users")?.get().has("james")).toBe(false);+ expect(onRevert).toHaveBeenCalledExactlyOnceWith([+ {+ namespace: "users",+ patches: [{ op: "add", path: ["james"], value: "James Jameson" }],+ revisePatches: [{ op: "remove", path: ["james"] }],+ },+ ]);+});+test("exchange transactions between followers", async () => {const emitter = new NanoEventsSyncEmitter();const follower1Store = createFollowerStore();diff --git a/apps/builder/app/shared/sync-client.ts b/apps/builder/app/shared/sync-client.tsindex 5b86010541..8f62f855de 100644--- a/apps/builder/app/shared/sync-client.ts+++ b/apps/builder/app/shared/sync-client.ts@@ -51,18 +51,21 @@ export class ImmerhinSyncObject implements SyncObject {store: Store;transformOnSend?: (changes: Change[]) => Change[];transformOnReceive?: (changes: Change[]) => Change[];+ onRevert?: (changes: Change[]) => void;constructor(name: string,store: Store,transform?: {onSend?: (changes: Change[]) => Change[];onReceive?: (changes: Change[]) => Change[];+ onRevert?: (changes: Change[]) => void;}) {this.name = name;this.store = store;this.transformOnSend = transform?.onSend;this.transformOnReceive = transform?.onReceive;+ this.onRevert = transform?.onRevert;}getState() {const state = new Map<string, unknown>();@@ -94,7 +97,13 @@ export class ImmerhinSyncObject implements SyncObject {this.store.addTransaction(transaction.id, payload, "remote");}revertTransaction(transaction: RevertedTransaction) {+ const revertedChanges = this.store.transactionManager.currentStack+ .find(({ id }) => id === transaction.id)+ ?.getChanges();this.store.revertTransaction(transaction.id);+ if (revertedChanges !== undefined) {+ this.onRevert?.(revertedChanges);+ }}subscribe(sendTransaction: (transaction: Transaction<Change[]>) => void,diff --git a/apps/builder/app/shared/sync/reload-required.test.ts b/apps/builder/app/shared/sync/reload-required.test.tsindex 5d6d0e74b5..63006edb2d 100644--- a/apps/builder/app/shared/sync/reload-required.test.ts+++ b/apps/builder/app/shared/sync/reload-required.test.ts@@ -22,3 +22,23 @@ test("uses the standard fatal sync state and reload flow", () => {error: "The MDX file changed remotely.",});});++test("shows one reload confirmation when the same fatal error is reported repeatedly", () => {+ const reload = vi.fn();+ const confirm = vi.fn(() => false);+ const input = {+ error: "This file changed since it was opened.",+ target: { confirm, location: { reload } } as never,+ };++ requireBuilderReload(input);+ requireBuilderReload(input);+ requireBuilderReload(input);++ expect(confirm).toHaveBeenCalledOnce();+ expect(reload).not.toHaveBeenCalled();+ expect($syncStatus.get()).toEqual({+ status: "fatal",+ error: "This file changed since it was opened.",+ });+});diff --git a/apps/builder/app/shared/sync/reload-required.ts b/apps/builder/app/shared/sync/reload-required.tsindex 379f637144..b5d62fe75c 100644--- a/apps/builder/app/shared/sync/reload-required.ts+++ b/apps/builder/app/shared/sync/reload-required.ts@@ -10,6 +10,9 @@ export const requireBuilderReload = ({target?: Pick<Window, "confirm" | "location">;toastId?: string;}) => {+ if ($syncStatus.get().status === "fatal") {+ return;+ }const shouldReload = target.confirm(error);if (shouldReload) {target.location.reload();diff --git a/apps/builder/app/shared/sync/sync-client.test.ts b/apps/builder/app/shared/sync/sync-client.test.tsindex 58f335cd32..7cc97d47db 100644--- a/apps/builder/app/shared/sync/sync-client.test.ts+++ b/apps/builder/app/shared/sync/sync-client.test.ts@@ -1,9 +1,28 @@-import { describe, expect, test } from "vitest";+import { afterEach, describe, expect, test, vi } from "vitest";+import { atom } from "nanostores";+import type { SyncEmitter } from "@webstudio-is/sync-client";import { __testing__ } from "./sync-client";import type { LoadedBuilderData } from "~/shared/builder-data";import { serverSyncStoreNames } from "./sync-stores";+import {+ $externalContentRoots,+ __testing__ as externalContentMutationsTesting,+ subscribeExternalContentTemplateMutations,+ type ExternalContentRoot,+} from "../external-content-mutations";+import {+ NanoEventsSyncEmitter,+ NanostoresSyncObject,+ SyncClient,+} from "../sync-client";-const { getServerSyncState, resolveMultiplayerRelayUrl } = __testing__;+const { applyBuilderData, getServerSyncState, resolveMultiplayerRelayUrl } =+ __testing__;+const { observeExternalContentRootMutations } = externalContentMutationsTesting;++afterEach(() => {+ $externalContentRoots.set(new Map());+});describe("getServerSyncState", () => {test("keeps only server-synchronized builder data", () => {@@ -53,6 +72,167 @@ describe("getServerSyncState", () => {});});+test("refreshes mounted external templates after a full project reload", () => {+ $externalContentRoots.set(+ new Map([+ [+ "current-root",+ {+ blockInstanceId: "current-block",+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ projectId: "project-1",+ },+ ],+ [+ "other-root",+ {+ blockInstanceId: "other-block",+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ projectId: "project-2",+ },+ ],+ ])+ );+ const refreshes: string[][] = [];+ const unsubscribe = subscribeExternalContentTemplateMutations((rootKeys) => {+ refreshes.push([...rootKeys]);+ });++ try {+ applyBuilderData({+ id: "build-1",+ version: 1,+ projectId: "project-1",+ project: { id: "project-1" },+ publisherHost: "example.com",+ pages: {},+ breakpoints: new Map(),+ instances: new Map(),+ styles: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ assets: new Map(),+ assetFolders: new Map(),+ marketplaceProduct: undefined,+ projectSettings: { meta: {}, compiler: {} },+ } as unknown as LoadedBuilderData);+ } finally {+ unsubscribe();+ }++ expect(refreshes).toEqual([["current-root"]]);+ expect(+ $externalContentRoots.get().get("current-root")?.templateMutationRevision+ ).toBe(1);+ expect(+ $externalContentRoots.get().get("other-root")?.templateMutationRevision+ ).toBeUndefined();+});++test("refreshes canvas templates once after a full project reload crosses realms", async () => {+ $externalContentRoots.set(+ new Map([+ [+ "current-root",+ {+ blockInstanceId: "current-block",+ instanceIds: new Set<string>(),+ mutationRevision: 0,+ projectId: "project-1",+ },+ ],+ ])+ );+ const $canvasRoots = atom(new Map<string, ExternalContentRoot>());+ const canvasRefreshes: string[][] = [];+ const unsubscribeCanvasObserver = observeExternalContentRootMutations({+ store: $canvasRoots,+ onMutation: () => {},+ onTemplateMutation(rootKeys) {+ canvasRefreshes.push([...rootKeys]);+ },+ });+ const innerEmitter = new NanoEventsSyncEmitter();+ // Builder and canvas have separate Nanostores listener queues. Deferring the+ // shared emitter reproduces that boundary while both stores run in this test.+ const emitter: SyncEmitter = {+ emit(message) {+ const received = structuredClone(message);+ queueMicrotask(() => innerEmitter.emit(received));+ },+ on(handler) {+ return innerEmitter.on(handler);+ },+ };+ const builderController = new AbortController();+ const canvasController = new AbortController();+ new SyncClient({+ role: "leader",+ object: new NanostoresSyncObject(+ "externalContentRoots",+ $externalContentRoots+ ),+ emitter,+ }).connect({ signal: builderController.signal });+ new SyncClient({+ role: "follower",+ object: new NanostoresSyncObject("externalContentRoots", $canvasRoots),+ emitter,+ }).connect({ signal: canvasController.signal });++ try {+ await vi.waitFor(() =>+ expect($canvasRoots.get().has("current-root")).toBe(true)+ );+ expect(+ $canvasRoots.get().get("current-root")?.templateMutationRevision+ ).toBeUndefined();++ applyBuilderData({+ id: "build-1",+ version: 1,+ projectId: "project-1",+ project: { id: "project-1" },+ publisherHost: "example.com",+ pages: {},+ breakpoints: new Map(),+ instances: new Map(),+ styles: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ assets: new Map(),+ assetFolders: new Map(),+ marketplaceProduct: undefined,+ projectSettings: { meta: {}, compiler: {} },+ } as unknown as LoadedBuilderData);+ await vi.waitFor(() =>+ expect(+ $canvasRoots.get().get("current-root")?.templateMutationRevision+ ).toBe(1)+ );+ } finally {+ builderController.abort();+ canvasController.abort();+ unsubscribeCanvasObserver();+ }++ expect(+ $externalContentRoots.get().get("current-root")?.templateMutationRevision+ ).toBe(1);+ expect($canvasRoots.get().get("current-root")?.templateMutationRevision).toBe(+ 1+ );+ expect(canvasRefreshes).toEqual([["current-root"]]);+});+describe("resolveMultiplayerRelayUrl", () => {test("keeps configured absolute URL outside local wstd.dev", () => {expect(diff --git a/apps/builder/app/shared/sync/sync-client.ts b/apps/builder/app/shared/sync/sync-client.tsindex 284bf2fe98..e44644682b 100644--- a/apps/builder/app/shared/sync/sync-client.ts+++ b/apps/builder/app/shared/sync/sync-client.ts@@ -31,6 +31,10 @@ import {$publisherHost,resetDataStores,} from "./data-stores";+import {+ getExternalContentRoots,+ publishExternalContentTemplateMutation,+} from "../external-content-mutations";let client: SyncClient | undefined;let currentProjectId: string | undefined;@@ -82,6 +86,11 @@ const applyBuilderData = (data: LoadedBuilderData) => {$styles.set(data.styles);$marketplaceProduct.set(data.marketplaceProduct);$projectSettings.set(data.projectSettings);+ publishExternalContentTemplateMutation(+ Array.from(getExternalContentRoots())+ .filter(([, root]) => root.projectId === data.project.id)+ .map(([key]) => key)+ );};const applyBuilderMetadata = (data: LoadedBuilderData) => {@@ -246,6 +255,7 @@ export const destroyClientSync = () => {export const getSyncClient = () => client;export const __testing__ = {+ applyBuilderData,getServerSyncState,resolveMultiplayerRelayUrl,};diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex a6ac920d85..b874c2d7eb 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -1,4 +1,4 @@-import { Store } from "immerhin";+import { Store, type Change } from "immerhin";import { enableMapSet, setAutoFreeze } from "immer";import { useEffect } from "react";import { batched } from "nanostores";@@ -95,6 +95,16 @@ setAutoFreeze(false);export const clientSyncStore = new Store();export const serverSyncStore = new Store();export const externalContentSyncStore = new Store();+const serverSyncRevertListeners = new Set<+ (changes: readonly Change[]) => void+>();++export const subscribeServerSyncReverts = (+ listener: (changes: readonly Change[]) => void+) => {+ serverSyncRevertListeners.add(listener);+ return () => serverSyncRevertListeners.delete(listener);+};const serverSyncStores = {pages: $pages,@@ -315,7 +325,13 @@ export const __testing__ = {export const createObjectPool = () => {return new SyncObjectPool([- new ImmerhinSyncObject("server", serverSyncStore),+ new ImmerhinSyncObject("server", serverSyncStore, {+ onRevert: (changes) => {+ for (const listener of serverSyncRevertListeners) {+ listener(changes);+ }+ },+ }),new ImmerhinSyncObject("externalContent", externalContentSyncStore),new ImmerhinSyncObject("client", clientSyncStore),new SelectedPageAndInstanceSyncObject(),diff --git a/apps/builder/e2e/fixtures/assets/named-template-source.mdx b/apps/builder/e2e/fixtures/assets/named-template-source.mdxnew file mode 100644index 0000000000..104d454719--- /dev/null+++ b/apps/builder/e2e/fixtures/assets/named-template-source.mdx@@ -0,0 +1 @@+<LifecycleCard>Authored lifecycle card</LifecycleCard>diff --git a/apps/builder/e2e/fixtures/assets/unresolved-source.mdx b/apps/builder/e2e/fixtures/assets/unresolved-source.mdxindex 031b134814..8e5344f07d 100644--- a/apps/builder/e2e/fixtures/assets/unresolved-source.mdx+++ b/apps/builder/e2e/fixtures/assets/unresolved-source.mdx@@ -1,5 +1,5 @@# Valid MDX sibling-<ws.element ws:name="Missing E2E Template" />+<MissingE2ETemplate />Valid content after the missing template.diff --git a/apps/builder/e2e/fixtures/mdx-content-block-project.ts b/apps/builder/e2e/fixtures/mdx-content-block-project.tsindex 96bab9ccca..f53fbc89b2 100644--- a/apps/builder/e2e/fixtures/mdx-content-block-project.ts+++ b/apps/builder/e2e/fixtures/mdx-content-block-project.ts@@ -6,6 +6,7 @@ type InstanceData = {id: string;component: string;tag?: string;+ name?: string;label?: string;children: Array<{ type: string; value: string }>;};@@ -67,12 +68,33 @@ export const configureEmptyHeadingTemplate = async (projectId: string) => {id: emptyHeadingId,component: "ws:element",tag: "h1",+ name: "EmptyHeadingTemplate",label: "Empty Heading Template",children: [],});await updateBuild(build.id, { instances: JSON.stringify(instances) });};+export const configureNamedTemplateLifecycle = async (projectId: string) => {+ const { build, instances } = await getBuildData(projectId);+ const templates = instances.find((instance) => instance.id === templateId);+ if (templates === undefined) {+ throw new Error("Expected the Content Block templates fixture instance");+ }+ const lifecycleTemplateId = "lifecycle-card-template";+ templates.children.push({ type: "id", value: lifecycleTemplateId });+ instances.push({+ type: "instance",+ id: lifecycleTemplateId,+ component: "ws:element",+ tag: "section",+ name: "LifecycleCard",+ label: "Lifecycle Card",+ children: [{ type: "text", value: "Default lifecycle card" }],+ });+ await updateBuild(build.id, { instances: JSON.stringify(instances) });+};+const configureSourceBlock = ({instances,props,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 1171b77cf6..50b2b45760 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@@ -3,6 +3,7 @@ import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";import {configureDynamicDetailContentBlock,configureEmptyHeadingTemplate,+ configureNamedTemplateLifecycle,configureRepresentableContentBlockBody,configureRepeatedContentBlock,} from "../fixtures/mdx-content-block-project";@@ -32,6 +33,7 @@ import {} from "../flows/sync-status";import { insertTemplateAfterCanvasText } from "../flows/template-insertion";import { openNavigatorPanel } from "../flows/navigator";+import { selectNavigatorItem } from "../flows/navigator";import { selectCanvasTextInstanceForProps } from "../flows/canvas-selection";import { fillSelectedStringProperty } from "../flows/props-panel";import { getProjectBuilderUrl, test } from "../test";@@ -41,6 +43,7 @@ test.describe.configure({ mode: "parallel" });const sourceFilename = "content-source.mdx";const alternateFilename = "alternate-source.mdx";const unresolvedFilename = "unresolved-source.mdx";+const namedTemplateFilename = "named-template-source.mdx";const emptyFilename = "empty-source.mdx";const sourceHeading = "MDX source heading";@@ -125,6 +128,22 @@ const expectCanvasTextOrder = async ({throw new Error(`Expected "${before}" before "${after}" on the canvas`);};+const expandNavigatorItem = async ({+ page,+ name,+}: {+ page: Page;+ name: string;+}) => {+ await openNavigatorPanel({ page });+ const item = page+ .locator("[data-navigator-tree] [data-tree-button]")+ .filter({ has: page.getByText(name, { exact: true }) })+ .last();+ await item.waitFor({ state: "visible" });+ await item.press("ArrowRight");+};+const insertTemplateIntoEmptyContentBlock = async ({page,templateName,@@ -273,7 +292,18 @@ test("Content Block MDX source lifecycle persists edits and resets to empty", as"Opening an MDX Asset after a canvas save must show the latest content");}+ const rawEditorHeading = "Raw editor heading";+ const rawEditorWrite = waitForAssetWrite(page, (source) =>+ source.includes(`## ${rawEditorHeading}`)+ );+ await fileEditor.click();+ await page.keyboard.press("ControlOrMeta+End");+ await page.keyboard.press("Enter");+ await page.keyboard.press("Enter");+ await page.keyboard.type(`## ${rawEditorHeading}`);await page.keyboard.press("Escape");+ await waitForCanvasText({ page, text: rawEditorHeading });+ await rawEditorWrite;await openFixture({page,projectId: fixture.projectId,@@ -420,10 +450,19 @@ test("Content Block MDX source lifecycle persists edits and resets to empty", as.waitFor();});-test("Empty MDX content supports insertion and keeps the next paragraph focused", async ({+test("Empty MDX content supports slash menu keyboard and mouse insertion", async ({page,context,}) => {+ const unexpectedDialogs: string[] = [];+ page.on("dialog", async (dialog) => {+ if (dialog.type() === "beforeunload") {+ await dialog.accept();+ return;+ }+ unexpectedDialogs.push(dialog.message());+ await dialog.dismiss();+ });const fixture = await createContentModeProject({context: context,email: "[email protected]",@@ -461,32 +500,81 @@ test("Empty MDX content supports insertion and keeps the next paragraph focused"await headingEditor.getByText("First heading", { exact: true }).waitFor();await page.keyboard.press("Enter");- const paragraphEditor = canvas.locator("p[contenteditable]");- await paragraphEditor.waitFor({ state: "visible" });- await page.keyboard.press("/");- await page+ const keyboardAnchorEditor = canvas.locator("p[contenteditable]").last();+ await keyboardAnchorEditor.waitFor({ state: "visible" });+ await page.keyboard.type("Keyboard anchor");+ await page.keyboard.type("/Empty");+ const keyboardTemplateItem = page.getByRole("menuitemradio", { name: "Empty Heading Template" })- .last()- .waitFor({ state: "visible" });- await page.keyboard.press("Escape");+ .last();+ await keyboardTemplateItem.waitFor({ state: "visible" });+ await page.keyboard.press("ArrowDown");+ await page.keyboard.press("Enter");+ await keyboardTemplateItem.waitFor({ state: "detached" });+ await canvas.locator("h1").nth(1).waitFor({ state: "visible" });+ await page.waitForTimeout(100);+ const headingCount = await canvas.locator("h1").count();+ if (headingCount !== 2) {+ throw new Error(+ `Expected one keyboard insertion, found ${headingCount - 1}`+ );+ }+ const keyboardHeadingEditor = canvas.locator("h1[contenteditable]").last();+ await page.keyboard.type("Keyboard heading");+ await keyboardHeadingEditor+ .getByText("Keyboard heading", { exact: true })+ .waitFor();+ await page.keyboard.press("Enter");++ const emptyParagraphEditor = canvas.locator("p[contenteditable]").last();+ await emptyParagraphEditor.waitFor({ state: "visible" });+ const replacedParagraphId =+ await emptyParagraphEditor.getAttribute("data-ws-id");+ if (replacedParagraphId === null) {+ throw new Error("Expected the paragraph instance being replaced");+ }+ await page.keyboard.press("/");+ const templateItem = page+ .getByRole("menuitemradio", {+ name: fixture.editableTextTemplateName,+ })+ .last();+ await templateItem.waitFor({ state: "visible" });+ await templateItem.click();+ await canvas+ .locator(`[data-ws-id="${replacedParagraphId}"]`)+ .waitFor({ state: "detached" });+ await waitForCanvasText({ page, text: fixture.editableTextTemplateText });+ if (+ (await canvas+ .getByText(fixture.editableTextTemplateText, { exact: true })+ .count()) !== 1+ ) {+ throw new Error("Expected one live slash menu insertion on the canvas");+ }+ const paragraphEditor = canvas+ .locator("p[contenteditable]")+ .filter({ hasText: fixture.editableTextTemplateText });+ await paragraphEditor.waitFor({ state: "visible" });+ const paragraphId = await paragraphEditor.getAttribute("data-ws-id");+ if (paragraphId === null) {+ throw new Error("Expected the focused paragraph instance id");+ }const paragraphWrite = waitForAssetWrite(page, (source) =>source.includes("Focused paragraph"));const paragraphMetadataWrite = waitForChangeToBeSaved({ page });+ await page.keyboard.press("ControlOrMeta+A");await page.keyboard.type("Focused paragraph");- const paragraphId = await paragraphEditor.getAttribute("data-ws-id");- if (paragraphId === null) {- throw new Error("Expected the focused paragraph instance id");- }await page.keyboard.press("Enter");- const emptyParagraphEditor = canvas.locator(+ const nextEmptyParagraphEditor = canvas.locator(`p[contenteditable]:not([data-ws-id="${paragraphId}"])`);- await emptyParagraphEditor.waitFor({ state: "visible" });+ await nextEmptyParagraphEditor.waitFor({ state: "visible" });await paragraphWrite;await paragraphMetadataWrite;const emptyParagraphId =- await emptyParagraphEditor.getAttribute("data-ws-id");+ await nextEmptyParagraphEditor.getAttribute("data-ws-id");if (emptyParagraphId === null) {throw new Error("Expected the new paragraph instance id");}@@ -494,6 +582,8 @@ test("Empty MDX content supports insertion and keeps the next paragraph focused"page,(source) =>source.includes("# First heading") &&+ source.includes("Keyboard anchor") &&+ source.includes("# Keyboard heading") &&source.includes("Focused paragraph") &&source.includes('ws:tag="p"') === false);@@ -504,21 +594,36 @@ test("Empty MDX content supports insertion and keeps the next paragraph focused".locator(`p[data-ws-id="${emptyParagraphId}"]`).waitFor({ state: "detached" });if (- (await paragraphEditor.evaluate(- (element) =>- element === document.activeElement ||- element.contains(document.activeElement)- )) === false+ (await canvas+ .locator(`p[data-ws-id="${paragraphId}"]`)+ .evaluate(+ (element) =>+ element === document.activeElement ||+ element.contains(document.activeElement)+ )) === false) {throw new Error("Expected the previous paragraph to regain focus");}await page.mouse.click(5, 5);const finalSource = (await finalWrite).request().postData() ?? "";- if (- finalSource.includes("# First heading") === false ||- finalSource.includes("Focused paragraph") === false ||- finalSource.includes('ws:tag="p"')- ) {+ const expectedContentOrder = [+ "# First heading",+ "Keyboard anchor",+ "# Keyboard heading",+ "Focused paragraph",+ ];+ let previousIndex = -1;+ for (const content of expectedContentOrder) {+ const index = finalSource.indexOf(content);+ if (+ index <= previousIndex ||+ finalSource.indexOf(content, index + 1) !== -1+ ) {+ throw new Error(`Unexpected final MDX source: ${finalSource}`);+ }+ previousIndex = index;+ }+ if (finalSource.includes("/Empty") || finalSource.includes('ws:tag="p"')) {throw new Error(`Unexpected final MDX source: ${finalSource}`);}@@ -529,7 +634,25 @@ test("Empty MDX content supports insertion and keeps the next paragraph focused"mode: "content",});await waitForCanvasText({ page, text: "First heading" });+ await waitForCanvasText({ page, text: "Keyboard anchor" });+ await waitForCanvasText({ page, text: "Keyboard heading" });await waitForCanvasText({ page, text: "Focused paragraph" });+ const reloadedCanvas = await waitForCanvasFrame({ page });+ for (const text of [+ "First heading",+ "Keyboard anchor",+ "Keyboard heading",+ "Focused paragraph",+ ]) {+ if ((await reloadedCanvas.getByText(text, { exact: true }).count()) !== 1) {+ throw new Error(`Expected one ${text} block after reload`);+ }+ }+ if (unexpectedDialogs.length > 0) {+ throw new Error(+ `Normal Content Block edits opened dialogs: ${unexpectedDialogs.join(", ")}`+ );+ }});test("Content Block requires a Builder reload after a stale file revision", async ({@@ -640,14 +763,20 @@ test("Unresolved MDX templates are selectable only in the Builder canvas", asynctext: "Valid content after the missing template.",});const canvas = await waitForCanvasFrame({ page });- const warning = canvas.getByText("Missing template: Missing E2E Template", {+ const warning = canvas.getByText("Missing template: MissingE2ETemplate", {exact: true,});await warning.waitFor();await warning.click();await selectContentBlock({ page });await page.getByRole("img", { name: /^MDX source warning:/ }).waitFor();- await page.getByRole("button", { name: "Open", exact: true }).waitFor();+ const openButton = page.getByRole("button", { name: "Open", exact: true });+ await openButton.click();+ await page+ .locator(".cm-lintRange-warning")+ .filter({ hasText: "MissingE2ETemplate" })+ .waitFor();+ await page.keyboard.press("Escape");const previewUrl = getProjectBuilderUrl({projectId: fixture.projectId,@@ -662,7 +791,87 @@ test("Unresolved MDX templates are selectable only in the Builder canvas", async});const previewCanvas = await waitForCanvasFrame({ page });await previewCanvas- .getByText("Missing template: Missing E2E Template", { exact: true })+ .getByText("Missing template: MissingE2ETemplate", { exact: true })+ .waitFor({ state: "hidden" });+});++test("Named MDX templates re-resolve after rename, reload, and removal", async ({+ page,+ context,+}) => {+ const fixture = await createContentModeProject({+ context,+ email: "[email protected]",+ title: "MDX Template Lifecycle E2E",+ });+ await configureNamedTemplateLifecycle(fixture.projectId);++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: namedTemplateFilename });+ await selectContentBlock({ page });+ await chooseContentBlockSource({ page, filename: namedTemplateFilename });+ await confirmContentBlockConnection({ page });+ await waitForCanvasText({ page, text: "Authored lifecycle card" });++ await expandNavigatorItem({ page, name: "Content Block" });+ await expandNavigatorItem({ page, name: "Block Template" });+ await selectNavigatorItem({ page, name: "Lifecycle Card" });+ await page.getByRole("tab", { name: "Settings" }).click();+ const nameInput = page.getByLabel("Name", { exact: true });+ await nameInput.fill("RenamedLifecycleCard");+ await nameInput.press("Tab");+ const renameSaved = waitForChangeToBeSaved({ page });+ await page.getByRole("button", { name: "Rename", exact: true }).click();+ await renameSaved;+ await selectContentBlock({ page });+ await waitForCanvasText({ page, text: "Missing template: LifecycleCard" });++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForCanvasText({ page, text: "Missing template: LifecycleCard" });++ await expandNavigatorItem({ page, name: "Content Block" });+ await expandNavigatorItem({ page, name: "Block Template" });+ await selectNavigatorItem({ page, name: "Lifecycle Card" });+ await page.getByRole("tab", { name: "Settings" }).click();+ await page.getByLabel("Name", { exact: true }).fill("LifecycleCard");+ await page.getByLabel("Name", { exact: true }).press("Tab");+ const restoreNameSaved = waitForChangeToBeSaved({ page });+ await page.getByRole("button", { name: "Rename", exact: true }).click();+ await restoreNameSaved;+ await selectContentBlock({ page });+ await waitForCanvasText({ page, text: "Authored lifecycle card" });++ await expandNavigatorItem({ page, name: "Content Block" });+ await expandNavigatorItem({ page, name: "Block Template" });+ await selectNavigatorItem({ page, name: "Lifecycle Card" });+ await page.keyboard.press("Delete");+ const deleteSaved = waitForChangeToBeSaved({ page });+ await page.getByRole("button", { name: "Delete", exact: true }).click();+ await deleteSaved;+ await selectContentBlock({ page });+ await waitForCanvasText({ page, text: "Missing template: LifecycleCard" });++ const previewUrl = getProjectBuilderUrl({+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "preview",+ });+ await page.goto(previewUrl);+ const previewCanvas = await waitForCanvasFrame({ page });+ await previewCanvas+ .getByText("Missing template: LifecycleCard", { exact: true })+ .waitFor({ state: "hidden" });+ await previewCanvas+ .getByText("Authored lifecycle card", { exact: true }).waitFor({ state: "hidden" });});@@ -679,7 +888,7 @@ test("Dynamic detail source follows the selected route parameter", async ({await openFixture({page,projectId: fixture.projectId,- authToken: fixture.editorToken,+ authToken: fixture.builderToken,});await openAssetsPanel({ page });await uploadAsset({ page, filename: sourceFilename });@@ -702,6 +911,7 @@ test("Dynamic detail source follows the selected route parameter", async ({projectId: fixture.projectId,authToken: fixture.editorToken,pageId: detailPageId,+ mode: "content",});await waitForCanvasText({ page, text: sourceHeading });@@ -736,7 +946,7 @@ test("Repeated Content Block scopes edit distinct MDX files without leakage", asawait openFixture({page,projectId: fixture.projectId,- authToken: fixture.editorToken,+ authToken: fixture.builderToken,});await openAssetsPanel({ page });await uploadAsset({ page, filename: sourceFilename });@@ -758,6 +968,7 @@ test("Repeated Content Block scopes edit distinct MDX files without leakage", aspage,projectId: fixture.projectId,authToken: fixture.editorToken,+ mode: "content",});await waitForCanvasText({ page, text: sourceHeading });await waitForCanvasText({ page, text: alternateHeading });@@ -777,6 +988,7 @@ test("Repeated Content Block scopes edit distinct MDX files without leakage", aspage,projectId: fixture.projectId,authToken: fixture.editorToken,+ mode: "content",});await waitForCanvasText({ page, text: editedHeading });await waitForCanvasText({ page, text: alternateHeading });diff --git a/apps/builder/e2e/tests/pages-actions-pages.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/pages-actions-pages.[shard-2].[shard-5].[shard-6].e2e.tsindex 86a892f1eb..e9856188fa 100644--- a/apps/builder/e2e/tests/pages-actions-pages.[shard-2].[shard-5].[shard-6].e2e.ts+++ b/apps/builder/e2e/tests/pages-actions-pages.[shard-2].[shard-5].[shard-6].e2e.ts@@ -646,12 +646,7 @@ test("Builder runs paste plugins through generic browser paste events", async ({"Instance text paste heading","p",],- [- "text/plain",- '<ws.element ws:tag="h2">JSX paste heading</ws.element>',- "JSX paste heading",- "h2",- ],+ ["text/plain", "<h2>JSX paste heading</h2>", "JSX paste heading", "h2"],["text/plain","<section><h2>HTML paste heading</h2></section>",diff --git a/docs/university/cli.md b/docs/university/cli.mdindex a654470beb..674bf9cace 100644--- a/docs/university/cli.md+++ b/docs/university/cli.md@@ -221,7 +221,7 @@ restarting an MCP client:```bashnpx webstudio meta.index-npx webstudio insert-fragment '{"parentInstanceId":"<parent-id>","fragment":"<ws.element ws:tag=\"section\" />"}' --dry-run+npx webstudio insert-fragment '{"parentInstanceId":"<parent-id>","fragment":"<section />"}' --dry-run```The explicit equivalent isdiff --git a/docs/university/core-components/content-block.md b/docs/university/core-components/content-block.mdindex 145e8125f1..ff4eeb9a20 100644--- a/docs/university/core-components/content-block.md+++ b/docs/university/core-components/content-block.md@@ -40,13 +40,15 @@ Notice that the child of Content Block is Templates. Drag/build the various instances you want to provide editors here.+A Content Block must have exactly one direct Templates container. A missing or second Templates container makes the block invalid. Connected MDX content does not resolve or publish until you restore that structure.+For example, your client wants to update the section under the hero with the latest promotion. Sometimes the promotion is for an event while other times it’s a product. You can create those two designs, add them to “Templates” within Content Block, and your client can insert instances of the desired template and edit its content.{% hint style="info" %}Editors don’t have access to the Style Panel, so be sure to provide fully designed templates.{% endhint %}-Every top-level instance within Templates will appear in Content mode like this:+Reusable top-level templates appear in Content mode like this. Structural and inline templates supplied for MDX styling, such as table cells and emphasis, do not appear as standalone insertion choices.<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>@@ -72,10 +74,11 @@ Connect a `.mdx` file when the Content Block's body should live in Assets instea1. Add the Content Block and design its shell in Design mode.2. Place the **Body** outlet where the article body should render.-3. Add any reusable custom content to **Templates**.-4. Give every top-level template a unique instance name. MDX uses that name to find the template.+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. When you connect an older Content Block without one, Webstudio adds it automatically.+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.#### Create and connect the file@@ -113,25 +116,70 @@ If the file changes after a canvas edit starts but before it is saved, reload th#### Write Markdown and MDX-Write headings, paragraphs, links, lists, tables, code, images, and other standard document content as Markdown. Webstudio writes a standard element as `<ws.element ws:tag="tag">` only when its authored properties cannot be represented by Markdown. It uses `ws:name` only to insert a uniquely named top-level template:+An `.mdx` file supports standard Markdown and constrained JSX in one document.++Write headings, paragraphs, links, lists, tables, code, images, and other standard document content as Markdown. Each node uses the uniquely matching semantic template from the Content Block when one exists. Matching uses the element tag or adapted component type, not the template's editable label. If no standard template exists, Webstudio renders the normal semantic fallback. The fallback is still a normal element or component, so its applicable component and global styles continue to work; it simply has no Content Block template styles. If more than one standard template matches, Webstudio reports a warning and uses the fallback.++Use lowercase JSX when Markdown cannot express the required HTML or SVG element or attributes:++```mdx+<section aria-label="Launch details">+ <h2>Launch offer</h2>+</section>+```++Standard SVG elements use the same syntax:++```mdx+<svg viewBox="0 0 24 24">+ <path d="M0 0h24v24H0z" />+</svg>+```++Use a capitalized JSX name for a uniquely named custom template:```mdx# Product update-Regular document content stays Markdown.+Regular document content stays Markdown and uses the matching standard templates.-<ws.element ws:name="Promotion Card" />+<PromotionCard tone="featured">+ ## Launch offer+</PromotionCard>```-The `ws:name` value must exactly match a unique top-level instance name in the Content Block's Templates list. Missing templates show a warning in Builder and are omitted from the published site. Invalid or unsupported MDX remains editable; Builder reports the source location and renders the valid content it can recover.+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.-Keep 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 `ws:name` references in the MDX files. An MCP-connected agent can preview and confirm that update across a selected group of files.+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.++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.++JSX attributes accept quoted static values and bare booleans. Webstudio converts quoted values to the property's declared string, number, or boolean type when possible. Imports, exports, expressions such as `{false}`, spreads, functions, and executable JavaScript are not supported. Internal forms such as `<ws.element>`, `ws:name`, `ws:tag`, `ws:label`, and `<$.*>` are not current authoring syntax.++An explicit JSX child tree that matches the designed template structure overlays its text and supported properties onto the cloned template descendants. Their template styles and structure stay intact. If the child structure does not match, the explicit children replace the template root's default children and each authored child resolves through a matching template when possible. An empty pair such as `<PromotionCard></PromotionCard>` clears the defaults, while a self-closing reference such as `<PromotionCard />` keeps them. If you edit inherited default content in Builder, Webstudio writes that content as explicit JSX children so the edit persists without changing the template.++Template resolution is live. If the file already contains `<PromotionCard />` or a Markdown element that has no matching template, adding the template later updates the rendered content without rewriting the MDX file. This also applies to elements added to an explicit JSX child tree. Renaming or removing a template re-resolves the same source.++If a Content Block that already renders connected MDX temporarily has zero or multiple Templates containers, Builder keeps the last valid rendered content and reports the structural error. Fixing the container structure resolves the current MDX again automatically.++Missing 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.++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.#### Use frontmatter in the designed shellEdit frontmatter as YAML in the MDX file editor. Visual body edits preserve the frontmatter source, including comments and formatting.-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` or an image source to `document.frontmatter.featureImage.src`. 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.+Store every frontmatter image as an exact `$ref` object so it resolves to structured Asset metadata:++```yaml+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.#### Use one file in repeated or shared contentdiff --git a/docs/university/mcp.md b/docs/university/mcp.mdindex 7e28784626..aaaa7bdec4 100644--- a/docs/university/mcp.md+++ b/docs/university/mcp.md@@ -105,7 +105,7 @@ Prefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragm```json{"parentInstanceId": "root-id",- "fragment": "<ws.element ws:tag='section' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag='h2'>Northstar Product OS</ws.element><ws.element ws:tag='p'>Reusable patterns for teams.</ws.element></ws.element>"+ "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>"}```@@ -114,33 +114,26 @@ Then run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. SiWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:```tsx-<ws.element- ws:tag="section"- style={{ padding: 32, borderRadius: 16 }}->- <ws.element ws:tag="h2">Operations Console</ws.element>- <ws.element ws:tag="p">+<section style={{ padding: 32, borderRadius: 16 }}>+ <h2>Operations Console</h2>+ <p>React-style object styles become editable Webstudio styles.- </ws.element>-</ws.element>--<ws.element- ws:tag="section"- ws:tokens={[token("accent", css`color: #0f766e;`)]}->- <ws.element- ws:tag="button"+ </p>+</section>++<section ws:tokens={[token("accent", css`color: #0f766e;`)]}>+ <buttononClick={new ActionValue(["event"], expression`console.log(event)`)}>Track launch- </ws.element>-</ws.element>+ </button>+</section>-<ws.element ws:tag="section">- <radix.Switch>- <radix.SwitchThumb />- </radix.Switch>-</ws.element>+<section>+ <Switch>+ <SwitchThumb />+ </Switch>+</section>```Rules:@@ -148,12 +141,12 @@ Rules:- 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`.- 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.- 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.-- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. `animation` is the component namespace for JSX such as `<animation.AnimateChildren>`; it is not a callable CSS keyframes helper.+- `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.- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.- 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={() => ...}`.- 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.-- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.+- 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.- The positional input is JSON and defaults to `{}`.- Use `--input-file` for large mutation payloads.- 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.@@ -169,7 +162,7 @@ Rules:Use a connected `.mdx` Asset when editors should change a Content Block body visually while the document remains stored as a file.1. Create the `.mdx` file under `.webstudio/assets`, then upload it and keep the returned Asset ID.-2. Inspect the Content Block and its Templates children. Every template referenced from MDX needs a unique top-level instance name.+2. 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.3. Connect the Asset with `connect-content-block-source`. Use a stable page-based `renderScope` for a direct occurrence.4. 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.5. Edit the complete source with `edit-content-block-source`, or replace the complete frontmatter map with `update-content-block-frontmatter`.@@ -184,15 +177,19 @@ webstudio reload-content-block-source '{"blockInstanceId":"<contentBlockInstancewebstudio migrate-content-block-template-references '{"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}'```-Prefer Markdown whenever it can represent the component and all authored properties. Use `<ws.element ws:tag="tag">` for a standard HTML element with authored properties Markdown cannot express. Use `<ws.element ws:name="Template name">` only for a uniquely named top-level Content Block template. Preserve unresolved template names and report their diagnostics.+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.++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.-When 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. A rename changes matching `ws:name` values. A removal deletes matching MDX elements. Invalid files remain unchanged and are reported in diagnostics.+When 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.Use 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>"}}`.`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. 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 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.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.@@ -1032,7 +1029,7 @@ source of truth. For tools with no required arguments, pass `{}`."type": "expression","value": "Posts.data.items"},- "itemFragment": "<ws.element ws:tag='article'><ws.element ws:tag='h2'>{expression`collectionItem.title ?? 'Untitled'`}</ws.element></ws.element>"+ "itemFragment": "<article><h2>{expression`collectionItem.title ?? 'Untitled'`}</h2></article>"}```@@ -1050,7 +1047,7 @@ source of truth. For tools with no required arguments, pass `{}`.}]},- "itemFragment": "<ws.element ws:tag='div'>{expression`collectionItem.name`}</ws.element>"+ "itemFragment": "<div>{expression`collectionItem.name`}</div>"}```@@ -1059,28 +1056,28 @@ source of truth. For tools with no required arguments, pass `{}`.```json{"parentInstanceId": "parent-id",- "fragment": "<ws.element ws:tag='section' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag='h2'>Northstar Product OS</ws.element><ws.element ws:tag='p'>Reusable patterns for teams.</ws.element></ws.element>"+ "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>"}``````json{"parentInstanceId": "parent-id",- "fragment": "<ws.element ws:tag='section' style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag='h2'>Operations Console</ws.element><ws.element ws:tag='p'>Semantic section with React-style object styles converted into editable Webstudio styles.</ws.element></ws.element>"+ "fragment": "<section style={{ padding: 32, borderRadius: 16 }}><h2>Operations Console</h2><p>Semantic section with React-style object styles converted into editable Webstudio styles.</p></section>"}``````json{"parentInstanceId": "parent-id",- "fragment": "<ws.element ws:tag='section' ws:tokens={[token('accent', css`color: #0f766e;`)]} ws:style={css`display: grid; gap: 12px;`}><ws.element ws:tag='h2'>Token Example</ws.element><ws.element ws:tag='button' onClick={new ActionValue(['event'], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"+ "fragment": "<section ws:tokens={[token('accent', css`color: #0f766e;`)]} ws:style={css`display: grid; gap: 12px;`}><h2>Token Example</h2><button onClick={new ActionValue(['event'], expression`console.log(event)`)}>Track launch</button></section>"}``````json{"parentInstanceId": "parent-id",- "fragment": "<ws.element ws:tag='section'><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"+ "fragment": "<section><Switch><SwitchThumb /></Switch></section>"}```@@ -1090,7 +1087,7 @@ source of truth. For tools with no required arguments, pass `{}`.{"parentInstanceId": "parent-id","pagePath": "/pricing",- "fragment": "<ws.element ws:tag='section'><ws.element ws:tag='h2'>Pricing</ws.element></ws.element>"+ "fragment": "<section><h2>Pricing</h2></section>"}```diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.jsonindex e8960022b5..a4fcbb4324 100644--- a/fixtures/react-router-cloudflare/.webstudio/data.json+++ b/fixtures/react-router-cloudflare/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1xyq4y2",+ "bundleVersion": "bundle-1x6rafk","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.jsonindex e8960022b5..a4fcbb4324 100644--- a/fixtures/react-router-docker/.webstudio/data.json+++ b/fixtures/react-router-docker/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1xyq4y2",+ "bundleVersion": "bundle-1x6rafk","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.jsonindex e8960022b5..a4fcbb4324 100644--- a/fixtures/react-router-netlify/.webstudio/data.json+++ b/fixtures/react-router-netlify/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1xyq4y2",+ "bundleVersion": "bundle-1x6rafk","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.jsonindex e8960022b5..a4fcbb4324 100644--- a/fixtures/react-router-vercel/.webstudio/data.json+++ b/fixtures/react-router-vercel/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1xyq4y2",+ "bundleVersion": "bundle-1x6rafk","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.jsonindex 8f2d5c9b6e..8dee425a36 100644--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1xyq4y2",+ "bundleVersion": "bundle-1x6rafk","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.jsonindex 0063d0d7d6..7a291f30a9 100644--- a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1xyq4y2",+ "bundleVersion": "bundle-1x6rafk","build": {"id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c","projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.jsonindex 8f2d5c9b6e..8dee425a36 100644--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1xyq4y2",+ "bundleVersion": "bundle-1x6rafk","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.jsonindex 0e39b766ab..7d8a2d0f94 100644--- a/fixtures/webstudio-features/.webstudio/data.json+++ b/fixtures/webstudio-features/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1xyq4y2",+ "bundleVersion": "bundle-1x6rafk","build": {"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32","projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 00ad66259e..7a1909a55a 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -83,7 +83,7 @@ webstudio insert-fragment --input-file .temp/insert-fragment.json --dry-run```json{"parentInstanceId": "<parent-id>",- "fragment": "<ws.element ws:tag='section' />"+ "fragment": "<section />"}```diff --git a/packages/cli/evaluations/high-impact/agent-runner.test.ts b/packages/cli/evaluations/high-impact/agent-runner.test.tsindex c69059549d..3f408e3448 100644--- a/packages/cli/evaluations/high-impact/agent-runner.test.ts+++ b/packages/cli/evaluations/high-impact/agent-runner.test.ts@@ -17,164 +17,83 @@ import {} from "./agent-runner";describe("high-impact agent runner", () => {- test("points source evaluations at the local CLI", () => {+ test("serializes fixture contracts without embedding project state", () => {const root = resolve(import.meta.dirname, "../../../..");- expect(getCliInvocation({ kind: "source", repositoryRoot: root })).toEqual({+ const target = { kind: "source", repositoryRoot: root } as const;+ expect(getCliInvocation(target)).toEqual({command: process.execPath,args: [resolve(root, "packages/cli/local.js"), "mcp"],});- const task = createMinimalAgentTask(authenticatedPageFixture, {- kind: "source",- repositoryRoot: root,- });- expect(task).not.toHaveProperty("project");- expect(task).toMatchObject({- constraints: expect.arrayContaining([- expect.any(String),- expect.stringContaining("only through the configured webstudio MCP"),- expect.stringContaining("Never use a shell"),- expect.stringContaining("exactly once at the beginning"),- expect.any(String),- expect.stringContaining("Never use broad project reads"),- expect.any(String),- expect.stringContaining("meta.next"),- expect.stringContaining("terminal static audit"),- expect.stringContaining("Use one verify-page-responsive call"),- expect.stringContaining("Do not call list-breakpoints"),- ]),++ const authTask = createMinimalAgentTask(authenticatedPageFixture, target);+ expect(authTask).toMatchObject({+ schemaVersion: 2,+ fixtureId: authenticatedPageFixture.id,+ objective: authenticatedPageFixture.objective,+ guidance: {+ tool: "meta.guide",+ arguments: {+ workflow: "authenticated-page",+ },+ argumentBindings: { brief: "objective" },+ calls: 1,+ followReturnedWorkflow: true,+ },+ mcp: getCliInvocation(target),});- const authConstraints = task.constraints.join("\n");- expect(authConstraints).toContain("Do not call list-breakpoints");- expect(authConstraints).toContain("do not call meta.get-more-tools");- expect(authConstraints).toContain(- "Create exactly one scoped non-secret fixture variable"- );- expect(authConstraints).toContain("Do not call list-variables again");- expect(authConstraints).toContain("static audit");- expect(authConstraints).toContain(- "copy the objective field verbatim into brief"- );- expect(authConstraints).toContain("call inspect-auth-context exactly once");- expect(authConstraints).not.toContain(- "call get-project-settings, list-pages, list-resources, and list-variables"- );- expect(authConstraints).toContain("call create-page exactly once");- expect(authConstraints).toContain("copy recipe.createResourceInput");- expect(authConstraints).toContain("entire create-resource tool input");- expect(authConstraints).toContain(- '"value":{"type":"string","value":"signed-out"}'- );- expect(authConstraints).toContain(- "Call insert-fragment-verified only after all three succeed"- );- expect(authConstraints).toContain(- "Do not call insert-fragment or verify-bindings separately"- );- expect(authConstraints).toContain(- "call verify-page-responsive exactly once"- );- expect(authConstraints).toContain(- "Do not call preview.start, screenshot, screenshot.responsive, or audit separately"- );- expect(- createMinimalAgentTask(designInputFixture, {- kind: "source",- repositoryRoot: root,- })- ).toMatchObject({++ const designTask = createMinimalAgentTask(designInputFixture, target);+ expect(designTask).toMatchObject({+ schemaVersion: 2,+ fixtureId: designInputFixture.id,+ objective: designInputFixture.objective,designReference: {desktop: { viewport: { width: 1440, height: 900 } },mobile: { viewport: { width: 390, height: 844 } },},- constraints: expect.arrayContaining([- expect.stringContaining("exactly three attach-design-token calls"),- expect.stringContaining("Omit the optional position field"),- expect.stringContaining("exactly one batched update-styles call"),- expect.stringContaining('"breakpoint":"<returned-mobile'),- expect.stringContaining("never breakpointId"),- expect.stringContaining("Use this exact fragment verbatim"),- expect.stringContaining('ws:tag="footer"'),- expect.stringContaining("Do not call clone-instance"),- expect.stringContaining("set-text-content"),- expect.stringContaining("call inspect-design-context exactly once"),- expect.stringContaining("Do not call list-pages, list-breakpoints"),- expect.stringContaining("Attach all three tokens in one parallel"),- expect.stringContaining("Do not call get-page-by-path"),- expect.stringContaining("call insert-fragment-verified once"),- expect.stringContaining("pagePath /summer"),- expect.stringContaining("do not call list-instances"),- expect.stringContaining("Do not call meta.index"),- ]),+ guidance: {+ tool: "meta.guide",+ arguments: {+ workflow: "design-input",+ },+ argumentBindings: { brief: "objective" },+ },+ });++ const fontTask = createMinimalAgentTask(fontAssetsFixture, target);+ expect(fontTask.inputs).toEqual(fontAssetsFixture.agent.inputs);+ expect(fontTask.guidance).toEqual({+ tool: "meta.guide",+ arguments: {+ workflow: "font-assets",+ },+ argumentBindings: { brief: "objective" },+ calls: 1,+ followReturnedWorkflow: true,+ });+ const blogTask = createMinimalAgentTask(markdownBlogFixture, target);+ expect(blogTask.inputs).toEqual(markdownBlogFixture.agent.inputs);+ expect(blogTask.guidance).toEqual({+ tool: "meta.guide",+ arguments: {+ workflow: "markdown-blog",+ },+ argumentBindings: { brief: "objective" },+ calls: 1,+ followReturnedWorkflow: true,});- expect(- createMinimalAgentTask(fontAssetsFixture, {- kind: "source",- repositoryRoot: root,- }).constraints- ).toEqual(- expect.arrayContaining([- expect.stringContaining("Do not call meta.index, meta.get-more-tools"),- expect.stringContaining("Call meta.guide exactly once"),- expect.stringContaining("exactly one upload-assets call"),- expect.stringContaining("parallel tool-call batch"),- expect.stringContaining("verify-font-assets exactly once"),- expect.stringContaining(- 'audit exactly once with {"scopes":["assets"],"limit":10}'- ),- expect.stringContaining("Do not call refresh or get-asset separately"),- ])- );- const blogConstraints = createMinimalAgentTask(markdownBlogFixture, {- kind: "source",- repositoryRoot: root,- }).constraints.join("\n");- expect(blogConstraints).toContain("one asset folder named Blog");- expect(blogConstraints).toContain("one upload-assets call");- expect(blogConstraints).toContain("aurora-trails.md");- expect(blogConstraints).toContain("city-walks.md");- expect(blogConstraints).toContain("Do not create or upload companion JSON");- expect(blogConstraints).toContain('"format":"md"');- expect(blogConstraints).toContain("/blog/:slug");- expect(blogConstraints).toContain(- '"field":["properties","draft"],"operator":"ne"'- );- expect(blogConstraints).toContain(- '"value":{"type":"literal","value":true}'- );- expect(blogConstraints).toContain('"limit":{"type":"literal","value":20}');- expect(blogConstraints).toContain('"offset":{"type":"literal","value":0}');- expect(blogConstraints).toContain("Never call update-assets-resource");- expect(blogConstraints).toContain(- "Database size is part of the evaluated outcome"- );- expect(blogConstraints).toContain("one materialized overview");- expect(blogConstraints).toContain("zero embedded Markdown body bytes");- expect(blogConstraints).toContain("stale resource");- expect(blogConstraints).toContain(- '"fields":[["properties","title"],["properties","slug"]'- );- expect(blogConstraints).toContain('"mode":"none"');- expect(blogConstraints).toContain('"mode":"markdown-body-ref"');- expect(blogConstraints).not.toContain('["properties","body"]');- expect(blogConstraints).toContain('["properties","author"]');- expect(blogConstraints).toContain("collectionItem.properties.author.name");- expect(blogConstraints).toContain("collectionItem.content.text");- expect(blogConstraints).toContain("$.MarkdownEmbed");- expect(blogConstraints).toContain(- "call verify-page-responsive exactly twice"- );- expect(blogConstraints).toContain('"path":"/blog/aurora-trails"');- expect(blogConstraints).not.toContain(- "Use one verify-page-responsive call for all requested viewports"- );expect(getFixtureToolNames(markdownBlogFixture)).toEqual(["meta.guide","meta.get-more-tools","create-asset-folder","upload-assets","create-page",+ "validate-asset-query",+ "preview-asset-query","create-assets-resource","insert-collection",+ "insert-fragment",+ "update-page","verify-page-responsive",]);expect(getFixtureToolNames(markdownBlogFixture)).not.toContain(@@ -183,40 +102,49 @@ describe("high-impact agent runner", () => {const discoveryTask = createMinimalAgentTask(markdownReferencesDiscoveryFixture,- {- kind: "source",- repositoryRoot: root,- }- );- const discoveryPrompt = JSON.stringify(discoveryTask);- expect(discoveryPrompt).not.toContain("$ref");- expect(discoveryPrompt).not.toContain('"where"');- expect(discoveryPrompt).not.toContain("markdown-body-ref");- expect(discoveryPrompt).not.toContain("collectionItem");- expect(discoveryPrompt).toContain("Do not dry-run or plan mutations");- expect(discoveryPrompt).toContain("without reshaping its fields");- expect(discoveryPrompt).toContain(- "reuse that returned folder id for every uploaded article"- );- expect(discoveryPrompt).toContain(- "exactly two create-assets-resource calls"- );- expect(discoveryPrompt).toContain(- "wrap the one-result detail data as a zero-or-one-item array"+ target);- expect(discoveryPrompt).toContain(- 'exactly once with {\\"tools\\":[\\"create-assets-resource\\"]}'+ expect(discoveryTask.inputs).toEqual(+ markdownReferencesDiscoveryFixture.agent.inputs);+ expect(discoveryTask.guidance).toEqual({+ tool: "meta.guide",+ arguments: {+ workflow: "markdown-blog",+ },+ argumentBindings: { brief: "objective" },+ calls: 1,+ followReturnedWorkflow: true,+ });expect(getFixtureToolNames(markdownReferencesDiscoveryFixture)).toEqual(["meta.guide","meta.get-more-tools","create-asset-folder","upload-assets","create-page",+ "validate-asset-query",+ "preview-asset-query","create-assets-resource","insert-collection",+ "insert-fragment",+ "update-page","verify-page-responsive",]);++ for (const task of [+ authTask,+ designTask,+ fontTask,+ blogTask,+ discoveryTask,+ ]) {+ expect(task).not.toHaveProperty("project");+ expect(JSON.stringify(task).split(task.objective)).toHaveLength(2);+ expect(task.constraints.length).toBeGreaterThan(0);+ expect(+ task.constraints.every((constraint) => typeof constraint === "string")+ ).toBe(true);+ }});test("retains only a bounded privacy-safe result from a real process", async () => {@@ -245,6 +173,7 @@ describe("high-impact agent runner", () => {resultPath,provider: "test-provider",model: "test-model",+ reasoningEffort: "low",getToolCalls: () => [{name: "meta.guide",@@ -278,14 +207,19 @@ describe("high-impact agent runner", () => {],evaluate: async () => ({passed: true,- checks: { privacy: "passed", audit: "passed" },+ checks: {+ privacy: "passed",+ audit: "passed",+ designTokenApplied: "passed",+ },failures: [],}),});expect(result).toMatchObject({- schemaVersion: 2,- outcome: "failed",+ schemaVersion: 3,+ outcome: "passed",cli: "packaged",+ reasoningEffort: "low",metrics: {durationMs: expect.any(Number),tokens: {@@ -319,19 +253,33 @@ describe("high-impact agent runner", () => {},},callSequence: ["meta.guide", "attach-design-token", "audit"],- checks: { usageCaptured: "passed" },+ checks: {+ designTokenApplied: "passed",+ usageCaptured: "passed",+ },});const source = await readFile(resultPath, "utf8");expect(source).not.toMatch(/transcript|stdout|stderr|credential/i);expect(source).not.toContain(usageEvent);- expect(JSON.parse(await readFile(taskPath, "utf8"))).toMatchObject({+ const task = JSON.parse(await readFile(taskPath, "utf8"));+ expect(task).toMatchObject({+ schemaVersion: 2,fixtureId: "authenticated-page-v1",mcp: { args: ["mcp"] },- constraints: expect.arrayContaining([- expect.stringContaining("terminal static audit"),- expect.stringContaining("Use one verify-page-responsive call"),- ]),+ guidance: {+ tool: "meta.guide",+ arguments: {+ workflow: "authenticated-page",+ },+ argumentBindings: { brief: "objective" },+ calls: 1,+ followReturnedWorkflow: true,+ },});+ expect(task).not.toHaveProperty("project");+ expect(task.constraints).toEqual(+ expect.arrayContaining([expect.any(String)])+ );} finally {await rm(directory, { recursive: true, force: true });}diff --git a/packages/cli/evaluations/high-impact/agent-runner.ts b/packages/cli/evaluations/high-impact/agent-runner.tsindex 2066178fd8..d12c50cc44 100644--- a/packages/cli/evaluations/high-impact/agent-runner.ts+++ b/packages/cli/evaluations/high-impact/agent-runner.ts@@ -1,8 +1,9 @@+// Builds bounded high-impact agent tasks and turns their recorded MCP activity+// and final project state into versioned evaluation results.import { createHash } from "node:crypto";import { mkdir, readFile, writeFile } from "node:fs/promises";import { dirname, resolve } from "node:path";-import type { HighImpactFixture } from "./fixtures";-import { markdownBlogFixtureDocuments } from "./markdown-blog-fixture";+import type { EvaluationReasoningEffort, HighImpactFixture } from "./fixtures";import type {EvaluationToolCall,HighImpactEvaluationResult,@@ -25,13 +26,14 @@ export type AgentCliTarget =| { kind: "packaged"; executable: string };export type AgentEvaluationResult = {- schemaVersion: 2;+ schemaVersion: 3;kind: "high-impact-minimal-context-agent-evaluation-result";fixtureId: HighImpactFixture["id"];outcome: "passed" | "failed";cli: "source" | "packaged";provider: string;model: string;+ reasoningEffort: EvaluationReasoningEffort;commandSha256: string;exitCode: number;metrics: {@@ -76,8 +78,12 @@ const fixtureToolNames = {"create-asset-folder","upload-assets","create-page",+ "validate-asset-query",+ "preview-asset-query","create-assets-resource","insert-collection",+ "insert-fragment",+ "update-page","verify-page-responsive",],"markdown-references-discovery-v1": [@@ -86,30 +92,19 @@ const fixtureToolNames = {"create-asset-folder","upload-assets","create-page",+ "validate-asset-query",+ "preview-asset-query","create-assets-resource","insert-collection",+ "insert-fragment",+ "update-page","verify-page-responsive",],} as const satisfies Record<HighImpactFixture["id"], readonly string[]>;-const markdownBlogUploadInput = JSON.stringify({- assets: markdownBlogFixtureDocuments.map(({ name, format }) => ({- name,- type: "file",- format,- folderId: "<blog-folder-id>",- meta: {},- })),- assetsDir: ".webstudio/assets",-});-export const getFixtureToolNames = (fixture: HighImpactFixture) =>fixtureToolNames[fixture.id];-const forbiddenResultKeys =- /(?:prompt|transcript|stdout|stderr|secret|credential|payload)/i;-const forbiddenTokenKey = /token/i;-export const getCliInvocation = (target: AgentCliTarget) =>target.kind === "source"? {@@ -127,74 +122,38 @@ export const createMinimalAgentTask = (? (fixture as HighImpactFixture & { designReference: unknown }).designReference: undefined;+ const isMarkdownBlogFixture =+ fixture.id === "markdown-blog-v1" ||+ fixture.id === "markdown-references-discovery-v1";return {- schemaVersion: 1,+ schemaVersion: 2,fixtureId: fixture.id,objective: fixture.objective,...(designReference === undefined ? {} : { designReference }),+ ...(fixture.agent.inputs === undefined+ ? {}+ : { inputs: fixture.agent.inputs }),+ guidance: {+ tool: "meta.guide",+ arguments: fixture.agent.guidance,+ argumentBindings: { brief: "objective" },+ calls: 1,+ followReturnedWorkflow: true,+ },mcp: getCliInvocation(target),constraints: ["Use the configured Webstudio project and local CLI.","Call Webstudio operations only through the configured webstudio MCP tools exposed directly in your tool list. Never use a shell, terminal, exec tool, node, webstudio CLI shortcut, mcp single-op-call, or mcp run. Shell-invoked operations are invisible to this evaluation and make the result fail.",- fixture.id === "markdown-blog-v1"- ? 'Call meta.guide exactly once at the beginning with {"brief":"<objective>"}: copy the objective field verbatim into brief. Treat its response as reference only; the fixture sequence below is authoritative and supersedes every workflow or next-step suggestion. Do not call meta.guide again.'- : 'Call meta.guide exactly once at the beginning with {"brief":"<objective>"}: copy the objective field verbatim into brief, follow the returned workflow, and do not call meta.guide again.',+ "Run the guidance call exactly once before other tools, then follow its returned workflow and recipe.","Choose focused reads and semantic edits yourself.","Never use broad project reads: snapshot, components.list, or components.coverage-plan.","Do not persist or report credentials or private session data.","Treat mutation meta.next steps as required. Do not report completion until audit and requested visual evidence pass.",- ...(fixture.id === "markdown-blog-v1"- ? []- : [- "Treat the successful final audit and requested visual evidence as terminal; do not mutate, verify, restart preview, or capture more evidence afterward.",- "Finish all visual polish before evidence capture. Use one verify-page-responsive call for all requested viewports and the terminal static audit. After it begins, do not mutate, rediscover, restart preview, or capture more evidence.",- ]),- ...(fixture.id === "authenticated-page-v1"- ? [- "For this fixture, meta.guide already returns the required auth discovery and authoring tool schemas. Do not call list-breakpoints because responsive styling is not required, and do not call meta.get-more-tools or any other tool discovery operation. Create exactly one scoped non-secret fixture variable and keep the required state gallery expression-free. Do not call list-variables again after creating it.",- "After meta.guide, call inspect-auth-context exactly once. Do not call get-project-settings, list-pages, list-resources, or list-variables separately.",- 'After the context read, call create-page exactly once. Then call create-variable exactly once with {"name":"Account preview state","scopeInstanceId":"<returned-account-root-id>","value":{"type":"string","value":"signed-out"}}, substituting only the returned root id. Keep type exactly string; do not invent a state type. Then call create-resource exactly once: copy recipe.createResourceInput from meta.guide as the entire create-resource tool input and substitute only its account root id placeholder. Do not wrap that input in another resource object. Keep name, method, url, headers, and searchParams nested under resource; never move them to the top level. Do not set exposeAsDataSource separately, parallelize these mutations, or retry failed calls. Call insert-fragment-verified only after all three succeed, using their returned ids and pagePath /account. Do not call insert-fragment or verify-bindings separately.',- 'Then call verify-page-responsive exactly once with {"path":"/account","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. It captures both required screenshots and runs the terminal static audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately.',- ]- : []),- ...(fixture.id === "markdown-references-discovery-v1"- ? [- 'Follow the structured recipe returned by meta.guide. Pass each complete recipe object without reshaping its fields, changing only documented id placeholders. Call meta.get-more-tools exactly once with {"tools":["create-assets-resource"]}; do not search by brief or rediscover tools later.',- "Create the Blog folder before uploading, and reuse that returned folder id for every uploaded article and both resource queries. Create exactly two create-assets-resource calls and exactly two insert-collection calls: one of each per page. Bind the overview Collection to the many-result overview data. For the detail Collection, wrap the one-result detail data as a zero-or-one-item array and render that item. Do not create repair or replacement resources or Collections.",- "Call each mutation in the documented workflow once as a committed mutation. Do not dry-run or plan mutations. If any tool fails, stop immediately and report the failure; never retry it, repair it with repeated mutations, or continue to verification.",- "Do not call verify-page-responsive until both Collections succeed. Then call it exactly once for /blog and exactly once for /blog/aurora-trails. Stop without retrying if either verification fails.",- ]- : []),- ...(fixture.id === "design-input-v1"+ "Finish all visual polish before evidence capture. Run the planned verify-page-responsive calls consecutively, once per route with all requested viewports and that route's static audit. During this final verification sequence, make no mutations, discovery calls, preview restarts, or separate evidence calls. After the last planned route verification, make no more tool calls.",+ ...(isMarkdownBlogFixture? [- "For this fixture, do not call list-instances because the project has no representative existing page pattern. Do not call meta.index, meta.get-more-tools, or any other tool discovery operation because meta.guide and the MCP handshake already provide the required schemas.",- "After meta.guide, call inspect-design-context exactly once before mutation. Do not call list-pages, list-breakpoints, list-design-tokens, list-assets, or list-variables separately. Do not call get-page-by-path or repeat discovery. Call create-page once, then call insert-fragment-verified once with pagePath /summer before token or style mutations. Do not call insert-fragment or verify-bindings separately.",- "For this fixture, make exactly three attach-design-token calls: attach only the returned Brand / Coral, Text / Ink, and Type / Heading token ids once each to compatible inserted element instance ids. Attach all three tokens in one parallel tool-call batch. Omit the optional position field and do not attempt any other token attachment.",- 'After the early binding checkpoint, make exactly one batched update-styles call containing all remaining fixed styles. Its updates array must include an item shaped exactly {"instanceId":"<returned-main-or-section-instance-id>","property":"padding-left","value":{"type":"keyword","value":"16px"},"breakpoint":"<returned-mobile-breakpoint-id>"}, substituting only returned ids. The update-styles field is breakpoint, never breakpointId. Do not omit this mobile item; it proves responsive behavior is persisted before preview.',- 'Use this exact fragment verbatim in the single insert-fragment-verified call; do not add props, styles, expressions, or alternate components until after it commits: <ws.element ws:tag="header"><ws.element ws:tag="nav"><ws.element ws:tag="a">Northstar</ws.element><ws.element ws:tag="button">Menu</ws.element></ws.element></ws.element><ws.element ws:tag="main"><ws.element ws:tag="section"><ws.element ws:tag="h1">Find your latitude</ws.element><ws.element ws:tag="p">Plan a memorable summer escape.</ws.element><ws.element ws:tag="a">Explore trips</ws.element></ws.element><ws.element ws:tag="section"><ws.element ws:tag="h2">Featured trips</ws.element><ws.element ws:tag="article"><ws.element ws:tag="h3">Coastal escape</ws.element><ws.element ws:tag="p">A restorative journey by the sea.</ws.element></ws.element></ws.element></ws.element><ws.element ws:tag="footer"><ws.element ws:tag="p">Northstar travel</ws.element></ws.element>',- "The exact fragment already contains all required content. Do not call clone-instance, update-text, set-text-content, or any other content or structure mutation after insertion; only attach the three tokens and apply the one batched style update.",- 'After the style update, call verify-page-responsive exactly once with {"path":"/summer","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. It captures both required screenshots and runs the terminal static audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately.',- ]- : []),- ...(fixture.id === "font-assets-v1"- ? [- "Do not call meta.index, meta.get-more-tools, or any other tool discovery operation because meta.guide and the MCP handshake already provide the required schemas. Upload both supplied fonts together with exactly one upload-assets call; do not use upload-asset.",- 'After upload, update both font assets together in one parallel tool-call batch. For each returned asset id, use exactly {"assetId":"<returned-asset-id>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}. Keep family, style, and weight inside values.meta; do not send an empty values object. Make exactly two update-asset calls total and stop instead of retrying if either fails.',- 'After both updates, call verify-font-assets exactly once with both returned asset ids, then call audit exactly once with {"scopes":["assets"],"limit":10}. Do not call refresh or get-asset separately.',- ]- : []),- ...(fixture.id === "markdown-blog-v1"- ? [- 'For this fixture, call meta.get-more-tools exactly once immediately after meta.guide with {"brief":"create-assets-resource"} to load the complete schema for its complex query input. Do not call meta.index, list/get/preview asset tools, list pages, or any other discovery operation. Then create one asset folder named Blog and upload all supplied Markdown files together with exactly one upload-assets call using type file, format md, that returned folder id, empty metadata, and assetsDir .webstudio/assets. Do not create or upload companion JSON descriptors.',- `Use this exact upload-assets input, substituting only the returned Blog folder id for <blog-folder-id>: ${markdownBlogUploadInput}.`,- "For this fixture, the exact sequence below supersedes every workflow and mutation meta.next suggestion. After a listed call succeeds, continue immediately to the next listed call without inspecting, repairing, updating, or repeating its result. If any call fails, stop immediately; retries and repair mutations fail this evaluation. Never call update-assets-resource or any tool not explicitly listed in these fixture constraints.",- "Create exactly two pages: first /blog, then /blog/:slug. Do not call create-assets-resource while creating either page. Never call create-assets-resource without a query. After both page calls succeed, make exactly two create-assets-resource calls total using the complete inputs below; any omitted query or additional resource fails this evaluation.",- "Database size is part of the evaluated outcome. The final project must have exactly the two intended reachable Assets queries, one materialized overview, all five source documents included without truncation, and zero embedded Markdown body bytes. Do not leave a placeholder, preview copy, stale resource, or replacement data source in the project.",- 'First call create-assets-resource exactly once with this complete overview input, substituting the returned overview root id and Blog folder id: {"name":"Published posts","scopeInstanceId":"<overview-root-id>","dataSourceName":"posts","query":{"result":"many","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["folderId"],"operator":"eq","value":{"type":"literal","value":"<blog-folder-id>"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"},{"field":["id"],"direction":"asc"}],"limit":{"type":"literal","value":20},"offset":{"type":"literal","value":0},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","author"],["properties","excerpt"]]},"content":{"mode":"none"}}}. Keep literal wrappers and field-path arrays unchanged.',- 'Then call create-assets-resource exactly once with this complete detail input, substituting the returned detail root id and the same Blog folder id: {"name":"Post by slug","scopeInstanceId":"<detail-root-id>","dataSourceName":"post","query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["folderId"],"operator":"eq","value":{"type":"literal","value":"<blog-folder-id>"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","author"]]},"content":{"mode":"markdown-body-ref"}}}. Do not call create-assets-resource again.',- 'After both resources succeed, call insert-collection exactly once on the overview root with {"parentInstanceId":"<overview-root-id>","data":{"type":"expression","value":"posts.data"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h2\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><ws.element ws:tag=\"p\">{expression`collectionItem.properties.excerpt ?? \\"\\"`}</ws.element><ws.element ws:tag=\"p\">By {expression`collectionItem.properties.author.name`}</ws.element><ws.element ws:tag=\"time\">{expression`collectionItem.properties.publishedAt ?? \\"\\"`}</ws.element><ws.element ws:tag=\"a\" href={expression`\\"/blog/\\" + collectionItem.properties.slug`}>Read article</ws.element></ws.element>"}, substituting only the returned overview root id.',- 'Then call insert-collection exactly once on the detail root with {"parentInstanceId":"<detail-root-id>","data":{"type":"expression","value":"post.data == null ? [] : [post.data]"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h1\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><ws.element ws:tag=\"p\">By {expression`collectionItem.properties.author.name`}</ws.element><$.MarkdownEmbed code={expression`collectionItem.content.text`} /></ws.element>"}, substituting only the returned detail root id. insert-collection validates and persists its bindings atomically, so do not call verify-bindings or perform any repair afterward.',- 'After both Collections succeed, call verify-page-responsive exactly twice: first with {"path":"/blog","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}, then with {"path":"/blog/aurora-trails","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. Do not mutate, rediscover, restart preview, or capture separate screenshots or audits after verification begins. If either verification fails, stop immediately without retrying or changing the project.',+ "Treat the supplied asset manifest as input inventory. Derive operation payloads from the MCP schemas and the markdown-blog guide instead of a fixture-specific answer.",+ "Substitute returned IDs only for the documented placeholders in the guide's recipe. Call each mutation once as a committed mutation; if one fails, stop and report it instead of retrying or inventing a repair workflow.",]: []),],@@ -202,42 +161,19 @@ export const createMinimalAgentTask = (};const assertBoundedResult = (result: AgentEvaluationResult) => {+ const identifiers = [+ result.provider,+ result.model,+ ...result.callSequence,+ ...Object.keys(result.checks),+ ];if (- boundedIdentifierPattern.test(result.provider) === false ||- boundedIdentifierPattern.test(result.model) === false+ identifiers.some(+ (identifier) => boundedIdentifierPattern.test(identifier) === false+ )) {- throw new Error("Agent provider and model must be bounded identifiers.");+ throw new Error("Agent result contains an invalid identifier.");}- const visit = (value: unknown, path: string[] = []): void => {- if (typeof value !== "object" || value === null) {- return;- }- for (const [key, child] of Object.entries(value)) {- const isAggregateUsage =- path.length === 1 && path[0] === "metrics" && key === "tokens";- const isMetricIdentifier =- path.length === 3 &&- path[0] === "metrics" &&- path[1] === "toolCalls" &&- [- "failuresByTool",- "failuresByCode",- "issuesByCode",- "issuesByPath",- "durationsByTool",- "responseBytesByTool",- ].includes(path[2]);- if (- isMetricIdentifier === false &&- (forbiddenResultKeys.test(key) ||- (forbiddenTokenKey.test(key) && isAggregateUsage === false))- ) {- throw new Error(`Agent result contains forbidden field ${key}.`);- }- visit(child, [...path, key]);- }- };- visit(result);if (JSON.stringify(result).length > 12_000) {throw new Error("Agent result exceeds the bounded artifact limit.");}@@ -252,6 +188,7 @@ export const runHighImpactAgentEvaluation = async ({resultPath,provider,model,+ reasoningEffort,getToolCalls,getCatalogObservations,evaluate,@@ -267,6 +204,7 @@ export const runHighImpactAgentEvaluation = async ({resultPath: string;provider: string;model: string;+ reasoningEffort: EvaluationReasoningEffort;getToolCalls: () => EvaluationToolCall[];getCatalogObservations: () => McpCatalogObservation[];evaluate: () => Promise<HighImpactEvaluationResult>;@@ -310,20 +248,17 @@ export const runHighImpactAgentEvaluation = async ({};const toolCallMetrics = getMcpEvaluationMetrics(toolCalls);const result: AgentEvaluationResult = {- schemaVersion: 2,+ schemaVersion: 3,kind: "high-impact-minimal-context-agent-evaluation-result",fixtureId: fixture.id,outcome:- execution.exitCode === 0 &&- evaluation.passed &&- usage !== undefined &&- toolCallMetrics.failed === 0 &&- toolCallMetrics.retries === 0+ execution.exitCode === 0 && evaluation.passed && usage !== undefined? "passed": "failed",cli: target.kind,provider,model,+ reasoningEffort,commandSha256: createHash("sha256").update(agentCommand).digest("hex"),exitCode: execution.exitCode,metrics: {diff --git a/packages/cli/evaluations/high-impact/artifacts.ts b/packages/cli/evaluations/high-impact/artifacts.tsindex 4ba5d8d014..ca80d3f0c2 100644--- a/packages/cli/evaluations/high-impact/artifacts.ts+++ b/packages/cli/evaluations/high-impact/artifacts.ts@@ -1,3 +1,4 @@+// Collects bounded rendered evidence without retaining page contents or logs.import { readFile, readdir } from "node:fs/promises";import { join, relative } from "node:path";import type { EvaluationArtifact } from "./validate";diff --git a/packages/cli/evaluations/high-impact/evaluation-regression.test.ts b/packages/cli/evaluations/high-impact/evaluation-regression.test.tsindex 1d3ec22191..c8dcf6a6c0 100644--- a/packages/cli/evaluations/high-impact/evaluation-regression.test.ts+++ b/packages/cli/evaluations/high-impact/evaluation-regression.test.ts@@ -10,13 +10,14 @@ import {const createResult = (values: Partial<AgentEvaluationResult> = {}): AgentEvaluationResult => ({- schemaVersion: 2,+ schemaVersion: 3,kind: "high-impact-minimal-context-agent-evaluation-result",fixtureId: "authenticated-page-v1",outcome: "passed",cli: "source",provider: "openai",model: "test-model",+ reasoningEffort: "low",commandSha256: "a".repeat(64),exitCode: 0,metrics: {@@ -138,6 +139,12 @@ describe("evaluation regression comparison", () => {baseline)).toMatchObject({ status: "incompatible", deltas: [], regressions: [] });+ expect(+ compareEvaluationResult(+ createResult({ reasoningEffort: "medium" }),+ baseline+ )+ ).toMatchObject({ status: "incompatible", deltas: [], regressions: [] });expect(compareEvaluationResult(createResult(), undefined)).toMatchObject({status: "missing",deltas: [],@@ -410,5 +417,27 @@ describe("evaluation regression comparison", () => {[])).toBe(true);+ expect(+ isAggregateTokenBaselineNonRegressed(+ [withTokens("authenticated-page-v1", 1_000)],+ [+ {+ ...withTokens("authenticated-page-v1", 1),+ reasoningEffort: "medium",+ },+ ]+ )+ ).toBe(true);+ expect(+ isAggregateTokenBaselineNonRegressed(+ [withTokens("authenticated-page-v1", 1_000)],+ [+ {+ ...withTokens("authenticated-page-v1", 1),+ schemaVersion: 2,+ } as unknown as AgentEvaluationResult,+ ]+ )+ ).toBe(true);});});diff --git a/packages/cli/evaluations/high-impact/evaluation-regression.ts b/packages/cli/evaluations/high-impact/evaluation-regression.tsindex bd054ecb41..c461d299f2 100644--- a/packages/cli/evaluations/high-impact/evaluation-regression.ts+++ b/packages/cli/evaluations/high-impact/evaluation-regression.ts@@ -1,3 +1,5 @@+// Compares versioned evaluation results with compatible baselines and applies+// the suite's explicit quality and token-regression acceptance rules.import type { AgentEvaluationResult } from "./agent-runner";export type EvaluationMetricDelta = {@@ -61,6 +63,17 @@ export const shouldUpdateEvaluationBaselines = ({comparisonsPassed &&aggregateTokensPassed;+const isCompatibleBaseline = (+ current: AgentEvaluationResult,+ baseline: AgentEvaluationResult+) =>+ current.schemaVersion === baseline.schemaVersion &&+ current.fixtureId === baseline.fixtureId &&+ current.cli === baseline.cli &&+ current.provider === baseline.provider &&+ current.model === baseline.model &&+ current.reasoningEffort === baseline.reasoningEffort;+export const isAggregateTokenBaselineNonRegressed = (current: readonly AgentEvaluationResult[],baselines: readonly AgentEvaluationResult[]@@ -73,7 +86,10 @@ export const isAggregateTokenBaselineNonRegressed = (let compared = 0;for (const result of current) {const baseline = baselineByFixture.get(result.fixtureId);- if (baseline === undefined) {+ if (+ baseline === undefined ||+ isCompatibleBaseline(result, baseline) === false+ ) {continue;}const currentTokens = result.metrics.tokens?.output;@@ -118,16 +134,6 @@ const getNumericMetrics = (return metrics;};-const isCompatibleBaseline = (- current: AgentEvaluationResult,- baseline: AgentEvaluationResult-) =>- current.schemaVersion === baseline.schemaVersion &&- current.fixtureId === baseline.fixtureId &&- current.cli === baseline.cli &&- current.provider === baseline.provider &&- current.model === baseline.model;-export const compareEvaluationResult = (current: AgentEvaluationResult,baseline: AgentEvaluationResult | undefineddiff --git a/packages/cli/evaluations/high-impact/evaluation-trace-contract.test.ts b/packages/cli/evaluations/high-impact/evaluation-trace-contract.test.tsnew file mode 100644index 0000000000..45e04bbb38--- /dev/null+++ b/packages/cli/evaluations/high-impact/evaluation-trace-contract.test.ts@@ -0,0 +1,81 @@+// Verifies the privacy-preserving request fingerprints consumed by evaluation+// outcome validation, including strict shapes and stable object-key ordering.+import { describe, expect, test } from "vitest";+import {+ getAssetQueryContractFingerprints,+ getPageSettingsContractFingerprint,+} from "./evaluation-trace-contract";++const createQuery = (value: unknown) => ({+ where: {+ all: [+ {+ field: ["properties", "slug"],+ operator: "eq",+ value,+ },+ ],+ },+ output: { mode: "base", includeMetadata: true },+});++describe("evaluation trace contracts", () => {+ test("fingerprints asset queries independently of object key order", () => {+ const query = createQuery({ first: "one", second: "two" });+ const reordered = createQuery({ second: "two", first: "one" });++ expect(getAssetQueryContractFingerprints(reordered)).toEqual(+ getAssetQueryContractFingerprints(query)+ );+ });++ test("separates exact query values from the query shape", () => {+ const first = getAssetQueryContractFingerprints(createQuery("first-post"));+ const second = getAssetQueryContractFingerprints(+ createQuery("second-post")+ );++ expect(first).toBeDefined();+ expect(second).toBeDefined();+ expect(first?.sha256).not.toBe(second?.sha256);+ expect(first?.shapeSha256).toBe(second?.shapeSha256);+ });++ test("rejects invalid asset queries", () => {+ expect(+ getAssetQueryContractFingerprints({ where: { unknown: [] } })+ ).toBeUndefined();+ });++ test("accepts only the exact page settings contract", () => {+ const input = {+ pageId: "blog-detail",+ values: {+ title: "Article",+ meta: {+ description: "Description",+ socialImageUrl: "/social.png",+ status: "200",+ },+ },+ };+ const reordered = {+ values: {+ meta: {+ status: input.values.meta.status,+ socialImageUrl: input.values.meta.socialImageUrl,+ description: input.values.meta.description,+ },+ title: input.values.title,+ },+ pageId: input.pageId,+ };++ expect(getPageSettingsContractFingerprint(reordered)).toBe(+ getPageSettingsContractFingerprint(input)+ );+ expect(+ getPageSettingsContractFingerprint({ ...input, unexpected: true })+ ).toBeUndefined();+ });+});diff --git a/packages/cli/evaluations/high-impact/evaluation-trace-contract.ts b/packages/cli/evaluations/high-impact/evaluation-trace-contract.tsnew file mode 100644index 0000000000..ae1651755c--- /dev/null+++ b/packages/cli/evaluations/high-impact/evaluation-trace-contract.ts@@ -0,0 +1,86 @@+// Fingerprints the small request contracts that outcome validation must+// correlate without retaining arbitrary agent payloads in the MCP trace.+import { createHash } from "node:crypto";+import { assetQuery } from "@webstudio-is/content-engine";+import { serializeJsonDeterministically } from "@webstudio-is/content-engine/compiler";+import { mapQueryWhere } from "@webstudio-is/query-builder/runtime";++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null && Array.isArray(value) === false;++const fingerprint = (domain: string, value: unknown) =>+ createHash("sha256")+ .update(domain)+ .update("\0")+ .update(serializeJsonDeterministically(value))+ .digest("hex");++const getValueShape = (value: unknown) => {+ if (value === null) {+ return "null";+ }+ if (Array.isArray(value)) {+ return "array";+ }+ return typeof value;+};++export const getAssetQueryContractFingerprints = (value: unknown) => {+ const parsed = assetQuery.safeParse(value);+ if (parsed.success === false) {+ return;+ }+ const shape = {+ ...parsed.data,+ where: mapQueryWhere(parsed.data.where, (condition) => ({+ ...condition,+ value: getValueShape(condition.value),+ })),+ };+ return {+ sha256: fingerprint("asset-query", parsed.data),+ shapeSha256: fingerprint("asset-query-shape", shape),+ };+};++const hasExactKeys = (value: Record<string, unknown>, keys: string[]) => {+ const actual = Object.keys(value).sort();+ const expected = [...keys].sort();+ return (+ actual.length === expected.length &&+ actual.every((key, index) => key === expected[index])+ );+};++export const getPageSettingsContractFingerprint = (value: unknown) => {+ if (+ isRecord(value) === false ||+ hasExactKeys(value, ["pageId", "values"]) === false ||+ typeof value.pageId !== "string" ||+ isRecord(value.values) === false ||+ hasExactKeys(value.values, ["title", "meta"]) === false ||+ typeof value.values.title !== "string" ||+ isRecord(value.values.meta) === false ||+ hasExactKeys(value.values.meta, [+ "description",+ "socialImageUrl",+ "status",+ ]) === false ||+ typeof value.values.meta.description !== "string" ||+ typeof value.values.meta.socialImageUrl !== "string" ||+ typeof value.values.meta.status !== "string"+ ) {+ return;+ }+ return fingerprint("page-settings", {+ pageId: value.pageId,+ values: {+ title: value.values.title,+ meta: {+ description: value.values.meta.description,+ socialImageUrl: value.values.meta.socialImageUrl,+ status: value.values.meta.status,+ },+ },+ });+};diff --git a/packages/cli/evaluations/high-impact/fixture-api.test.ts b/packages/cli/evaluations/high-impact/fixture-api.test.tsindex fc4388b1f6..55aff4c6f6 100644--- a/packages/cli/evaluations/high-impact/fixture-api.test.ts+++ b/packages/cli/evaluations/high-impact/fixture-api.test.ts@@ -23,10 +23,52 @@ import {markdownBlogFixtureDocuments,writeMarkdownBlogFixtureFiles,} from "./markdown-blog-fixture";+import { evaluateHighImpactOutcome } from "./validate";const execFileAsync = promisify(execFile);describe("high-impact fixture API", () => {+ test("keeps an untouched fixture page unchanged after persistence", async () => {+ const fixtureApi = await startHighImpactFixtureApi(fontAssetsFixture);+ try {+ const result = evaluateHighImpactOutcome({+ fixture: fontAssetsFixture,+ project: fixtureApi.getProject(),+ toolCalls: [],+ });++ expect(result.checks.pageUnchanged).toBe("passed");+ } finally {+ await fixtureApi.close();+ }+ });++ test("round-trips persisted page title and metadata", async () => {+ const fixture = structuredClone(authenticatedPageFixture);+ fixture.project.pages[0] = {+ ...fixture.project.pages[0]!,+ title: 'account.data.name ?? "Account"',+ meta: {+ description: 'account.data.description ?? ""',+ socialImageUrl: 'account.data.image.src ?? ""',+ status: "account.data ? 200 : 404",+ },+ };+ const fixtureApi = await startHighImpactFixtureApi(fixture);+ try {+ expect(fixtureApi.getProject().pages[0]).toMatchObject({+ title: 'account.data.name ?? "Account"',+ meta: {+ description: 'account.data.description ?? ""',+ socialImageUrl: 'account.data.image.src ?? ""',+ status: "account.data ? 200 : 404",+ },+ });+ } finally {+ await fixtureApi.close();+ }+ });+test("links and reads through the source CLI without persisting credentials", async () => {const fixtureApi = await startHighImpactFixtureApi(authenticatedPageFixture@@ -206,6 +248,50 @@ describe("high-impact fixture API", () => {)));+ const query = {+ result: "one",+ where: {+ all: [+ { field: ["extension"], operator: "eq", value: "md" },+ {+ field: ["folderId"],+ operator: "eq",+ value: folderId,+ },+ {+ field: ["properties", "slug"],+ operator: "eq",+ value: "aurora-trails",+ },+ ],+ },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["properties", "title"]],+ },+ content: { mode: "markdown-body-ref" },+ };+ await expect(+ run("validate-asset-query", { query })+ ).resolves.toMatchObject({+ ok: true,+ data: { valid: true, filterCount: 3 },+ });+ await expect(+ run("preview-asset-query", { query })+ ).resolves.toMatchObject({+ ok: true,+ data: {+ data: {+ item: {+ properties: { title: "Aurora trails" },+ content: { text: expect.stringContaining("# Aurora trails") },+ },+ totalCount: 1,+ },+ },+ });await expect(readFile(join(projectDirectory, ".webstudio/assets/aurora-trails.md"),diff --git a/packages/cli/evaluations/high-impact/fixture-api.ts b/packages/cli/evaluations/high-impact/fixture-api.tsindex 45d2fd4c87..bd3f4a3f47 100644--- a/packages/cli/evaluations/high-impact/fixture-api.ts+++ b/packages/cli/evaluations/high-impact/fixture-api.ts@@ -1,4 +1,14 @@+// 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 {+ executeAssetQuery,+ getAssetQueryWhereMetrics,+ parseMarkdownDocumentSource,+ validateAssetQuery,+ type AssetQueryInput,+ type ContentDatabaseDocument,+} 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";@@ -30,8 +40,8 @@ const createPersistedPages = (project: EvaluationProject) => ({rootFolderId: "root-folder",pages: project.pages.map((page) => ({...page,- title: page.name,- meta: {},+ title: page.title ?? page.name,+ meta: page.meta ?? {},})),folders: [{@@ -51,6 +61,8 @@ const stateToProject = (state: BuilderState): EvaluationProject => ({name: page.name,path: page.path,rootInstanceId: page.rootInstanceId,+ title: page.title,+ meta: page.meta,})),instances: Array.from(state.instances?.values() ?? []@@ -124,7 +136,79 @@ export const startHighImpactFixtureApi = async (let version = initialVersion;let generatedId = 0;const calls: EvaluationToolCall[] = [];+ const uploadedFileContents = new Map<string, Uint8Array>();let origin = "";+ const validateFixtureAssetQuery = (query: unknown) => {+ const validation = validateAssetQuery({ query });+ if (validation.success === false) {+ throw Object.assign(new Error("Invalid fixture asset query."), {+ code: "INVALID_INPUT",+ issues: validation.issues,+ });+ }+ return validation;+ };+ const loadFixtureDocuments = async () => {+ const documents: ContentDatabaseDocument[] = [];+ for (const asset of state.assets?.values() ?? []) {+ if (asset.type !== "file" || asset.format !== "md") {+ continue;+ }+ const content = uploadedFileContents.get(asset.id);+ if (content === undefined) {+ continue;+ }+ const document = await parseMarkdownDocumentSource({ source: content });+ documents.push({+ _id: asset.id,+ _type: "asset.file",+ name: asset.name,+ path: asset.name,+ key: asset.id,+ folderId: asset.folderId,+ extension: asset.format,+ mimeType: "text/markdown",+ size: asset.size,+ createdAt: asset.createdAt,+ revision: `fixture-${asset.id}`,+ contentRef: asset.id,+ properties: structuredClone(+ document.frontmatter+ ) as ContentDatabaseDocument["properties"],+ });+ }+ return documents;+ };+ const readFixtureContent = async (contentRef: string) => {+ const content = uploadedFileContents.get(contentRef);+ if (content === undefined) {+ throw new Error(`Fixture content not found: ${contentRef}`);+ }+ return {+ data: (async function* () {+ yield content;+ })(),+ contentLength: content.byteLength,+ };+ };+ const runFixtureAssetQuery = async <Result>({+ name,+ input,+ execute,+ }: {+ name: "validate-asset-query" | "preview-asset-query";+ input: Record<string, unknown>;+ execute: () => Promise<Result> | Result;+ }) => {+ const call: EvaluationToolCall = { name, arguments: input };+ calls.push(call);+ try {+ return await execute();+ } catch (error) {+ call.isError = true;+ throw error;+ }+ };const fixtureApi = await startRuntimeFixtureApi(async ({ request, response, pathname, operationPath, readInput }) => {let data: unknown;@@ -173,6 +257,7 @@ export const startHighImpactFixtureApi = async (),}: { ...assetBase, type, format: formatValue, meta: {} };+ uploadedFileContents.set(asset.id, body);calls.push({name: "upload-asset",arguments: {@@ -245,6 +330,56 @@ export const startHighImpactFixtureApi = async (buildId,version,});+ } else if (operationPath === "assetQueries.validate") {+ const input = (await readInput()) as Record<string, unknown>;+ data = await runFixtureAssetQuery({+ name: "validate-asset-query",+ input,+ execute: () => {+ const validation = validateFixtureAssetQuery(input.query);+ return {+ valid: true as const,+ referencedFieldPaths: validation.referencedFieldPaths,+ filterCount: getAssetQueryWhereMetrics(validation.query.where)+ .filters,+ sortCount: validation.query.sort.length,+ warnings: validation.warnings,+ issues: validation.issues,+ };+ },+ });+ } else if (operationPath === "assetQueries.preview") {+ const input = (await readInput()) as Record<string, unknown>;+ data = await runFixtureAssetQuery({+ name: "preview-asset-query",+ input,+ execute: async () => {+ const validation = validateFixtureAssetQuery(input.query);+ const documents = await loadFixtureDocuments();+ const result = await executeAssetQuery({+ query: validation.query as AssetQueryInput,+ documents,+ read: readFixtureContent,+ });+ const usedBytes = Buffer.byteLength(JSON.stringify(documents));+ const diagnostics = {+ usedBytes,+ maxBytes: 512_000,+ unboundedBytes: usedBytes,+ includedDocumentCount: documents.length,+ omittedDocumentCount: 0,+ truncated: false,+ };+ return {+ data: result,+ __diagnostics__: {+ scope: "query-preview" as const,+ query: diagnostics,+ database: diagnostics,+ },+ };+ },+ });} else if (operationPath === "projects.permissions" ||operationPath === ""diff --git a/packages/cli/evaluations/high-impact/fixtures.ts b/packages/cli/evaluations/high-impact/fixtures.tsindex bc21c48284..fac47403f6 100644--- a/packages/cli/evaluations/high-impact/fixtures.ts+++ b/packages/cli/evaluations/high-impact/fixtures.ts@@ -1,12 +1,48 @@-import type { Asset, AssetFolder } from "@webstudio-is/sdk";-import { fontAssetFixtureFiles } from "./font-assets-fixture";-import { markdownBlogFixtureArticles } from "./markdown-blog-fixture";+// 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 {+ fontAssetFixtureFiles,+ fontAssetFixtureUploadMeta,+} from "./font-assets-fixture";+import {+ markdownBlogFixtureArticles,+ markdownBlogFixtureDocuments,+} from "./markdown-blog-fixture";++export type EvaluationReasoningEffort = "low" | "medium" | "high";++type EvaluationAgentInputs = {+ assets: {+ directory: string;+ files: Array<{+ name: string;+ type: "file" | "font";+ format: string;+ meta: Record<string, unknown>;+ }>;+ };+};++type EvaluationAgentConfig = {+ reasoningEffort: EvaluationReasoningEffort;+ guidance: {+ workflow:+ | "authenticated-page"+ | "design-input"+ | "font-assets"+ | "markdown-blog";+ };+ inputs?: EvaluationAgentInputs;+};export type EvaluationPage = {id: string;name: string;path: string;rootInstanceId: string;+ title?: Page["title"];+ meta?: Page["meta"];};export type EvaluationInstance = {@@ -66,6 +102,7 @@ export type HighImpactFixture = {| "markdown-references-discovery-v1";objective: string;project: EvaluationProject;+ agent: EvaluationAgentConfig;};const homePage: EvaluationPage = {@@ -73,6 +110,8 @@ const homePage: EvaluationPage = {name: "Home",path: "",rootInstanceId: "home-root",+ title: "Home",+ meta: {},};const emptyProject = (): EvaluationProject => ({@@ -106,10 +145,26 @@ const emptyProject = (): EvaluationProject => ({styles: [],});+const markdownBlogAgentInputs: EvaluationAgentInputs = {+ assets: {+ directory: ".webstudio/assets",+ files: markdownBlogFixtureDocuments.map(({ name, format }) => ({+ name,+ type: "file",+ format,+ meta: {},+ })),+ },+};+export const authenticatedPageFixture: HighImpactFixture = {id: "authenticated-page-v1",objective:"Add an editable /account page using the project's existing authentication convention. Cover signed-out, loading, signed-in, and failed-auth UI states, then audit and visually verify the states. Do not persist credentials or private session data.",+ agent: {+ reasoningEffort: "low",+ guidance: { workflow: "authenticated-page" },+ },project: {...emptyProject(),resources: [@@ -150,6 +205,10 @@ export const designInputFixture: HighImpactFixture & {id: "design-input-v1",objective:"Build an editable /summer page from the supplied desktop and mobile design reference. Preserve and reuse the existing design system, implement responsive behavior with the project's breakpoints, inspect desktop/mobile screenshots, then run a static route audit without duplicating the rendered captures.",+ agent: {+ reasoningEffort: "high",+ guidance: { workflow: "design-input" },+ },project: {...emptyProject(),styleSources: [@@ -215,18 +274,43 @@ export const designInputFixture: HighImpactFixture & {export const fontAssetsFixture: HighImpactFixture = {id: "font-assets-v1",objective: `Upload ${fontAssetFixtureFiles.map(({ name }) => name).join(" and ")} from .webstudio/assets as font assets, initially using family Imported Rajdhani, style normal, and weight 400. Then use update-asset exactly once on each uploaded asset to set values.meta to family Rajdhani, style normal, and weight 600. Verify both returned asset ids with verify-font-assets, run the audit, and do not change the page.`,+ agent: {+ reasoningEffort: "low",+ guidance: { workflow: "font-assets" },+ inputs: {+ assets: {+ directory: ".webstudio/assets",+ files: fontAssetFixtureFiles.map(({ name, format }) => ({+ name,+ type: "font",+ format,+ meta: fontAssetFixtureUploadMeta,+ })),+ },+ },+ },project: emptyProject(),};export const markdownBlogFixture: HighImpactFixture = {id: "markdown-blog-v1",- objective: `Upload the ${markdownBlogFixtureArticles.length} provided Markdown articles from .webstudio/assets into one Blog asset folder. Build an editable, size-optimal blog overview at /blog and a dynamic detail page at /blog/:slug using exactly one fully configured scoped Assets resource per page, Collections, and Markdown Embed. Include the complete structured query in each initial resource creation; never create a default, placeholder, duplicate, preview copy, or repair replacement. Both queries must read the Markdown files directly. The overview query must be fully static and bounded, exclude drafts, sort newest first with a deterministic ID tie-breaker, select only the rendered title, slug, excerpt, publication date, and author frontmatter, and load no bodies so it can be materialized. The detail query must use only the dynamic slug, select only rendered metadata, and return one Markdown body without embedding it in the published database. The compiled database must include all articles without truncation, no embedded bodies, and only the intended materialized overview. Render the author name on both pages. Verify both /blog and /blog/aurora-trails at desktop and mobile sizes.`,+ objective: `Upload the ${markdownBlogFixtureArticles.length} provided Markdown articles from .webstudio/assets into one Blog asset folder. Build an editable, size-optimal blog overview at /blog and a dynamic detail page at /blog/:slug using exactly one fully configured scoped Assets resource per page, one overview Collection, and a directly bound detail Markdown Embed. Include the complete structured query in each initial resource creation; never create a default, placeholder, duplicate, preview copy, or repair replacement. Both queries must read the Markdown files directly. The overview query must be fully static and bounded, exclude drafts, sort newest first with a deterministic ID tie-breaker, select only the rendered title, slug, excerpt, publication date, and author frontmatter, and load no bodies so it can be materialized. The detail query must use only the dynamic slug, select only rendered metadata, and return one Markdown body without embedding it in the published database. The compiled database must include all articles without truncation, no embedded bodies, and only the intended materialized overview. Render the author name on both pages. Verify both /blog and /blog/aurora-trails at desktop and mobile sizes.`,+ agent: {+ reasoningEffort: "medium",+ guidance: { workflow: "markdown-blog" },+ inputs: markdownBlogAgentInputs,+ },project: emptyProject(),};export const markdownReferencesDiscoveryFixture: HighImpactFixture = {id: "markdown-references-discovery-v1",objective: `Upload the supplied ${markdownBlogFixtureArticles.map(({ name }) => name).join(", ")} Markdown articles from .webstudio/assets. Build an editable blog overview at /blog and one dynamic article page at /blog/:slug. Query the Markdown files directly so draft articles are excluded, posts are ordered newest first, each post displays its frontmatter author, and only the selected Markdown body is fetched from Asset storage without being embedded in the published database. Verify the overview and /blog/aurora-trails at desktop and mobile sizes. Discover the supported workflow and data shapes from Webstudio MCP guidance.`,+ agent: {+ reasoningEffort: "medium",+ guidance: { workflow: "markdown-blog" },+ inputs: markdownBlogAgentInputs,+ },project: emptyProject(),};diff --git a/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts b/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.tsindex 584e15f293..9e2a1b7f6a 100644--- a/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts+++ b/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts@@ -8,6 +8,16 @@ import {} from "./mcp-trace-proxy";describe("bounded MCP tracing", () => {+ test("rejects an unbounded tool name", () => {+ expect(+ getMcpTraceRequest({+ id: 1,+ method: "tools/call",+ params: { name: "x".repeat(129) },+ })+ ).toBeUndefined();+ });+test("measures the bounded tools catalog payload", () => {expect(getMcpCatalogObservation({@@ -109,6 +119,73 @@ describe("bounded MCP tracing", () => {).not.toMatchObject({ call: { arguments: { path: expect.any(String) } } });});+ test("retains fingerprints instead of Markdown query and page-setting payloads", () => {+ const queryRequest = getMcpTraceRequest({+ id: 11,+ method: "tools/call",+ params: {+ name: "validate-asset-query",+ arguments: {+ query: {+ result: "one",+ where: {+ all: [+ {+ field: ["properties", "slug"],+ operator: "eq",+ value: "system.params.slug",+ },+ ],+ },+ content: { mode: "markdown-body-ref" },+ },+ },+ },+ });+ const pageRequest = getMcpTraceRequest(+ {+ id: 12,+ method: "tools/call",+ params: {+ name: "update-page",+ arguments: {+ pageId: "detail-page",+ values: {+ title: 'post.data.properties.title ?? "Article"',+ meta: {+ description: 'post.data.properties.excerpt ?? ""',+ socialImageUrl: 'post.data.properties.featureImage.src ?? ""',+ status: "post.data ? 200 : 404",+ },+ },+ },+ },+ },+ 0,+ new Set(["update-page"])+ );++ expect(queryRequest).toMatchObject({+ call: {+ arguments: {+ assetQuerySha256: expect.stringMatching(/^[a-f0-9]{64}$/),+ assetQueryShapeSha256: expect.stringMatching(/^[a-f0-9]{64}$/),+ },+ },+ });+ expect(pageRequest).toMatchObject({+ call: {+ arguments: {+ pageSettingsSha256: expect.stringMatching(/^[a-f0-9]{64}$/),+ },+ },+ });+ const retained = JSON.stringify([queryRequest, pageRequest]);+ expect(retained).not.toContain("system.params.slug");+ expect(retained).not.toContain("post.data.properties");+ expect(retained).not.toContain("detail-page");+ });+test("records confirmation flow without retaining its token", () => {expect(getMcpTraceRequest(diff --git a/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts b/packages/cli/evaluations/high-impact/mcp-trace-proxy.tsindex d7d9e12dda..5d4f2fd2f2 100644--- a/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts+++ b/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts@@ -1,8 +1,14 @@+// Proxies MCP stdio traffic for an evaluation while recording the bounded,+// sanitized request evidence needed by structured outcome validation.import { appendFileSync } from "node:fs";import { spawn } from "node:child_process";import { pathToFileURL } from "node:url";import { boundedIdentifierPattern, isPlainRecord } from "../../src/type-utils";import type { McpCatalogObservation } from "./evaluation-metrics";+import {+ getAssetQueryContractFingerprints,+ getPageSettingsContractFingerprint,+} from "./evaluation-trace-contract";type JsonRpcId = string | number;@@ -15,6 +21,9 @@ export type BoundedMcpCall = {dryRun?: true;confirmDestructive?: true;hasConfirmationToken?: true;+ assetQuerySha256?: string;+ assetQueryShapeSha256?: string;+ pageSettingsSha256?: string;};startedAtMs: number;durationMs?: number;@@ -112,7 +121,8 @@ export const getMcpTraceRequest = (if ((typeof id !== "string" && typeof id !== "number") ||isPlainRecord(params) === false ||- typeof params.name !== "string"+ typeof params.name !== "string" ||+ boundedIdentifierPattern.test(params.name) === false) {return;}@@ -166,6 +176,26 @@ export const getMcpTraceRequest = (if (typeof params.arguments.confirmationToken === "string") {args.hasConfirmationToken = true;}+ if (+ params.name === "validate-asset-query" ||+ params.name === "preview-asset-query"+ ) {+ const fingerprints = getAssetQueryContractFingerprints(+ params.arguments.query+ );+ if (fingerprints !== undefined) {+ args.assetQuerySha256 = fingerprints.sha256;+ args.assetQueryShapeSha256 = fingerprints.shapeSha256;+ }+ }+ if (params.name === "update-page") {+ const pageSettingsSha256 = getPageSettingsContractFingerprint(+ params.arguments+ );+ if (pageSettingsSha256 !== undefined) {+ args.pageSettingsSha256 = pageSettingsSha256;+ }+ }if (Object.keys(args).length > 0) {call.arguments = args;}diff --git a/packages/cli/evaluations/high-impact/results/authenticated-page-v1.json b/packages/cli/evaluations/high-impact/results/authenticated-page-v1.jsonindex d9fed98287..d561a15c04 100644--- a/packages/cli/evaluations/high-impact/results/authenticated-page-v1.json+++ b/packages/cli/evaluations/high-impact/results/authenticated-page-v1.json@@ -1,37 +1,38 @@{- "schemaVersion": 2,+ "schemaVersion": 3,"kind": "high-impact-minimal-context-agent-evaluation-result","fixtureId": "authenticated-page-v1","outcome": "passed","cli": "source","provider": "openai","model": "gpt-5.4-mini",- "commandSha256": "1f722c6fb110b0de65a89d07326dc21acfee50935b68ff1a5d3e1d483be791fe",+ "reasoningEffort": "low",+ "commandSha256": "3150ac354964486518b633ed39c3c58807dd68c80a875b01a5acfce14dbeadf6","exitCode": 0,"metrics": {- "durationMs": 60397,+ "durationMs": 61462,"tokens": {- "input": 176838,- "cachedInput": 162048,- "uncachedInput": 14790,+ "input": 172843,+ "cachedInput": 146688,+ "uncachedInput": 26155,"cacheWriteInput": 0,- "output": 2366,- "reasoningOutput": 1293,- "total": 179204,- "cachedInputRate": 0.9164+ "output": 1768,+ "reasoningOutput": 574,+ "total": 174611,+ "cachedInputRate": 0.8487},"mcpCatalog": {"responses": 1,- "totalResponseBytes": 53114,- "maxResponseBytes": 53114,- "latestToolCount": 184,- "latestResponseBytes": 53114,- "latestInputSchemaBytes": 29971,- "latestDescriptionBytes": 4529+ "totalResponseBytes": 61453,+ "maxResponseBytes": 61453,+ "latestToolCount": 196,+ "latestResponseBytes": 61453,+ "latestInputSchemaBytes": 35007,+ "latestDescriptionBytes": 6407},"toolCalls": {- "total": 7,- "succeeded": 7,+ "total": 5,+ "succeeded": 5,"failed": 0,"failuresByTool": {},"failuresByCode": {},@@ -40,89 +41,65 @@"durationsByTool": {"create-page": {"count": 1,- "totalMs": 45,- "p95Ms": 45,- "maxMs": 45- },- "create-resource": {- "count": 1,- "totalMs": 33,- "p95Ms": 33,- "maxMs": 33- },- "create-variable": {- "count": 1,- "totalMs": 37,- "p95Ms": 37,- "maxMs": 37+ "totalMs": 35,+ "p95Ms": 35,+ "maxMs": 35},"insert-fragment-verified": {"count": 1,- "totalMs": 65,- "p95Ms": 65,- "maxMs": 65+ "totalMs": 82,+ "p95Ms": 82,+ "maxMs": 82},"inspect-auth-context": {"count": 1,- "totalMs": 28,- "p95Ms": 28,- "maxMs": 28+ "totalMs": 36,+ "p95Ms": 36,+ "maxMs": 36},"meta.guide": {"count": 1,- "totalMs": 13,- "p95Ms": 13,- "maxMs": 13+ "totalMs": 2,+ "p95Ms": 2,+ "maxMs": 2},"verify-page-responsive": {"count": 1,- "totalMs": 10855,- "p95Ms": 10855,- "maxMs": 10855+ "totalMs": 11466,+ "p95Ms": 11466,+ "maxMs": 11466}},"responseBytesByTool": {"create-page": {"count": 1,- "totalBytes": 1342,- "p95Bytes": 1342,- "maxBytes": 1342- },- "create-resource": {- "count": 1,- "totalBytes": 1644,- "p95Bytes": 1644,- "maxBytes": 1644- },- "create-variable": {- "count": 1,- "totalBytes": 1554,- "p95Bytes": 1554,- "maxBytes": 1554+ "totalBytes": 2050,+ "p95Bytes": 2050,+ "maxBytes": 2050},"insert-fragment-verified": {"count": 1,- "totalBytes": 2662,- "p95Bytes": 2662,- "maxBytes": 2662+ "totalBytes": 2956,+ "p95Bytes": 2956,+ "maxBytes": 2956},"inspect-auth-context": {"count": 1,- "totalBytes": 2576,- "p95Bytes": 2576,- "maxBytes": 2576+ "totalBytes": 2644,+ "p95Bytes": 2644,+ "maxBytes": 2644},"meta.guide": {"count": 1,- "totalBytes": 15934,- "p95Bytes": 15934,- "maxBytes": 15934+ "totalBytes": 12314,+ "p95Bytes": 12314,+ "maxBytes": 12314},"verify-page-responsive": {"count": 1,- "totalBytes": 11730,- "p95Bytes": 11730,- "maxBytes": 11730+ "totalBytes": 11800,+ "p95Bytes": 11800,+ "maxBytes": 11800}},"retries": 0,@@ -130,25 +107,23 @@"broadReads": 0,"dryRuns": 0,"plannedMutations": 0,- "committedMutations": 4,+ "committedMutations": 2,"verifications": 2,- "totalDurationMs": 11076,- "p50DurationMs": 37,- "p95DurationMs": 10855,- "totalResponseBytes": 37442,- "p50ResponseBytes": 2576,- "p95ResponseBytes": 15934,- "maxResponseBytes": 15934,- "timeToFirstMutationMs": 25967,- "timeToFirstVerificationMs": 39551+ "totalDurationMs": 11621,+ "p50DurationMs": 36,+ "p95DurationMs": 11466,+ "totalResponseBytes": 31764,+ "p50ResponseBytes": 2956,+ "p95ResponseBytes": 12314,+ "maxResponseBytes": 12314,+ "timeToFirstMutationMs": 25867,+ "timeToFirstVerificationMs": 32553}},"callSequence": ["meta.guide","inspect-auth-context","create-page",- "create-variable",- "create-resource","insert-fragment-verified","verify-page-responsive"],diff --git a/packages/cli/evaluations/high-impact/results/design-input-v1.json b/packages/cli/evaluations/high-impact/results/design-input-v1.jsonindex 90d8f20f8b..6f0a674ac3 100644--- a/packages/cli/evaluations/high-impact/results/design-input-v1.json+++ b/packages/cli/evaluations/high-impact/results/design-input-v1.json@@ -1,37 +1,38 @@{- "schemaVersion": 2,+ "schemaVersion": 3,"kind": "high-impact-minimal-context-agent-evaluation-result","fixtureId": "design-input-v1","outcome": "passed","cli": "source","provider": "openai","model": "gpt-5.4-mini",- "commandSha256": "942755cc0025a46d00f539f1720d60cbbb3e26498a6fc835500deda6d7c875c1",+ "reasoningEffort": "high",+ "commandSha256": "997153fdcf54e79769ae4d44d5e63edcf23dcfe454b605a18143503a1ef5e997","exitCode": 0,"metrics": {- "durationMs": 150790,+ "durationMs": 478038,"tokens": {- "input": 217420,- "cachedInput": 186496,- "uncachedInput": 30924,+ "input": 466219,+ "cachedInput": 415488,+ "uncachedInput": 50731,"cacheWriteInput": 0,- "output": 8186,- "reasoningOutput": 4893,- "total": 225606,- "cachedInputRate": 0.8578+ "output": 31377,+ "reasoningOutput": 20466,+ "total": 497596,+ "cachedInputRate": 0.8912},"mcpCatalog": {"responses": 1,- "totalResponseBytes": 53114,- "maxResponseBytes": 53114,- "latestToolCount": 184,- "latestResponseBytes": 53114,- "latestInputSchemaBytes": 29971,- "latestDescriptionBytes": 4529+ "totalResponseBytes": 61453,+ "maxResponseBytes": 61453,+ "latestToolCount": 196,+ "latestResponseBytes": 61453,+ "latestInputSchemaBytes": 35007,+ "latestDescriptionBytes": 6407},"toolCalls": {- "total": 9,- "succeeded": 9,+ "total": 11,+ "succeeded": 11,"failed": 0,"failuresByTool": {},"failuresByCode": {},@@ -39,108 +40,108 @@"issuesByPath": {},"durationsByTool": {"attach-design-token": {- "count": 3,- "totalMs": 88,- "p95Ms": 42,- "maxMs": 42+ "count": 2,+ "totalMs": 33,+ "p95Ms": 23,+ "maxMs": 23},"create-page": {"count": 1,- "totalMs": 31,- "p95Ms": 31,- "maxMs": 31+ "totalMs": 23,+ "p95Ms": 23,+ "maxMs": 23},"insert-fragment-verified": {"count": 1,- "totalMs": 42,- "p95Ms": 42,- "maxMs": 42+ "totalMs": 95,+ "p95Ms": 95,+ "maxMs": 95},"inspect-design-context": {"count": 1,- "totalMs": 40,- "p95Ms": 40,- "maxMs": 40+ "totalMs": 37,+ "p95Ms": 37,+ "maxMs": 37},"meta.guide": {"count": 1,- "totalMs": 75,- "p95Ms": 75,- "maxMs": 75+ "totalMs": 5,+ "p95Ms": 5,+ "maxMs": 5},"update-styles": {- "count": 1,- "totalMs": 59,- "p95Ms": 59,- "maxMs": 59+ "count": 4,+ "totalMs": 220,+ "p95Ms": 143,+ "maxMs": 143},"verify-page-responsive": {"count": 1,- "totalMs": 10165,- "p95Ms": 10165,- "maxMs": 10165+ "totalMs": 12087,+ "p95Ms": 12087,+ "maxMs": 12087}},"responseBytesByTool": {"attach-design-token": {- "count": 3,- "totalBytes": 3900,- "p95Bytes": 1304,- "maxBytes": 1304+ "count": 2,+ "totalBytes": 4016,+ "p95Bytes": 2012,+ "maxBytes": 2012},"create-page": {"count": 1,- "totalBytes": 1342,- "p95Bytes": 1342,- "maxBytes": 1342+ "totalBytes": 2050,+ "p95Bytes": 2050,+ "maxBytes": 2050},"insert-fragment-verified": {"count": 1,- "totalBytes": 2954,- "p95Bytes": 2954,- "maxBytes": 2954+ "totalBytes": 5198,+ "p95Bytes": 5198,+ "maxBytes": 5198},"inspect-design-context": {"count": 1,- "totalBytes": 3082,- "p95Bytes": 3082,- "maxBytes": 3082+ "totalBytes": 3150,+ "p95Bytes": 3150,+ "maxBytes": 3150},"meta.guide": {"count": 1,- "totalBytes": 15130,- "p95Bytes": 15130,- "maxBytes": 15130+ "totalBytes": 10030,+ "p95Bytes": 10030,+ "maxBytes": 10030},"update-styles": {- "count": 1,- "totalBytes": 2762,- "p95Bytes": 2762,- "maxBytes": 2762+ "count": 4,+ "totalBytes": 23452,+ "p95Bytes": 13568,+ "maxBytes": 13568},"verify-page-responsive": {"count": 1,- "totalBytes": 10663,- "p95Bytes": 10663,- "maxBytes": 10663+ "totalBytes": 10697,+ "p95Bytes": 10697,+ "maxBytes": 10697}},"retries": 0,"focusedReads": 1,"broadReads": 0,- "dryRuns": 0,- "plannedMutations": 0,+ "dryRuns": 2,+ "plannedMutations": 2,"committedMutations": 6,"verifications": 2,- "totalDurationMs": 10500,- "p50DurationMs": 42,- "p95DurationMs": 10165,- "totalResponseBytes": 39833,- "p50ResponseBytes": 2762,- "p95ResponseBytes": 15130,- "maxResponseBytes": 15130,- "timeToFirstMutationMs": 36333,- "timeToFirstVerificationMs": 41878+ "totalDurationMs": 12500,+ "p50DurationMs": 23,+ "p95DurationMs": 12087,+ "totalResponseBytes": 58593,+ "p50ResponseBytes": 3559,+ "p95ResponseBytes": 13568,+ "maxResponseBytes": 13568,+ "timeToFirstMutationMs": 36104,+ "timeToFirstVerificationMs": 159265}},"callSequence": [@@ -150,7 +151,9 @@"insert-fragment-verified","attach-design-token","attach-design-token",- "attach-design-token",+ "update-styles",+ "update-styles",+ "update-styles","update-styles","verify-page-responsive"],diff --git a/packages/cli/evaluations/high-impact/results/font-assets-v1.json b/packages/cli/evaluations/high-impact/results/font-assets-v1.jsonindex 9fee485232..d593b13ecf 100644--- a/packages/cli/evaluations/high-impact/results/font-assets-v1.json+++ b/packages/cli/evaluations/high-impact/results/font-assets-v1.json@@ -1,33 +1,34 @@{- "schemaVersion": 2,+ "schemaVersion": 3,"kind": "high-impact-minimal-context-agent-evaluation-result","fixtureId": "font-assets-v1","outcome": "passed","cli": "source","provider": "openai","model": "gpt-5.4-mini",- "commandSha256": "894c6e39ef40250b37452fea3c1c8255932b086cae057392775f60e33eee8e81",+ "reasoningEffort": "low",+ "commandSha256": "6061f43100a5944dcc20cff24a704446f13bf7846846797db7942e95d73f3a3b","exitCode": 0,"metrics": {- "durationMs": 42054,+ "durationMs": 40085,"tokens": {- "input": 154475,- "cachedInput": 134528,- "uncachedInput": 19947,+ "input": 194782,+ "cachedInput": 175616,+ "uncachedInput": 19166,"cacheWriteInput": 0,- "output": 1936,- "reasoningOutput": 715,- "total": 156411,- "cachedInputRate": 0.8709+ "output": 1494,+ "reasoningOutput": 297,+ "total": 196276,+ "cachedInputRate": 0.9016},"mcpCatalog": {"responses": 1,- "totalResponseBytes": 53114,- "maxResponseBytes": 53114,- "latestToolCount": 184,- "latestResponseBytes": 53114,- "latestInputSchemaBytes": 29971,- "latestDescriptionBytes": 4529+ "totalResponseBytes": 61453,+ "maxResponseBytes": 61453,+ "latestToolCount": 196,+ "latestResponseBytes": 61453,+ "latestInputSchemaBytes": 35007,+ "latestDescriptionBytes": 6407},"toolCalls": {"total": 6,@@ -40,65 +41,65 @@"durationsByTool": {"audit": {"count": 1,- "totalMs": 18,- "p95Ms": 18,- "maxMs": 18+ "totalMs": 20,+ "p95Ms": 20,+ "maxMs": 20},"meta.guide": {"count": 1,- "totalMs": 16,- "p95Ms": 16,- "maxMs": 16+ "totalMs": 5,+ "p95Ms": 5,+ "maxMs": 5},"update-asset": {"count": 2,- "totalMs": 41,- "p95Ms": 29,- "maxMs": 29+ "totalMs": 38,+ "p95Ms": 21,+ "maxMs": 21},"upload-assets": {"count": 1,- "totalMs": 51,- "p95Ms": 51,- "maxMs": 51+ "totalMs": 38,+ "p95Ms": 38,+ "maxMs": 38},"verify-font-assets": {"count": 1,- "totalMs": 7,- "p95Ms": 7,- "maxMs": 7+ "totalMs": 9,+ "p95Ms": 9,+ "maxMs": 9}},"responseBytesByTool": {"audit": {"count": 1,- "totalBytes": 4638,- "p95Bytes": 4638,- "maxBytes": 4638+ "totalBytes": 10978,+ "p95Bytes": 10978,+ "maxBytes": 10978},"meta.guide": {"count": 1,- "totalBytes": 6566,- "p95Bytes": 6566,- "maxBytes": 6566+ "totalBytes": 3524,+ "p95Bytes": 3524,+ "maxBytes": 3524},"update-asset": {"count": 2,- "totalBytes": 1760,- "p95Bytes": 880,- "maxBytes": 880+ "totalBytes": 1876,+ "p95Bytes": 938,+ "maxBytes": 938},"upload-assets": {"count": 1,- "totalBytes": 2196,- "p95Bytes": 2196,- "maxBytes": 2196+ "totalBytes": 2292,+ "p95Bytes": 2292,+ "maxBytes": 2292},"verify-font-assets": {"count": 1,- "totalBytes": 2220,- "p95Bytes": 2220,- "maxBytes": 2220+ "totalBytes": 2268,+ "p95Bytes": 2268,+ "maxBytes": 2268}},"retries": 0,@@ -108,15 +109,15 @@"plannedMutations": 0,"committedMutations": 3,"verifications": 1,- "totalDurationMs": 133,- "p50DurationMs": 16,- "p95DurationMs": 51,- "totalResponseBytes": 17380,- "p50ResponseBytes": 2196,- "p95ResponseBytes": 6566,- "maxResponseBytes": 6566,- "timeToFirstMutationMs": 28505,- "timeToFirstVerificationMs": 37196+ "totalDurationMs": 110,+ "p50DurationMs": 17,+ "p95DurationMs": 38,+ "totalResponseBytes": 20938,+ "p50ResponseBytes": 2268,+ "p95ResponseBytes": 10978,+ "maxResponseBytes": 10978,+ "timeToFirstMutationMs": 24420,+ "timeToFirstVerificationMs": 33444}},"callSequence": [diff --git a/packages/cli/evaluations/high-impact/results/markdown-blog-v1.json b/packages/cli/evaluations/high-impact/results/markdown-blog-v1.jsonindex 6ecabe40be..b024c18246 100644--- a/packages/cli/evaluations/high-impact/results/markdown-blog-v1.json+++ b/packages/cli/evaluations/high-impact/results/markdown-blog-v1.json@@ -1,37 +1,38 @@{- "schemaVersion": 2,+ "schemaVersion": 3,"kind": "high-impact-minimal-context-agent-evaluation-result","fixtureId": "markdown-blog-v1","outcome": "passed","cli": "source","provider": "openai","model": "gpt-5.4-mini",- "commandSha256": "1db2da8f7b8d32044006973fb9a352c6e5110603c9d07b3a4924642e6f2f8ae7",+ "reasoningEffort": "medium",+ "commandSha256": "cf1bbd3329f85a3a63dd74c03101b88525eda7c4ccc338624f557c9b149128d2","exitCode": 0,"metrics": {- "durationMs": 121762,+ "durationMs": 141139,"tokens": {- "input": 469568,- "cachedInput": 436096,- "uncachedInput": 33472,+ "input": 510652,+ "cachedInput": 464640,+ "uncachedInput": 46012,"cacheWriteInput": 0,- "output": 5829,- "reasoningOutput": 3703,- "total": 475397,- "cachedInputRate": 0.9287+ "output": 7089,+ "reasoningOutput": 3833,+ "total": 517741,+ "cachedInputRate": 0.9099},"mcpCatalog": {"responses": 1,- "totalResponseBytes": 53114,- "maxResponseBytes": 53114,- "latestToolCount": 184,- "latestResponseBytes": 53114,- "latestInputSchemaBytes": 29971,- "latestDescriptionBytes": 4529+ "totalResponseBytes": 61453,+ "maxResponseBytes": 61453,+ "latestToolCount": 196,+ "latestResponseBytes": 61453,+ "latestInputSchemaBytes": 35007,+ "latestDescriptionBytes": 6407},"toolCalls": {- "total": 13,- "succeeded": 13,+ "total": 16,+ "succeeded": 16,"failed": 0,"failuresByTool": {},"failuresByCode": {},@@ -40,133 +41,184 @@"durationsByTool": {"create-asset-folder": {"count": 1,- "totalMs": 40,- "p95Ms": 40,- "maxMs": 40+ "totalMs": 31,+ "p95Ms": 31,+ "maxMs": 31},"create-assets-resource": {- "count": 3,- "totalMs": 100,- "p95Ms": 51,- "maxMs": 51+ "count": 2,+ "totalMs": 65,+ "p95Ms": 46,+ "maxMs": 46},"create-page": {"count": 2,- "totalMs": 31,- "p95Ms": 20,- "maxMs": 20+ "totalMs": 27,+ "p95Ms": 18,+ "maxMs": 18},"insert-collection": {- "count": 2,- "totalMs": 69,- "p95Ms": 53,- "maxMs": 53- },- "meta.get_more_tools": {"count": 1,- "totalMs": 17,- "p95Ms": 17,- "maxMs": 17+ "totalMs": 62,+ "p95Ms": 62,+ "maxMs": 62},- "meta.guide": {+ "insert-fragment": {"count": 1,"totalMs": 16,"p95Ms": 16,"maxMs": 16},+ "meta.get-more-tools": {+ "count": 1,+ "totalMs": 2,+ "p95Ms": 2,+ "maxMs": 2+ },+ "meta.guide": {+ "count": 1,+ "totalMs": 4,+ "p95Ms": 4,+ "maxMs": 4+ },+ "preview-asset-query": {+ "count": 1,+ "totalMs": 30,+ "p95Ms": 30,+ "maxMs": 30+ },+ "update-page": {+ "count": 1,+ "totalMs": 11,+ "p95Ms": 11,+ "maxMs": 11+ },"upload-assets": {"count": 1,- "totalMs": 21,- "p95Ms": 21,- "maxMs": 21+ "totalMs": 25,+ "p95Ms": 25,+ "maxMs": 25+ },+ "validate-asset-query": {+ "count": 2,+ "totalMs": 60,+ "p95Ms": 36,+ "maxMs": 36},"verify-page-responsive": {"count": 2,- "totalMs": 12197,- "p95Ms": 10670,- "maxMs": 10670+ "totalMs": 12853,+ "p95Ms": 11240,+ "maxMs": 11240}},"responseBytesByTool": {"create-asset-folder": {"count": 1,- "totalBytes": 884,- "p95Bytes": 884,- "maxBytes": 884+ "totalBytes": 942,+ "p95Bytes": 942,+ "maxBytes": 942},"create-assets-resource": {- "count": 3,- "totalBytes": 6482,- "p95Bytes": 3158,- "maxBytes": 3158+ "count": 2,+ "totalBytes": 4742,+ "p95Bytes": 2371,+ "maxBytes": 2371},"create-page": {"count": 2,- "totalBytes": 2688,- "p95Bytes": 1346,- "maxBytes": 1346+ "totalBytes": 4104,+ "p95Bytes": 2054,+ "maxBytes": 2054},"insert-collection": {- "count": 2,- "totalBytes": 4452,- "p95Bytes": 2259,- "maxBytes": 2259+ "count": 1,+ "totalBytes": 3001,+ "p95Bytes": 3001,+ "maxBytes": 3001+ },+ "insert-fragment": {+ "count": 1,+ "totalBytes": 2587,+ "p95Bytes": 2587,+ "maxBytes": 2587},- "meta.get_more_tools": {+ "meta.get-more-tools": {"count": 1,- "totalBytes": 116222,- "p95Bytes": 116222,- "maxBytes": 116222+ "totalBytes": 21813,+ "p95Bytes": 21813,+ "maxBytes": 21813},"meta.guide": {"count": 1,- "totalBytes": 6358,- "p95Bytes": 6358,- "maxBytes": 6358+ "totalBytes": 15854,+ "p95Bytes": 15854,+ "maxBytes": 15854+ },+ "preview-asset-query": {+ "count": 1,+ "totalBytes": 2619,+ "p95Bytes": 2619,+ "maxBytes": 2619+ },+ "update-page": {+ "count": 1,+ "totalBytes": 1985,+ "p95Bytes": 1985,+ "maxBytes": 1985},"upload-assets": {"count": 1,- "totalBytes": 3646,- "p95Bytes": 3646,- "maxBytes": 3646+ "totalBytes": 4360,+ "p95Bytes": 4360,+ "maxBytes": 4360+ },+ "validate-asset-query": {+ "count": 2,+ "totalBytes": 2984,+ "p95Bytes": 1492,+ "maxBytes": 1492},"verify-page-responsive": {"count": 2,- "totalBytes": 28506,- "p95Bytes": 14373,- "maxBytes": 14373+ "totalBytes": 28098,+ "p95Bytes": 14443,+ "maxBytes": 14443}},"retries": 0,"focusedReads": 0,"broadReads": 0,- "dryRuns": 1,- "plannedMutations": 1,- "committedMutations": 8,+ "dryRuns": 0,+ "plannedMutations": 0,+ "committedMutations": 9,"verifications": 2,- "totalDurationMs": 12491,- "p50DurationMs": 21,- "p95DurationMs": 10670,- "totalResponseBytes": 169238,- "p50ResponseBytes": 2259,- "p95ResponseBytes": 116222,- "maxResponseBytes": 116222,- "timeToFirstMutationMs": 30485,- "timeToFirstVerificationMs": 99015+ "totalDurationMs": 13186,+ "p50DurationMs": 24,+ "p95DurationMs": 11240,+ "totalResponseBytes": 93089,+ "p50ResponseBytes": 2371,+ "p95ResponseBytes": 21813,+ "maxResponseBytes": 21813,+ "timeToFirstMutationMs": 36423,+ "timeToFirstVerificationMs": 112003}},"callSequence": ["meta.guide",- "meta.get_more_tools","create-asset-folder","upload-assets","create-page","create-page",+ "validate-asset-query",+ "validate-asset-query",+ "preview-asset-query",+ "meta.get-more-tools","create-assets-resource","create-assets-resource","insert-collection",- "insert-collection",- "create-assets-resource",+ "insert-fragment",+ "update-page","verify-page-responsive","verify-page-responsive"],@@ -176,13 +228,18 @@"expressions": "passed","boundedReads": "passed","markdownUploads": "passed",+ "documentGraphSources": "passed","blogAssetFolder": "passed","blogRoutes": "passed","scopedBlogResources": "passed",+ "queryVerification": "passed","listingQuery": "passed","detailQuery": "passed",+ "documentGraphQueries": "passed",+ "optimalBlogDatabase": "passed","editableBlogBindings": "passed","bindingVerification": "passed",+ "detailPageSettings": "passed","blogRouteEvidence": "passed","usageCaptured": "passed"}diff --git a/packages/cli/evaluations/high-impact/results/markdown-references-discovery-v1.json b/packages/cli/evaluations/high-impact/results/markdown-references-discovery-v1.jsonindex c2c50160a5..535b062354 100644--- a/packages/cli/evaluations/high-impact/results/markdown-references-discovery-v1.json+++ b/packages/cli/evaluations/high-impact/results/markdown-references-discovery-v1.json@@ -1,37 +1,38 @@{- "schemaVersion": 2,+ "schemaVersion": 3,"kind": "high-impact-minimal-context-agent-evaluation-result","fixtureId": "markdown-references-discovery-v1","outcome": "passed","cli": "source","provider": "openai","model": "gpt-5.4-mini",- "commandSha256": "129c4beeb0730eadd324419a95969b599a39bb2776e0d1d93920d61bbc9e182a",+ "reasoningEffort": "medium",+ "commandSha256": "95e4a1a263be4bd7d2884264d9aa62f2a377e6082f1a0ca3635717a0dd179eab","exitCode": 0,"metrics": {- "durationMs": 162261,+ "durationMs": 157344,"tokens": {- "input": 335174,- "cachedInput": 299776,- "uncachedInput": 35398,+ "input": 479244,+ "cachedInput": 439296,+ "uncachedInput": 39948,"cacheWriteInput": 0,- "output": 8397,- "reasoningOutput": 5497,- "total": 343571,- "cachedInputRate": 0.8944+ "output": 8042,+ "reasoningOutput": 4539,+ "total": 487286,+ "cachedInputRate": 0.9166},"mcpCatalog": {"responses": 1,- "totalResponseBytes": 54701,- "maxResponseBytes": 54701,- "latestToolCount": 185,- "latestResponseBytes": 54701,- "latestInputSchemaBytes": 30201,- "latestDescriptionBytes": 5708+ "totalResponseBytes": 61453,+ "maxResponseBytes": 61453,+ "latestToolCount": 196,+ "latestResponseBytes": 61453,+ "latestInputSchemaBytes": 35007,+ "latestDescriptionBytes": 6407},"toolCalls": {- "total": 12,- "succeeded": 12,+ "total": 20,+ "succeeded": 20,"failed": 0,"failuresByTool": {},"failuresByCode": {},@@ -40,101 +41,149 @@"durationsByTool": {"create-asset-folder": {"count": 1,- "totalMs": 48,- "p95Ms": 48,- "maxMs": 48+ "totalMs": 38,+ "p95Ms": 38,+ "maxMs": 38},"create-assets-resource": {"count": 2,- "totalMs": 61,- "p95Ms": 42,- "maxMs": 42+ "totalMs": 78,+ "p95Ms": 59,+ "maxMs": 59},"create-page": {"count": 2,- "totalMs": 40,- "p95Ms": 27,- "maxMs": 27+ "totalMs": 36,+ "p95Ms": 26,+ "maxMs": 26},"insert-collection": {- "count": 2,- "totalMs": 119,- "p95Ms": 103,- "maxMs": 103+ "count": 1,+ "totalMs": 21,+ "p95Ms": 21,+ "maxMs": 21+ },+ "insert-fragment": {+ "count": 3,+ "totalMs": 96,+ "p95Ms": 61,+ "maxMs": 61},- "meta.get_more_tools": {+ "meta.get-more-tools": {"count": 1,- "totalMs": 14,- "p95Ms": 14,- "maxMs": 14+ "totalMs": 3,+ "p95Ms": 3,+ "maxMs": 3},"meta.guide": {"count": 1,- "totalMs": 21,- "p95Ms": 21,- "maxMs": 21+ "totalMs": 3,+ "p95Ms": 3,+ "maxMs": 3+ },+ "preview-asset-query": {+ "count": 1,+ "totalMs": 13,+ "p95Ms": 13,+ "maxMs": 13+ },+ "update-page": {+ "count": 2,+ "totalMs": 27,+ "p95Ms": 14,+ "maxMs": 14},"upload-assets": {"count": 1,- "totalMs": 22,- "p95Ms": 22,- "maxMs": 22+ "totalMs": 27,+ "p95Ms": 27,+ "maxMs": 27},- "verify-page-responsive": {+ "validate-asset-query": {"count": 2,- "totalMs": 14517,- "p95Ms": 12878,- "maxMs": 12878+ "totalMs": 42,+ "p95Ms": 26,+ "maxMs": 26+ },+ "verify-page-responsive": {+ "count": 3,+ "totalMs": 14763,+ "p95Ms": 11091,+ "maxMs": 11091}},"responseBytesByTool": {"create-asset-folder": {"count": 1,- "totalBytes": 884,- "p95Bytes": 884,- "maxBytes": 884+ "totalBytes": 942,+ "p95Bytes": 942,+ "maxBytes": 942},"create-assets-resource": {"count": 2,- "totalBytes": 3324,- "p95Bytes": 1662,- "maxBytes": 1662+ "totalBytes": 4742,+ "p95Bytes": 2371,+ "maxBytes": 2371},"create-page": {"count": 2,- "totalBytes": 2684,- "p95Bytes": 1342,- "maxBytes": 1342+ "totalBytes": 4104,+ "p95Bytes": 2054,+ "maxBytes": 2054},"insert-collection": {- "count": 2,- "totalBytes": 4518,- "p95Bytes": 2293,- "maxBytes": 2293+ "count": 1,+ "totalBytes": 3001,+ "p95Bytes": 3001,+ "maxBytes": 3001+ },+ "insert-fragment": {+ "count": 3,+ "totalBytes": 7623,+ "p95Bytes": 2587,+ "maxBytes": 2587},- "meta.get_more_tools": {+ "meta.get-more-tools": {"count": 1,- "totalBytes": 19474,- "p95Bytes": 19474,- "maxBytes": 19474+ "totalBytes": 21813,+ "p95Bytes": 21813,+ "maxBytes": 21813},"meta.guide": {"count": 1,- "totalBytes": 15748,- "p95Bytes": 15748,- "maxBytes": 15748+ "totalBytes": 15856,+ "p95Bytes": 15856,+ "maxBytes": 15856+ },+ "preview-asset-query": {+ "count": 1,+ "totalBytes": 2619,+ "p95Bytes": 2619,+ "maxBytes": 2619+ },+ "update-page": {+ "count": 2,+ "totalBytes": 3968,+ "p95Bytes": 1985,+ "maxBytes": 1985},"upload-assets": {"count": 1,- "totalBytes": 4200,- "p95Bytes": 4200,- "maxBytes": 4200+ "totalBytes": 4360,+ "p95Bytes": 4360,+ "maxBytes": 4360},- "verify-page-responsive": {+ "validate-asset-query": {"count": 2,- "totalBytes": 29404,- "p95Bytes": 14825,- "maxBytes": 14825+ "totalBytes": 2984,+ "p95Bytes": 1492,+ "maxBytes": 1492+ },+ "verify-page-responsive": {+ "count": 3,+ "totalBytes": 40381,+ "p95Bytes": 14437,+ "maxBytes": 14437}},"retries": 0,@@ -142,30 +191,38 @@"broadReads": 0,"dryRuns": 0,"plannedMutations": 0,- "committedMutations": 8,- "verifications": 2,- "totalDurationMs": 14842,- "p50DurationMs": 22,- "p95DurationMs": 12878,- "totalResponseBytes": 80236,- "p50ResponseBytes": 2225,- "p95ResponseBytes": 19474,- "maxResponseBytes": 19474,- "timeToFirstMutationMs": 65003,- "timeToFirstVerificationMs": 122016+ "committedMutations": 12,+ "verifications": 3,+ "totalDurationMs": 15147,+ "p50DurationMs": 21,+ "p95DurationMs": 2231,+ "totalResponseBytes": 112393,+ "p50ResponseBytes": 2485,+ "p95ResponseBytes": 15856,+ "maxResponseBytes": 21813,+ "timeToFirstMutationMs": 33283,+ "timeToFirstVerificationMs": 102917}},"callSequence": ["meta.guide",- "meta.get_more_tools","create-asset-folder",+ "upload-assets","create-page","create-page",- "upload-assets",+ "validate-asset-query",+ "validate-asset-query",+ "preview-asset-query",+ "meta.get-more-tools","create-assets-resource","create-assets-resource",+ "insert-fragment","insert-collection",- "insert-collection",+ "update-page",+ "verify-page-responsive",+ "update-page",+ "insert-fragment",+ "insert-fragment","verify-page-responsive","verify-page-responsive"],@@ -181,11 +238,14 @@"blogAssetFolder": "passed","blogRoutes": "passed","scopedBlogResources": "passed",+ "queryVerification": "passed","listingQuery": "passed","detailQuery": "passed","documentGraphQueries": "passed",+ "optimalBlogDatabase": "passed","editableBlogBindings": "passed","bindingVerification": "passed",+ "detailPageSettings": "passed","blogRouteEvidence": "passed","usageCaptured": "passed"}diff --git a/packages/cli/evaluations/high-impact/run-local-agent.test.ts b/packages/cli/evaluations/high-impact/run-local-agent.test.tsnew file mode 100644index 0000000000..4b29b67781--- /dev/null+++ b/packages/cli/evaluations/high-impact/run-local-agent.test.ts@@ -0,0 +1,20 @@+// Verifies that evaluation setup failures are reported before outcome checks+// can misclassify a missing project snapshot or reachable content plan.+import { describe, expect, test } from "vitest";+import { __testing__ } from "./run-local-agent";++const { getEvaluationContentCompilationInput } = __testing__;++describe("high-impact evaluation content compilation setup", () => {+ test("rejects a missing project-session snapshot explicitly", () => {+ expect(() => getEvaluationContentCompilationInput(undefined)).toThrowError(+ "Evaluation project session is unavailable"+ );+ });++ test("rejects a snapshot without reachable Assets resources explicitly", () => {+ expect(() =>+ getEvaluationContentCompilationInput({ state: {} } as never)+ ).toThrowError("Evaluation blog has no reachable Assets resources");+ });+});diff --git a/packages/cli/evaluations/high-impact/run-local-agent.ts b/packages/cli/evaluations/high-impact/run-local-agent.tsindex 7e5f23da8c..1685763c11 100644--- a/packages/cli/evaluations/high-impact/run-local-agent.ts+++ b/packages/cli/evaluations/high-impact/run-local-agent.ts@@ -1,3 +1,5 @@+// Orchestrates local high-impact agent fixtures, isolated project setup,+// content-database evidence, baseline comparison, and result persistence.import { execFile } from "node:child_process";import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { createRequire } from "node:module";@@ -74,10 +76,13 @@ const selectFixtures = (fixtureId: string | undefined) => {return [fixture];};-const compileEvaluationContentDatabase = async (projectDirectory: string) => {- const snapshot = await createCliProjectSessionStorage(- getCliProjectSessionFile(projectDirectory)- ).load();+type EvaluationProjectSnapshot = Awaited<+ ReturnType<ReturnType<typeof createCliProjectSessionStorage>["load"]>+>;++const getEvaluationContentCompilationInput = (+ snapshot: EvaluationProjectSnapshot+) => {if (snapshot === undefined) {throw new Error("Evaluation project session is unavailable");}@@ -89,6 +94,17 @@ const compileEvaluationContentDatabase = async (projectDirectory: string) => {if (plan === undefined) {throw new Error("Evaluation blog has no reachable Assets resources");}+ return { snapshot, plan };+};++export const __testing__ = { getEvaluationContentCompilationInput };++const compileEvaluationContentDatabase = async (projectDirectory: string) => {+ const loadedSnapshot = await createCliProjectSessionStorage(+ getCliProjectSessionFile(projectDirectory)+ ).load();+ const { snapshot, plan } =+ getEvaluationContentCompilationInput(loadedSnapshot);const { artifact } = await compileContentSource({source: createFileSystemContentSource({projectId: snapshot.projectId,@@ -132,6 +148,7 @@ const runFixture = async ({const localCli = resolve(repositoryRoot, "packages/cli/local.js");const codex = process.env.WEBSTUDIO_HIGH_IMPACT_CODEX ?? "codex";const model = process.env.WEBSTUDIO_HIGH_IMPACT_MODEL ?? "gpt-5.4-mini";+ const reasoningEffort = fixture.agent.reasoningEffort;const directory = await mkdtemp(join(tmpdir(), "webstudio-high-impact-agent-"));@@ -180,6 +197,8 @@ const runFixture = async ({"--json","--model",shellQuote(model),+ "--config",+ shellQuote(`model_reasoning_effort="${reasoningEffort}"`),"--cd",shellQuote(projectDirectory),...mcpConfig.flatMap((config) => ["--config", shellQuote(config)]),@@ -203,6 +222,7 @@ const runFixture = async ({resultPath,provider: "openai",model,+ reasoningEffort,env,signal,getToolCalls: () => toolCalls,@@ -394,4 +414,9 @@ const run = async () => {}};-await run();+if (+ process.argv[1] !== undefined &&+ import.meta.url === pathToFileURL(process.argv[1]).href+) {+ await run();+}diff --git a/packages/cli/evaluations/high-impact/validate.test.ts b/packages/cli/evaluations/high-impact/validate.test.tsindex f9be624979..0a155371a6 100644--- a/packages/cli/evaluations/high-impact/validate.test.ts+++ b/packages/cli/evaluations/high-impact/validate.test.ts@@ -1,5 +1,11 @@import { describe, expect, test } from "vitest";-import { createStructuredAssetQueryResourceBody } from "@webstudio-is/sdk";+import {+ collectionComponent,+ createStructuredAssetQueryResourceBody,+ encodeDataSourceVariable,+ parseStructuredAssetQueryResourceBody,+} from "@webstudio-is/sdk";+import { mapQueryWhere } from "@webstudio-is/query-builder/runtime";import { assetsResourceUrl } from "@webstudio-is/sdk/runtime";import {authenticatedPageFixture,@@ -16,10 +22,42 @@ import {fontAssetFixtureMeta,} from "./font-assets-fixture";import { markdownBlogFixtureDocuments } from "./markdown-blog-fixture";+import { getMcpTraceRequest, getMcpTraceResponse } from "./mcp-trace-proxy";import { evaluateHighImpactOutcome, type EvaluationToolCall } from "./validate";const clone = <Value>(value: Value): Value => structuredClone(value);+let traceRequestId = 0;+const traceCall = (+ name: string,+ args: Record<string, unknown>+): EvaluationToolCall => {+ const id = traceRequestId++;+ const request = getMcpTraceRequest(+ {+ id,+ method: "tools/call",+ params: { name, arguments: args },+ },+ 0,+ new Set(name === "update-page" ? [name] : [])+ );+ if (request === undefined) {+ throw new Error(`Expected a bounded trace for ${name}`);+ }+ const response = getMcpTraceResponse(+ {+ id,+ result: { structuredContent: { meta: { session: { committed: true } } } },+ },+ new Map([[id, request.call]])+ );+ if (response === undefined) {+ throw new Error(`Expected a completed trace for ${name}`);+ }+ return response;+};+const addAuthPage = (): EvaluationProject => {const project = clone(authenticatedPageFixture.project);project.pages.push({@@ -169,6 +207,12 @@ const addMarkdownBlog = (): EvaluationProject => {name: "Blog post",path: "/blog/:slug",rootInstanceId: "blog-detail-root",+ title: 'post.data.properties.title ?? "Article"',+ meta: {+ description: 'post.data.properties.excerpt ?? ""',+ socialImageUrl: 'post.data.properties.featureImage.src ?? ""',+ status: "post.data ? 200 : 404",+ },});project.instances.push(@@ -179,7 +223,7 @@ const addMarkdownBlog = (): EvaluationProject => {},{id: "blog-collection",- component: "Collection",+ component: collectionComponent,children: [{ type: "id", value: "blog-card" }],},{@@ -202,38 +246,49 @@ const addMarkdownBlog = (): EvaluationProject => {{id: "blog-detail-root",component: "Body",- children: [{ type: "id", value: "detail-collection" }],+ children: [{ type: "id", value: "detail-article" }],},{- id: "detail-collection",- component: "Collection",+ id: "detail-article",+ component: "Box",children: [+ { type: "id", value: "detail-title" },{ type: "id", value: "detail-author" },{ type: "id", value: "markdown" },],},+ {+ id: "detail-title",+ component: "Heading",+ children: [+ {+ type: "expression",+ value: "post.data.properties.title",+ },+ ],+ },{id: "detail-author",component: "Text",children: [{type: "expression",- value: "collectionItem.properties.author.name",+ value: "post.data.properties.author.name",},],},{id: "markdown",- component: "@webstudio-is/sdk-components-react:MarkdownEmbed",+ component: "MarkdownEmbed",children: [],});project.props.push({id: "markdown-content",instanceId: "markdown",- name: "content",+ name: "code",type: "expression",- value: "collectionItem.content.text",+ value: "post.data.content.text",});const resource = (id: string,@@ -298,6 +353,11 @@ const addMarkdownBlog = (): EvaluationProject => {operator: "eq",value: "system.params.slug",},+ {+ field: ["properties", "draft"],+ operator: "ne",+ value: "true",+ },],},sort: [],@@ -309,6 +369,8 @@ const addMarkdownBlog = (): EvaluationProject => {fields: [["properties", "title"],["properties", "author"],+ ["properties", "excerpt"],+ ["properties", "featureImage", "src"],],},content: { mode: "markdown-body-ref" },@@ -419,9 +481,52 @@ describe("Markdown blog evaluation", () => {documentGraphEdgeCount: 0,embeddedContentBytes: 0,};+ const queryFixtures = addMarkdownBlog().resources.map((resource) =>+ parseStructuredAssetQueryResourceBody(String(resource.body))+ );+ const overviewQuery = queryFixtures[0];+ const detailQuery = queryFixtures[1];+ if (overviewQuery === undefined || detailQuery === undefined) {+ throw new Error("Expected valid Markdown blog query fixtures");+ }+ const toResolvedFixtureQuery = (+ query: typeof overviewQuery | typeof detailQuery,+ slug = "aurora-trails"+ ) => ({+ ...query,+ where: mapQueryWhere(query.where, (condition) => ({+ ...condition,+ value:+ condition.field.join(".") === "properties.slug"+ ? slug+ : JSON.parse(condition.value),+ })),+ limit: Number(query.limit),+ offset: Number(query.offset),+ });+ const overviewValidationQuery = toResolvedFixtureQuery(overviewQuery);+ const detailValidationQuery = toResolvedFixtureQuery(detailQuery);+ const detailPageSettingsInput = {+ pageId: "blog-detail",+ values: {+ title: 'post.data.properties.title ?? "Article"',+ meta: {+ description: 'post.data.properties.excerpt ?? ""',+ socialImageUrl: 'post.data.properties.featureImage.src ?? ""',+ status: "post.data ? 200 : 404",+ },+ },+ };const successfulCalls: EvaluationToolCall[] = [{ name: "meta.guide" },- { name: "verify-bindings" },+ traceCall("validate-asset-query", { query: overviewValidationQuery }),+ traceCall("validate-asset-query", { query: detailValidationQuery }),+ traceCall("preview-asset-query", { query: detailValidationQuery }),+ { name: "create-assets-resource" },+ { name: "create-assets-resource" },+ { name: "insert-collection" },+ { name: "insert-fragment" },+ traceCall("update-page", detailPageSettingsInput),{name: "verify-page-responsive",arguments: {@@ -455,6 +560,7 @@ describe("Markdown blog evaluation", () => {test("accepts persisted MCP expressions and boolean query operands", () => {const project = addMarkdownBlog();+ const postIdentifier = encodeDataSourceVariable("post");project.dataSources.push({id: "collection-item",type: "parameter",@@ -477,10 +583,12 @@ describe("Markdown blog evaluation", () => {child.type === "expression"? {...child,- value: child.value.replace(- "collectionItem",- "$ws$dataSource$collection__DASH__item?"- ),+ value: child.value+ .replace(+ "collectionItem",+ "$ws$dataSource$collection__DASH__item?"+ )+ .replace("post", postIdentifier),}: child),@@ -489,13 +597,22 @@ describe("Markdown blog evaluation", () => {prop.type === "expression"? {...prop,- value: String(prop.value).replace(- "collectionItem",- "$ws$dataSource$collection__DASH__item?"- ),+ value: String(prop.value)+ .replace(+ "collectionItem",+ "$ws$dataSource$collection__DASH__item?"+ )+ .replace("post", postIdentifier),}: prop);+ const markdownCodeProp = project.props.find(+ (prop) => prop.id === "markdown-content"+ );+ if (markdownCodeProp === undefined) {+ throw new Error("Expected Markdown Embed code prop");+ }+ markdownCodeProp.value = `${postIdentifier}?.data?.content?.text`;const result = evaluateHighImpactOutcome({fixture: markdownBlogFixture,@@ -507,6 +624,366 @@ describe("Markdown blog evaluation", () => {expect(result).toMatchObject({ passed: true, failures: [] });});+ test("rejects wrapping a result-one detail resource in a Collection", () => {+ const project = addMarkdownBlog();+ const detailArticle = project.instances.find(+ (instance) => instance.id === "detail-article"+ );+ if (detailArticle === undefined) {+ throw new Error("Expected detail article fixture");+ }+ detailArticle.component = collectionComponent;+ project.instances = project.instances.map((instance) => ({+ ...instance,+ children: instance.children.map((child) =>+ child.type === "expression"+ ? {+ ...child,+ value: child.value.replaceAll("post.data", "collectionItem"),+ }+ : child+ ),+ }));+ project.props = project.props.map((prop) => ({+ ...prop,+ value:+ prop.type === "expression"+ ? String(prop.value).replaceAll("post.data", "collectionItem")+ : prop.value,+ }));++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project,+ toolCalls: successfulCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.editableBlogBindings).toBe("failed");+ });++ test("requires both insertion paths and the detail page settings", () => {+ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: addMarkdownBlog(),+ toolCalls: successfulCalls.filter(+ (call) => call.name !== "insert-fragment" && call.name !== "update-page"+ ),+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks).toMatchObject({+ bindingVerification: "failed",+ detailPageSettings: "failed",+ });+ });++ test("rejects a duplicate overview Collection and successful insertion", () => {+ const project = addMarkdownBlog();+ const overviewRoot = project.instances.find(+ (instance) => instance.id === "blog-root"+ );+ if (overviewRoot === undefined) {+ throw new Error("Expected blog overview root");+ }+ overviewRoot.children.push({+ type: "id",+ value: "duplicate-blog-collection",+ });+ project.instances.push({+ id: "duplicate-blog-collection",+ component: collectionComponent,+ children: [],+ });+ const toolCalls = successfulCalls.flatMap((call) =>+ call.name === "insert-collection"+ ? [call, { name: "insert-collection" }]+ : [call]+ );++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project,+ toolCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks).toMatchObject({+ editableBlogBindings: "failed",+ bindingVerification: "failed",+ });+ });++ test("accepts a supporting fragment in addition to the bound detail fragment", () => {+ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: addMarkdownBlog(),+ toolCalls: successfulCalls.flatMap((call) =>+ call.name === "insert-fragment"+ ? [{ name: "insert-fragment" }, call]+ : [call]+ ),+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.bindingVerification).toBe("passed");+ });++ test("requires validating both queries and previewing the detail query before binding", () => {+ for (const omittedCall of ["validate-asset-query", "preview-asset-query"]) {+ let omitted = false;+ const toolCalls = successfulCalls.filter((call) => {+ if (call.name === omittedCall && omitted === false) {+ omitted = true;+ return false;+ }+ return true;+ });+ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: addMarkdownBlog(),+ toolCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.queryVerification).toBe("failed");+ }+ });++ test("accepts preview after resource creation when it still precedes binding", () => {+ const previewCall = successfulCalls.find(+ (call) => call.name === "preview-asset-query"+ );+ if (previewCall === undefined) {+ throw new Error("Expected detail query preview call");+ }+ const toolCalls = successfulCalls.filter((call) => call !== previewCall);+ const insertionIndex = toolCalls.findIndex(+ (call) => call.name === "insert-collection"+ );+ toolCalls.splice(insertionIndex, 0, previewCall);++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: addMarkdownBlog(),+ toolCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.queryVerification).toBe("passed");+ });++ test("rejects validation calls for incomplete placeholder queries", () => {+ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: addMarkdownBlog(),+ toolCalls: successfulCalls.map((call, index) =>+ index === 2+ ? traceCall("validate-asset-query", {+ query: {+ result: "one",+ content: { mode: "markdown-body-ref" },+ },+ })+ : call+ ),+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.queryVerification).toBe("failed");+ });++ test("requires previewing the detail query with the concrete article slug", () => {+ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: addMarkdownBlog(),+ toolCalls: successfulCalls.map((call) =>+ call.name === "preview-asset-query"+ ? traceCall("preview-asset-query", {+ query: toResolvedFixtureQuery(detailQuery, "wrong-article"),+ })+ : call+ ),+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.queryVerification).toBe("failed");+ });++ test("requires the detail query draft filter and every consumed metadata field", () => {+ const project = addMarkdownBlog();+ project.resources[1] = {+ ...project.resources[1],+ body: String(project.resources[1]?.body)+ .replaceAll("draft", "omitted")+ .replaceAll("excerpt", "omitted")+ .replaceAll("featureImage", "omitted"),+ };++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project,+ toolCalls: successfulCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.detailQuery).toBe("failed");+ });++ test.each([+ ["overview", 0, "listingQuery"],+ ["detail", 1, "detailQuery"],+ ] as const)(+ "requires the %s resource filters to use one top-level all group",+ (_resourceName, resourceIndex, check) => {+ const project = addMarkdownBlog();+ const resource = project.resources[resourceIndex];+ const configuration = parseStructuredAssetQueryResourceBody(+ String(resource?.body)+ );+ if (resource === undefined || configuration === undefined) {+ throw new Error("Expected a structured Assets resource fixture");+ }+ if (!("all" in configuration.where)) {+ throw new Error("Expected an all query fixture");+ }+ resource.body = createStructuredAssetQueryResourceBody({+ ...configuration,+ where: { any: configuration.where.all },+ });++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project,+ toolCalls: successfulCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks[check]).toBe("failed");+ }+ );++ test("rejects an extra stale Assets resource", () => {+ const project = addMarkdownBlog();+ project.resources.push({+ id: "stale-post-resource",+ name: "Placeholder",+ control: "system",+ method: "post",+ url: JSON.stringify(assetsResourceUrl),+ headers: [],+ body: "",+ });++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project,+ toolCalls: successfulCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.scopedBlogResources).toBe("failed");+ });++ test("requires persisted detail settings and an update targeting that page", () => {+ const wrongSettingsProject = addMarkdownBlog();+ const detailPage = wrongSettingsProject.pages.find(+ (page) => page.id === "blog-detail"+ );+ if (detailPage === undefined) {+ throw new Error("Expected detail page fixture");+ }+ detailPage.title = "Static article";+ const wrongSettings = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: wrongSettingsProject,+ toolCalls: successfulCalls,+ contentDatabase: optimalContentDatabase,+ });+ const wrongTarget = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: addMarkdownBlog(),+ toolCalls: successfulCalls.map((call) =>+ call.name === "update-page"+ ? traceCall("update-page", {+ ...detailPageSettingsInput,+ pageId: "blog",+ })+ : call+ ),+ contentDatabase: optimalContentDatabase,+ });++ expect(wrongSettings.checks.detailPageSettings).toBe("failed");+ expect(wrongTarget.checks.detailPageSettings).toBe("failed");+ });++ test("requires the Markdown Embed instance itself to own the code binding", () => {+ const project = addMarkdownBlog();+ const codeProp = project.props.find(+ (prop) => prop.id === "markdown-content"+ );+ if (codeProp === undefined) {+ throw new Error("Expected Markdown Embed code prop");+ }+ codeProp.instanceId = "detail-article";++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project,+ toolCalls: successfulCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.editableBlogBindings).toBe("failed");+ });++ test.each([+ ["blog-collection", "FakeCollection"],+ ["markdown", "FakeMarkdownEmbed"],+ ])(+ "requires the exact component identity for %s",+ (instanceId, component) => {+ const project = addMarkdownBlog();+ const instance = project.instances.find(+ (candidate) => candidate.id === instanceId+ );+ if (instance === undefined) {+ throw new Error(`Expected ${instanceId} fixture`);+ }+ instance.component = component;++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project,+ toolCalls: successfulCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.editableBlogBindings).toBe("failed");+ }+ );++ test("requires the Markdown Embed code prop to be the direct content expression", () => {+ const project = addMarkdownBlog();+ const codeProp = project.props.find(+ (prop) => prop.id === "markdown-content"+ );+ if (codeProp === undefined) {+ throw new Error("Expected Markdown Embed code prop");+ }+ codeProp.value = 'post.data.content.text && "not markdown"';++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project,+ toolCalls: successfulCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.editableBlogBindings).toBe("failed");+ });+test("rejects blog resources that do not select the referenced author", () => {const project = addMarkdownBlog();project.resources = project.resources.map((resource) => ({@@ -588,6 +1065,128 @@ describe("Markdown blog evaluation", () => {});});+ test("requires a route verification as the terminal call", () => {+ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: addMarkdownBlog(),+ toolCalls: [...successfulCalls, { name: "list-pages" }],+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.blogRouteEvidence).toBe("failed");+ });++ test("accepts route checks separated by work when verification is terminal", () => {+ const toolCalls = [+ ...successfulCalls.slice(0, -1),+ { name: "list-pages" },+ successfulCalls.at(-1)!,+ ];+ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: addMarkdownBlog(),+ toolCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.blogRouteEvidence).toBe("passed");+ });++ test("accepts corrected settings followed by a final consecutive route check", () => {+ const finalVerificationIndex = successfulCalls.findIndex(+ (call) => call.name === "verify-page-responsive"+ );+ const toolCalls = successfulCalls.slice(0, finalVerificationIndex);+ toolCalls.push(+ {+ name: "verify-page-responsive",+ arguments: {+ path: "/blog",+ viewports: [{ width: 1440 }, { width: 390 }],+ },+ },+ traceCall("update-page", detailPageSettingsInput),+ ...successfulCalls.slice(finalVerificationIndex)+ );++ const result = evaluateHighImpactOutcome({+ fixture: markdownReferencesDiscoveryFixture,+ project: addMarkdownBlog(),+ toolCalls: [{ name: "meta.get-more-tools" }, ...toolCalls],+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks).toMatchObject({+ detailPageSettings: "passed",+ blogRouteEvidence: "passed",+ });+ });++ test("accepts the two terminal route checks in either order", () => {+ const toolCalls = [...successfulCalls];+ const firstVerificationIndex = toolCalls.findIndex(+ (call) => call.name === "verify-page-responsive"+ );+ const firstVerification = toolCalls[firstVerificationIndex];+ const secondVerification = toolCalls[firstVerificationIndex + 1];+ if (firstVerification === undefined || secondVerification === undefined) {+ throw new Error("Expected two route verification calls");+ }+ toolCalls.splice(+ firstVerificationIndex,+ 2,+ secondVerification,+ firstVerification+ );++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project: addMarkdownBlog(),+ toolCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.blogRouteEvidence).toBe("passed");+ });++ test("rejects pages beyond the fixture and the two requested blog routes", () => {+ const project = addMarkdownBlog();+ project.pages.push({+ id: "unrequested-page",+ name: "Unrequested",+ path: "/unrequested",+ rootInstanceId: "blog-root",+ });++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project,+ toolCalls: successfulCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.blogRoutes).toBe("failed");+ });++ test("rejects asset folders beyond the fixture and the requested Blog folder", () => {+ const project = addMarkdownBlog();+ project.assetFolders.push({+ id: "unrequested-folder",+ projectId: "project",+ name: "Unrequested",+ createdAt: "2026-01-01T00:00:00.000Z",+ });++ const result = evaluateHighImpactOutcome({+ fixture: markdownBlogFixture,+ project,+ toolCalls: successfulCalls,+ contentDatabase: optimalContentDatabase,+ });++ expect(result.checks.blogAssetFolder).toBe("failed");+ });+test("requires documentation discovery for the unprompted reference workflow", () => {const project = addMarkdownBlog();const withoutDiscovery = evaluateHighImpactOutcome({@@ -611,6 +1210,21 @@ describe("Markdown blog evaluation", () => {});expect(withDiscovery).toMatchObject({ passed: true, failures: [] });expect(withDiscovery.checks.referenceDocumentationDiscovery).toBe("passed");++ const withTwoFocusedDiscoveryCalls = evaluateHighImpactOutcome({+ fixture: markdownReferencesDiscoveryFixture,+ project,+ contentDatabase: optimalContentDatabase,+ toolCalls: [+ { name: "meta.guide" },+ { name: "meta.get-more-tools" },+ { name: "meta.get-more-tools" },+ ...successfulCalls.slice(1),+ ],+ });+ expect(+ withTwoFocusedDiscoveryCalls.checks.referenceDocumentationDiscovery+ ).toBe("passed");});test("rejects a duplicated or oversized compiled blog database", () => {@@ -659,21 +1273,6 @@ describe("Markdown blog evaluation", () => {expect(result.checks.retryFreeExecution).toBe("failed");});-- test("rejects repeated document-reference tool discovery", () => {- const result = evaluateHighImpactOutcome({- fixture: markdownReferencesDiscoveryFixture,- project: addMarkdownBlog(),- toolCalls: [- { name: "meta.guide" },- { name: "meta.get-more-tools" },- { name: "meta.get-more-tools" },- ...successfulCalls,- ],- });-- expect(result.checks.referenceDocumentationDiscovery).toBe("failed");- });});describe("authenticated-page evaluation", () => {@@ -738,6 +1337,26 @@ describe("authenticated-page evaluation", () => {visualEvidence: "failed",});});++ test("requires guidance before every other operation", () => {+ const lateGuidance = evaluateHighImpactOutcome({+ fixture: authenticatedPageFixture,+ project: addAuthPage(),+ toolCalls: [{ name: "audit" }, { name: "meta.guide" }],+ });+ expect(lateGuidance.checks.guidance).toBe("failed");++ const repeatedGuidance = evaluateHighImpactOutcome({+ fixture: authenticatedPageFixture,+ project: addAuthPage(),+ toolCalls: [+ { name: "meta.guide" },+ { name: "inspect-auth-context" },+ { name: "meta.guide" },+ ],+ });+ expect(repeatedGuidance.checks.guidance).toBe("passed");+ });});describe("design-input evaluation", () => {diff --git a/packages/cli/evaluations/high-impact/validate.ts b/packages/cli/evaluations/high-impact/validate.tsindex e447a62837..01e4eb34a3 100644--- a/packages/cli/evaluations/high-impact/validate.ts+++ b/packages/cli/evaluations/high-impact/validate.ts@@ -1,13 +1,21 @@+// Validates each high-impact fixture from typed final-state and MCP-trace+// evidence instead of depending on agent prose or exact replayed wording.import { parseExpressionAt } from "acorn";-import { transpileExpression } from "@webstudio-is/expression";+import {+ parseJsonExpression,+ parseStaticMemberPath,+ transpileExpression,+} from "@webstudio-is/expression";import { getFontFaces } from "@webstudio-is/fonts";-import { getQueryConditions } from "@webstudio-is/query-builder/runtime";+import { mapQueryWhere } from "@webstudio-is/query-builder/runtime";import {+ collectionComponent,decodeDataSourceVariable,isAssetsResource,parseStructuredAssetQueryResourceBody,type FontAsset,type Resource,+ type StructuredAssetQueryResourceConfiguration,type StructuredAssetQueryWhereBinding,} from "@webstudio-is/sdk";import {@@ -30,6 +38,10 @@ import {markdownBlogFixtureDocuments,} from "./markdown-blog-fixture";import { hasMcpToolCallRetries, isBroadRead } from "./evaluation-metrics";+import {+ getAssetQueryContractFingerprints,+ getPageSettingsContractFingerprint,+} from "./evaluation-trace-contract";export type EvaluationToolCall = {name: string;@@ -260,12 +272,17 @@ const validateCommon = (failures: string[]) => {const source = stringifyProject(input.project);+ const guidanceCalls = input.toolCalls.filter(+ (call) => call.name === "meta.guide"+ );recordCheck(checks,failures,"guidance",- hasSuccessfulCall(input.toolCalls, "meta.guide"),- "The agent did not request focused guidance before authoring."+ guidanceCalls.length >= 1 &&+ guidanceCalls[0]?.isError !== true &&+ input.toolCalls[0] === guidanceCalls[0],+ "The agent must request focused guidance before other operations.");recordCheck(checks,@@ -576,11 +593,22 @@ const getAssetResourceConfigurations = (project: EvaluationProject) =>return configuration === undefined ? [] : [{ resource, configuration }];});+const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null;+const pathsEqual = (left: unknown, right: readonly string[]) =>Array.isArray(left) &&left.length === right.length &&left.every((segment, index) => segment === right[index]);+const hasExactAllWhere = (+ where: StructuredAssetQueryWhereBinding,+ conditionCount: number+) =>+ "all" in where &&+ where.all.length === conditionCount &&+ where.all.every((condition) => "field" in condition);+const hasWhereCondition = ({where,field,@@ -593,14 +621,19 @@ const hasWhereCondition = ({operator: string;value: string;normalizeExpression?: (expression: string) => string;-}) =>- getQueryConditions(where).some(+}) => {+ if (!("all" in where)) {+ return false;+ }+ return where.all.some((condition) =>+ "field" in condition &&pathsEqual(condition.field, field) &&condition.operator === operator &&typeof condition.value === "string" &&normalizeExpression(condition.value) === normalizeExpression(value));+};const getMemberPath = (value: unknown): string[] | undefined => {if (typeof value !== "object" || value === null || !("type" in value)) {@@ -680,6 +713,14 @@ const hasOutputField = (output: unknown, field: string[]) =>Array.isArray(output.fields) &&output.fields.some((candidate) => pathsEqual(candidate, field));+const hasExactOutputFields = (output: unknown, fields: string[][]) =>+ isRecord(output) &&+ output.mode === "fields" &&+ output.includeMetadata === false &&+ Array.isArray(output.fields) &&+ output.fields.length === fields.length &&+ fields.every((field) => hasOutputField(output, field));+const hasSort = (sort: unknown,expected: Array<{ field: string[]; direction: string }>@@ -706,17 +747,12 @@ const validateMarkdownBlog = (const toolDiscoveryIndex = input.toolCalls.findIndex((call) => call.name === "meta.get-more-tools" && call.isError !== true);- const toolDiscoveryCount = input.toolCalls.filter(- (call) => call.name === "meta.get-more-tools"- ).length;recordCheck(checks,failures,"referenceDocumentationDiscovery",- guidanceIndex !== -1 &&- toolDiscoveryIndex > guidanceIndex &&- toolDiscoveryCount === 1,- "The reference workflow must use guidance followed by exactly one focused tool discovery call."+ guidanceIndex !== -1 && toolDiscoveryIndex > guidanceIndex,+ "The reference workflow must use guidance followed by focused tool discovery.");recordCheck(checks,@@ -743,6 +779,18 @@ const validateMarkdownBlog = (const blogFolder = input.project.assetFolders.find((folder) => folder.name === "Blog");+ const fixtureAssetFolderIds = new Set(+ input.fixture.project.assetFolders.map((folder) => folder.id)+ );+ const preservesFixtureAssetFolders = input.fixture.project.assetFolders.every(+ (expected) =>+ input.project.assetFolders.some(+ (candidate) =>+ candidate.id === expected.id &&+ candidate.name === expected.name &&+ candidate.parentId === expected.parentId+ )+ );recordCheck(checks,failures,@@ -767,22 +815,55 @@ const validateMarkdownBlog = (failures,"blogAssetFolder",blogFolder !== undefined &&+ blogFolder.parentId === undefined &&+ fixtureAssetFolderIds.has(blogFolder.id) === false &&+ input.project.assetFolders.length ===+ input.fixture.project.assetFolders.length + 1 &&+ preservesFixtureAssetFolders &&folderIds.size === 1 &&folderIds.has(blogFolder.id),- "The Markdown articles are not all stored in one Blog asset folder."+ "The project must preserve its existing asset folders and add only one Blog folder containing every Markdown article.");const overview = getPageEvaluationContext(input.project, "/blog");const detail = getPageEvaluationContext(input.project, "/blog/:slug");+ const fixturePageIds = new Set(+ input.fixture.project.pages.map((page) => page.id)+ );+ const preservesFixturePages = input.fixture.project.pages.every((expected) =>+ input.project.pages.some(+ (candidate) =>+ candidate.id === expected.id &&+ candidate.path === expected.path &&+ candidate.rootInstanceId === expected.rootInstanceId+ )+ );recordCheck(checks,failures,"blogRoutes",- overview.page !== undefined && detail.page !== undefined,- "The /blog overview and /blog/:slug detail pages are required."+ overview.page !== undefined &&+ detail.page !== undefined &&+ overview.page.id !== detail.page.id &&+ fixturePageIds.has(overview.page.id) === false &&+ fixturePageIds.has(detail.page.id) === false &&+ input.project.pages.length === input.fixture.project.pages.length + 2 &&+ preservesFixturePages,+ "The project must preserve its existing pages and add only /blog and /blog/:slug.");const configurations = getAssetResourceConfigurations(input.project);+ const assetResources = input.project.resources.filter((resource) =>+ isAssetsResource(resource as Resource)+ );+ const assetResourceIds = new Set(+ assetResources.map((resource) => String(resource.id))+ );+ const assetResourceDataSources = input.project.dataSources.filter(+ (dataSource) =>+ dataSource.type === "resource" &&+ assetResourceIds.has(String(dataSource.resourceId))+ );const dataSourceNameById = new Map(input.project.dataSources.map((dataSource) => [String(dataSource.id),@@ -808,6 +889,87 @@ const validateMarkdownBlog = (return expression;}};+ const matchesOverviewQuery = (+ configuration: StructuredAssetQueryResourceConfiguration | undefined+ ) =>+ configuration !== undefined &&+ blogFolder !== undefined &&+ configuration.result === "many" &&+ hasExactAllWhere(configuration.where, 3) &&+ hasWhereCondition({+ where: configuration.where,+ field: ["extension"],+ operator: "eq",+ value: '"md"',+ }) &&+ hasWhereCondition({+ where: configuration.where,+ field: ["folderId"],+ operator: "eq",+ value: JSON.stringify(blogFolder.id),+ }) &&+ hasWhereCondition({+ where: configuration.where,+ field: ["properties", "draft"],+ operator: "ne",+ value: "true",+ normalizeExpression,+ }) &&+ hasSort(configuration.sort, [+ { field: ["properties", "publishedAt"], direction: "desc" },+ { field: ["id"], direction: "asc" },+ ]) &&+ configuration.limit === "20" &&+ configuration.offset === "0" &&+ hasExactOutputFields(configuration.output, [+ ["properties", "title"],+ ["properties", "slug"],+ ["properties", "publishedAt"],+ ["properties", "author"],+ ["properties", "excerpt"],+ ]) &&+ configuration.content.mode === "none";+ const matchesDetailQuery = (+ configuration: StructuredAssetQueryResourceConfiguration | undefined,+ slugValue: string+ ) =>+ configuration !== undefined &&+ blogFolder !== undefined &&+ configuration.result === "one" &&+ hasExactAllWhere(configuration.where, 4) &&+ hasWhereCondition({+ where: configuration.where,+ field: ["extension"],+ operator: "eq",+ value: '"md"',+ }) &&+ hasWhereCondition({+ where: configuration.where,+ field: ["folderId"],+ operator: "eq",+ value: JSON.stringify(blogFolder.id),+ }) &&+ hasWhereCondition({+ where: configuration.where,+ field: ["properties", "slug"],+ operator: "eq",+ value: slugValue,+ normalizeExpression,+ }) &&+ hasWhereCondition({+ where: configuration.where,+ field: ["properties", "draft"],+ operator: "ne",+ value: "true",+ normalizeExpression,+ }) &&+ hasExactOutputFields(configuration.output, [+ ["properties", "title"],+ ["properties", "author"],+ ["properties", "excerpt"],+ ["properties", "featureImage", "src"],+ ]) &&+ configuration.content.mode === "markdown-body-ref";const findConfigurationByDataSourceName = (name: string) => {const resourceId = input.project.dataSources.find((dataSource) => dataSource.type === "resource" && dataSource.name === name@@ -839,77 +1001,124 @@ const validateMarkdownBlog = (checks,failures,"scopedBlogResources",- isResourceScopedTo(listingEntry?.resource.id, overviewInstanceIds) &&+ assetResources.length === 2 &&+ configurations.length === 2 &&+ assetResourceDataSources.length === 2 &&+ new Set(assetResourceDataSources.map(({ resourceId }) => resourceId))+ .size === 2 &&+ listingEntry?.resource.id !== articleEntry?.resource.id &&+ isResourceScopedTo(listingEntry?.resource.id, overviewInstanceIds) &&isResourceScopedTo(articleEntry?.resource.id, detailInstanceIds),- "Each Assets resource must be scoped to its corresponding blog page."+ "The blog must have exactly two valid Assets resources, each scoped to its corresponding page without stale placeholders."+ );++ const indexedCalls = input.toolCalls.map((call, index) => ({ call, index }));+ const validationCalls = indexedCalls.filter(+ ({ call }) => call.name === "validate-asset-query");+ const previewCalls = indexedCalls.filter(+ ({ call }) => call.name === "preview-asset-query"+ );+ const resourceCreationCalls = indexedCalls.filter(+ ({ call }) => call.name === "create-assets-resource"+ );+ const toResolvedQuery = (+ configuration: StructuredAssetQueryResourceConfiguration | undefined+ ) => {+ if (configuration === undefined) {+ return;+ }+ let valid = true;+ const resolveValue = (expression: string) => {+ const literal = parseJsonExpression(expression);+ if (literal !== undefined) {+ return literal;+ }+ if (normalizeExpression(expression) === "system.params.slug") {+ return "aurora-trails";+ }+ valid = false;+ };+ const query = {+ ...configuration,+ where: mapQueryWhere(configuration.where, (condition) => ({+ ...condition,+ value: resolveValue(condition.value),+ })),+ limit: resolveValue(configuration.limit),+ offset: resolveValue(configuration.offset),+ };+ return valid ? query : undefined;+ };+ const overviewQueryFingerprints = getAssetQueryContractFingerprints(+ toResolvedQuery(listing)+ );+ const detailQueryFingerprints = getAssetQueryContractFingerprints(+ toResolvedQuery(article)+ );+ const validatedQueryShapeFingerprints = validationCalls.map(+ ({ call }) => call.arguments?.assetQueryShapeSha256+ );+ const overviewValidationIndex = validationCalls.find(+ ({ call }) =>+ call.arguments?.assetQueryShapeSha256 ===+ overviewQueryFingerprints?.shapeSha256+ )?.index;+ const detailValidationIndex = validationCalls.find(+ ({ call }) =>+ call.arguments?.assetQueryShapeSha256 ===+ detailQueryFingerprints?.shapeSha256+ )?.index;+ const detailPreviewIndex = previewCalls.find(+ ({ call }) =>+ call.arguments?.assetQuerySha256 === detailQueryFingerprints?.sha256+ )?.index;+ const firstResourceCreationIndex =+ resourceCreationCalls[0]?.index ?? Number.POSITIVE_INFINITY;+ const firstBindingIndex =+ indexedCalls.find(+ ({ call }) =>+ call.name === "insert-collection" || call.name === "insert-fragment"+ )?.index ?? Number.POSITIVE_INFINITY;recordCheck(checks,failures,- "listingQuery",- listing !== undefined &&- blogFolder !== undefined &&- hasWhereCondition({- where: listing.where,- field: ["extension"],- operator: "eq",- value: '"md"',- }) &&- hasWhereCondition({- where: listing.where,- field: ["folderId"],- operator: "eq",- value: JSON.stringify(blogFolder.id),- }) &&- hasWhereCondition({- where: listing.where,- field: ["properties", "draft"],- operator: "ne",- value: "true",- normalizeExpression,- }) &&- hasSort(listing.sort, [- { field: ["properties", "publishedAt"], direction: "desc" },- { field: ["id"], direction: "asc" },- ]) &&- listing.limit === "20" &&- ["title", "slug", "publishedAt"].every((field) =>- hasOutputField(listing.output, ["properties", field])+ "queryVerification",+ validationCalls.length >= 2 &&+ validationCalls.every(({ call }) => call.isError !== true) &&+ overviewQueryFingerprints !== undefined &&+ detailQueryFingerprints !== undefined &&+ validatedQueryShapeFingerprints.includes(+ overviewQueryFingerprints.shapeSha256) &&- hasOutputField(listing.output, ["properties", "excerpt"]) &&- listing.output.includeMetadata === false,+ validatedQueryShapeFingerprints.includes(+ detailQueryFingerprints.shapeSha256+ ) &&+ previewCalls.length >= 1 &&+ previewCalls.every(({ call }) => call.isError !== true) &&+ resourceCreationCalls.length === 2 &&+ resourceCreationCalls.every(({ call }) => call.isError !== true) &&+ overviewValidationIndex !== undefined &&+ overviewValidationIndex < firstResourceCreationIndex &&+ detailValidationIndex !== undefined &&+ detailValidationIndex < firstResourceCreationIndex &&+ detailPreviewIndex !== undefined &&+ detailPreviewIndex < firstBindingIndex,+ "Both blog queries must be validated before resource creation, and the detail query must be previewed before binding."+ );+ recordCheck(+ checks,+ failures,+ "listingQuery",+ matchesOverviewQuery(listing),"The overview Assets resource is not a bounded metadata-only published-post query.");recordCheck(checks,failures,"detailQuery",- article !== undefined &&- blogFolder !== undefined &&- article.content.mode === "markdown-body-ref" &&- hasWhereCondition({- where: article.where,- field: ["extension"],- operator: "eq",- value: '"md"',- }) &&- hasWhereCondition({- where: article.where,- field: ["folderId"],- operator: "eq",- value: JSON.stringify(blogFolder.id),- }) &&- hasWhereCondition({- where: article.where,- field: ["properties", "slug"],- operator: "eq",- value: "system.params.slug",- normalizeExpression,- }) &&- article.result === "one" &&- article.output.includeMetadata === false &&- hasOutputField(article.output, ["properties", "body"]) === false,- "The detail Assets resource does not defer one Markdown body selected by the dynamic slug parameter."+ matchesDetailQuery(article, "system.params.slug"),+ "The detail Assets resource must exclude drafts, select the metadata consumed by the page, and defer one Markdown body selected by the dynamic slug parameter.");recordCheck(checks,@@ -966,13 +1175,27 @@ const validateMarkdownBlog = (};const overviewExpressionPaths = getPageExpressionPaths(overview.instances);const detailExpressionPaths = getPageExpressionPaths(detail.instances);+ const overviewCollections = overview.instances.filter(+ (instance) => instance.component === collectionComponent+ );+ const markdownEmbedInstances = detail.instances.filter(+ (instance) => instance.component === "MarkdownEmbed"+ );+ const markdownEmbed = markdownEmbedInstances[0];+ const markdownCodeBindings = input.project.props.filter(+ (prop) =>+ prop.instanceId === markdownEmbed?.id &&+ prop.name === "code" &&+ prop.type === "expression"+ );+ const markdownCodePath = parseStaticMemberPath(+ normalizeExpression(String(markdownCodeBindings[0]?.value ?? ""))+ );recordCheck(checks,failures,"editableBlogBindings",- overview.instances.some((instance) =>- instance.component.toLowerCase().endsWith("collection")- ) &&+ overviewCollections.length === 1 &&["collectionItem.properties.title","collectionItem.properties.excerpt",@@ -980,33 +1203,89 @@ const validateMarkdownBlog = ("collectionItem.properties.slug","collectionItem.properties.author.name",].every((expression) => overviewExpressionPaths.has(expression)) &&- detail.instances.some((instance) =>- instance.component.toLowerCase().endsWith("collection")- ) &&- detail.instances.some((instance) =>- instance.component.toLowerCase().endsWith("markdownembed")+ detail.instances.every(+ (instance) => instance.component !== collectionComponent) &&- detailExpressionPaths.has("collectionItem.content.text") &&- detailExpressionPaths.has("collectionItem.properties.author.name"),- "The blog is not rendered through editable Collections, author bindings, and a Markdown Embed."+ markdownEmbedInstances.length === 1 &&+ markdownCodeBindings.length === 1 &&+ pathsEqual(markdownCodePath, ["post", "data", "content", "text"]) &&+ detailExpressionPaths.has("post.data.properties.title") &&+ detailExpressionPaths.has("post.data.properties.author.name"),+ "The overview must use an editable Collection and the result-one detail must bind directly to a Markdown Embed.");recordCheck(checks,failures,"bindingVerification",- hasSuccessfulCall(input.toolCalls, "insert-fragment-verified") ||- hasSuccessfulCall(input.toolCalls, "verify-bindings") ||- hasSuccessfulCall(input.toolCalls, "insert-collection"),- "The persisted blog bindings were not verified."+ input.toolCalls.filter(+ (call) => call.name === "insert-collection" && call.isError !== true+ ).length === 1 &&+ input.toolCalls.filter(+ (call) => call.name === "insert-fragment" && call.isError !== true+ ).length >= 1,+ "One persisted overview Collection and at least one direct fragment must be inserted successfully.");-- const verificationCalls = input.toolCalls.filter(- (call) => call.name === "verify-page-responsive" && call.isError !== true+ recordCheck(+ checks,+ failures,+ "detailPageSettings",+ (() => {+ const expected = {+ title: 'post.data.properties.title ?? "Article"',+ description: 'post.data.properties.excerpt ?? ""',+ socialImageUrl: 'post.data.properties.featureImage.src ?? ""',+ status: "post.data ? 200 : 404",+ };+ const matchesExpression = (value: unknown, expression: string) =>+ typeof value === "string" &&+ normalizeExpression(value) === normalizeExpression(expression);+ const pageMatches =+ matchesExpression(detail.page?.title, expected.title) &&+ matchesExpression(+ detail.page?.meta?.description,+ expected.description+ ) &&+ matchesExpression(+ detail.page?.meta?.socialImageUrl,+ expected.socialImageUrl+ ) &&+ matchesExpression(detail.page?.meta?.status, expected.status);+ const updateCalls = input.toolCalls.filter(+ (call) => call.name === "update-page" && call.isError !== true+ );+ const expectedPageSettingsFingerprint =+ detail.page === undefined+ ? undefined+ : getPageSettingsContractFingerprint({+ pageId: detail.page.id,+ values: {+ title: expected.title,+ meta: {+ description: expected.description,+ socialImageUrl: expected.socialImageUrl,+ status: expected.status,+ },+ },+ });+ const callMatches =+ updateCalls.length >= 1 &&+ expectedPageSettingsFingerprint !== undefined &&+ updateCalls.some(+ (call) =>+ call.arguments?.pageSettingsSha256 ===+ expectedPageSettingsFingerprint+ );+ return pageMatches && callMatches;+ })(),+ "The dynamic detail page title, description, social image, and status must be persisted and applied to the detail page from the post resource.");- const verifiedPaths = new Set(- verificationCalls.map((call) => String(call.arguments?.path ?? ""))++ const verificationCalls = input.toolCalls.flatMap((call, index) =>+ call.name === "verify-page-responsive" && call.isError !== true+ ? [{ call, index }]+ : []);- const hasBothViewports = verificationCalls.every((call) => {+ const hasBothViewports = verificationCalls.every(({ call }) => {const viewports = Array.isArray(call.arguments?.viewports)? call.arguments.viewports: [];@@ -1025,15 +1304,19 @@ const validateMarkdownBlog = ());});+ const verificationPaths = new Set(+ verificationCalls.map(({ call }) => call.arguments?.path)+ );recordCheck(checks,failures,"blogRouteEvidence",- verificationCalls.length === 2 &&- verifiedPaths.has("/blog") &&- verifiedPaths.has("/blog/aurora-trails") &&+ verificationCalls.length >= 2 &&+ verificationCalls.at(-1)?.index === input.toolCalls.length - 1 &&+ verificationPaths.has("/blog") &&+ verificationPaths.has("/blog/aurora-trails") &&hasBothViewports,- "Both blog routes require successful desktop and mobile rendered verification."+ "The workflow must verify /blog and /blog/aurora-trails at desktop and mobile sizes, with verification as the final call.");};diff --git a/packages/cli/scripts/release-smoke.ts b/packages/cli/scripts/release-smoke.tsindex 502fbf1359..d4acf9c4f4 100644--- a/packages/cli/scripts/release-smoke.ts+++ b/packages/cli/scripts/release-smoke.ts@@ -1643,7 +1643,7 @@ const run = async () => {});await assertLocalDryRun("local fragment insertion", "insert-fragment", {parentInstanceId: "home-root",- fragment: '<ws.element ws:tag="p">Release smoke</ws.element>',+ fragment: "<p>Release smoke</p>",});await assertLocalDryRun("local component insertion", "insert-component", {parentInstanceId: "home-root",diff --git a/packages/cli/src/cli.test.ts b/packages/cli/src/cli.test.tsindex 670b7fd37d..95d722dcef 100644--- a/packages/cli/src/cli.test.ts+++ b/packages/cli/src/cli.test.ts@@ -146,14 +146,14 @@ describe("registerCommands", () => {expect(getTopLevelMcpToolForwardArgs(["insert-fragment",- '{"parentInstanceId":"parent-id","fragment":"<$.Box />"}',+ '{"parentInstanceId":"parent-id","fragment":"<Box />"}',"--dry-run",])).toEqual(["mcp","single-op-call","insert-fragment",- '{"parentInstanceId":"parent-id","fragment":"<$.Box />"}',+ '{"parentInstanceId":"parent-id","fragment":"<Box />"}',"--dry-run",]);expect(diff --git a/packages/cli/src/content-engine-reference.test.ts b/packages/cli/src/content-engine-reference.test.tsindex 8a622dc5f7..13a4a79384 100644--- a/packages/cli/src/content-engine-reference.test.ts+++ b/packages/cli/src/content-engine-reference.test.ts@@ -1,8 +1,27 @@import { describe, expect, test } from "vitest";-import { assertContentEngineReferenceCoverage } from "./content-engine-reference";+import {+ assertContentEngineReferenceCoverage,+ structuredAssetImageRecipe,+} from "./content-engine-reference";describe("Content Engine reference", () => {test("covers the schema-backed query contract", () => {expect(assertContentEngineReferenceCoverage).not.toThrow();});++ test("defines structured frontmatter image fields and bindings", () => {+ expect(structuredAssetImageRecipe).toEqual({+ frontmatter: {+ featureImage: { $ref: "./assets/hero.png" },+ },+ outputFields: [+ ["properties", "featureImage", "src"],+ ["properties", "featureImage", "description"],+ ],+ bindings: {+ src: "post.properties.featureImage.src",+ alt: "post.properties.featureImage.description ?? post.properties.title",+ },+ });+ });});diff --git a/packages/cli/src/content-engine-reference.ts b/packages/cli/src/content-engine-reference.tsindex b2ee9b1b06..382f4fda9d 100644--- a/packages/cli/src/content-engine-reference.ts+++ b/packages/cli/src/content-engine-reference.ts@@ -13,6 +13,20 @@ type ReferenceRow = Readonly<{description: string;}>;+export const structuredAssetImageRecipe = {+ frontmatter: {+ featureImage: { $ref: "./assets/hero.png" },+ },+ outputFields: [+ ["properties", "featureImage", "src"],+ ["properties", "featureImage", "description"],+ ],+ bindings: {+ src: "post.properties.featureImage.src",+ alt: "post.properties.featureImage.description ?? post.properties.title",+ },+} as const;+const formatBytes = (bytes: number) => {if (bytes % (1024 * 1024) === 0) {return `${bytes / (1024 * 1024)} MiB`;@@ -397,7 +411,7 @@ export const renderContentEngineReferenceMarkdown = ({"","```yaml","featureImage:",- " $ref: ./assets/hero.png",+ ` $ref: ${structuredAssetImageRecipe.frontmatter.featureImage.$ref}`,"```","","The reference declares only the relationship. The query decides which metadata enters its result and published database. A complete `properties.featureImage` selection returns the Asset Manager asset metadata together with its resolved `src`. This includes fields such as `id`, `name`, `description`, `mimeType`, `width`, and `height`; new asset metadata becomes available to references without changing the document. Select only the nested fields the page uses:",@@ -409,14 +423,14 @@ export const renderContentEngineReferenceMarkdown = ({' "includeMetadata": false,',' "fields": [',' ["properties", "title"],',- ' ["properties", "featureImage", "src"],',- ' ["properties", "featureImage", "description"]',+ ` [${structuredAssetImageRecipe.outputFields[0].map((part) => JSON.stringify(part)).join(", ")}],`,+ ` [${structuredAssetImageRecipe.outputFields[1].map((part) => JSON.stringify(part)).join(", ")}]`," ]"," }","}","```","",- "The selected value becomes an object. Bind an Image source to `post.properties.featureImage.src` and its alternative text to `post.properties.featureImage.description ?? post.properties.title`. A missing description therefore falls back to the article title without duplicating text in frontmatter.",+ `The selected value becomes an object. Bind an Image source to \`${structuredAssetImageRecipe.bindings.src}\` and its alternative text to \`${structuredAssetImageRecipe.bindings.alt}\`. A missing description therefore falls back to the article title without duplicating text in frontmatter.`,"","External URLs remain ordinary strings. Existing local path strings also keep their URL string shape, so adopting structured references does not change existing queries or bindings.","",diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex ace1a62289..4d677971a3 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":"<ws.element ws:tag=\'section\' ws:style={css`padding: 32px;`}><ws.element ws:tag=\'h2\'>Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\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- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\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 `<radix.Switch><radix.SwitchThumb /></radix.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 the Content Block\'s `ws:block-template` child. 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 whenever it can represent the component and all authored properties. Use `<ws.element ws:tag="tag">` for a standard HTML element with authored properties that Markdown cannot express. Use `<ws.element ws:name="Template name">` only for a uniquely named top-level Content Block template.\n- Read the Content Block\'s Templates children before writing `ws:name`. The value must exactly match a unique top-level template instance name. 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. A rename changes matching `ws:name` values; a removal deletes matching MDX elements. 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- 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":"<ws.element ws:tag=\'article\'><ws.element ws:tag=\'h2\'>{expression`collectionItem.title`}</ws.element></ws.element>"}\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":"<ws.element ws:tag=\'section\'><ws.element ws:tag=\'p\'>Section copy</ws.element></ws.element>"}\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 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',"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": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag=\'h2\'>Launch Kit</ws.element><ws.element ws:tag=\'p\'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag=\'button\'>Get started</ws.element></ws.element>"\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 the block\'s `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. 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 whenever it can represent the component and all authored properties. Use `<ws.element ws:tag="tag">` for a standard HTML element with authored properties Markdown cannot express. Use `<ws.element ws:name="Template name">` only for a uniquely named top-level Content Block template. 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 updates across selected MDX files.\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. Use that operation 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<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\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 `<radix.Switch><radix.SwitchThumb /></radix.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<animation.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 <ws.element\n ws:tag="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 <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.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 <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.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 <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.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<animation.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 <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.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.\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 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.\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',"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": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag=\'h2\'>Northstar Product OS</ws.element><ws.element ws:tag=\'p\'>Reusable patterns for teams.</ws.element></ws.element>"\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<ws.element\n ws:tag="section"\n style={{ padding: 32, borderRadius: 16 }}\n>\n <ws.element ws:tag="h2">Operations Console</ws.element>\n <ws.element ws:tag="p">\n React-style object styles become editable Webstudio styles.\n </ws.element>\n</ws.element>\n\n<ws.element\n ws:tag="section"\n ws:tokens={[token("accent", css`color: #0f766e;`)]}\n>\n <ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </ws.element>\n</ws.element>\n\n<ws.element ws:tag="section">\n <radix.Switch>\n <radix.SwitchThumb />\n </radix.Switch>\n</ws.element>\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. `animation` is the component namespace for JSX such as `<animation.AnimateChildren>`; it 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 `<radix.Switch><radix.SwitchThumb /></radix.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 its Templates children. Every template referenced from MDX needs a unique top-level instance name.\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 whenever it can represent the component and all authored properties. Use `<ws.element ws:tag="tag">` for a standard HTML element with authored properties Markdown cannot express. Use `<ws.element ws:name="Template name">` only for a uniquely named top-level Content Block template. 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. A rename changes matching `ws:name` values. A removal deletes matching MDX elements. 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. 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; 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',"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": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag=\'h2\'>Launch Kit</ws.element><ws.element ws:tag=\'p\'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag=\'button\'>Get started</ws.element></ws.element>"\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 the block\'s `ws:block-template` child. 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 whenever it can represent the component and all authored properties. Use `<ws.element ws:tag="tag">` for a standard HTML element with authored properties Markdown cannot express. Use `<ws.element ws:name="Template name">` only for a uniquely named top-level template. 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. 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 changes across selected MDX files.\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 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',"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;diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.mdindex e6e8aebafc..49a3b78369 100644--- a/packages/cli/src/docs/api-use-cases.md+++ b/packages/cli/src/docs/api-use-cases.md@@ -418,7 +418,7 @@ Commands:Commands:-- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag='section' ws:style={css`padding: 32px;`}><ws.element ws:tag='h2'>Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}+- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section ws:style={css`padding: 32px;`}><h2>Product OS</h2><Switch><SwitchThumb /></Switch></section>"}- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}@@ -426,7 +426,7 @@ Notes:- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.-- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.+- Use lowercase HTML JSX such as `<div>` and `<form>`. The internal `ws:` namespace is not HTML-tag shorthand.- For Webstudio's complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.- 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.- 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.@@ -434,7 +434,7 @@ Notes:- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.- 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={() => ...}`.- 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.-- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.+- 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>`.- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.- 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.- 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.@@ -451,7 +451,7 @@ Commands: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 the Content Block's `ws:block-template` child. 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.+- 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.## Store Content Block content in MDX@@ -476,11 +476,14 @@ Notes:- `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`.- 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>"}}}`.- 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 whenever it can represent the component and all authored properties. Use `<ws.element ws:tag="tag">` for a standard HTML element with authored properties that Markdown cannot express. Use `<ws.element ws:name="Template name">` only for a uniquely named top-level Content Block template.-- Read the Content Block's Templates children before writing `ws:name`. The value must exactly match a unique top-level template instance name. 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. A rename changes matching `ws:name` values; a removal deletes matching MDX elements. Invalid files remain unchanged and are reported in diagnostics.+- 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.+- 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.- 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.@@ -1212,7 +1215,7 @@ Notes:Commands:-- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag='article'><ws.element ws:tag='h2'>{expression`collectionItem.title`}</ws.element></ws.element>"}+- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<article><h2>{expression`collectionItem.title`}</h2></article>"}- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}Notes:@@ -1277,7 +1280,7 @@ Commands:- MCP tool: create-design-token {"tokens":"tokens.json contents"}- MCP tool: define-css-variable {"vars":"vars.json contents"}- MCP tool: list-breakpoints {}-- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag='section'><ws.element ws:tag='p'>Section copy</ws.element></ws.element>"}+- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section><p>Section copy</p></section>"}- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpoint":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}- MCP tool: preview.start {}- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.mdindex f84ff9952d..01a381917f 100644--- a/packages/cli/src/docs/manual-llm.md+++ b/packages/cli/src/docs/manual-llm.md@@ -72,7 +72,7 @@ Save the readable payload in `.temp/insert-fragment.json`:```json{"parentInstanceId": "parent-id",- "fragment": "<ws.element ws:tag='section' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag='h2'>Launch Kit</ws.element><ws.element ws:tag='p'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag='button'>Get started</ws.element></ws.element>"+ "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>"}```@@ -88,11 +88,11 @@ For this simple path, do not grep source files, dump full MCP resources, or writWhen 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.-When 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 the block's `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. Verify this structure before handoff.+When 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 whenever it can represent the component and all authored properties. Use `<ws.element ws:tag="tag">` for a standard HTML element with authored properties Markdown cannot express. Use `<ws.element ws:name="Template name">` only for a uniquely named top-level Content Block template. 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 updates across selected MDX files.+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.-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. Use that operation 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 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>"}}`.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.@@ -101,17 +101,14 @@ Use Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/WeUse 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.```tsx-<ws.element- ws:tag="button"- onClick={new ActionValue(["event"], expression`console.log(event)`)}->+<button onClick={new ActionValue(["event"], expression`console.log(event)`)}>Open-</ws.element>+</button>```Plain 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.-If 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 `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.+If 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.## Animation Components@@ -137,7 +134,7 @@ Video Animation settings: `timeline` is a boolean. Prefer `insert-component` forUse 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"`.```tsx-<animation.AnimateChildren+<AnimateChildrenaction={{type: "view",axis: "block",@@ -168,8 +165,7 @@ Use JSX fragments for authored animation structures when you need styled, editab],}}>- <ws.element- ws:tag="section"+ <sectionws:style={css`display: grid;gap: 16px;@@ -179,18 +175,16 @@ Use JSX fragments for authored animation structures when you need styled, editabcolor: white;`}>- <ws.element ws:tag="h2">Launch metrics</ws.element>- <ws.element ws:tag="p">- A polished card that fades up as it enters the viewport.- </ws.element>- </ws.element>-</animation.AnimateChildren>+ <h2>Launch metrics</h2>+ <p>A polished card that fades up as it enters the viewport.</p>+ </section>+</AnimateChildren>```-For Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:+For Text Animation, keep `AnimateText` as the direct child of Animation Group and place the text-containing element inside it:```tsx-<animation.AnimateChildren+<AnimateChildrenaction={{type: "view",animations: [@@ -290,20 +284,16 @@ For Text Animation, keep `animation.AnimateText` as the direct child of AnimatioisPinned: true,}}>- <animation.AnimateText- splitBy="space"- slidingWindow={5}- easing="easeOutQuart"- >- <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>- </animation.AnimateText>-</animation.AnimateChildren>+ <AnimateText splitBy="space" slidingWindow={5} easing="easeOutQuart">+ <h2>Animate words with controlled rhythm</h2>+ </AnimateText>+</AnimateChildren>```-For Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:+For Stagger Animation, put the repeated cards or rows directly inside `StaggerAnimation`:```tsx-<animation.AnimateChildren+<AnimateChildrenaction={{type: "view",animations: [@@ -325,9 +315,8 @@ For Stagger Animation, put the repeated cards or rows directly inside `animation],}}>- <animation.StaggerAnimation>- <ws.element- ws:tag="article"+ <StaggerAnimation>+ <articlews:style={css`padding: 20px;border: 1px solid #d1d5db;@@ -335,9 +324,8 @@ For Stagger Animation, put the repeated cards or rows directly inside `animation`}>Plan- </ws.element>- <ws.element- ws:tag="article"+ </article>+ <articlews:style={css`padding: 20px;border: 1px solid #d1d5db;@@ -345,9 +333,8 @@ For Stagger Animation, put the repeated cards or rows directly inside `animation`}>Build- </ws.element>- <ws.element- ws:tag="article"+ </article>+ <articlews:style={css`padding: 20px;border: 1px solid #d1d5db;@@ -355,15 +342,15 @@ For Stagger Animation, put the repeated cards or rows directly inside `animation`}>Launch- </ws.element>- </animation.StaggerAnimation>-</animation.AnimateChildren>+ </article>+ </StaggerAnimation>+</AnimateChildren>```For Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:```tsx-<animation.AnimateChildren+<AnimateChildrenaction={{type: "view",animations: [@@ -379,16 +366,16 @@ For Video Animation, use the registered template via `insert-component` when pos],}}>- <animation.VideoAnimation timeline={true}>- <$.Video+ <VideoAnimation timeline={true}>+ <Videopreload="auto"autoPlay={true}muted={true}playsInline={true}crossOrigin="anonymous"/>- </animation.VideoAnimation>-</animation.AnimateChildren>+ </VideoAnimation>+</AnimateChildren>```## Command Surface Boundarydiff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.mdindex 40505604b8..de17c00cca 100644--- a/packages/cli/src/docs/manual-mcp.md+++ b/packages/cli/src/docs/manual-mcp.md@@ -78,7 +78,7 @@ Prefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragm```json{"parentInstanceId": "root-id",- "fragment": "<ws.element ws:tag='section' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag='h2'>Northstar Product OS</ws.element><ws.element ws:tag='p'>Reusable patterns for teams.</ws.element></ws.element>"+ "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>"}```@@ -87,33 +87,26 @@ Then run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. SiWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:```tsx-<ws.element- ws:tag="section"- style={{ padding: 32, borderRadius: 16 }}->- <ws.element ws:tag="h2">Operations Console</ws.element>- <ws.element ws:tag="p">+<section style={{ padding: 32, borderRadius: 16 }}>+ <h2>Operations Console</h2>+ <p>React-style object styles become editable Webstudio styles.- </ws.element>-</ws.element>--<ws.element- ws:tag="section"- ws:tokens={[token("accent", css`color: #0f766e;`)]}->- <ws.element- ws:tag="button"+ </p>+</section>++<section ws:tokens={[token("accent", css`color: #0f766e;`)]}>+ <buttononClick={new ActionValue(["event"], expression`console.log(event)`)}>Track launch- </ws.element>-</ws.element>--<ws.element ws:tag="section">- <radix.Switch>- <radix.SwitchThumb />- </radix.Switch>-</ws.element>+ </button>+</section>++<section>+ <Switch>+ <SwitchThumb />+ </Switch>+</section>```Rules:@@ -121,12 +114,12 @@ Rules:- 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`.- 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.- 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.-- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. `animation` is the component namespace for JSX such as `<animation.AnimateChildren>`; it is not a callable CSS keyframes helper.+- `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.- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.- 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={() => ...}`.- 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.-- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.+- 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.- The positional input is JSON and defaults to `{}`.- Use `--input-file` for large mutation payloads.- 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.@@ -142,7 +135,7 @@ Rules:Use a connected `.mdx` Asset when editors should change a Content Block body visually while the document remains stored as a file.1. Create the `.mdx` file under `.webstudio/assets`, then upload it and keep the returned Asset ID.-2. Inspect the Content Block and its Templates children. Every template referenced from MDX needs a unique top-level instance name.+2. 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.3. Connect the Asset with `connect-content-block-source`. Use a stable page-based `renderScope` for a direct occurrence.4. 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.5. Edit the complete source with `edit-content-block-source`, or replace the complete frontmatter map with `update-content-block-frontmatter`.@@ -157,15 +150,19 @@ webstudio reload-content-block-source '{"blockInstanceId":"<contentBlockInstancewebstudio migrate-content-block-template-references '{"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}'```-Prefer Markdown whenever it can represent the component and all authored properties. Use `<ws.element ws:tag="tag">` for a standard HTML element with authored properties Markdown cannot express. Use `<ws.element ws:name="Template name">` only for a uniquely named top-level Content Block template. Preserve unresolved template names and report their diagnostics.+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.++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.-When 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. A rename changes matching `ws:name` values. A removal deletes matching MDX elements. Invalid files remain unchanged and are reported in diagnostics.+When 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.Use 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>"}}`.`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. 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 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.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 f2a8ef72e4..3678f7097f 100644--- a/packages/cli/src/docs/mcp-startup-epilogue.md+++ b/packages/cli/src/docs/mcp-startup-epilogue.md@@ -15,7 +15,7 @@ Save the input as `.temp/insert-fragment.json`; use single quotes for JSX attrib```json{"parentInstanceId": "parent-id",- "fragment": "<ws.element ws:tag='section' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag='h2'>Launch Kit</ws.element><ws.element ws:tag='p'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag='button'>Get started</ws.element></ws.element>"+ "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>"}```@@ -29,9 +29,9 @@ node packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.jsFor 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`.-When 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 the block's `ws:block-template` child. Templates themselves are protected; an editor's inserted copy becomes editable Content Block body content. Verify this structure before handoff.+When 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 whenever it can represent the component and all authored properties. Use `<ws.element ws:tag="tag">` for a standard HTML element with authored properties Markdown cannot express. Use `<ws.element ws:name="Template name">` only for a uniquely named top-level template. 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. 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 changes across selected MDX files.+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.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/prebuild.test.ts b/packages/cli/src/prebuild.test.tsindex 2d113639c9..1da869d1a7 100644--- a/packages/cli/src/prebuild.test.ts+++ b/packages/cli/src/prebuild.test.ts@@ -836,6 +836,14 @@ describe("prebuild", () => {{id: "content",component: "ws:block",+ children: [{ type: "id", value: "content-templates" }],+ },+ ],+ [+ "content-templates",+ {+ id: "content-templates",+ component: "ws:block-template",children: [],},],@@ -925,6 +933,14 @@ describe("prebuild", () => {id: "nested-block",component: "ws:block",label: "Nested",+ children: [{ type: "id", value: "nested-templates" }],+ },+ ],+ [+ "nested-templates",+ {+ id: "nested-templates",+ component: "ws:block-template",children: [],},],diff --git a/packages/content-engine/package.json b/packages/content-engine/package.jsonindex 4388a50cac..22ab35f17b 100644--- a/packages/content-engine/package.json+++ b/packages/content-engine/package.json@@ -20,7 +20,9 @@"@webstudio-is/expression": "workspace:*","@webstudio-is/query-builder": "workspace:*","canonicalize": "3.0.0",+ "estree-util-is-identifier-name": "3.0.0","hast-util-to-mdast": "9.0.0",+ "html-tags": "^4.0.0","lru-cache": "10.4.3","mdast-util-gfm": "2.0.2","mdast-util-mdx-expression": "1.3.2",@@ -34,11 +36,13 @@"remark-gfm": "3.0.1","remark-mdx": "2.3.0","remark-parse": "10.0.2",+ "svg-tags": "1.0.0","unified": "10.1.2","yaml": "2.9.0","zod": "^4.4.3"},"devDependencies": {+ "@types/svg-tags": "1.0.2","@webstudio-is/tsconfig": "workspace:*","esbuild": "^0.25.3","vitest": "^3.1.2"diff --git a/packages/content-engine/src/mdx-serialization.ts b/packages/content-engine/src/mdx-serialization.tsindex dc1ac72460..24f863d08a 100644--- a/packages/content-engine/src/mdx-serialization.ts+++ b/packages/content-engine/src/mdx-serialization.ts@@ -1,3 +1,7 @@+/**+ * Serializes the safe MDX document model back to authored MDX while choosing+ * Markdown or JSX syntax without exposing runtime Webstudio instances.+ */import {defaultHandlers,toMdast,@@ -13,6 +17,9 @@ import {type MdxJsxTextElement,} from "mdast-util-mdx-jsx";import { toMarkdown } from "mdast-util-to-markdown";+import { name as isIdentifierName } from "estree-util-is-identifier-name";+import htmlTags from "html-tags";+import svgTags from "svg-tags";import { serializeMarkdownFrontmatter } from "./frontmatter";import type {MdxAuthoredNode,@@ -37,6 +44,8 @@ type SerializationNode = {mode?: MdxMode;props?: readonly MdxAuthoredProp[];propsUseJsxNames?: boolean;+ jsxName?: string;+ selfClosing?: boolean;rawText?: string;rawSource?: string;};@@ -45,6 +54,28 @@ type SerializationNode = {const protectTextWhitespace = (value: string) =>value.replace(/[\t\n\v\f\r ]/g, "\uE000");+/** Authored template JSX uses one valid PascalCase JavaScript identifier. */+export const isMdxTemplateComponentName = (name: unknown): boolean => {+ if (typeof name !== "string" || isIdentifierName(name) === false) {+ return false;+ }+ const firstCharacter = Array.from(name)[0];+ return (+ firstCharacter !== undefined &&+ firstCharacter === firstCharacter.toUpperCase() &&+ firstCharacter !== firstCharacter.toLowerCase()+ );+};++const supportedIntrinsicElementTags = new Set<string>([+ ...htmlTags,+ ...svgTags,+]);++/** Authored intrinsic JSX is limited to known HTML and SVG elements. */+export const isMdxIntrinsicElementName = (name: unknown): name is string =>+ typeof name === "string" && supportedIntrinsicElementTags.has(name);+const toHastProperties = (props: readonly MdxAuthoredProp[]) =>Object.fromEntries(mapAttributeNames({@@ -73,21 +104,27 @@ const toTextNode = (: { type: "text", value };const toWebstudioElement = ({+ tagName = "ws.element",+ jsxName,mode,props,children,propsUseJsxNames,+ selfClosing,}: {+ tagName?: string;+ jsxName?: string;mode: MdxMode;props: readonly MdxAuthoredProp[];children: readonly MdxAuthoredNode[];propsUseJsxNames: boolean;+ selfClosing?: boolean;}): SerializationNode => ({type: "element",- tagName: "ws.element",+ tagName,properties: {},children: children.map((child) => toSerializationNode(child)),- data: { mode, props, propsUseJsxNames },+ data: { mode, props, propsUseJsxNames, jsxName, selfClosing },});const toSerializationNode = (@@ -108,17 +145,46 @@ const toSerializationNode = (};}if (node.type === "template") {+ const selfClosing = node.selfClosing ?? node.children.length === 0;+ if (selfClosing && node.children.length > 0) {+ throw new Error("Self-closing MDX templates cannot contain children");+ }+ if (+ node.props.some(({ name }) => name === "ws:name" || name === "ws:tag")+ ) {+ throw new Error("Named MDX templates cannot use ws:name or ws:tag");+ }+ if (isMdxTemplateComponentName(node.name)) {+ return toWebstudioElement({+ tagName: "ws.template",+ jsxName: node.name,+ mode: node.mdxMode,+ props: node.props,+ children: node.children,+ propsUseJsxNames: true,+ selfClosing,+ });+ }+ if (node.name.length === 0) {+ throw new Error("MDX template names must not be empty");+ }return toWebstudioElement({mode: node.mdxMode,props: [{ name: "ws:name", value: node.name }, ...node.props],children: node.children,propsUseJsxNames: true,+ selfClosing,});}if (node.syntax === "mdx") {+ const canUseDirectJsx = isMdxIntrinsicElementName(node.tag);return toWebstudioElement({+ tagName: "ws.element",+ jsxName: canUseDirectJsx ? node.tag : undefined,mode: node.mdxMode,- props: [{ name: "ws:tag", value: node.tag }, ...node.props],+ props: canUseDirectJsx+ ? node.props+ : [{ name: "ws:tag", value: node.tag }, ...node.props],children: node.children,propsUseJsxNames: false,});@@ -168,18 +234,23 @@ const mapWebstudioElement: Handle = (state, node) => {name: prop.name,value: prop.value === true ? null : prop.value,}));- const children = state.all(node as never);+ let children = state.all(node as never);+ if (data?.selfClosing === false && children.length === 0) {+ // hast-util-to-mdast removes empty text nodes. An empty raw node survives+ // its cleanup and makes the MDX serializer emit an explicit closing tag.+ children = [{ type: "html", value: "" }];+ }if (data?.mode === "text") {return {type: "mdxJsxTextElement",- name: "ws.element",+ name: data?.jsxName ?? "ws.element",attributes,children,} as MdxJsxTextElement;}return {type: "mdxJsxFlowElement",- name: "ws.element",+ name: data?.jsxName ?? "ws.element",attributes,children: state.toFlow(children),} as MdxJsxFlowElement;@@ -240,7 +311,11 @@ export const serializeMdxDocument = (document: MdxDocument) => {} as Parameters<typeof toMdast>[0];const mdast = toMdast(hast, {document: true,- handlers: { li: mapListItem, "ws.element": mapWebstudioElement },+ handlers: {+ li: mapListItem,+ "ws.element": mapWebstudioElement,+ "ws.template": mapWebstudioElement,+ },nodeHandlers: { comment: mapComment, opaque: mapOpaque, text: mapText },});const body = toMarkdown(mdast, {diff --git a/packages/content-engine/src/mdx.test.ts b/packages/content-engine/src/mdx.test.tsindex a0d4085e42..0ff4794cff 100644--- a/packages/content-engine/src/mdx.test.ts+++ b/packages/content-engine/src/mdx.test.ts@@ -5,6 +5,7 @@ import {createMdxCodeBlock,createMdxSourceDiagnostics,discoverMdxAssetReferences,+ isMdxTemplateComponentName,MdxDocumentError,parseMdxDocument,parseMdxDocumentRecovering,@@ -17,9 +18,36 @@ import {validateTextAssetSource,validateTextAssetSourceBytes,type MdxAuthoredNode,+ type MdxDocument,} from "./mdx";import { contentEngineLimits } from "./limits";+test("validates template names as PascalCase JavaScript identifiers", () => {+ expect(isMdxTemplateComponentName("PromotionCard")).toBe(true);+ expect(isMdxTemplateComponentName("ÉditionCard")).toBe(true);+ expect(isMdxTemplateComponentName("Card$2")).toBe(true);+ expect(isMdxTemplateComponentName("promotionCard")).toBe(false);+ expect(isMdxTemplateComponentName("$Card")).toBe(false);+ expect(isMdxTemplateComponentName("Promotion-Card")).toBe(false);+});++test("canonicalizes the legacy public template node shape", () => {+ const document: MdxDocument = {+ frontmatter: { properties: {} },+ children: [+ {+ type: "template",+ name: "Card",+ props: [],+ children: [],+ mdxMode: "flow",+ },+ ],+ };++ expect(serializeMdxDocument(document)).toBe("<Card />\n");+});+test("creates and reads canonical fenced code blocks", async () => {const node = createMdxCodeBlock({value: "const ready = true;",@@ -147,6 +175,302 @@ const forceGenericMdx = (node: MdxAuthoredNode): MdxAuthoredNode => {};describe("parseMdxDocument", () => {+ test("parses and preserves safe named JSX template references", async () => {+ const source = `<Card tone="quiet">\n ## Nested heading\n</Card>\n`;+ const document = await parseMdxDocument({ source });++ expect(omitSourceRanges(document.children)).toEqual([+ {+ type: "template",+ syntax: "jsx",+ selfClosing: false,+ name: "Card",+ props: [{ name: "tone", value: "quiet" }],+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "h2",+ props: [],+ children: [{ type: "text", value: "Nested heading" }],+ },+ ],+ mdxMode: "flow",+ },+ ]);+ expect(+ document.children[0]?.type === "template"+ ? document.children[0].props[0]?.sourceRange+ : undefined+ ).toEqual({+ start: { line: 1, column: 7, offset: 6 },+ end: { line: 1, column: 19, offset: 18 },+ });+ expect(serializeMdxDocument(document)).toBe(source);+ });++ test("parses and preserves intrinsic HTML JSX", async () => {+ const source = `<section data-kind="hero">\n <h2>Title</h2>\n</section>\n`;+ const document = await parseMdxDocument({ source });++ expect(omitSourceRanges(document.children)).toEqual([+ {+ type: "element",+ syntax: "mdx",+ tag: "section",+ props: [{ name: "data-kind", value: "hero" }],+ children: [+ {+ type: "element",+ syntax: "mdx",+ tag: "h2",+ props: [],+ children: [{ type: "text", value: "Title" }],+ mdxMode: "text",+ },+ ],+ mdxMode: "flow",+ },+ ]);+ expect(serializeMdxDocument(document)).toBe(source);+ });++ test("parses and preserves intrinsic SVG JSX", async () => {+ const source = `<svg viewBox="0 0 24 24">+ <path d="M0 0h24v24H0z" />+</svg>+`;+ const document = await parseMdxDocument({ source });++ expect(document.children[0]).toMatchObject({+ type: "element",+ syntax: "mdx",+ tag: "svg",+ children: [+ expect.objectContaining({+ type: "element",+ syntax: "mdx",+ tag: "path",+ }),+ ],+ });+ expect(serializeMdxDocument(document)).toBe(source);+ });++ test.each(["Foo", "my-widget"])(+ "preserves legacy generic tag %s when direct JSX would change its meaning",+ async (tag) => {+ const legacySource = `<ws.element ws:tag="${tag}">Text</ws.element>\n`;+ const document = await parseMdxDocument({ source: legacySource });+ const serialized = serializeMdxDocument(document);++ expect(serialized).toBe(legacySource);+ expect(+ omitSourceRanges(await parseMdxDocument({ source: serialized }))+ ).toEqual(omitSourceRanges(document));+ }+ );++ test("preserves self-closing and explicitly empty template children", async () => {+ const selfClosing = await parseMdxDocument({ source: "<Card />\n" });+ const explicitlyEmpty = await parseMdxDocument({+ source: "<Card></Card>\n",+ });++ expect(selfClosing.children[0]).toMatchObject({+ type: "template",+ syntax: "jsx",+ selfClosing: true,+ children: [],+ });+ expect(explicitlyEmpty.children[0]).toMatchObject({+ type: "template",+ syntax: "jsx",+ selfClosing: false,+ children: [],+ });+ expect(serializeMdxDocument(selfClosing)).toBe("<Card />\n");+ expect(serializeMdxDocument(explicitlyEmpty)).toBe("<Card>\n\n</Card>\n");+ expect(+ (+ await parseMdxDocument({+ source: serializeMdxDocument(explicitlyEmpty),+ })+ ).children[0]+ ).toMatchObject({ type: "template", selfClosing: false, children: [] });+ });++ test("preserves an explicitly empty inline template", async () => {+ const source = "Before <Card></Card> after\n";+ const document = await parseMdxDocument({ source });+ const paragraph = document.children[0];++ expect(paragraph).toMatchObject({ type: "element", tag: "p" });+ expect(+ paragraph?.type === "element" ? paragraph.children[1] : undefined+ ).toMatchObject({+ type: "template",+ mdxMode: "text",+ selfClosing: false,+ children: [],+ });+ expect(serializeMdxDocument(document)).toBe(source);+ });++ test("keeps line-separated JSX components outside a Markdown paragraph", async () => {+ const source =+ '<PromotionCard>test</PromotionCard>\n<Heading tag="h1">Test</Heading>\n';+ const document = await parseMdxDocument({ source });++ expect(document.children).toMatchObject([+ { type: "template", name: "PromotionCard" },+ { type: "template", name: "Heading" },+ ]);+ expect(serializeMdxDocument(document)).toBe(+ '<PromotionCard>test</PromotionCard>\n\n<Heading tag="h1">Test</Heading>\n'+ );++ const inlineDocument = await parseMdxDocument({+ source: "<Badge>New</Badge> <Badge>Sale</Badge>\n",+ });+ expect(inlineDocument.children[0]).toMatchObject({+ type: "element",+ tag: "p",+ });+ });++ test("tracks nested template closing syntax independently", async () => {+ const document = await parseMdxDocument({+ source: "<Card>\n <Link />\n</Card>\n",+ });+ const card = document.children[0];++ expect(card).toMatchObject({ type: "template", selfClosing: false });+ expect(+ card?.type === "template" ? card.children[0] : undefined+ ).toMatchObject({ type: "template", selfClosing: true });+ });++ test.each([+ "Base",+ "Link",+ "Meta",+ "Noscript",+ "Script",+ "Style",+ "Template",+ "Title",+ ])(+ "accepts capitalized template component %s despite the intrinsic denylist",+ async (name) => {+ const document = await parseMdxDocument({ source: `<${name} />\n` });++ expect(document.children[0]).toMatchObject({+ type: "template",+ syntax: "jsx",+ selfClosing: true,+ name,+ });+ expect(serializeMdxDocument(document)).toBe(`<${name} />\n`);+ await expect(+ parseMdxDocument({ source: `<${name.toLowerCase()} />\n` })+ ).rejects.toMatchObject({ code: "unsafe-mdx" });+ }+ );++ test("rejects reserved Webstudio selectors on named JSX templates", async () => {+ await expect(+ parseMdxDocument({ source: '<Card ws:name="Other" />\n' })+ ).rejects.toMatchObject({+ code: "unsafe-mdx",+ reason: "Named MDX templates cannot use ws:name or ws:tag",+ });+ await expect(+ parseMdxDocument({ source: '<Card ws:tag="section" />\n' })+ ).rejects.toMatchObject({+ code: "unsafe-mdx",+ reason: "Named MDX templates cannot use ws:name or ws:tag",+ });+ });++ test("falls back to ws.element when a JSX template name is not serializable", async () => {+ const source = serializeMdxDocument({+ frontmatter: { properties: {} },+ children: [+ {+ type: "template",+ syntax: "jsx",+ selfClosing: true,+ name: "Hero Card",+ props: [],+ children: [],+ mdxMode: "flow",+ },+ ],+ });++ expect(source).toBe('<ws.element ws:name="Hero Card" />\n');+ expect((await parseMdxDocument({ source })).children[0]).toMatchObject({+ type: "template",+ syntax: "ws-element",+ selfClosing: true,+ name: "Hero Card",+ });+ });++ test("rejects reserved selectors in programmatically created named JSX", () => {+ expect(() =>+ serializeMdxDocument({+ frontmatter: { properties: {} },+ children: [+ {+ type: "template",+ syntax: "jsx",+ selfClosing: true,+ name: "Card",+ props: [{ name: "ws:name", value: "Other" }],+ children: [],+ mdxMode: "flow",+ },+ ],+ })+ ).toThrow("Named MDX templates cannot use ws:name or ws:tag");+ });++ test("preserves legacy ws.element template reference syntax", async () => {+ const source = '<ws.element ws:name="Hero Card" />\n';+ const document = await parseMdxDocument({ source });++ expect(omitSourceRanges(document.children)).toEqual([+ {+ type: "template",+ syntax: "ws-element",+ selfClosing: true,+ name: "Hero Card",+ props: [],+ children: [],+ mdxMode: "flow",+ },+ ]);+ expect(serializeMdxDocument(document)).toBe(source);+ });++ test("preserves explicitly empty legacy template children", async () => {+ const document = await parseMdxDocument({+ source: '<ws.element ws:name="Hero Card"></ws.element>\n',+ });++ expect(document.children[0]).toMatchObject({+ type: "template",+ syntax: "ws-element",+ selfClosing: false,+ children: [],+ });+ expect(serializeMdxDocument(document)).toBe(+ '<ws.element ws:name="Hero Card">\n\n</ws.element>\n'+ );+ });+test("parses Markdown-only input identically through Markdown and MDX", () => {const source = `---title: Shared grammar@@ -622,7 +946,7 @@ Paragraph with <ws.element ws:tag="span">inline</ws.element> content.expect(serialized.indexOf("title:")).toBeLessThan(serialized.indexOf("author:"));- expect(serialized).toContain('<ws.element ws:tag="section"');+ expect(serialized).toContain('<section data-kind="hero"');expect(serialized).toContain('<ws.element ws:name="Hero Card"');expect(serialized).toContain("{/* keep this note */}");@@ -691,7 +1015,7 @@ Paragraph with <ws.element ws:tag="span">inline</ws.element> content.expect(source).toContain("- First\n- Second");expect(source).not.toContain('<ws.element ws:tag="p"');expect(source).not.toContain('<ws.element ws:tag="ul"');- expect(source).toContain('<ws.element ws:tag="section" data-kind="hero">');+ expect(source).toContain('<section data-kind="hero">');expect(source).toContain("## Title");expect(source).not.toContain('<ws.element ws:tag="h2"');expect(@@ -904,13 +1228,9 @@ next</ws.element>const preferred = serializeMdxDocument(await preferMarkdownSyntax(document));- expect(preferred).toContain(- '<ws.element ws:tag="ul">\n <ws.element ws:tag="div">Not a list item</ws.element>\n</ws.element>'- );- expect(preferred).toContain(- '<ws.element ws:tag="a" href="/guide" target="_blank">Guide</ws.element>'- );- expect(preferred).toContain('<ws.element ws:tag="ol" start="007">');+ expect(preferred).toContain("<ul>\n <div>Not a list item</div>\n</ul>");+ expect(preferred).toContain('<a href="/guide" target="_blank">Guide</a>');+ expect(preferred).toContain('<ol start="007">');});test.each([@@ -935,6 +1255,8 @@ next</ws.element>children: [{type: "template",+ syntax: "ws-element",+ selfClosing: true,name: "Card",props: [{ name: "className", value: "featured" },@@ -949,7 +1271,7 @@ next</ws.element>});expect(source).toBe(- '<ws.element ws:name="Card" className="featured" htmlFor="title" tabIndex="0" readOnly />\n'+ '<Card className="featured" htmlFor="title" tabIndex="0" readOnly />\n');expect(omitSourceRanges(await parseMdxDocument({ source }))).toMatchObject({frontmatter: { properties: {} },@@ -980,14 +1302,14 @@ next</ws.element>});});- test("roundtrips template JSX prop names without component metadata", async () => {+ test("canonicalizes legacy template JSX without component metadata", async () => {const source = '<ws.element ws:name="Card" class="featured" />\n';const document = await parseMdxDocument({ source });- expect(serializeMdxDocument(document)).toBe(source);+ expect(serializeMdxDocument(document)).toBe('<Card class="featured" />\n');});- test("preserves template prop aliases for metadata-aware materialization", async () => {+ test("preserves legacy template prop aliases while canonicalizing syntax", async () => {const source ='<ws.element ws:name="Card" class="legacy" className="canonical" />\n';const document = await parseMdxDocument({ source });@@ -999,6 +1321,26 @@ next</ws.element>{ name: "className", value: "canonical" },],});+ expect(serializeMdxDocument(document)).toBe(+ '<Card class="legacy" className="canonical" />\n'+ );+ });++ test("preserves component JSX prop aliases for metadata-aware materialization", async () => {+ const source =+ '<Image class="legacy" className="canonical" alt="Example" />\n';+ const document = await parseMdxDocument({ source });++ expect(document.children[0]).toMatchObject({+ type: "template",+ syntax: "jsx",+ name: "Image",+ props: [+ { name: "class", value: "legacy" },+ { name: "className", value: "canonical" },+ { name: "alt", value: "Example" },+ ],+ });expect(serializeMdxDocument(document)).toBe(source);});@@ -1066,8 +1408,7 @@ next</ws.element>'<ws.element ws:tag="div" {...props} />',"mdxJsxExpressionAttribute",],- ["arbitrary components", "<Card />", "mdxJsxFlowElement"],- ["HTML-looking JSX", "<div>Unsafe</div>", "mdxJsxTextElement"],+ ["unknown lowercase JSX", "<card />", "mdxJsxFlowElement"],])("rejects %s", async (_name, source, nodeType) => {await expect(parseMdxDocument({ source })).rejects.toMatchObject({code: "unsafe-mdx",@@ -1220,7 +1561,7 @@ describe("parseMdxDocumentRecovering", () => {test("continues after an unsupported component to report every sibling", async () => {const result = await validateMdxDocumentSource({- source: "{first()}\n\n<Card />\n\n{second()}\n",+ source: "{first()}\n\n<Card.Item />\n\n{second()}\n",});expect(result.diagnostics).toEqual([@@ -1238,12 +1579,14 @@ describe("parseMdxDocumentRecovering", () => {{code: "unsafe-mdx",severity: "warning",- message: "Only the ws.element component is supported in authored MDX",+ message:+ "Only standard HTML and SVG elements and named template components are supported in authored MDX",nodeType: "mdxJsxFlowElement",- reason: "Only the ws.element component is supported in authored MDX",+ reason:+ "Only standard HTML and SVG elements and named template components are supported in authored MDX",sourceRange: {start: { line: 3, column: 1, offset: 11 },- end: { line: 3, column: 9, offset: 19 },+ end: { line: 3, column: 14, offset: 24 },},},{@@ -1253,8 +1596,8 @@ describe("parseMdxDocumentRecovering", () => {nodeType: "mdxFlowExpression",reason: "Executable MDX expressions are not supported",sourceRange: {- start: { line: 5, column: 1, offset: 21 },- end: { line: 5, column: 11, offset: 31 },+ start: { line: 5, column: 1, offset: 26 },+ end: { line: 5, column: 11, offset: 36 },},},]);@@ -1262,13 +1605,13 @@ describe("parseMdxDocumentRecovering", () => {test("reports diagnostics nested inside an unsupported component", async () => {const result = await validateMdxDocumentSource({- source: "<Card>{danger()}<Other /></Card>\n",+ source: "<Card.Item>{danger()}<Other.Item /></Card.Item>\n",});expect(result.diagnostics.map(({ message }) => message)).toEqual([- "Only the ws.element component is supported in authored MDX",+ "Only standard HTML and SVG elements and named template components are supported in authored MDX","Executable MDX expressions are not supported",- "Only the ws.element component is supported in authored MDX",+ "Only standard HTML and SVG elements and named template components are supported in authored MDX",]);expect(result.diagnostics.map((diagnostic) =>@@ -1276,7 +1619,7 @@ describe("parseMdxDocumentRecovering", () => {? diagnostic.sourceRange?.start.offset: undefined)- ).toEqual([0, 6, 16]);+ ).toEqual([0, 11, 21]);});test("ignores invalid JSX properties without dropping the element", async () => {diff --git a/packages/content-engine/src/mdx.ts b/packages/content-engine/src/mdx.tsindex 601d684c92..8138a42452 100644--- a/packages/content-engine/src/mdx.ts+++ b/packages/content-engine/src/mdx.ts@@ -1,3 +1,7 @@+/**+ * Defines the safe MDX document model and owns parsing, validation, asset+ * reference discovery, and source-preserving document edits.+ */import {defaultHandlers,toHast,@@ -34,7 +38,11 @@ import {} from "./markdown-ast";import { findMarkdownFrontmatter } from "./markdown-scanner";import { extractMarkdownBody } from "./markdown-body";-import { serializeMdxDocument } from "./mdx-serialization";+import {+ isMdxIntrinsicElementName,+ isMdxTemplateComponentName,+ serializeMdxDocument,+} from "./mdx-serialization";import { MarkdownMetadataError } from "./markdown-errors";export type MdxSourcePoint = Readonly<{@@ -100,6 +108,20 @@ export type MdxAuthoredNode =}>| Readonly<{type: "template";+ /**+ * Additive parse metadata. Legacy callers may omit it; serialization+ * then preserves the historical ws.element representation.+ */+ syntax?: "jsx" | "ws-element";+ /**+ * Self-closing template usages inherit the template's default children.+ * Paired tags explicitly replace them, including when children is empty.+ */+ /**+ * Additive parse metadata. Legacy callers may omit it, in which case+ * serialization infers the historical behavior from children.+ */+ selfClosing?: boolean;name: string;props: readonly MdxAuthoredProp[];children: readonly MdxAuthoredNode[];@@ -314,33 +336,69 @@ const toSourceRange = (position: unknown): MdxSourceRange | undefined => {}};-const addMdxJsxAttributePositions = (root: SyntaxTreeNode, source: string) => {- if (source.includes("<ws.element") === false) {+const addMdxJsxSourceMetadata = (root: SyntaxTreeNode, source: string) => {+ if (source.includes("<") === false) {return;}- let ranges: Array<{ start: unknown; end: unknown }>;+ let events: ReturnType<typeof postprocess>;try {- ranges = postprocess(+ events = postprocess(parse({ extensions: [mdxjs()] }).document().write(preprocess()(source, undefined, true))- ).flatMap(([phase, token]) => {- const tokenType: string = token.type;- return phase === "enter" &&- (tokenType === "mdxJsxFlowTagAttribute" ||- tokenType === "mdxJsxTextTagAttribute" ||- tokenType === "mdxJsxFlowTagExpressionAttribute" ||- tokenType === "mdxJsxTextTagExpressionAttribute")- ? [{ start: token.start, end: token.end }]- : [];- });+ );} catch {- // Source validation remains owned by the document parser. Location- // enrichment must not make otherwise recoverable MDX unrecoverable.+ // Source validation remains owned by the document parser. Location and+ // syntax enrichment must not make otherwise recoverable MDX unrecoverable.return;}+ const ranges = events.flatMap(([phase, token]) => {+ const tokenType: string = token.type;+ return phase === "enter" &&+ (tokenType === "mdxJsxFlowTagAttribute" ||+ tokenType === "mdxJsxTextTagAttribute" ||+ tokenType === "mdxJsxFlowTagExpressionAttribute" ||+ tokenType === "mdxJsxTextTagExpressionAttribute")+ ? [{ start: token.start, end: token.end }]+ : [];+ });+ const selfClosingTagOffsets = new Set<number>();+ let activeTagStartOffset: number | undefined;+ for (const [phase, token] of events) {+ const tokenType: string = token.type;+ if (+ phase === "enter" &&+ (tokenType === "mdxJsxFlowTag" || tokenType === "mdxJsxTextTag")+ ) {+ activeTagStartOffset = toSourcePoint(token.start)?.offset;+ continue;+ }+ if (+ phase === "enter" &&+ tokenType.endsWith("TagSelfClosingMarker") &&+ activeTagStartOffset !== undefined+ ) {+ selfClosingTagOffsets.add(activeTagStartOffset);+ continue;+ }+ if (+ phase === "exit" &&+ (tokenType === "mdxJsxFlowTag" || tokenType === "mdxJsxTextTag")+ ) {+ activeTagStartOffset = undefined;+ }+ }const visit = (node: SyntaxTreeNode) => {const nodeRange = toSourceRange(node.position);+ if (+ nodeRange?.start.offset !== undefined &&+ (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement")+ ) {+ node.data = {+ ...(isRecord(node.data) ? node.data : {}),+ mdxSelfClosing: selfClosingTagOffsets.has(nodeRange.start.offset),+ };+ }if (nodeRange !== undefined && Array.isArray(node.attributes)) {let rangeIndex = ranges.findIndex(({ start }) => {const point = toSourcePoint(start);@@ -682,20 +740,35 @@ const createMdxJsxElementHandler =(options: MapHastOptions = {}): Handler =>(state, value) => {const node = value as SyntaxTreeNode;- if (node.name !== "ws.element") {+ const tagName =+ typeof node.name === "string"+ ? node.name+ : throwUnsafeNode(node, "MDX JSX elements must have a name");+ const isTemplate = isMdxTemplateComponentName(tagName);+ const isIntrinsic = isMdxIntrinsicElementName(tagName);+ if (+ tagName !== "ws.element" &&+ isTemplate === false &&+ isIntrinsic === false+ ) {return throwUnsafeNode(node,- "Only the ws.element component is supported in authored MDX"+ "Only standard HTML and SVG elements and named template components are supported in authored MDX");}const staticProps = mapStaticProps(node, options);const properties = Object.fromEntries(staticProps.map((prop) => [prop.name, prop.value]));- const result = state(value, "ws.element", properties, state.all(value));+ const result = state(value, tagName, properties, state.all(value));if (isSyntaxTreeNode(result)) {setHastData(result, {mdxMode: getMdxMode(node),+ mdxSelfClosing:+ isRecord(node.data) && node.data.mdxSelfClosing === true,+ ...(tagName === "ws.element" || isIntrinsic+ ? {}+ : { mdxTemplateName: tagName, mdxTemplateProps: staticProps }),mdxPropSourceRanges: Object.fromEntries(staticProps.flatMap((prop) =>prop.sourceRange === undefined@@ -741,6 +814,24 @@ const mapParagraph: Handler = (state, value) => {if (children.length === 1 && children[0].type === "mdxJsxTextElement") {return state.one(value.children[0], value);}+ const jsxChildren = children.filter(+ (child) => child.type === "mdxJsxTextElement"+ );+ if (+ jsxChildren.length > 1 &&+ children.every(+ (child) =>+ child.type === "mdxJsxTextElement" ||+ (child.type === "text" &&+ typeof child.value === "string" &&+ child.value.includes("\n") &&+ child.value.trim() === "")+ )+ ) {+ return state+ .all(value)+ .filter((child) => child.type !== "text" || child.value.trim() !== "");+ }return defaultHandlers.paragraph(state, value);};@@ -864,6 +955,19 @@ const findHastMdxMode = (node: SyntaxTreeNode): MdxMode | undefined => {}};+const findHastTemplateName = (node: SyntaxTreeNode) =>+ isRecord(node.data) && typeof node.data.mdxTemplateName === "string"+ ? node.data.mdxTemplateName+ : undefined;++const findHastTemplateProps = (node: SyntaxTreeNode) =>+ isRecord(node.data) && Array.isArray(node.data.mdxTemplateProps)+ ? (node.data.mdxTemplateProps as readonly MdxAuthoredProp[])+ : undefined;++const getHastMdxSelfClosing = (node: SyntaxTreeNode) =>+ isRecord(node.data) && node.data.mdxSelfClosing === true;+const mapHastProperties = (node: SyntaxTreeNode,options: MapHastOptions,@@ -1016,6 +1120,8 @@ const mapWebstudioElement = (}return {type: "template",+ syntax: "ws-element",+ selfClosing: getHastMdxSelfClosing(node),name: nameProp.value,props: props.filter((prop) => prop.name !== "ws:name"),children: mapHastChildren(node, options),@@ -1100,8 +1206,42 @@ const mapHastNode = ();}const authoredMdxMode = findHastMdxMode(node);+ const templateName = findHastTemplateName(node);+ const templateProps =+ templateName === undefined ? undefined : findHastTemplateProps(node);+ const { props, requiresMdxFallback } =+ templateProps === undefined+ ? mapHastProperties(+ node,+ options,+ node.tagName === "ws.element" || templateName !== undefined,+ node.tagName === "ws.element" &&+ isRecord(node.properties) &&+ Object.hasOwn(node.properties, "ws:name")+ )+ : { props: templateProps, requiresMdxFallback: false };+ if (node.tagName === "ws.element") {+ return mapWebstudioElement(node, props, options);+ }+ if (templateName !== undefined) {+ if (props.some(({ name }) => name === "ws:name" || name === "ws:tag")) {+ return throwUnsafeNode(+ node,+ "Named MDX templates cannot use ws:name or ws:tag"+ );+ }+ return {+ type: "template",+ syntax: "jsx",+ selfClosing: getHastMdxSelfClosing(node),+ name: templateName,+ props,+ children: mapHastChildren(node, options),+ mdxMode: getHastMdxMode(node),+ sourceRange: toSourceRange(node.position),+ };+ }if (- node.tagName !== "ws.element" &&authoredMdxMode !== undefined &&unsupportedElementTags.has(node.tagName.toLowerCase())) {@@ -1110,17 +1250,6 @@ const mapHastNode = (`Webstudio element tag ${node.tagName} is not supported`);}- const { props, requiresMdxFallback } = mapHastProperties(- node,- options,- node.tagName === "ws.element",- node.tagName === "ws.element" &&- isRecord(node.properties) &&- Object.hasOwn(node.properties, "ws:name")- );- if (node.tagName === "ws.element") {- return mapWebstudioElement(node, props, options);- }let mdxMode = authoredMdxMode ?? (requiresMdxFallback ? "text" : undefined);const children = mapHastChildren(node, options);const onlyChild = children.length === 1 ? children[0] : undefined;@@ -1403,7 +1532,7 @@ export const parseMdxDocument = async ({cause,});}- addMdxJsxAttributePositions(root, source);+ addMdxJsxSourceMetadata(root, source);validateAstLimits(root);return {@@ -1433,7 +1562,7 @@ export const parseMdxDocumentRecovering = async ({try {validateMdxSourceBytes({ source, maximumBytes });const root = parseMarkdownAst(source, "mdx");- addMdxJsxAttributePositions(root, source);+ addMdxJsxSourceMetadata(root, source);validateAstLimits(root);const diagnostics: MdxDocumentError[] = [];const recovery = createRecoveringHandlers({ source, diagnostics });@@ -1729,6 +1858,9 @@ const areAuthoredNodesEquivalent = (if (left.type === "template" && right.type === "template") {return (left.name === right.name &&+ (left.syntax ?? "ws-element") === (right.syntax ?? "ws-element") &&+ (left.selfClosing ?? left.children.length === 0) ===+ (right.selfClosing ?? right.children.length === 0) &&areAuthoredPropsEqual(left.props, right.props) &&areAuthoredNodeListsEquivalent(left.children, right.children, false));@@ -1873,5 +2005,5 @@ export const replaceMdxFrontmatter = async ({return replaceMarkdownFrontmatter({ source, properties });};-export { serializeMdxDocument };+export { isMdxTemplateComponentName, serializeMdxDocument };export { createCanonicalAssetPath } from "./asset-path";diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex 47c7169fd5..3ed5cb23f2 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -1455,6 +1455,8 @@ export const setInstanceTag = runtimeProjectMutation("set-instance-tag");export const setInstanceLabel = runtimeProjectMutation("set-instance-label");+export const setInstanceName = runtimeProjectMutation("set-instance-name");+export const updateSelectedStyleDeclarations = runtimeProjectMutation("update-selected-styles");diff --git a/packages/project-build/src/content-database.test.ts b/packages/project-build/src/content-database.test.tsindex 13155d90cc..9d29397247 100644--- a/packages/project-build/src/content-database.test.ts+++ b/packages/project-build/src/content-database.test.ts@@ -266,6 +266,67 @@ describe("Content Block MDX compilation", () => {expect(queryIds).not.toContain("__content-block-mdx__:private.mdx");});+ test("retains nested sources through semantic component templates", async () => {+ const build = createBuild({});+ build.instances[0].children = [{ type: "id", value: "templates" }];+ build.instances.push(+ {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: [{ type: "id", value: "paragraph" }],+ },+ {+ type: "instance",+ id: "paragraph",+ component: "Paragraph",+ children: [{ type: "id", value: "nested" }],+ },+ {+ type: "instance",+ id: "nested",+ component: "ws:block",+ children: [],+ }+ );+ build.props.push({+ id: "nested-source",+ instanceId: "nested",+ name: "src",+ type: "asset",+ value: "nested.mdx",+ });+ const source = "Authored paragraph\n";+ const artifact = {+ format: "webstudio-content-database",+ version: 1,+ documents: [+ {+ _id: "article.mdx",+ _type: "asset.file",+ name: "article.mdx",+ path: "article.mdx",+ key: "article",+ extension: "mdx",+ mimeType: "text/mdx",+ size: source.length,+ revision: "article-revision",+ contentRef: "article.mdx",+ },+ ],+ contents: { "article.mdx": source },+ } as unknown as ContentArtifactV1;++ const plan = await resolvePublishedMdxDependencyClosure({+ build,+ artifact,+ });++ expect(plan?.queries.map(({ id }) => id)).toContain(+ "__content-block-mdx__:nested.mdx"+ );+ });+test("keeps internal MDX retention out of Assets Resource plans", () => {expect(createBuildContentCompilationPlan(createBuild({}))).toBeUndefined();});diff --git a/packages/project-build/src/content-database.ts b/packages/project-build/src/content-database.tsindex 9c3fc85a6a..39c13c83a9 100644--- a/packages/project-build/src/content-database.ts+++ b/packages/project-build/src/content-database.ts@@ -33,8 +33,12 @@ import {} from "@webstudio-is/sdk";import { parseStaticMemberPath } from "@webstudio-is/expression";import type { Pages } from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import { parseMdxDocumentRecovering } from "@webstudio-is/content-engine/mdx";-import { resolveMdxTemplates } from "./runtime/mdx-template-resolution";+import {+ assertMdxTemplateStructure,+ resolveMdxTemplates,+} from "./runtime/mdx-template-resolution";type BuildValues<Value> =| readonly Value[]@@ -226,6 +230,7 @@ export const resolvePublishedMdxDependencyClosure = async ({]));const props = getBuildValues<Prop>(build.props);+ const propsById = new Map(props.map((prop) => [prop.id, prop]));const sourcesByBlockId = getContentBlockSources({instances: instances.values(),props,@@ -301,8 +306,10 @@ export const resolvePublishedMdxDependencyClosure = async ({renderScope: "publication-dependency-discovery",},instances,- metas: new Map(),+ props: propsById,+ metas: componentMetas,});+ assertMdxTemplateStructure(resolution);for (const reference of resolution.references) {if (reference.type === "resolved-template") {visitTemplateSubtree(reference.templateInstanceId);diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.tsindex 396bc12291..571768e9f2 100644--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts@@ -353,6 +353,106 @@ export const runtimeOperationContractData = [],additionalProperties: false,},+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ambiguous-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ semanticKey: {+ type: "string",+ minLength: 1,+ },+ templateNames: {+ minItems: 2,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "semanticKey",+ "templateNames",+ ],+ additionalProperties: false,+ },{type: "object",properties: {@@ -833,6 +933,106 @@ export const runtimeOperationContractData = [],additionalProperties: false,},+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ambiguous-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ semanticKey: {+ type: "string",+ minLength: 1,+ },+ templateNames: {+ minItems: 2,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "semanticKey",+ "templateNames",+ ],+ additionalProperties: false,+ },{type: "object",properties: {@@ -1332,6 +1532,106 @@ export const runtimeOperationContractData = [],additionalProperties: false,},+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ambiguous-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ semanticKey: {+ type: "string",+ minLength: 1,+ },+ templateNames: {+ minItems: 2,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "semanticKey",+ "templateNames",+ ],+ additionalProperties: false,+ },{type: "object",properties: {@@ -1797,6 +2097,106 @@ export const runtimeOperationContractData = [],additionalProperties: false,},+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ambiguous-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ semanticKey: {+ type: "string",+ minLength: 1,+ },+ templateNames: {+ minItems: 2,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "semanticKey",+ "templateNames",+ ],+ additionalProperties: false,+ },{type: "object",properties: {@@ -2268,6 +2668,106 @@ export const runtimeOperationContractData = [],additionalProperties: false,},+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ambiguous-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ semanticKey: {+ type: "string",+ minLength: 1,+ },+ templateNames: {+ minItems: 2,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "semanticKey",+ "templateNames",+ ],+ additionalProperties: false,+ },{type: "object",properties: {@@ -2793,107 +3293,207 @@ export const runtimeOperationContractData = [},code: {type: "string",- const: "ignored-template-prop",+ const: "ambiguous-template",},severity: {type: "string",const: "warning",},- templateName: {- type: "string",- minLength: 1,- },- propName: {+ semanticKey: {type: "string",minLength: 1,},- reason: {- type: "string",- enum: ["unknown", "incompatible", "design-only", "stale"],+ templateNames: {+ minItems: 2,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },},},required: ["blockInstanceId","code","severity",- "templateName",- "propName",- "reason",+ "semanticKey",+ "templateNames",],additionalProperties: false,},- ],- },- },- },- required: ["assetId", "source", "status", "diagnostics"],- additionalProperties: {},- },- readNamespaces: [- "pages",- "instances",- "props",- "dataSources",- "resources",- "styleSources",- "styleSourceSelections",- "styles",- "breakpoints",- "assets",- ],- writeNamespaces: ["assets"],- invalidatesNamespaces: ["assets"],- retryOnConflict: false,- requiresAssets: true,- },- {- id: "contentBlocks.reloadSource",- command: "reload-content-block-source",- client: "reloadContentBlockSource",- permit: "view",- kind: "read",- inputSchema: {- type: "object",- properties: {- blockInstanceId: {- type: "string",- minLength: 1,- },- renderScope: {- type: "string",- minLength: 1,- description:- "Stable occurrence key; does not load route or resource data.",- },- variables: {- description:- 'Concrete expression values. Result-one example: {post:{data:{id:"<mdxAssetId>"}}}.',- type: "object",- propertyNames: {- type: "string",- },- additionalProperties: {},- },- },- required: ["blockInstanceId", "renderScope"],- },- outputSchema: {- type: "object",- properties: {- assetId: {- type: "string",- },- source: {- type: "string",- },- status: {- type: "string",- enum: ["saved", "pending", "saving", "failed", "conflicting"],- },- diagnostics: {- type: "array",- items: {- oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ },+ required: ["assetId", "source", "status", "diagnostics"],+ additionalProperties: {},+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: ["assets"],+ invalidatesNamespaces: ["assets"],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.reloadSource",+ command: "reload-content-block-source",+ client: "reloadContentBlockSource",+ permit: "view",+ kind: "read",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ description:+ "Stable occurrence key; does not load route or resource data.",+ },+ variables: {+ description:+ 'Concrete expression values. Result-one example: {post:{data:{id:"<mdxAssetId>"}}}.',+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {},+ },+ },+ required: ["blockInstanceId", "renderScope"],+ },+ outputSchema: {+ type: "object",+ properties: {+ assetId: {+ type: "string",+ },+ source: {+ type: "string",+ },+ status: {+ type: "string",+ enum: ["saved", "pending", "saving", "failed", "conflicting"],+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [{type: "object",properties: {@@ -3167,6 +3767,106 @@ export const runtimeOperationContractData = [],additionalProperties: false,},+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ambiguous-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ semanticKey: {+ type: "string",+ minLength: 1,+ },+ templateNames: {+ minItems: 2,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "semanticKey",+ "templateNames",+ ],+ additionalProperties: false,+ },{type: "object",properties: {@@ -7083,6 +7783,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -10289,6 +10993,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -13506,6 +14214,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -16712,6 +17424,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -22619,6 +23335,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -26033,6 +26753,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -29608,6 +30332,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -40710,6 +41438,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -43995,6 +44727,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -50653,6 +51389,106 @@ export const runtimeOperationContractData = [],additionalProperties: false,},+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ambiguous-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ semanticKey: {+ type: "string",+ minLength: 1,+ },+ templateNames: {+ minItems: 2,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "semanticKey",+ "templateNames",+ ],+ additionalProperties: false,+ },{type: "object",properties: {@@ -50941,6 +51777,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -56836,6 +57676,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -66722,6 +67566,10 @@ export const runtimeOperationContractData = [description:"Optional HTML tag override for component rendering. Omit for component defaults; never pass an empty string.",},+ name: {+ type: "string",+ minLength: 1,+ },label: {type: "string",},@@ -66980,6 +67828,72 @@ export const runtimeOperationContractData = [invalidatesNamespaces: ["instances"],retryOnConflict: true,},+ {+ id: "instances.setName",+ command: "set-instance-name",+ client: "setInstanceName",+ permit: "edit",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ name: {+ type: "string",+ },+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },+ },+ required: ["instanceId", "name"],+ },+ outputSchema: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ name: {+ type: "string",+ },+ },+ required: ["instanceId", "name"],+ additionalProperties: {},+ },+ readNamespaces: ["instances", "props"],+ writeNamespaces: ["instances"],+ invalidatesNamespaces: ["instances"],+ retryOnConflict: true,+ },{id: "styles.getDeclarations",command: "get-styles",diff --git a/packages/project-build/src/docs.generated.ts b/packages/project-build/src/docs.generated.tsindex a88cea6aca..c29103a97d 100644--- a/packages/project-build/src/docs.generated.ts+++ b/packages/project-build/src/docs.generated.ts@@ -4,7 +4,7 @@ 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 `ws.element` root.\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\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',} as const;diff --git a/packages/project-build/src/docs/expressions.md b/packages/project-build/src/docs/expressions.mdindex e78b17d15a..76658b2fbf 100644--- a/packages/project-build/src/docs/expressions.md+++ b/packages/project-build/src/docs/expressions.md@@ -120,7 +120,7 @@ response wrapper or one indexed item. The command creates the Collection andits private item parameters atomically, then renders the item root once perentry. Bind descendants with expressions such as `collectionItem.name`; forobject iteration, `collectionItemKey` contains the current key. Wrap multiple-repeated siblings in one `ws.element` root.+repeated siblings in one lowercase HTML root such as `<div>`.## Verificationdiff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex d69fc45fb0..a16782a2dc 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -9,6 +9,7 @@ import { ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";import { parseExpressionAt } from "acorn";import { describe, expect, test, vi } from "vitest";import { z } from "zod";+import { parseDirectPathExpression } from "@webstudio-is/expression";import type { WsComponentMeta } from "@webstudio-is/sdk";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import { validateAssetQuery } from "@webstudio-is/content-engine";@@ -17,6 +18,7 @@ import { runtimeOperationContracts } from "./contracts/builder-runtime";import { getInputSchemaMetadata } from "./contracts/input-schema";import { imageDescriptionsSetInput } from "./runtime/assets";import { BuilderRuntimeError } from "./runtime/errors";+import { parseWebstudioJsxFragment } from "./runtime/jsx";import {createProjectSessionMcpCore,createProjectSessionMcpServer,@@ -4261,7 +4263,7 @@ describe("project session mcp adapter", () => {inputFile: expect.objectContaining({path: ".temp/design-system-section.json",contents: expect.objectContaining({- fragment: expect.stringContaining("ws:tag='h2'"),+ fragment: expect.stringContaining("<h2>"),}),}),nextPhase: "commit-section",@@ -4792,6 +4794,30 @@ describe("project session mcp adapter", () => {expect(markdownBlogGuide.structuredContent.data).toEqual(expect.objectContaining({recipe: expect.objectContaining({+ executionOrder: [+ { tool: "create-asset-folder", calls: 1 },+ { tool: "upload-assets", calls: 1 },+ { tool: "create-page", calls: 2 },+ { tool: "validate-asset-query", calls: 2 },+ { tool: "preview-asset-query", calls: 1 },+ { tool: "meta.get-more-tools", calls: 1 },+ { tool: "create-assets-resource", calls: 2 },+ { tool: "insert-collection", calls: 1 },+ { tool: "insert-fragment", calls: 1 },+ { tool: "update-page", calls: 1 },+ {+ tool: "verify-page-responsive",+ calls: 2,+ terminal: true,+ },+ ],+ toolDiscovery: {+ tool: "meta.get-more-tools",+ when: "after-query-verification",+ input: {+ tools: ["create-assets-resource"],+ },+ },overviewResource: expect.objectContaining({dataSourceName: "posts",query: expect.objectContaining({@@ -4800,6 +4826,17 @@ describe("project session mcp adapter", () => {offset: { type: "literal", value: 0 },}),}),+ overviewValidationQuery: expect.objectContaining({+ where: {+ all: expect.arrayContaining([+ expect.objectContaining({ value: "md" }),+ expect.objectContaining({ value: "<blog-folder-id>" }),+ expect.objectContaining({ value: true }),+ ]),+ },+ limit: 20,+ offset: 0,+ }),detailResource: expect.objectContaining({dataSourceName: "post",query: expect.objectContaining({@@ -4807,6 +4844,17 @@ describe("project session mcp adapter", () => {content: { mode: "markdown-body-ref" },}),}),+ detailValidationQuery: expect.objectContaining({+ result: "one",+ where: {+ all: expect.arrayContaining([+ expect.objectContaining({ value: "md" }),+ expect.objectContaining({ value: "<blog-folder-id>" }),+ expect.objectContaining({ value: "aurora-trails" }),+ expect.objectContaining({ value: true }),+ ]),+ },+ }),overviewCollection: expect.objectContaining({itemFragment: expect.stringContaining("collectionItem.properties.author.name"@@ -4814,7 +4862,7 @@ describe("project session mcp adapter", () => {}),detailFragment: expect.objectContaining({parentInstanceId: "<detail-root-id>",- fragment: expect.stringContaining("post.data.content.text"),+ fragment: expect.any(String),}),detailPageSettings: expect.objectContaining({pageId: "<detail-page-id>",@@ -4839,6 +4887,56 @@ describe("project session mcp adapter", () => {]),}));+ const markdownBlogRecipe = (+ markdownBlogGuide.structuredContent.data as {+ recipe: {+ detailResource: {+ query: {+ output: { fields: string[][] };+ };+ };+ detailFragment: { fragment: string };+ detailPageSettings: {+ values: {+ meta: { socialImageUrl: string };+ };+ };+ };+ }+ ).recipe;+ const detailFragment = await parseWebstudioJsxFragment(+ markdownBlogRecipe.detailFragment.fragment+ );+ const markdownEmbedInstances = detailFragment.instances.filter(+ (instance) => instance.component === "MarkdownEmbed"+ );+ const markdownCodeProps = detailFragment.props.filter(+ (prop) =>+ prop.instanceId === markdownEmbedInstances[0]?.id &&+ prop.name === "code" &&+ prop.type === "expression"+ );+ expect(markdownEmbedInstances).toHaveLength(1);+ expect(markdownCodeProps).toHaveLength(1);+ expect(+ parseDirectPathExpression(String(markdownCodeProps[0]?.value))?.path+ ).toEqual(["post", "data", "content", "text"]);+ expect(+ markdownBlogRecipe.detailResource.query.output.fields+ ).toContainEqual(["properties", "featureImage", "src"]);+ expect(+ markdownBlogRecipe.detailResource.query.output.fields+ ).not.toContainEqual(["properties", "featureImage"]);+ expect(+ markdownBlogRecipe.detailPageSettings.values.meta.socialImageUrl+ ).toBe('post.data.properties.featureImage.src ?? ""');+ expect(+ (+ markdownBlogGuide.structuredContent.data as {+ recipe: Record<string, unknown>;+ }+ ).recipe+ ).not.toHaveProperty("detailCollection");expect(authenticatedPageGuide.structuredContent.data).toEqual(expect.objectContaining({recipe: {@@ -4869,6 +4967,21 @@ describe("project session mcp adapter", () => {}));expect(fontAssetGuide.structuredContent.data).not.toHaveProperty("brief");+ expect(fontAssetGuide.structuredContent.data).toEqual(+ expect.objectContaining({+ recipe: {+ upload: {+ tool: "upload-assets",+ input: {+ assetsDir: ".webstudio/assets",+ assetFields: ["name", "type", "format", "meta"],+ excludedAssetFields: ["path"],+ },+ },+ audit: { tool: "audit", input: {} },+ },+ })+ );for (const tool of (fontAssetGuide.structuredContent.data as {tools: Array<Record<string, unknown>>;@@ -4880,6 +4993,18 @@ describe("project session mcp adapter", () => {}expect(designInputGuide.structuredContent.data).toEqual(expect.objectContaining({+ recipe: {+ insertion: { includeStyles: false },+ tokenReuse: {+ minimumAttachments: 1,+ source: "inspect-design-context",+ },+ responsiveStyles: {+ tool: "update-styles",+ breakpointSource: "inspect-design-context",+ minimumBreakpointSpecificUpdates: 1,+ },+ },tools: expect.arrayContaining([expect.objectContaining({ name: "inspect-design-context" }),expect.objectContaining({ name: "components.search" }),@@ -5224,7 +5349,8 @@ describe("project session mcp adapter", () => {}),expect.objectContaining({component: "@webstudio-is/sdk-components-react-radix:Checkbox",- jsxElement: "<radix.Checkbox />",+ jsxName: "RadixCheckbox",+ jsxElement: "<RadixCheckbox />",hasTemplate: true,templateRootComponents: ["@webstudio-is/sdk-components-react-radix:Label",@@ -5233,7 +5359,8 @@ describe("project session mcp adapter", () => {expect.objectContaining({component:"@webstudio-is/sdk-components-react-radix:SelectItemIndicator",- jsxElement: "<radix.SelectItemIndicator />",+ jsxName: "SelectItemIndicator",+ jsxElement: "<SelectItemIndicator />",standaloneInsertable: false,}),]),@@ -5622,7 +5749,6 @@ describe("project session mcp adapter", () => {expect(collectionDetails.structuredContent.data).toEqual(expect.objectContaining({component: "ws:collection",- jsxElement: "<ws.collection />",props: expect.objectContaining({data: expect.objectContaining({ type: "json", required: true }),item: expect.objectContaining({ type: "string" }),@@ -5630,13 +5756,18 @@ describe("project session mcp adapter", () => {}),}));+ expect(collectionDetails.structuredContent.data).not.toHaveProperty(+ "jsxElement"+ );expect(blockTemplateDetails.structuredContent.data).toEqual(expect.objectContaining({component: "ws:block-template",- jsxElement: "<ws.blockTemplate />",standaloneInsertable: false,}));+ expect(blockTemplateDetails.structuredContent.data).not.toHaveProperty(+ "jsxElement"+ );expect(selectTemplateDetails.structuredContent.data).toEqual(expect.objectContaining({found: true,@@ -5787,25 +5918,25 @@ describe("project session mcp adapter", () => {covered: expect.arrayContaining([expect.objectContaining({component: "@webstudio-is/sdk-components-react-radix:Switch",- jsxElement: "<radix.Switch />",+ jsxElement: "<Switch />",}),]),missing: expect.arrayContaining([expect.objectContaining({component: "@webstudio-is/sdk-components-react-radix:Select",- jsxElement: "<radix.Select />",+ jsxElement: "<RadixSelect />",}),]),missingRoots: expect.arrayContaining([expect.objectContaining({component: "@webstudio-is/sdk-components-react-radix:Select",- jsxElement: "<radix.Select />",+ jsxElement: "<RadixSelect />",}),]),missingParts: expect.arrayContaining([expect.objectContaining({component: "@webstudio-is/sdk-components-react-radix:AccordionItem",- jsxElement: "<radix.AccordionItem />",+ jsxElement: "<AccordionItem />",}),]),})@@ -6041,22 +6172,11 @@ describe("project session mcp adapter", () => {result: { instances },});}- if (command === "insert-fragment") {- const fragment =- isTestRecord(input) && isTestRecord(input.fragment)- ? input.fragment- : undefined;+ if (command === "insert-component") {expect(input).toEqual(expect.objectContaining({parentInstanceId: "animation-group",- fragment: expect.objectContaining({- instances: expect.arrayContaining([- expect.objectContaining({- component:- "@webstudio-is/sdk-components-animation:AnimateText",- }),- ]),- }),+ component: "@webstudio-is/sdk-components-animation:AnimateText",}));instances.push({@@ -6065,16 +6185,14 @@ describe("project session mcp adapter", () => {depth: 2,});return createEnvelope({- operationId: "instances.insertFragment",+ operationId: "instances.insertComponent",result: {- rootInstanceIds: ["animate-text"],instanceIds: ["animate-text"],parentInstanceId:isTestRecord(input) &&typeof input.parentInstanceId === "string"? input.parentInstanceId: undefined,- fragment,},state: { committed: true, freshness: {} },version: 2,@@ -6099,16 +6217,10 @@ describe("project session mcp adapter", () => {});expect(executeOperation).toHaveBeenNthCalledWith(2, {- command: "insert-fragment",+ command: "insert-component",input: expect.objectContaining({parentInstanceId: "animation-group",- fragment: expect.objectContaining({- instances: expect.arrayContaining([- expect.objectContaining({- component: "@webstudio-is/sdk-components-animation:AnimateText",- }),- ]),- }),+ component: "@webstudio-is/sdk-components-animation:AnimateText",}),dryRun: false,});@@ -6116,7 +6228,7 @@ describe("project session mcp adapter", () => {expect.objectContaining({inserted: expect.objectContaining({component: "@webstudio-is/sdk-components-animation:AnimateText",- mode: "fragment",+ mode: "component",}),parentInstanceId: "animation-group",})diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex 488807765c..56f2048403 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -7,6 +7,7 @@ import {getInputJsonSchemaMetadata,getInputJsonSchemaProperties,getFileExtension,+ getComponentJsxName,inputJsonSchemaAcceptsType,parseComponentName,toInputJsonSchemaObject,@@ -18,7 +19,10 @@ import {allowedArrayMethods,allowedStringMethods,} from "@webstudio-is/expression";-import type { TextAssetSourceDiagnostic } from "@webstudio-is/content-engine/mdx";+import {+ isMdxTemplateComponentName,+ type TextAssetSourceDiagnostic,+} from "@webstudio-is/content-engine/mdx";import { validateAssetQuery } from "@webstudio-is/content-engine";import { distance as getLevenshteinDistance } from "fastest-levenshtein";import type { BuilderApiCapability } from "./contracts/permissions";@@ -70,12 +74,7 @@ import {ListToolsRequestSchema,ReadResourceRequestSchema,} from "@modelcontextprotocol/sdk/types.js";-import {- animationComponentNamespace,- componentMetas,- radixComponentNamespace,-} from "@webstudio-is/sdk-components-registry/metas";-import { camelCase } from "change-case";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import { readProjectBuildDoc } from "./docs";import type { ComponentTemplateRegistry } from "./runtime/component-template";import {@@ -2401,7 +2400,7 @@ export const mcpArgumentExamples: Record<parentInstanceId: "parent-id",data: { type: "expression", value: "Posts.data.items" },itemFragment:- "<ws.element ws:tag='article'><ws.element ws:tag='h2'>{expression`collectionItem.title ?? 'Untitled'`}</ws.element></ws.element>",+ "<article><h2>{expression`collectionItem.title ?? 'Untitled'`}</h2></article>",},{parentInstanceId: "parent-id",@@ -2409,38 +2408,35 @@ export const mcpArgumentExamples: Record<type: "json",value: [{ name: "Starter" }, { name: "Pro" }],},- itemFragment:- "<ws.element ws:tag='div'>{expression`collectionItem.name`}</ws.element>",+ itemFragment: "<div>{expression`collectionItem.name`}</div>",},],"insert-fragment": [{parentInstanceId: "parent-id",fragment:- "<ws.element ws:tag='section' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag='h2'>Northstar Product OS</ws.element><ws.element ws:tag='p'>Reusable patterns for teams.</ws.element></ws.element>",+ "<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>",},{parentInstanceId: "parent-id",fragment:- "<ws.element ws:tag='section' style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag='h2'>Operations Console</ws.element><ws.element ws:tag='p'>Semantic section with React-style object styles converted into editable Webstudio styles.</ws.element></ws.element>",+ "<section style={{ padding: 32, borderRadius: 16 }}><h2>Operations Console</h2><p>Semantic section with React-style object styles converted into editable Webstudio styles.</p></section>",},{parentInstanceId: "parent-id",fragment:- "<ws.element ws:tag='section' ws:tokens={[token('accent', css`color: #0f766e;`)]} ws:style={css`display: grid; gap: 12px;`}><ws.element ws:tag='h2'>Token Example</ws.element><ws.element ws:tag='button' onClick={new ActionValue(['event'], expression`console.log(event)`)}>Track launch</ws.element></ws.element>",+ "<section ws:tokens={[token('accent', css`color: #0f766e;`)]} ws:style={css`display: grid; gap: 12px;`}><h2>Token Example</h2><button onClick={new ActionValue(['event'], expression`console.log(event)`)}>Track launch</button></section>",},{parentInstanceId: "parent-id",- fragment:- "<ws.element ws:tag='section'><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>",+ fragment: "<section><Switch><SwitchThumb /></Switch></section>",},],"insert-fragment-verified": [{parentInstanceId: "parent-id",pagePath: "/pricing",- fragment:- "<ws.element ws:tag='section'><ws.element ws:tag='h2'>Pricing</ws.element></ws.element>",+ fragment: "<section><h2>Pricing</h2></section>",},],"update-text": [@@ -4015,6 +4011,10 @@ export const hiddenMcpOperationCommands = new Set<string>([const mcpOperationSchemaInlineSizes = new Map<string, number>([["search-project", 0],+ ["set-instance-name", 0],+ ["migrate-content-block-template-references", 0],+ ["edit-content-block-source", 0],+ ["update-content-block-frontmatter", 0],["insert-fragment", 1_000],["create-assets-resource", 2_500],["update-assets-resource", 2_500],@@ -4510,7 +4510,7 @@ const getTemplateInput = (input: unknown) => {const getInsertFragmentInput = async (input: unknown) => {if (isPlainRecord(input) === false) {throw new Error(- 'insert-fragment requires {"parentInstanceId":"...","fragment":"<ws.element ws:tag=\'section\' />"}.'+ 'insert-fragment requires {"parentInstanceId":"...","fragment":"<section />"}.');}if ("parentId" in input && "parentInstanceId" in input === false) {@@ -4533,7 +4533,7 @@ const getInsertFragmentInput = async (input: unknown) => {}if (typeof input.fragment !== "string") {throw new Error(- 'insert-fragment requires fragment as a Webstudio JSX string, for example {"fragment":"<ws.element ws:tag=\'section\' />"}.'+ 'insert-fragment requires fragment as a Webstudio JSX string, for example {"fragment":"<section />"}.');}const { fragment: fragmentSource, ...runtimeInput } =@@ -5293,16 +5293,13 @@ const getComponentSummaryEntry = ({}const [parsedNamespace, exportName] = parseComponentName(component);const namespace = parsedNamespace ?? "global";- const jsxNamespace =- parsedNamespace === radixComponentNamespace- ? "radix"- : parsedNamespace === animationComponentNamespace- ? "animation"- : parsedNamespace === "ws"- ? "ws"- : "$";- const jsxExportName =- parsedNamespace === "ws" ? camelCase(exportName) : exportName;+ const candidateJsxName = getComponentJsxName({+ component,+ components: componentMetas.keys(),+ });+ const jsxName = isMdxTemplateComponentName(candidateJsxName)+ ? candidateJsxName+ : undefined;const template = templateMeta?.template;const hasTemplate = template !== undefined;const instancesById = new Map(@@ -5346,7 +5343,7 @@ const getComponentSummaryEntry = ({component,exportName,namespace,- jsxElement: `<${jsxNamespace}.${jsxExportName} />`,+ ...(jsxName === undefined ? {} : { jsxName, jsxElement: `<${jsxName} />` }),label: meta.label,category: visibleCategory,contentCategory: meta.contentModel?.category,@@ -5830,16 +5827,13 @@ const getComponentCoverageStatus = async ({);const toCoverageEntry = ({component,+ jsxName,jsxElement,namespace,label,- }: {- component: string;- jsxElement: string;- namespace: string;- label?: string;- }) => ({+ }: ComponentSummaryEntry) => ({component,+ jsxName,jsxElement,namespace,label,@@ -5939,18 +5933,12 @@ const getComponentCoverageInsertNext = async ({throw new Error("components.coverage-insert-next found no component.");}const insert = await executeOperation({- command:- selectedRoot === undefined ? "insert-fragment" : "insert-component",- input:- selectedRoot === undefined- ? {- parentInstanceId: partParentInstanceId,- fragment: await parseWebstudioJsxFragment(selected.jsxElement),- }- : {- parentInstanceId,- component: selected.component,- },+ command: "insert-component",+ input: {+ parentInstanceId:+ selectedRoot === undefined ? partParentInstanceId : parentInstanceId,+ component: selected.component,+ },dryRun,});const after = await getComponentCoverageStatus({@@ -5980,7 +5968,7 @@ const getComponentCoverageInsertNext = async ({label: selected.label,jsxElement: selected.jsxElement,namespace: selected.namespace,- mode: selectedRoot === undefined ? "fragment" : "component",+ mode: "component",},parentInstanceId:selectedRoot === undefined ? partParentInstanceId : parentInstanceId,@@ -6164,7 +6152,7 @@ const insertFragmentInputFilePath = ".temp/insert-fragment.json";const insertFragmentInputFileExample = {parentInstanceId: "parent-id",fragment:- "<ws.element ws:tag='section' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag='h2'>Section title</ws.element><ws.element ws:tag='p'>Section copy.</ws.element></ws.element>",+ "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Section title</h2><p>Section copy.</p></section>",};const getToolCatalogOverview = (tools: readonly ProjectSessionMcpTool[]) => ({@@ -6202,7 +6190,7 @@ const getMetaIndex = ("Do not call every discovery tool up front. Use this meta.index response for orientation, then call at most one focused discovery tool before acting.",tools:'Use meta.get-more-tools({"tools":["insert-fragment"]}) for the primary authored/styled insertion tool. Use {"brief":"style updates"} only for search. Page through webstudio://project/tools only when broader operation discovery is necessary.',- insertFragment: `Primary authored/styled insertion command shape: save ${JSON.stringify(insertFragmentInputFileExample)} as ${insertFragmentInputFilePath}, then run node packages/cli/local.js insert-fragment --input-file ${insertFragmentInputFilePath} --dry-run. Use parentInstanceId, not parentId. Use Webstudio components/helpers such as ws.element, radix.*, css, token, expression, and ActionValue. Use ws:style={css\`...\`} for Webstudio-native CSS, or style={{ padding: 24 }} for React-style object syntax converted into editable Webstudio styles. Use node packages/cli/local.js mcp single-op-call insert-fragment only when you need the explicit MCP form.`,+ insertFragment: `Primary authored/styled insertion command shape: save ${JSON.stringify(insertFragmentInputFileExample)} as ${insertFragmentInputFilePath}, then run node packages/cli/local.js insert-fragment --input-file ${insertFragmentInputFilePath} --dry-run. Use parentInstanceId, not parentId. Use lowercase HTML elements, direct registered component identifiers, and helpers such as css, token, expression, and ActionValue. Use ws:style={css\`...\`} for Webstudio-native CSS, or style={{ padding: 24 }} for React-style object syntax converted into editable Webstudio styles. Use node packages/cli/local.js mcp single-op-call insert-fragment only when you need the explicit MCP form.`,resources:"Use MCP resources/list to discover overview and full resources.",projectSearch:@@ -6259,16 +6247,115 @@ const metaGoalGuides = ["verify-page-responsive",],workflow: [- 'Call meta.get-more-tools once with {"tools":["create-assets-resource"]}; the recipe below supplies the remaining inputs.',+ "Follow recipe.executionOrder in order. Resolve documented placeholders from earlier results, and do not add calls outside that sequence.",'Create one asset folder named exactly "Blog", then call upload-assets exactly once with all Markdown files and assetsDir ".webstudio/assets". Put slug, title, author, publishedAt, excerpt, and draft in frontmatter. Each asset uses {"name":"<filename>.md","type":"file","format":"md","folderId":"<blog-folder-id>","meta":{}}; do not create companion files.','Create exactly two pages once: "/blog" and "/blog/:slug". Do not dry-run page creation, create one page per post, or copy Markdown into static page content.',- "Substitute the returned folder id in both recipe queries. Validate both, then preview the detail query with one concrete slug. Keep overview values literal and keep system.params.slug as the detail query's only dynamic value.",+ "Substitute the returned folder id in every recipe query. Pass recipe.overviewValidationQuery and recipe.detailValidationQuery directly to validate-asset-query, then pass recipe.detailValidationQuery directly to preview-asset-query. These execution queries contain resolved JSON values. Do not copy the expression-bearing resource queries into validation or preview tools.",+ "After both validations and the preview succeed, call recipe.toolDiscovery exactly once immediately before creating the resources. Do not call meta.get-more-tools again.",'Create exactly one scoped Assets resource per page by copying recipe.overviewResource and recipe.detailResource unchanged except for id placeholders. Keep the detail query result as "one" and bind it directly without a Collection. Do not add query defaults or create placeholder resources.',"Insert recipe.overviewCollection under the overview root with insert-collection, then insert recipe.detailFragment under the detail root with insert-fragment. The overview repeats posts; the detail page binds post.data directly.","Apply the page settings with update-page using recipe.detailPageSettings so the article title, description, social image, and 404 status use the same post resource as the page content.",'After both insertions succeed, ask whether the user wants visual verification unless they explicitly requested it. If they decline, use focused reads and a static audit. If they opt in, call verify-page-responsive once for "/blog" and once for one concrete detail path with desktop and mobile viewports. Confirm Assets-backed content and empty/not-found behavior. Stop on an error instead of retrying.',],recipe: {+ executionOrder: [+ { tool: "create-asset-folder", calls: 1 },+ { tool: "upload-assets", calls: 1 },+ { tool: "create-page", calls: 2 },+ { tool: "validate-asset-query", calls: 2 },+ { tool: "preview-asset-query", calls: 1 },+ { tool: "meta.get-more-tools", calls: 1 },+ { tool: "create-assets-resource", calls: 2 },+ { tool: "insert-collection", calls: 1 },+ { tool: "insert-fragment", calls: 1 },+ { tool: "update-page", calls: 1 },+ { tool: "verify-page-responsive", calls: 2, terminal: true },+ ],+ toolDiscovery: {+ tool: "meta.get-more-tools",+ when: "after-query-verification",+ input: {+ tools: ["create-assets-resource"],+ },+ },+ overviewValidationQuery: {+ result: "many",+ where: {+ all: [+ {+ field: ["extension"],+ operator: "eq",+ value: "md",+ },+ {+ field: ["folderId"],+ operator: "eq",+ value: "<blog-folder-id>",+ },+ {+ field: ["properties", "draft"],+ operator: "ne",+ value: true,+ },+ ],+ },+ sort: [+ { field: ["properties", "publishedAt"], direction: "desc" },+ { field: ["id"], direction: "asc" },+ ],+ limit: 20,+ offset: 0,+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [+ ["properties", "title"],+ ["properties", "slug"],+ ["properties", "publishedAt"],+ ["properties", "author"],+ ["properties", "excerpt"],+ ],+ },+ content: { mode: "none" },+ },+ detailValidationQuery: {+ result: "one",+ where: {+ all: [+ {+ field: ["extension"],+ operator: "eq",+ value: "md",+ },+ {+ field: ["folderId"],+ operator: "eq",+ value: "<blog-folder-id>",+ },+ {+ field: ["properties", "slug"],+ operator: "eq",+ value: "aurora-trails",+ },+ {+ field: ["properties", "draft"],+ operator: "ne",+ value: true,+ },+ ],+ },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [+ ["properties", "title"],+ ["properties", "author"],+ ["properties", "excerpt"],+ ["properties", "featureImage", "src"],+ ],+ },+ content: { mode: "markdown-body-ref" },+ },overviewResource: {name: "Published posts",scopeInstanceId: "<overview-root-id>",@@ -6351,7 +6438,7 @@ const metaGoalGuides = [["properties", "title"],["properties", "author"],["properties", "excerpt"],- ["properties", "featureImage"],+ ["properties", "featureImage", "src"],],},content: { mode: "markdown-body-ref" },@@ -6361,12 +6448,12 @@ const metaGoalGuides = [parentInstanceId: "<overview-root-id>",data: { type: "expression", value: "posts.data" },itemFragment:- '<ws.element ws:tag="article"><ws.element ws:tag="h2">{expression`collectionItem.properties.title ?? "Untitled"`}</ws.element><ws.element ws:tag="p">{expression`collectionItem.properties.excerpt ?? ""`}</ws.element><ws.element ws:tag="p">By {expression`collectionItem.properties.author.name`}</ws.element><ws.element ws:tag="time">{expression`collectionItem.properties.publishedAt ?? ""`}</ws.element><ws.element ws:tag="a" href={expression`"/blog/" + collectionItem.properties.slug`}>Read article</ws.element></ws.element>',+ '<article><h2>{expression`collectionItem.properties.title ?? "Untitled"`}</h2><p>{expression`collectionItem.properties.excerpt ?? ""`}</p><p>By {expression`collectionItem.properties.author.name`}</p><time>{expression`collectionItem.properties.publishedAt ?? ""`}</time><a href={expression`"/blog/" + collectionItem.properties.slug`}>Read article</a></article>',},detailFragment: {parentInstanceId: "<detail-root-id>",fragment:- '<ws.element ws:tag="article"><ws.element ws:tag="h1">{expression`post.data.properties.title ?? "Untitled"`}</ws.element><ws.element ws:tag="p">By {expression`post.data.properties.author.name ?? ""`}</ws.element><$.MarkdownEmbed code={expression`post.data.content.text ?? ""`} /></ws.element>',+ '<article><h1>{expression`post.data.properties.title ?? "Untitled"`}</h1><p>By {expression`post.data.properties.author.name ?? ""`}</p><MarkdownEmbed code={expression`post.data.content.text`} /></article>',},detailPageSettings: {pageId: "<detail-page-id>",@@ -6374,7 +6461,7 @@ const metaGoalGuides = [title: 'post.data.properties.title ?? "Article"',meta: {description: 'post.data.properties.excerpt ?? ""',- socialImageUrl: 'post.data.properties.featureImage ?? ""',+ socialImageUrl: 'post.data.properties.featureImage.src ?? ""',status: "post.data ? 200 : 404",},},@@ -6438,7 +6525,7 @@ const metaGoalGuides = [workflow: ["Find the array or object to repeat. For a scoped resource result, select the complete nested array/object, commonly below the result's data field; do not bind the response wrapper or one indexed item.","Call insert-collection once with the complete iterable and one repeated-item JSX root. Use expression`collectionItem.name` and expression`collectionItemKey` inside the item fragment; the operation creates and binds private parameters atomically.",- "Wrap multiple repeated sibling instances in one ws.element. Do not create, replace, or delete Collection parameter records manually.",+ "Wrap multiple repeated sibling instances in one lowercase HTML element such as <div>. Do not create, replace, or delete Collection parameter records manually.","Verify that every array/object entry renders once. For repeated Radix items, bind a stable unique id or slug to required value props.",],},@@ -6481,7 +6568,7 @@ const metaGoalGuides = ["When fixture/session data must feed a resource, create the page and scoped fixture variables there. Use create-page's returned rootInstanceId directly instead of listing instances to rediscover it. Call list-variables after creation only when a resource expression actually needs the returned encoded name. Do not repeat list-variables when the fixture variable is not referenced, as in the expression-free state gallery, and do not guess or reference variables before they exist.","Create resources only after their scope and referenced variables exist. When reusing the discovered /api/auth/session convention, pass recipe.createResourceInput directly as the entire create-resource tool input, unchanged except for its account root id placeholder. Do not wrap it in another resource object. Keep every request field nested under resource. resource.url is the HTTP request target, not a provider call or session-state expression. Use literal wrappers only for fixed header, search-parameter, and body text.","Keep the server-mediated session resource as provider-convention evidence, but use only non-secret scoped fixture variables to drive local auth-state visibility. Do not bind that server-only resource into local preview rendering: its endpoint is intentionally absent locally and can recurse through the generated route.",- 'Insert signed-out, loading, signed-in, and failed-auth panels together as one expression-free semantic fragment that acts as a state gallery. Keep all four panels visible together for local visual verification; do not add conditional visibility bindings or mutate fixture state solely to capture more screenshots. Use that exact fragment verbatim without adding styles, props, expressions, components, or changing its nesting: <ws.element ws:tag="main"><ws.element ws:tag="section"><ws.element ws:tag="h2">Signed-out</ws.element></ws.element><ws.element ws:tag="section"><ws.element ws:tag="h2">Loading</ws.element></ws.element><ws.element ws:tag="section"><ws.element ws:tag="h2">Signed-in</ws.element></ws.element><ws.element ws:tag="section"><ws.element ws:tag="h2">Failed-auth</ws.element></ws.element></ws.element>.',+ "Insert signed-out, loading, signed-in, and failed-auth panels together as one expression-free semantic fragment that acts as a state gallery. Keep all four panels visible together for local visual verification; do not add conditional visibility bindings or mutate fixture state solely to capture more screenshots. Use that exact fragment verbatim without adding styles, props, expressions, components, or changing its nesting: <main><section><h2>Signed-out</h2></section><section><h2>Loading</h2></section><section><h2>Signed-in</h2></section><section><h2>Failed-auth</h2></section></main>.","Do not call selector-based structural tools such as wrap-instance unless a focused list-instances result supplied the complete non-empty selector from the target through its page root. Prefer direct style, prop, or binding corrections when the structure is already sound.",'Insert the complete account fragment with insert-fragment-verified and {"pagePath":"/account"} so persisted bindings are checked in the same call. Resolve every returned validity, scope, and reference finding before previewing. If post-commit verification reports an infrastructure failure, do not repeat the insertion; call verify-bindings separately for /account. Updating only a fixture variable\'s literal state does not require another binding verification.','Ask whether the user wants visual verification unless they explicitly requested it. If they decline, run a focused static audit and stop without preview or screenshots. If they opt in, call verify-page-responsive once with path "/account" and the required desktop and mobile viewports; it starts or refreshes the session preview, captures both viewports in one browser session, and immediately runs the static page audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately. Do not run discovery, inspect-instance, mutate, or repeat binding verification after this terminal verification begins. The screenshots are the rendered evidence and the bundled audit is the static evidence. Do not claim the real provider flow works until redirects, session refresh, failure handling, and protected data access are exercised in its configured environment.',@@ -6516,7 +6603,19 @@ const metaGoalGuides = ["Use upload-asset or upload-assets with the local filename, detected format, and complete family, style, and weight metadata. Use the returned asset ids directly; do not read a project snapshot to rediscover uploaded assets.","Use update-asset to correct font metadata without re-uploading the binary.","After font mutations, call verify-font-assets exactly once with every changed asset id. It refreshes the asset namespace and returns the persisted metadata in one bounded verification call; do not call refresh or get-asset separately.",+ "Finish with exactly one audit call using recipe.audit. Do not pass asset ids or other unsupported fields to audit.",],+ recipe: {+ upload: {+ tool: "upload-assets",+ input: {+ assetsDir: ".webstudio/assets",+ assetFields: ["name", "type", "format", "meta"],+ excludedAssetFields: ["path"],+ },+ },+ audit: { tool: "audit", input: {} },+ },},{id: "design-input",@@ -6537,13 +6636,25 @@ const metaGoalGuides = ["Interpret the supplied design before mutating: identify page sections, responsive behavior, reusable patterns, assets, typography, color, spacing, and interaction states. Ask for missing source assets rather than inventing brand-critical content.","Before the first mutation, call inspect-design-context exactly once instead of calling list-pages, list-breakpoints, list-design-tokens, list-assets, or list-variables separately. Use one list-instances call only when needed to inspect a representative existing page pattern. Do not call get-styles: the bounded design context and optional focused instance result provide the reusable design-system evidence needed here without risking an oversized style dump. Reuse exact existing values, breakpoint ids, and patterns; do not create a parallel design system from approximate screenshot colors or spacing.","Call create-page exactly once and use its returned rootInstanceId as the insertion parent. Insert the complete semantic page in one fragment when practical, and use the insertion result's instanceIds for follow-up token attachments. Do not call list-instances after the first mutation to rediscover ids already returned by mutations.",- "Attach existing design tokens to the new page's instances when they represent the intended typography, color, or other shared style. Reusing only the token's current raw value creates a disconnected local copy.",- "Create semantic editable structure with insert-fragment-verified using ws.element and literal text first; apply fixed CSS only through ws:style={css`...`}. Do not improvise component names, expression syntax, or object-valued style expressions in the fragment. Use assets for real imagery and text/controls for real content; do not flatten the design into one image or absolute-position every element.",+ "After insertion, call attach-design-token at least once with an exact existing style source id returned by inspect-design-context. Attach it where the shared typography, color, or other token is intended. Reusing only the token's current raw value creates a disconnected local copy.",+ "Create semantic editable structure with insert-fragment-verified using only lowercase HTML elements and literal text. Do not include inline styles or ws:style in the fragment; apply fixed CSS with update-styles after insertion. Do not improvise component names, expression syntax, or object-valued style expressions. Use assets for real imagery and text or controls for real content; do not flatten the design into one image or absolute-position every element.","Implement responsive behavior inside the project's actual breakpoint ranges.",'Represent literal CSS values as {"type":"keyword","value":"..."}, including lengths such as "48px" and colors such as "#fff". Do not invent value types such as "length"; use {"type":"unit","value":48,"unit":"px"} only when numeric structure is specifically needed.',"Each update-styles updates item is flat: include instanceId, property, value, and optional breakpoint directly on every item. Do not group properties under styles or declarations.",'Call insert-fragment-verified exactly once with {"pagePath":"/summer"} so insertion and persisted binding verification share one bounded call; do not guess a page id or alternate input shape. Treat its verification result as the structural and binding checkpoint before attaching tokens or applying fixed style/page updates. If post-commit verification reports an infrastructure failure, do not repeat the insertion; call verify-bindings separately for /summer. Later fixed-value mutations do not require another binding verification. Finish them before asking whether the user wants visual verification, unless they explicitly requested it. If they decline, run a focused static audit and stop without preview or screenshots. If they opt in, call verify-page-responsive once with path "/summer" and exactly the two supplied viewports, 1440x900 and 390x844. It starts or refreshes preview automatically, captures both viewports, and immediately runs the static page audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately, and do not add exploratory or intermediate captures. Do not mutate, rediscover, or repeat binding verification after this terminal verification begins. The screenshots are the rendered evidence and the bundled audit is the static evidence. Visual similarity is evidence, not permission to discard accessibility or project conventions.',],+ recipe: {+ insertion: { includeStyles: false },+ tokenReuse: {+ minimumAttachments: 1,+ source: "inspect-design-context",+ },+ responsiveStyles: {+ tool: "update-styles",+ breakpointSource: "inspect-design-context",+ minimumBreakpointSpecificUpdates: 1,+ },+ },},{id: "craft",@@ -6877,14 +6988,14 @@ const designSystemWorkflowPhases: Record<contents: {parentInstanceId: "root-id",fragment:- "<ws.element ws:tag='section' ws:style={css`padding: 24px;`}><ws.element ws:tag='h2'>Design System</ws.element></ws.element>",+ "<section ws:style={css`padding: 24px;`}><h2>Design System</h2></section>",},},constraints: ["Save inputFile.contents at inputFile.path, replacing only root-id, then use the commandPattern as-is.","Keep the dry-run fragment tiny, ideally under 500 characters.","Do not design the real page in this phase.",- "Use ws.element tags or components confirmed by components.get; do not use deprecated $.Box, $.Heading, $.Paragraph, or $.Button.",+ "Use lowercase HTML tags or direct component identifiers confirmed by components.get; do not use legacy ws.element, $.Box, $.Heading, $.Paragraph, or $.Button syntax.","Return immediately after one dry-run result.",],expectedReturn: [@@ -6932,7 +7043,7 @@ const designSystemWorkflowPhases: Record<constraints: ["Do not treat coverage 72/72 as completion by itself.","Keep every covered component on the page while improving layout and styling.",- "Use styled ws.element sections/cards, update-styles, and move-instance as needed.",+ "Use styled lowercase HTML sections/cards, update-styles, and move-instance as needed.","Return a checkpoint with visual/presentation changes and final coverage.",],expectedReturn: [diff --git a/packages/project-build/src/runtime/block.test.ts b/packages/project-build/src/runtime/block.test.tsindex d6a954963e..aa2e5264a9 100644--- a/packages/project-build/src/runtime/block.test.ts+++ b/packages/project-build/src/runtime/block.test.ts@@ -3,11 +3,11 @@ import {blockComponent,blockBodyComponent,blockTemplateComponent,+ assignUniqueBlockTemplateNamesMutable,contentBlockSourceProp,type Instance,} from "@webstudio-is/sdk";import {- assignUniqueBlockTemplateNamesMutable,canDeleteInstanceInContentMode,canMoveInstanceInContentMode,findBlockTemplateNameCollision,@@ -103,6 +103,46 @@ describe("block tree helpers", () => {]);});+ test("rejects blocks with multiple Templates containers", () => {+ const instances = new Map<Instance["id"], Instance>([+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates-1" },+ { type: "id", value: "templates-2" },+ ]),+ ],+ [+ "templates-1",+ createInstance("templates-1", blockTemplateComponent, [+ { type: "id", value: "hero" },+ ]),+ ],+ [+ "templates-2",+ createInstance("templates-2", blockTemplateComponent, [+ { type: "id", value: "pricing" },+ ]),+ ],+ ["hero", createInstance("hero", "Box")],+ ["pricing", createInstance("pricing", "Box")],+ ]);++ expect(+ findBlockTemplates({ anchor: ["block"], instances })+ ).toBeUndefined();+ });++ test("does not expose templates without a Templates container", () => {+ const instances = new Map<Instance["id"], Instance>([+ ["block", createInstance("block", blockComponent)],+ ]);++ expect(+ findBlockTemplates({ anchor: ["block"], instances })+ ).toBeUndefined();+ });+test("finds block template insertion index", () => {const instances = new Map<Instance["id"], Instance>([[@@ -349,14 +389,21 @@ describe("block template names", () => {{ type: "id", value: "card" },]),],- ["hero", { ...createInstance("hero", "Box"), label: "Hero Card" }],+ [+ "hero",+ {+ ...createInstance("hero", "Box"),+ name: "HeroCard",+ label: "Hero Card",+ },+ ],["card", createInstance("card", "Box")],]);test("assigns unique names to newly inserted template entries", () => {const instances = createBlockInstances();instances.set("card-copy", createInstance("card-copy", "Box"));instances.set("card-copy-2", createInstance("card-copy-2", "Box"));- instances.get("card-copy-2")!.label = "Box 2";+ instances.get("card-copy-2")!.name = "Box2";assignUniqueBlockTemplateNamesMutable({instanceIds: ["card-copy", "card-copy-2"],@@ -364,8 +411,9 @@ describe("block template names", () => {instances,});- expect(instances.get("card-copy")?.label).toBe("Box 2");- expect(instances.get("card-copy-2")?.label).toBe("Box 3");+ expect(instances.get("card-copy")?.name).toBe("Box2");+ expect(instances.get("card-copy-2")?.name).toBe("Box3");+ expect(instances.get("hero")?.label).toBe("Hero Card");});test("finds exact name collisions in the same flat list", () => {@@ -374,14 +422,14 @@ describe("block template names", () => {expect(findBlockTemplateNameCollision({instance: instances.get("card")!,- nextInstance: { ...instances.get("card")!, label: "Hero Card" },+ nextInstance: { ...instances.get("card")!, name: "HeroCard" },instances,})?.instance.id).toBe("hero");expect(findBlockTemplateNameCollision({instance: instances.get("card")!,- nextInstance: { ...instances.get("card")!, label: "hero card" },+ nextInstance: { ...instances.get("card")!, name: "heroCard" },instances,})).toBeUndefined();@@ -416,8 +464,8 @@ describe("block template names", () => {expect(getBlockTemplateNameConfirmation({changes: [- { instance, nextInstance: { ...instance, label: "Article Card" } },- { instance: hero, nextInstance: { ...hero, label: "Article Hero" } },+ { instance, nextInstance: { ...instance, name: "ArticleCard" } },+ { instance: hero, nextInstance: { ...hero, name: "ArticleHero" } },],instances,props: new Map([[source.id, source]]).values(),@@ -425,11 +473,11 @@ describe("block template names", () => {).toEqual({action: "rename",templates: [- { instanceId: "card", oldName: "Box", newName: "Article Card" },+ { instanceId: "card", oldName: "Box", newName: "ArticleCard" },{instanceId: "hero",- oldName: "Hero Card",- newName: "Article Hero",+ oldName: "HeroCard",+ newName: "ArticleHero",},],});diff --git a/packages/project-build/src/runtime/block.ts b/packages/project-build/src/runtime/block.tsindex c13a6eeaa4..b5338e7405 100644--- a/packages/project-build/src/runtime/block.ts+++ b/packages/project-build/src/runtime/block.ts@@ -1,18 +1,16 @@import {- allocateUniqueContentBlockTemplateName,blockComponent,blockTemplateComponent,findContentBlockBodyContainerPaths,findParentInstanceReference,findContentBlockTemplateContainers,getContentBlockSource,- getInstanceName,+ getContentBlockTemplateName,type ContentBlockSource,type Instance,type Instances,type Prop,} from "@webstudio-is/sdk";-import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import { computeStringExpression } from "./data";import type { InstanceSelector } from "./tree";@@ -29,47 +27,6 @@ export const resolveContentBlockSourceAssetId = ({? undefined: computeStringExpression(source.value, values);-export const assignUniqueBlockTemplateNamesMutable = ({- instanceIds,- parent,- replacedInstanceIds = [],- instances,-}: {- instanceIds: readonly Instance["id"][];- parent: Instance;- replacedInstanceIds?: readonly Instance["id"][];- instances: Instances;-}) => {- if (parent.component !== blockTemplateComponent) {- return;- }- const ignoredIds = new Set([...instanceIds, ...replacedInstanceIds]);- const existingNames = new Set<string>();- for (const child of parent.children) {- const instance =- child.type === "id" ? instances.get(child.value) : undefined;- if (instance !== undefined && ignoredIds.has(instance.id) === false) {- existingNames.add(getInstanceName({ instance, metas: componentMetas }));- }- }-- for (const instanceId of instanceIds) {- const instance = instances.get(instanceId);- if (instance === undefined) {- continue;- }- const currentName = getInstanceName({ instance, metas: componentMetas });- const uniqueName = allocateUniqueContentBlockTemplateName({- name: currentName,- existingNames,- });- if (uniqueName !== currentName) {- instance.label = uniqueName;- }- existingNames.add(uniqueName);- }-};-export const findBlockTemplateNameCollision = ({instance,nextInstance,@@ -79,11 +36,8 @@ export const findBlockTemplateNameCollision = ({nextInstance: Instance;instances: Instances;}) => {- const name = getInstanceName({- instance: nextInstance,- metas: componentMetas,- });- if (name === getInstanceName({ instance, metas: componentMetas })) {+ const name = getContentBlockTemplateName(nextInstance);+ if (name === getContentBlockTemplateName(instance)) {return;}const parent = findParentInstanceReference(instances, instance.id)?.instance;@@ -97,7 +51,7 @@ export const findBlockTemplateNameCollision = ({const sibling = instances.get(child.value);if (sibling !== undefined &&- getInstanceName({ instance: sibling, metas: componentMetas }) === name+ getContentBlockTemplateName(sibling) === name) {return { instance: sibling, name };}@@ -148,10 +102,7 @@ export const getSourceBackedBlockTemplateContext = ({blockInstanceId: block.id,templatesInstanceId: templates.id,templateInstanceId,- templateName: getInstanceName({- instance: template,- metas: componentMetas,- }),+ templateName: getContentBlockTemplateName(template),source,};};@@ -183,7 +134,7 @@ export const getBlockTemplateNameConfirmation = ({const newName =nextInstance === undefined? undefined- : getInstanceName({ instance: nextInstance, metas: componentMetas });+ : getContentBlockTemplateName(nextInstance);if (newName === oldName) {continue;}@@ -362,13 +313,14 @@ export const findBlockTemplates = ({return;}- const templateInstance = findContentBlockTemplateContainers({+ const templateInstances = findContentBlockTemplateContainers({blockInstance,instances,- })[0];- if (templateInstance === undefined) {+ });+ if (templateInstances.length !== 1) {return;}+ const templateInstance = templateInstances[0];return templateInstance.children.filter((child) => child.type === "id")diff --git a/packages/project-build/src/runtime/collection.ts b/packages/project-build/src/runtime/collection.tsindex e1c9c1a0c3..9d209c1d59 100644--- a/packages/project-build/src/runtime/collection.ts+++ b/packages/project-build/src/runtime/collection.ts@@ -75,7 +75,7 @@ const getItemRootInstanceId = (fragment: WebstudioFragment) => {) {return throwBuilderRuntimeError("BAD_REQUEST",- "Collection itemFragment must contain exactly one root instance. Wrap repeated sibling elements in one ws:element or component."+ "Collection itemFragment must contain exactly one root instance. Wrap repeated sibling elements in one lowercase HTML element or registered component.");}const instances = new Map(diff --git a/packages/project-build/src/runtime/component-templates.test.ts b/packages/project-build/src/runtime/component-templates.test.tsindex 0b13ec1492..e9c8edcba7 100644--- a/packages/project-build/src/runtime/component-templates.test.ts+++ b/packages/project-build/src/runtime/component-templates.test.ts@@ -14,9 +14,10 @@ describe("getComponentTemplates", () => {}),}));- expect(- templates.get("@webstudio-is/sdk-components-react-radix:Switch")- ).toEqual(+ const switchTemplate = templates.get(+ "@webstudio-is/sdk-components-react-radix:Switch"+ );+ expect(switchTemplate).toEqual(expect.objectContaining({template: expect.objectContaining({children: expect.any(Array),@@ -24,5 +25,8 @@ describe("getComponentTemplates", () => {}),}));+ expect(switchTemplate?.template.instances[0]?.component).toBe(+ "@webstudio-is/sdk-components-react-radix:Switch"+ );});});diff --git a/packages/project-build/src/runtime/component-templates.ts b/packages/project-build/src/runtime/component-templates.tsindex eaf6d48087..9935ae505c 100644--- a/packages/project-build/src/runtime/component-templates.ts+++ b/packages/project-build/src/runtime/component-templates.ts@@ -23,7 +23,7 @@ export const getComponentTemplates = () => {const templatesByComponent = new Map<string, GeneratedTemplateMeta>();for (const library of canvasComponentLibraries) {- const { templates } = library;+ const { componentIds, templates } = library;const namespace = "namespace" in library ? library.namespace : undefined;const prefix = namespace === undefined ? "" : `${namespace}:`;for (const [componentName, meta] of Object.entries(@@ -32,7 +32,10 @@ export const getComponentTemplates = () => {const { template, ...generatedMeta } = meta;templatesByComponent.set(`${prefix}${componentName}`, {...generatedMeta,- template: renderTemplate(template, undefined, [], { componentMetas }),+ template: renderTemplate(template, undefined, [], {+ componentIds,+ componentMetas,+ }),});}}diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.tsindex a0f203c83f..2a304f6a6d 100644--- a/packages/project-build/src/runtime/components.test.ts+++ b/packages/project-build/src/runtime/components.test.ts@@ -130,7 +130,7 @@ test("assigns a unique name when inserting into a Templates list", async () => {component: "Box",children: [],});- const fragment = await parseWebstudioJsxFragment("<$.Box />");+ const fragment = await parseWebstudioJsxFragment("<Box />");const mutation = insertFragment(state,@@ -142,7 +142,30 @@ test("assigns a unique name when inserting into a Templates list", async () => {expect.objectContaining({id: "generated-0",component: "Box",- label: "Box 2",+ name: "Box2",+ })+ );+});++test("uses the public collision-safe component identifier as the template name", async () => {+ const parent: Instance = {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ };+ const fragment = await parseWebstudioJsxFragment("<RadixCheckbox />");++ const mutation = insertFragment(+ createState(parent),+ { parentInstanceId: parent.id, fragment },+ { createId: createIdFactory() }+ );++ expect(getAddedValues<Instance>(mutation, "instances")).toContainEqual(+ expect.objectContaining({+ component: "@webstudio-is/sdk-components-react-radix:Checkbox",+ name: "RadixCheckbox",}));});@@ -588,7 +611,7 @@ test("inserts fragment into page template", async () => {component: elementComponent,children: [{ type: "id", value: parent.id }],};- const fragment = await parseWebstudioJsxFragment("<$.Box />");+ const fragment = await parseWebstudioJsxFragment("<Box />");const mutation = insertFragment(createTemplateState({ root, parent }),@@ -613,7 +636,7 @@ test("inserts fragment into page template", async () => {test("rejects invalid HtmlEmbed code from externally authored fragments", async () => {const parent = createParent();const fragment = await parseWebstudioJsxFragment(- `<$.HtmlEmbed code={"<div><span></div>"} />`+ `<HtmlEmbed code={"<div><span></div>"} />`);expect(() =>@@ -754,22 +777,8 @@ test("rejects unknown Webstudio core components", () => {});test("rejects unknown Webstudio core components in JSX fragments", async () => {- const parent = createParent();- const fragment = await parseWebstudioJsxFragment(`<ws.div />`);-- expect(() =>- insertFragment(- createState(parent),- {- parentInstanceId: parent.id,- fragment,- },- {- createId: createIdFactory(),- }- )- ).toThrow(- 'Component "ws:div" does not exist. The "ws:" namespace contains Webstudio core components, not HTML tag shorthands.'+ await expect(parseWebstudioJsxFragment(`<ws.div />`)).rejects.toThrow(+ 'Component "ws:div" does not exist. The "ws:" namespace contains Webstudio core components, not HTML tag shorthands. In JSX, use a lowercase HTML element such as <div>.');});@@ -886,7 +895,7 @@ test("inserts webstudio jsx fragment with styles", async () => {}\`}><ws.element ws:tag="h2">Northstar Design System</ws.element>- <radix.Switch><radix.SwitchThumb /></radix.Switch>+ <Switch><SwitchThumb /></Switch></ws.element>`),},{@@ -1281,7 +1290,7 @@ test("inserts animation action props parsed from webstudio jsx fragments", asyncconst parent = createParent();const state = createState(parent);const fragment = await parseWebstudioJsxFragment(- `<animation.AnimateChildren action={{type:"view",animations:[{timing:{fill:"backwards",rangeStart:["entry",{type:"unit",value:0,unit:"%"}],rangeEnd:["entry",{type:"unit",value:100,unit:"%"}]},keyframes:[{styles:{opacity:{type:"unit",value:0,unit:"number"}}}]}]}}><ws.element ws:tag="h2">Reveal</ws.element></animation.AnimateChildren>`+ `<AnimateChildren action={{type:"view",animations:[{timing:{fill:"backwards",rangeStart:["entry",{type:"unit",value:0,unit:"%"}],rangeEnd:["entry",{type:"unit",value:100,unit:"%"}]},keyframes:[{styles:{opacity:{type:"unit",value:0,unit:"number"}}}]}]}}><ws.element ws:tag="h2">Reveal</ws.element></AnimateChildren>`);expect(fragment.props).toContainEqual(@@ -1317,39 +1326,29 @@ test("inserts animation action props parsed from webstudio jsx fragments", async});test("detects likely Webstudio JSX fragments", () => {- expect(isLikelyWebstudioJsxFragment("<$.Box />")).toBe(true);- expect(isLikelyWebstudioJsxFragment("\n < $ .Box />")).toBe(true);- expect(isLikelyWebstudioJsxFragment("< $ . Box />")).toBe(true);+ expect(isLikelyWebstudioJsxFragment("<Box />")).toBe(true);expect(isLikelyWebstudioJsxFragment('<ws.element ws:tag="section" />')).toBe(true);- expect(isLikelyWebstudioJsxFragment("<radix.Switch />")).toBe(true);- expect(isLikelyWebstudioJsxFragment("<animation.VideoAnimation />")).toBe(- true- );- expect(isLikelyWebstudioJsxFragment("<$. />")).toBe(false);- expect(isLikelyWebstudioJsxFragment("<$.>")).toBe(false);- expect(isLikelyWebstudioJsxFragment("</$.Box>")).toBe(false);+ expect(isLikelyWebstudioJsxFragment("<Switch />")).toBe(true);+ expect(isLikelyWebstudioJsxFragment("<VideoAnimation />")).toBe(true);+ expect(isLikelyWebstudioJsxFragment("</Box>")).toBe(false);expect(isLikelyWebstudioJsxFragment("<section>HTML</section>")).toBe(false);expect(isLikelyWebstudioJsxFragment("## Markdown")).toBe(false);});test("inspects webstudio jsx fragment syntax without evaluation", () => {expect(() =>- inspectWebstudioJsxFragmentSyntax(- `<$.Box data-safe={{ process: "text" }} />`- )+ inspectWebstudioJsxFragmentSyntax(`<Box data-safe={{ process: "text" }} />`)).not.toThrow();expect(() =>- inspectWebstudioJsxFragmentSyntax(`import { Box } from "x"; <$.Box />`)+ inspectWebstudioJsxFragmentSyntax(`import { Box } from "x"; <Box />`)).toThrow("Do not use import or export in JSX fragments");expect(() =>- inspectWebstudioJsxFragmentSyntax(`<$.Box data-secret={process.env} />`)+ inspectWebstudioJsxFragmentSyntax(`<Box data-secret={process.env} />`)).toThrow('Do not access "process" in JSX fragments');expect(() =>- inspectWebstudioJsxFragmentSyntax(- `<$.Box data-secret={import("node:fs")} />`- )+ inspectWebstudioJsxFragmentSyntax(`<Box data-secret={import("node:fs")} />`)).toThrow("Do not use dynamic import() in JSX fragments");expect(() =>inspectWebstudioJsxFragmentSyntax(`<div>Hello</div>`)@@ -1367,12 +1366,12 @@ test("rejects unsupported css rules after interpolation", async () => {});test("explains unmatched jsx without implying session state", async () => {- const validFragment = `<$.Box><$.Heading>Title</$.Heading></$.Box>`;+ const validFragment = `<Box><Heading>Title</Heading></Box>`;await expect(parseWebstudioJsxFragment(validFragment)).resolves.toEqual(expect.objectContaining({ children: expect.any(Array) }));await expect(- parseWebstudioJsxFragment(`<$.Box><$.Heading>Title</$.Box>`)+ parseWebstudioJsxFragment(`<Box><Heading>Title</Box>`)).rejects.toThrow("Every opening element must use the same closing tag or end with />. Fragment parsing is stateless");@@ -1383,7 +1382,7 @@ test("explains unmatched jsx without implying session state", async () => {test("inserts bare template-backed components from webstudio jsx fragments", async () => {const parent = createParent();- const fragment = await parseWebstudioJsxFragment(`<radix.Switch />`);+ const fragment = await parseWebstudioJsxFragment(`<Switch />`);const mutation = insertFragment(createState(parent),@@ -1407,7 +1406,7 @@ test("inserts bare template-backed components from webstudio jsx fragments", asytest("inserts authored template part structure from webstudio jsx fragments", async () => {const parent = createParent();const fragment = await parseWebstudioJsxFragment(- `<radix.Switch><ws.element ws:tag="div"><radix.SwitchThumb /></ws.element></radix.Switch>`+ `<Switch><ws.element ws:tag="div"><SwitchThumb /></ws.element></Switch>`);const mutation = insertFragment(@@ -1470,7 +1469,7 @@ test("inserts authored Content Block template structure from webstudio jsx fragmtest("supports react style props in webstudio jsx fragments", async () => {const fragment = await parseWebstudioJsxFragment(- `<$.Box style={{ padding: 24 }}>Hello</$.Box>`+ `<Box style={{ padding: 24 }}>Hello</Box>`);expect(fragment.props.find((prop) => prop.name === "style")).toBeUndefined();expect(fragment.styleSources).toEqual([@@ -1492,10 +1491,10 @@ test("supports react style props in webstudio jsx fragments", async () => {]));await expect(- parseWebstudioJsxFragment(`<$.Box ws:style="padding: 24px;">Hello</$.Box>`)+ parseWebstudioJsxFragment(`<Box ws:style="padding: 24px;">Hello</Box>`)).rejects.toThrow(/^ws:style must come from css`...`/);await expect(- parseWebstudioJsxFragment(`<$.Box ws:style={css\`\`}>Hello</$.Box>`)+ parseWebstudioJsxFragment(`<Box ws:style={css\`\`}>Hello</Box>`)).rejects.toThrow(/^ws:style must include at least one valid CSS declaration/);@@ -1503,16 +1502,16 @@ test("supports react style props in webstudio jsx fragments", async () => {test("rejects invalid token syntax in webstudio jsx fragments", async () => {await expect(- parseWebstudioJsxFragment(`<$.Box ws:tokens="brand">Hello</$.Box>`)+ parseWebstudioJsxFragment(`<Box ws:tokens="brand">Hello</Box>`)).rejects.toThrow(/^ws:tokens must be an array of token\(\.\.\.\) values/);await expect(parseWebstudioJsxFragment(- `<$.Box ws:tokens={[token("brand", "color: red;")]}>Hello</$.Box>`+ `<Box ws:tokens={[token("brand", "color: red;")]}>Hello</Box>`)).rejects.toThrow(/^token\(\) styles must come from css`...`/);await expect(parseWebstudioJsxFragment(- `<$.Box ws:tokens={[token("brand", css\`\`)]}>Hello</$.Box>`+ `<Box ws:tokens={[token("brand", css\`\`)]}>Hello</Box>`)).rejects.toThrow(/^token\(\) styles must include at least one valid CSS declaration/@@ -1521,7 +1520,7 @@ test("rejects invalid token syntax in webstudio jsx fragments", async () => {test("rejects unsupported expressions in shared fragment inputs", async () => {const fragment = await parseWebstudioJsxFragment(- `<$.Text>{expression\`items.map(item => item.title).join(", ")\`}</$.Text>`+ `<Text>{expression\`items.map(item => item.title).join(", ")\`}</Text>`);const result = insertFragmentInput.safeParse({parentInstanceId: "parent",@@ -1558,7 +1557,7 @@ test("rejects unsupported expressions in shared fragment inputs", async () => {test("uses component content models to require element children", async () => {const parent = createParent();const invalidFragment = await parseWebstudioJsxFragment(- `<radix.Collapsible><radix.CollapsibleTrigger>Open</radix.CollapsibleTrigger></radix.Collapsible>`+ `<Collapsible><CollapsibleTrigger>Open</CollapsibleTrigger></Collapsible>`);expect(() =>insertFragment(@@ -1569,7 +1568,7 @@ test("uses component content models to require element children", async () => {).toThrow('"CollapsibleTrigger" does not accept text content');const fragment = await parseWebstudioJsxFragment(- `<radix.Collapsible><radix.CollapsibleTrigger><ws.element ws:tag="span">Open</ws.element></radix.CollapsibleTrigger></radix.Collapsible>`+ `<Collapsible><CollapsibleTrigger><ws.element ws:tag="span">Open</ws.element></CollapsibleTrigger></Collapsible>`);expect(() =>insertFragment(@@ -1583,7 +1582,7 @@ test("uses component content models to require element children", async () => {test("reports unsupported existing resource references in jsx", async () => {await expect(parseWebstudioJsxFragment(- `<$.Form action={new ResourceValue("resource-id")} />`+ `<Form action={new ResourceValue("resource-id")} />`)).rejects.toThrow("ResourceValue requires a resource definition. Existing resource ids are not supported in JSX"@@ -1594,7 +1593,7 @@ test("converts react prop aliases in webstudio jsx fragments", async () => {expect((await parseWebstudioJsxFragment(- `<$.Box className="panel" tabIndex={2} readOnly>Hello</$.Box>`+ `<Box className="panel" tabIndex={2} readOnly>Hello</Box>`)).props).toEqual([@@ -1615,11 +1614,8 @@ test("converts react prop aliases in webstudio jsx fragments", async () => {}),]);expect(- (- await parseWebstudioJsxFragment(- `<$.Label htmlFor="email">Email</$.Label>`- )- ).props+ (await parseWebstudioJsxFragment(`<Label htmlFor="email">Email</Label>`))+ .props).toEqual([expect.objectContaining({name: "for",@@ -1631,15 +1627,13 @@ test("converts react prop aliases in webstudio jsx fragments", async () => {test("rejects javascript function props in webstudio jsx fragments", async () => {await expect(- parseWebstudioJsxFragment(- `<$.Button onClick={() => alert(1)}>Click</$.Button>`- )+ parseWebstudioJsxFragment(`<Button onClick={() => alert(1)}>Click</Button>`)).rejects.toThrow('Invalid JSX prop "onClick". Do not pass JavaScript functions. Use Webstudio actions instead');await expect(parseWebstudioJsxFragment(- `<$.Box data-config={{ onSave: () => alert(1) }}>Save</$.Box>`+ `<Box data-config={{ onSave: () => alert(1) }}>Save</Box>`)).rejects.toThrow('Invalid JSX prop "data-config" at "onSave". Do not pass JavaScript functions. Use Webstudio actions instead'@@ -1648,7 +1642,7 @@ test("rejects javascript function props in webstudio jsx fragments", async () =>expect((await parseWebstudioJsxFragment(- `<$.Button onClick={new ActionValue(["event"], expression\`console.log(event)\`)}>Click</$.Button>`+ `<Button onClick={new ActionValue(["event"], expression\`console.log(event)\`)}>Click</Button>`)).props).toEqual([@@ -1668,49 +1662,49 @@ test("rejects javascript function props in webstudio jsx fragments", async () =>test("rejects non-serializable prop values in webstudio jsx fragments", async () => {await expect(- parseWebstudioJsxFragment(`<$.Box data-value={undefined}>Value</$.Box>`)+ parseWebstudioJsxFragment(`<Box data-value={undefined}>Value</Box>`)).rejects.toThrow('Invalid JSX prop "data-value". Do not pass undefined. Omit the prop or use null instead.');await expect(- parseWebstudioJsxFragment(`<$.Box data-value={NaN}>Value</$.Box>`)+ parseWebstudioJsxFragment(`<Box data-value={NaN}>Value</Box>`)).rejects.toThrow('Invalid JSX prop "data-value". Do not pass NaN or Infinity. Use a finite number instead.');await expect(- parseWebstudioJsxFragment(`<$.Box data-value={BigInt(1)}>Value</$.Box>`)+ parseWebstudioJsxFragment(`<Box data-value={BigInt(1)}>Value</Box>`)).rejects.toThrow('Invalid JSX prop "data-value". Do not pass BigInt values. Use a string, finite number, or expression instead.');await expect(parseWebstudioJsxFragment(- `<$.Box data-config={{ values: [1, Symbol("bad")] }}>Value</$.Box>`+ `<Box data-config={{ values: [1, Symbol("bad")] }}>Value</Box>`)).rejects.toThrow('Invalid JSX prop "data-config" at "values.1". Do not pass Symbol values. Use a string, finite number, or expression instead.');await expect(- parseWebstudioJsxFragment(`<$.Box data-value={new Date(0)}>Value</$.Box>`)+ parseWebstudioJsxFragment(`<Box data-value={new Date(0)}>Value</Box>`)).rejects.toThrow('Invalid JSX prop "data-value". Do not pass Date objects. Use plain JSON-compatible values instead.');await expect(parseWebstudioJsxFragment(- `<$.Box data-value={new Map([["a", 1]])}>Value</$.Box>`+ `<Box data-value={new Map([["a", 1]])}>Value</Box>`)).rejects.toThrow('Invalid JSX prop "data-value". Do not pass Map objects. Use plain JSON-compatible values instead.');await expect(parseWebstudioJsxFragment(- `{(() => { class Config {}; return <$.Box data-value={new Config()}>Value</$.Box>; })()}`+ `{(() => { class Config {}; return <Box data-value={new Config()}>Value</Box>; })()}`)).rejects.toThrow('Invalid JSX prop "data-value". Do not pass Config objects. Use plain JSON-compatible values instead.');await expect(parseWebstudioJsxFragment(- `{(() => { const data = {}; data.self = data; return <$.Box data-value={data}>Value</$.Box>; })()}`+ `{(() => { const data = {}; data.self = data; return <Box data-value={data}>Value</Box>; })()}`)).rejects.toThrow('Invalid JSX prop "data-value" at "self". Do not pass circular objects. Use plain JSON-compatible values instead.'@@ -1719,50 +1713,48 @@ test("rejects non-serializable prop values in webstudio jsx fragments", async ()test("rejects host runtime globals in webstudio jsx fragments", async () => {await expect(- parseWebstudioJsxFragment(`<$.Box data-secret={process.env}>Secret</$.Box>`)+ parseWebstudioJsxFragment(`<Box data-secret={process.env}>Secret</Box>`)).rejects.toThrow('Do not access "process" in JSX fragments');await expect(parseWebstudioJsxFragment(- `<$.Box data-version={globalThis.process?.versions?.node}>Version</$.Box>`+ `<Box data-version={globalThis.process?.versions?.node}>Version</Box>`)).rejects.toThrow('Do not access "globalThis" in JSX fragments');await expect(parseWebstudioJsxFragment(- `<$.Box data-secret={this.constructor.constructor("return process.env")()}>Secret</$.Box>`+ `<Box data-secret={this.constructor.constructor("return process.env")()}>Secret</Box>`)).rejects.toThrow('Do not access "constructor" in JSX fragments');await expect(parseWebstudioJsxFragment(- `<$.Box data-secret={this["constructor"]["constructor"]("return process.env")()}>Secret</$.Box>`+ `<Box data-secret={this["constructor"]["constructor"]("return process.env")()}>Secret</Box>`)).rejects.toThrow('Do not access "constructor" in JSX fragments');await expect(parseWebstudioJsxFragment(- `<$.Box data-secret={({})["con" + "structor"]["con" + "structor"]("return process.env")()}>Secret</$.Box>`+ `<Box data-secret={({})["con" + "structor"]["con" + "structor"]("return process.env")()}>Secret</Box>`)).rejects.toThrow("Code generation from strings disallowed");await expect(- parseWebstudioJsxFragment(`<$.Box data-secret={eval("1")}>Secret</$.Box>`)+ parseWebstudioJsxFragment(`<Box data-secret={eval("1")}>Secret</Box>`)).rejects.toThrow('Do not access "eval" in JSX fragments');await expect(parseWebstudioJsxFragment(- `<$.Box data-secret={Function("return process.env")()}>Secret</$.Box>`+ `<Box data-secret={Function("return process.env")()}>Secret</Box>`)).rejects.toThrow('Do not access "Function" in JSX fragments');await expect(- parseWebstudioJsxFragment(- `<$.Box data-secret={require("fs")}>Secret</$.Box>`- )+ parseWebstudioJsxFragment(`<Box data-secret={require("fs")}>Secret</Box>`)).rejects.toThrow('Do not access "require" in JSX fragments');await expect(- parseWebstudioJsxFragment(`<$.Box data-secret={module}>Secret</$.Box>`)+ parseWebstudioJsxFragment(`<Box data-secret={module}>Secret</Box>`)).rejects.toThrow('Do not access "module" in JSX fragments');await expect(- parseWebstudioJsxFragment(`<$.Box data-secret={exports}>Secret</$.Box>`)+ parseWebstudioJsxFragment(`<Box data-secret={exports}>Secret</Box>`)).rejects.toThrow('Do not access "exports" in JSX fragments');await expect(parseWebstudioJsxFragment(- `<$.Box data-secret={import("node:fs")}>Secret</$.Box>`+ `<Box data-secret={import("node:fs")}>Secret</Box>`)).rejects.toThrow("Do not use dynamic import() in JSX fragments");});@@ -1771,7 +1763,7 @@ test("allows restricted words in non-executed jsx values", async () => {expect((await parseWebstudioJsxFragment(- `<$.Paragraph>The constructor pattern is a JavaScript escape hatch.</$.Paragraph>`+ `<Paragraph>The constructor pattern is a JavaScript escape hatch.</Paragraph>`)).instances[0]?.children).toEqual([@@ -1783,7 +1775,7 @@ test("allows restricted words in non-executed jsx values", async () => {expect((await parseWebstudioJsxFragment(- `<$.Box data-config={{ constructor: "documentation", process: "docs", eval: "docs", Function: "docs", globalThis: "docs" }}>Value</$.Box>`+ `<Box data-config={{ constructor: "documentation", process: "docs", eval: "docs", Function: "docs", globalThis: "docs" }}>Value</Box>`)).props).toEqual([@@ -1802,7 +1794,7 @@ test("allows restricted words in non-executed jsx values", async () => {expect((await parseWebstudioJsxFragment(- `<$.Box data-config={{ exports: "docs", module: "docs", require: "docs" }}>Value</$.Box>`+ `<Box data-config={{ exports: "docs", module: "docs", require: "docs" }}>Value</Box>`)).props).toEqual([@@ -1819,7 +1811,7 @@ test("allows restricted words in non-executed jsx values", async () => {expect((await parseWebstudioJsxFragment(- `<$.Button onClick={new ActionValue([], expression\`console.log(process)\`)}>Click</$.Button>`+ `<Button onClick={new ActionValue([], expression\`console.log(process)\`)}>Click</Button>`)).props).toEqual([@@ -1840,32 +1832,32 @@ test("allows restricted words in non-executed jsx values", async () => {test("rejects host runtime globals inside jsx expression holes", async () => {await expect(parseWebstudioJsxFragment(- `<$.Box data-secret={expression\`${"${process.env}"}\`}>Secret</$.Box>`+ `<Box data-secret={expression\`${"${process.env}"}\`}>Secret</Box>`)).rejects.toThrow('Do not access "process" in JSX fragments');});test("rejects manual system ids in webstudio jsx fragments", async () => {await expect(- parseWebstudioJsxFragment(`<$.Box ws:id="manual-id" />`)- ).rejects.toThrow("Do not set ws:id in JSX fragments");- await expect(- parseWebstudioJsxFragment(`<$.Box ws:id="0" />`)+ parseWebstudioJsxFragment(`<Box ws:id="manual-id" />`)).rejects.toThrow("Do not set ws:id in JSX fragments");+ await expect(parseWebstudioJsxFragment(`<Box ws:id="0" />`)).rejects.toThrow(+ "Do not set ws:id in JSX fragments"+ );await expect(- parseWebstudioJsxFragment(`<$.Box {...{"ws:id": "0"}} />`)+ parseWebstudioJsxFragment(`<Box {...{"ws:id": "0"}} />`)).rejects.toThrow("Do not set ws:id in JSX fragments");});test("rejects module syntax in webstudio jsx fragments", async () => {await expect(- parseWebstudioJsxFragment(`import { Box } from "x"; <$.Box />`)+ parseWebstudioJsxFragment(`import { Box } from "x"; <Box />`)).rejects.toThrow("Do not use import or export in JSX fragments");await expect(- parseWebstudioJsxFragment(`export const view = <$.Box />`)+ parseWebstudioJsxFragment(`export const view = <Box />`)).rejects.toThrow("Do not use import or export in JSX fragments");await expect(- parseWebstudioJsxFragment(`import { Box } from "x"; <$.Box />`)+ parseWebstudioJsxFragment(`import { Box } from "x"; <Box />`)).rejects.toMatchObject({code: "INVALID_INPUT",issues: [@@ -1873,15 +1865,14 @@ test("rejects module syntax in webstudio jsx fragments", async () => {code: "invalid_webstudio_jsx",path: ["fragment"],constraint: "declarative_jsx_without_modules",- example:- '<ws.element ws:tag="section"><ws.element ws:tag="h2">Title</ws.element></ws.element>',+ example: "<section><h2>Title</h2></section>",}),],});});test("rejects react fragment shorthand in webstudio jsx fragments", async () => {- await expect(parseWebstudioJsxFragment(`<><$.Box /></>`)).rejects.toThrow(+ await expect(parseWebstudioJsxFragment(`<><Box /></>`)).rejects.toThrow("Do not use React fragment shorthand <>...</> inside Webstudio JSX");await expect(parseWebstudioJsxFragment(`<>Text</>`)).rejects.toThrow(@@ -1889,19 +1880,20 @@ test("rejects react fragment shorthand in webstudio jsx fragments", async () =>);});-test("rejects raw html tags in webstudio jsx fragments", async () => {- await expect(parseWebstudioJsxFragment(`<div>Hello</div>`)).rejects.toThrow(- "Use Webstudio components such as <$.Box>...</$.Box>"+test("compiles lowercase html tags in webstudio jsx fragments", async () => {+ const fragment = await parseWebstudioJsxFragment(+ `<div>Hello</div><button>Open</button>`);- await expect(- parseWebstudioJsxFragment(`<button>Open</button>`)- ).rejects.toThrow("Use Webstudio components such as <$.Box>...</$.Box>");+ expect(fragment.instances).toEqual([+ expect.objectContaining({ component: "ws:element", tag: "div" }),+ expect.objectContaining({ component: "ws:element", tag: "button" }),+ ]);});test("validates ws.element tag in fragment insertion", async () => {const parent = createParent();const fragment = await parseWebstudioJsxFragment(- `<ws.element><$.Paragraph>Missing tag</$.Paragraph></ws.element>`+ `<ws.element><Paragraph>Missing tag</Paragraph></ws.element>`);expect(() =>insertFragment(@@ -1918,14 +1910,14 @@ test("validates ws.element tag in fragment insertion", async () => {).toThrow('Component "ws:element" requires a non-empty tag');await expect(parseWebstudioJsxFragment(- `<ws.element ws:tag={""}><$.Paragraph>Empty tag</$.Paragraph></ws.element>`+ `<ws.element ws:tag={""}><Paragraph>Empty tag</Paragraph></ws.element>`)).rejects.toThrow("Tag cannot be empty");expect((await parseWebstudioJsxFragment(- `<ws.element ws:tag="section"><$.Heading>Semantic Section</$.Heading></ws.element>`+ `<ws.element ws:tag="section"><Heading>Semantic Section</Heading></ws.element>`)).instances[0]).toEqual(@@ -1938,31 +1930,28 @@ test("validates ws.element tag in fragment insertion", async () => {test("allows html and fragment syntax inside text values", async () => {expect(- (await parseWebstudioJsxFragment(`<$.CodeText>{"<div>"}</$.CodeText>`))+ (await parseWebstudioJsxFragment(`<CodeText>{"<div>"}</CodeText>`)).instances[0]?.children).toEqual([{ type: "text", value: "<div>" }]);expect(- (await parseWebstudioJsxFragment(`<$.Paragraph>{"<>"}</$.Paragraph>`))+ (await parseWebstudioJsxFragment(`<Paragraph>{"<>"}</Paragraph>`)).instances[0]?.children).toEqual([{ type: "text", value: "<>" }]);expect(- (- await parseWebstudioJsxFragment(- `<$.CodeText>{'ws:id="demo"'}</$.CodeText>`- )- ).instances[0]?.children+ (await parseWebstudioJsxFragment(`<CodeText>{'ws:id="demo"'}</CodeText>`))+ .instances[0]?.children).toEqual([{ type: "text", value: 'ws:id="demo"' }]);expect((await parseWebstudioJsxFragment(- `<$.CodeText>{'ws:style="demo"'}</$.CodeText>`+ `<CodeText>{'ws:style="demo"'}</CodeText>`)).instances[0]?.children).toEqual([{ type: "text", value: 'ws:style="demo"' }]);expect((await parseWebstudioJsxFragment(- `<$.CodeText>{\`\nimport { Box } from "x";\nexport default Box;\n\`}</$.CodeText>`+ `<CodeText>{\`\nimport { Box } from "x";\nexport default Box;\n\`}</CodeText>`)).instances[0]?.children).toEqual([@@ -1973,34 +1962,32 @@ test("allows html and fragment syntax inside text values", async () => {]);});-test("suggests built-in helpers for unknown jsx identifiers", async () => {- await expect(parseWebstudioJsxFragment(`<Box />`)).rejects.toThrow(- "Use component namespaces $, ws, radix, and animation and value helpers css, token, expression, Variable, Parameter, ResourceValue, ActionValue, AssetValue, PageValue, and PlaceholderValue. Box is not defined"- );+test("resolves direct registered component identifiers", async () => {+ expect((await parseWebstudioJsxFragment(`<Box />`)).instances).toEqual([+ expect.objectContaining({ component: "Box" }),+ ]);});-test("explains that animation is a component namespace", async () => {+test("rejects the removed animation helper", async () => {await expect(parseWebstudioJsxFragment(- '<$.Box data-animation={animation("pulse", css`opacity: 1;`)} />'+ '<Box data-animation={animation("pulse", css`opacity: 1;`)} />')- ).rejects.toThrow(- "animation is a component namespace such as <animation.AnimateChildren>; it is not a callable CSS keyframes helper."- );+ ).rejects.toThrow("animation is not defined");});test("rejects empty webstudio jsx fragments", async () => {await expect(parseWebstudioJsxFragment("")).rejects.toThrow(- "JSX fragment must contain at least one Webstudio component"+ "JSX fragment must contain at least one element or component");await expect(parseWebstudioJsxFragment("{null}")).rejects.toThrow(- "JSX fragment must contain at least one Webstudio component"+ "JSX fragment must contain at least one element or component");});test("does not treat deprecated catalog status as fragment invalidity", async () => {const parent = createParent();- const fragment = await parseWebstudioJsxFragment(`<$.Box />`);+ const fragment = await parseWebstudioJsxFragment(`<Box />`);const mutation = insertFragment(createState(parent),@@ -2084,7 +2071,7 @@ test("does not treat hidden catalog status as component invalidity", async () =>test("rejects xml components in html webstudio jsx fragments", async () => {const parent = createParent();- const fragment = await parseWebstudioJsxFragment(`<$.XmlNode />`);+ const fragment = await parseWebstudioJsxFragment(`<XmlNode />`);expect(() =>insertFragment(@@ -2589,7 +2576,7 @@ test("reports generated record collision context without exposing the id", asyncvalue: "existing",});const fragment = await parseWebstudioJsxFragment(- '<$.HtmlEmbed code="<p>New</p>" />'+ '<HtmlEmbed code="<p>New</p>" />');try {diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.tsindex 5cdbcdfc80..cdbf057710 100644--- a/packages/project-build/src/runtime/components.ts+++ b/packages/project-build/src/runtime/components.ts@@ -1,6 +1,7 @@import equal from "fast-deep-equal";import {blockTemplateComponent,+ assignUniqueBlockTemplateNamesMutable,elementComponent,instanceComponent,ROOT_INSTANCE_ID,@@ -69,10 +70,7 @@ import {getNewFragmentContentModelWarnings,} from "./matcher";import { z } from "zod";-import {- assignUniqueBlockTemplateNamesMutable,- getBlockTemplateNameConfirmation,-} from "./block";+import { getBlockTemplateNameConfirmation } from "./block";const conflictResolutionInput = z.enum(["ours", "theirs", "merge"])@@ -222,7 +220,7 @@ const getUnknownCoreComponentError = ({componentMetas.has(component) === false &&templates.has(component) === false) {- return `Component "${component}" does not exist. The "ws:" namespace contains Webstudio core components, not HTML tag shorthands. To create a native HTML element, use component "ws:element" with its "tag" property, for example <ws.element ws:tag="div">...</ws.element>.`;+ return `Component "${component}" does not exist. The "ws:" namespace contains Webstudio core components, not HTML tag shorthands. In structured instance data, create a native HTML element with component "ws:element" and its "tag" property.`;}};@@ -592,7 +590,7 @@ const validateFragmentComponent = ({) {return throwBuilderRuntimeError("BAD_REQUEST",- 'Component "ws:element" requires a non-empty tag, for example <ws.element ws:tag="section">...</ws.element>. Use a Webstudio component such as <$.Box>...</$.Box> when you do not need a specific HTML tag.'+ 'Component "ws:element" requires a non-empty tag. In JSX, use a lowercase HTML element such as <section>...</section>; in structured instance data, set component "ws:element" and tag "section".');}const insertCategory = templates.get(component)?.category ?? meta?.category;@@ -866,6 +864,7 @@ const createInsertFragmentMutation = <): [],instances: nextData.instances,+ components: componentMetas.keys(),});const requiredTemplateNameConfirmation =mode === "replace" && parent.component === blockTemplateComponentdiff --git a/packages/project-build/src/runtime/content-block-application.test.ts b/packages/project-build/src/runtime/content-block-application.test.tsindex ae2cd9d458..e8f54a7933 100644--- a/packages/project-build/src/runtime/content-block-application.test.ts+++ b/packages/project-build/src/runtime/content-block-application.test.ts@@ -12,6 +12,7 @@ import type { BuilderState } from "../state/builder-state";import { createDefaultPages } from "../shared/pages-utils";import {createContentBlockApplication,+ getMdxAssetSourceBlockInstanceIds,inspectMdxAssetSource,} from "./content-block-application";@@ -135,6 +136,13 @@ describe("createContentBlockApplication", () => {{ id: "connect", payload: [...connected.projectPayload] },]).state;+ expect(+ getMdxAssetSourceBlockInstanceIds({+ assetId: "asset",+ state: connectedState,+ })+ ).toEqual(["block"]);+await expect(inspectMdxAssetSource({source: '<ws.element ws:name="Missing" />',@@ -423,6 +431,6 @@ describe("createContentBlockApplication", () => {confirmationToken: plan.confirmationToken,});expect(result.status).toBe("complete");- expect(fixture.getSource()).toContain('ws:name="New"');+ expect(fixture.getSource()).toContain("<New />");});});diff --git a/packages/project-build/src/runtime/content-block-application.ts b/packages/project-build/src/runtime/content-block-application.tsindex db247d179a..09718c2d3b 100644--- a/packages/project-build/src/runtime/content-block-application.ts+++ b/packages/project-build/src/runtime/content-block-application.ts@@ -41,6 +41,33 @@ const getData = (state: BuilderState): Omit<WebstudioData, "pages"> => ({: { assetFolders: state.assetFolders }),});+/** Finds every Content Block whose current source resolves to an MDX Asset. */+export const getMdxAssetSourceBlockInstanceIds = ({+ assetId,+ state,+}: {+ assetId: string;+ state: BuilderState;+}) => {+ const values = new Map<string, unknown>();+ for (const dataSource of state.dataSources?.values() ?? []) {+ if (dataSource.type === "variable") {+ values.set(dataSource.name, dataSource.value.value);+ }+ }+ return Array.from(+ getContentBlockSources({+ instances: state.instances?.values() ?? [],+ props: state.props?.values() ?? [],+ })+ ).flatMap(([blockInstanceId, contentSource]) =>+ resolveContentBlockSourceAssetId({ source: contentSource, values }) ===+ assetId+ ? [blockInstanceId]+ : []+ );+};+export const mdxAssetInspectionNamespaces = componentInsertReadNamespaces;const describeValueShape = (value: unknown): string => {@@ -100,22 +127,10 @@ export const inspectMdxAssetSource = async ({return diagnostics;}const data = getData(state);- const values = new Map<string, unknown>();- for (const dataSource of state.dataSources?.values() ?? []) {- if (dataSource.type === "variable") {- values.set(dataSource.name, dataSource.value.value);- }- }- for (const [blockInstanceId, contentSource] of getContentBlockSources({- instances: state.instances?.values() ?? [],- props: state.props?.values() ?? [],+ for (const blockInstanceId of getMdxAssetSourceBlockInstanceIds({+ assetId,+ state,})) {- if (- resolveContentBlockSourceAssetId({ source: contentSource, values }) !==- assetId- ) {- continue;- }const identity = createContentBlockExternalContentIdentity({blockInstanceId,asset,diff --git a/packages/project-build/src/runtime/content-mode-permissions.test.ts b/packages/project-build/src/runtime/content-mode-permissions.test.tsindex 09f1893e74..76a8ce886e 100644--- a/packages/project-build/src/runtime/content-mode-permissions.test.ts+++ b/packages/project-build/src/runtime/content-mode-permissions.test.ts@@ -1554,6 +1554,72 @@ describe("content mode permissions", () => {).toEqual({ success: true });});+ test("keeps unresolved tag metadata while applying a transaction", () => {+ const instance: Instance = {+ type: "instance",+ id: "dynamic-image",+ component: "LegacyImage",+ children: [],+ };+ const capabilities = getContentModeCapabilities({+ instances: new Map([[instance.id, instance]]),+ metas: new Map([+ ["LegacyImage", { presetStyle: { img: [] } }],+ [+ "Image",+ {+ presetStyle: { img: [] },+ props: {+ alt: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },+ },+ ],+ ]),+ props: new Map([+ [+ "dynamic-tag",+ {+ id: "dynamic-tag",+ instanceId: instance.id,+ name: "tag",+ type: "expression",+ value: '"section"',+ mode: "read",+ },+ ],+ ]),+ styleSources,+ contentRootIds: new Set([instance.id]),+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ {+ op: "add",+ path: ["alt-prop"],+ value: {+ id: "alt-prop",+ instanceId: instance.id,+ name: "alt",+ type: "string",+ value: "Alternative text",+ },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: 'Prop "alt-prop" is not editable in content mode.',+ });+ });+test("validates new props against instances added in the same transaction", () => {const capabilities = getContentModeCapabilities({instances: new Map([diff --git a/packages/project-build/src/runtime/content-mode-permissions.ts b/packages/project-build/src/runtime/content-mode-permissions.tsindex eb6b9bba8d..4b1de4e41c 100644--- a/packages/project-build/src/runtime/content-mode-permissions.ts+++ b/packages/project-build/src/runtime/content-mode-permissions.ts@@ -1589,7 +1589,7 @@ export const applyContentModeTransaction = ({])),props: new Map(capabilities.props),- htmlTagsByInstanceId: new Map(capabilities.htmlTagsByInstanceId),+ htmlTagsByInstanceId: getHtmlTagsFromProps(capabilities.props),styleSources: new Map(capabilities.styleSources),styleSourceSelections: new Map(capabilities.styleSourceSelections),styles: new Map(capabilities.styles),diff --git a/packages/project-build/src/runtime/content-model.test.tsx b/packages/project-build/src/runtime/content-model.test.tsxindex f83430bbaa..9a69643929 100644--- a/packages/project-build/src/runtime/content-model.test.tsx+++ b/packages/project-build/src/runtime/content-model.test.tsx@@ -1,7 +1,12 @@import { describe, expect, test } from "vitest";import { type Prop, type Props } from "@webstudio-is/sdk";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";-import { $, expression, renderData, ws } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ expression,+ renderData,+ ws,+} from "@webstudio-is/template";import {canHaveTextContent,findClosestContainer,@@ -11,6 +16,23 @@ import {isTreeSatisfyingContentModel,} from "./content-model";+const Body = createTemplateComponentFixture("Body");+const Bold = createTemplateComponentFixture("Bold");+const Box = createTemplateComponentFixture("Box");+const CodeText = createTemplateComponentFixture("CodeText");+const Fragment = createTemplateComponentFixture("Fragment");+const HeadSlot = createTemplateComponentFixture("HeadSlot");+const HtmlEmbed = createTemplateComponentFixture("HtmlEmbed");+const Image = createTemplateComponentFixture("Image");+const Italic = createTemplateComponentFixture("Italic");+const JsonLd = createTemplateComponentFixture("JsonLd");+const Link = createTemplateComponentFixture("Link");+const Paragraph = createTemplateComponentFixture("Paragraph");+const Slot = createTemplateComponentFixture("Slot");+const Vimeo = createTemplateComponentFixture("Vimeo");+const VimeoSpinner = createTemplateComponentFixture("VimeoSpinner");+const XmlNode = createTemplateComponentFixture("XmlNode");+const defaultMetas = componentMetas;test("checks direct text capability without promoting the outer rich-text root", () => {@@ -72,11 +94,11 @@ test("support Box with ws:tag", () => {expect(isTreeSatisfyingContentModel({...renderData(- <$.Body ws:id="bodyId">- <$.Box ws:tag="span">- <$.Box ws:tag="article"></$.Box>- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:tag="span">+ <Box ws:tag="article"></Box>+ </Box>+ </Body>),metas: defaultMetas,instanceSelector: ["bodyId"],@@ -88,11 +110,11 @@ test("support legacy tag property", () => {expect(isTreeSatisfyingContentModel({...renderData(- <$.Body ws:id="bodyId">- <$.Box tag="span">- <$.Box tag="article"></$.Box>- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box tag="span">+ <Box tag="article"></Box>+ </Box>+ </Body>),metas: defaultMetas,instanceSelector: ["bodyId"],@@ -165,11 +187,11 @@ test("slot without tag accepts transparent category", () => {...renderData(<ws.element ws:tag="body" ws:id="bodyId"><ws.element ws:tag="ul">- <$.Slot>- <$.Fragment>+ <Slot>+ <Fragment><ws.element ws:tag="li"></ws.element>- </$.Fragment>- </$.Slot>+ </Fragment>+ </Slot></ws.element></ws.element>),@@ -213,6 +235,31 @@ test("transparent category accepts flow", () => {).toBeTruthy();});+test("transparent root element accepts flow without allowing interactive children", () => {+ expect(+ isTreeSatisfyingContentModel({+ ...renderData(+ <ws.element ws:tag="a" ws:id="linkId">+ <ws.element ws:tag="p"></ws.element>+ </ws.element>+ ),+ metas: defaultMetas,+ instanceSelector: ["linkId"],+ })+ ).toBeTruthy();+ expect(+ isTreeSatisfyingContentModel({+ ...renderData(+ <ws.element ws:tag="a" ws:id="linkId">+ <ws.element ws:tag="button"></ws.element>+ </ws.element>+ ),+ metas: defaultMetas,+ instanceSelector: ["linkId"],+ })+ ).toBeFalsy();+});+test("phrasing category accepts element with transparent children", () => {expect(isTreeSatisfyingContentModel({@@ -287,9 +334,9 @@ test("reports the ancestor that introduces a transparent constraint", () => {...renderData(<ws.element ws:tag="body" ws:id="bodyId"><ws.element ws:tag="ul" ws:id="listId">- <$.Slot>+ <Slot><ws.element ws:tag="div" />- </$.Slot>+ </Slot></ws.element></ws.element>),@@ -400,11 +447,11 @@ test("prevent nesting interactive instances with slots in between", () => {...renderData(<ws.element ws:tag="body" ws:id="bodyId"><ws.element ws:tag="button">- <$.Slot>- <$.Fragment>+ <Slot>+ <Fragment><ws.element ws:tag="textarea"></ws.element>- </$.Fragment>- </$.Slot>+ </Fragment>+ </Slot></ws.element></ws.element>),@@ -571,9 +618,9 @@ test("support xml node with tags", () => {isTreeSatisfyingContentModel({...renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.XmlNode tag="url">- <$.XmlNode tag="loc"></$.XmlNode>- </$.XmlNode>+ <XmlNode tag="url">+ <XmlNode tag="loc"></XmlNode>+ </XmlNode></ws.element>),metas: defaultMetas,@@ -622,7 +669,7 @@ describe("component content model", () => {isTreeSatisfyingContentModel({...renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.JsonLd code='{"@context":"https://schema.org"}' />+ <JsonLd code='{"@context":"https://schema.org"}' /></ws.element>),metas: defaultMetas,@@ -635,9 +682,9 @@ describe("component content model", () => {expect(isTreeSatisfyingContentModel({...renderData(- <$.HeadSlot ws:id="headSlotId">- <$.JsonLd code='{"@context":"https://schema.org"}' />- </$.HeadSlot>+ <HeadSlot ws:id="headSlotId">+ <JsonLd code='{"@context":"https://schema.org"}' />+ </HeadSlot>),metas: defaultMetas,instanceSelector: ["headSlotId"],@@ -650,9 +697,9 @@ describe("component content model", () => {isTreeSatisfyingContentModel({...renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.HtmlEmbed>+ <HtmlEmbed><ws.descendant />- </$.HtmlEmbed>+ </HtmlEmbed></ws.element>),metas: defaultMetas,@@ -663,9 +710,9 @@ describe("component content model", () => {isTreeSatisfyingContentModel({...renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.HtmlEmbed>+ <HtmlEmbed><ws.element ws:tag="div" />- </$.HtmlEmbed>+ </HtmlEmbed></ws.element>),metas: defaultMetas,@@ -679,9 +726,9 @@ describe("component content model", () => {isTreeSatisfyingContentModel({...renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.Vimeo>- <$.VimeoSpinner></$.VimeoSpinner>- </$.Vimeo>+ <Vimeo>+ <VimeoSpinner></VimeoSpinner>+ </Vimeo></ws.element>),metas: defaultMetas,@@ -692,11 +739,11 @@ describe("component content model", () => {isTreeSatisfyingContentModel({...renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.Vimeo>+ <Vimeo><ws.element ws:tag="div">- <$.VimeoSpinner></$.VimeoSpinner>+ <VimeoSpinner></VimeoSpinner></ws.element>- </$.Vimeo>+ </Vimeo></ws.element>),metas: defaultMetas,@@ -707,7 +754,7 @@ describe("component content model", () => {isTreeSatisfyingContentModel({...renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.VimeoSpinner></$.VimeoSpinner>+ <VimeoSpinner></VimeoSpinner></ws.element>),metas: defaultMetas,@@ -721,11 +768,11 @@ describe("component content model", () => {isTreeSatisfyingContentModel({...renderData(<ws.element ws:tag="body" ws:id="bodyId">- <$.Vimeo ws:id="vimeoId">+ <Vimeo ws:id="vimeoId"><ws.element ws:tag="div" ws:id="divId">- <$.VimeoSpinner></$.VimeoSpinner>+ <VimeoSpinner></VimeoSpinner></ws.element>- </$.Vimeo>+ </Vimeo></ws.element>),metas: defaultMetas,@@ -738,7 +785,7 @@ describe("component content model", () => {describe("rich text tree", () => {test("uses provided html tags index without scanning props", () => {const { instances } = renderData(- <$.Paragraph ws:id="instanceId"></$.Paragraph>+ <Paragraph ws:id="instanceId"></Paragraph>);const props = new (class extends Map<string, Prop> {values(): MapIterator<Prop> {@@ -759,11 +806,11 @@ describe("rich text tree", () => {test("reads updated tag props from mutable props maps", () => {const { instances, props } = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">+ <Body ws:id="bodyId">+ <Box ws:id="boxId"><ws.element ws:tag="article"></ws.element>- </$.Box>- </$.Body>+ </Box>+ </Body>);expect(@@ -796,14 +843,14 @@ describe("rich text tree", () => {test("check empty instance is rich text", () => {expect(isRichTextTree({- ...renderData(<$.Bold ws:id="instanceId"></$.Bold>),+ ...renderData(<Bold ws:id="instanceId"></Bold>),metas: defaultMetas,instanceId: "instanceId",})).toBeTruthy();expect(isRichTextTree({- ...renderData(<$.HeadSlot ws:id="instanceId"></$.HeadSlot>),+ ...renderData(<HeadSlot ws:id="instanceId"></HeadSlot>),metas: defaultMetas,instanceId: "instanceId",})@@ -813,16 +860,14 @@ describe("rich text tree", () => {test("any instance with text can be edited", () => {expect(isRichTextTree({- ...renderData(<$.HeadSlot ws:id="instanceId">my text</$.HeadSlot>),+ ...renderData(<HeadSlot ws:id="instanceId">my text</HeadSlot>),metas: defaultMetas,instanceId: "instanceId",})).toBeTruthy();expect(isRichTextTree({- ...renderData(- <$.HeadSlot ws:id="instanceId">{expression``}</$.HeadSlot>- ),+ ...renderData(<HeadSlot ws:id="instanceId">{expression``}</HeadSlot>),metas: defaultMetas,instanceId: "instanceId",})@@ -833,9 +878,9 @@ describe("rich text tree", () => {expect(isRichTextTree({...renderData(- <$.Bold ws:id="instanceId">- <$.Italic></$.Italic>- </$.Bold>+ <Bold ws:id="instanceId">+ <Italic></Italic>+ </Bold>),metas: defaultMetas,instanceId: "instanceId",@@ -847,9 +892,9 @@ describe("rich text tree", () => {expect(isRichTextTree({...renderData(- <$.Paragraph ws:id="instanceId">- <$.Bold>bold</$.Bold>- </$.Paragraph>+ <Paragraph ws:id="instanceId">+ <Bold>bold</Bold>+ </Paragraph>),metas: defaultMetas,instanceId: "instanceId",@@ -858,9 +903,9 @@ describe("rich text tree", () => {expect(isRichTextTree({...renderData(- <$.HeadSlot ws:id="instanceId">- <$.Bold>bold</$.Bold>- </$.HeadSlot>+ <HeadSlot ws:id="instanceId">+ <Bold>bold</Bold>+ </HeadSlot>),metas: defaultMetas,instanceId: "instanceId",@@ -872,9 +917,9 @@ describe("rich text tree", () => {expect(isRichTextTree({...renderData(- <$.Box ws:id="instanceId">- <$.Paragraph></$.Paragraph>- </$.Box>+ <Box ws:id="instanceId">+ <Paragraph></Paragraph>+ </Box>),metas: defaultMetas,instanceId: "instanceId",@@ -920,9 +965,9 @@ describe("rich text tree", () => {...renderData(<ws.element ws:tag="body" ws:id="bodyId"><ws.element ws:tag="span" ws:id="spanId">- <$.Link ws:id="linkId">- <$.Bold ws:id="boldId">link</$.Bold>- </$.Link>+ <Link ws:id="linkId">+ <Bold ws:id="boldId">link</Bold>+ </Link></ws.element></ws.element>),@@ -1036,7 +1081,7 @@ describe("rich text tree", () => {...renderData(<ws.element ws:tag="body" ws:id="bodyId"><ws.element ws:tag="div" ws:id="divId">- <$.Image ws:id="imgId" />+ <Image ws:id="imgId" /></ws.element></ws.element>),@@ -1052,11 +1097,11 @@ describe("closest container", () => {expect(findClosestContainer({...renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Image ws:id="imageId" />- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <Image ws:id="imageId" />+ </Box>+ </Body>),metas: defaultMetas,instanceSelector: ["imageId", "boxId", "bodyId"],@@ -1068,11 +1113,11 @@ describe("closest container", () => {expect(findClosestContainer({...renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Box ws:id="box-with-text">text</$.Box>- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <Box ws:id="box-with-text">text</Box>+ </Box>+ </Body>),metas: defaultMetas,instanceSelector: ["box-with-text", "boxId", "bodyId"],@@ -1084,11 +1129,11 @@ describe("closest container", () => {expect(findClosestContainer({...renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Box ws:id="box-with-expr">{expression`1 + 1`}</$.Box>- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <Box ws:id="box-with-expr">{expression`1 + 1`}</Box>+ </Box>+ </Body>),metas: defaultMetas,instanceSelector: ["box-with-expr", "boxId", "bodyId"],@@ -1099,7 +1144,7 @@ describe("closest container", () => {test("allow root with text", () => {expect(findClosestContainer({- ...renderData(<$.Body ws:id="bodyId">text</$.Body>),+ ...renderData(<Body ws:id="bodyId">text</Body>),metas: defaultMetas,instanceSelector: ["bodyId"],})@@ -1112,11 +1157,11 @@ describe("closest non textual container", () => {expect(findClosestNonTextualContainer({...renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Image ws:id="imageId" />- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <Image ws:id="imageId" />+ </Box>+ </Body>),metas: defaultMetas,instanceSelector: ["imageId", "boxId", "bodyId"],@@ -1128,11 +1173,11 @@ describe("closest non textual container", () => {expect(findClosestNonTextualContainer({...renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.CodeText ws:id="codeId" />- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <CodeText ws:id="codeId" />+ </Box>+ </Body>),metas: defaultMetas,instanceSelector: ["codeId", "boxId", "bodyId"],@@ -1144,11 +1189,11 @@ describe("closest non textual container", () => {expect(findClosestNonTextualContainer({...renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Box ws:id="box-with-text">text</$.Box>- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <Box ws:id="box-with-text">text</Box>+ </Box>+ </Body>),metas: defaultMetas,instanceSelector: ["box-with-text", "boxId", "bodyId"],@@ -1160,11 +1205,11 @@ describe("closest non textual container", () => {expect(findClosestNonTextualContainer({...renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Box ws:id="box-with-expr">{expression`1 + 1`}</$.Box>- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <Box ws:id="box-with-expr">{expression`1 + 1`}</Box>+ </Box>+ </Body>),metas: defaultMetas,instanceSelector: ["box-with-expr", "boxId", "bodyId"],@@ -1176,13 +1221,13 @@ describe("closest non textual container", () => {expect(findClosestNonTextualContainer({...renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Box ws:id="box-with-bold">- <$.Bold ws:id="boldId"></$.Bold>- </$.Box>- </$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <Box ws:id="box-with-bold">+ <Bold ws:id="boldId"></Bold>+ </Box>+ </Box>+ </Body>),metas: defaultMetas,instanceSelector: ["box-with-bold", "boxId", "bodyId"],@@ -1193,7 +1238,7 @@ describe("closest non textual container", () => {test("allow root with text", () => {expect(findClosestNonTextualContainer({- ...renderData(<$.Body ws:id="body">text</$.Body>),+ ...renderData(<Body ws:id="body">text</Body>),metas: defaultMetas,instanceSelector: ["body"],})@@ -1220,9 +1265,9 @@ describe("closest non textual container", () => {...renderData(<ws.element ws:tag="body" ws:id="bodyId"><ws.element ws:tag="span" ws:id="spanId">- <$.Link ws:id="linkId">- <$.Bold ws:id="boldId">link</$.Bold>- </$.Link>+ <Link ws:id="linkId">+ <Bold ws:id="boldId">link</Bold>+ </Link></ws.element></ws.element>),diff --git a/packages/project-build/src/runtime/content-model.ts b/packages/project-build/src/runtime/content-model.tsindex e33a367b3d..2309fb283e 100644--- a/packages/project-build/src/runtime/content-model.ts+++ b/packages/project-build/src/runtime/content-model.ts@@ -129,10 +129,12 @@ const getElementChildren = (let elementChildren = getElementContentModel(tag)?.children ?? ["transparent",];- if (elementChildren.includes("transparent") && allowedCategories) {- // merge categories from parent and current element when transparent occured+ if (elementChildren.includes("transparent")) {+ // Transparent elements inherit their parent's content model. Without a+ // known parent, HTML allows any flow content.+ const inheritedCategories = allowedCategories ?? ["flow"];elementChildren = elementChildren.flatMap((category) =>- category === "transparent" ? allowedCategories : category+ category === "transparent" ? inheritedCategories : category);}// introduce custom non-interactive category to restrict nesting interactive elementsdiff --git a/packages/project-build/src/runtime/cutover.ts b/packages/project-build/src/runtime/cutover.tsindex 65fa392ec7..ff8d713d13 100644--- a/packages/project-build/src/runtime/cutover.ts+++ b/packages/project-build/src/runtime/cutover.ts@@ -199,7 +199,11 @@ export const builderRuntimeCutoverManifests = [},{family: "instance-metadata-mutations",- operationIds: ["instances.setTag", "instances.setLabel"] as const,+ operationIds: [+ "instances.setTag",+ "instances.setLabel",+ "instances.setName",+ ] as const,callers: ["Builder settings panel", "Builder navigator"] as const,},{diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsxindex d4024522a8..956b4a3eed 100644--- a/packages/project-build/src/runtime/data.test.tsx+++ b/packages/project-build/src/runtime/data.test.tsx@@ -1,6 +1,6 @@import { describe, expect, test, vi } from "vitest";import {- $,+ createTemplateComponentFixture,ActionValue,expression,Parameter,@@ -75,6 +75,12 @@ import {validateResourceUrlExpression,} from "./data";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Fragment = createTemplateComponentFixture("Fragment");+const Slot = createTemplateComponentFixture("Slot");+const Text = createTemplateComponentFixture("Text");+test("creates Map-backed patches without mutating caller-owned data", () => {const before = {instances: new Map([@@ -839,9 +845,9 @@ test("find available variables", () => {const bodyVariable = new Variable("bodyVariable", "");const boxVariable = new Variable("boxVariable", "");const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" vars={expression`${boxVariable}`}></$.Box>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" vars={expression`${boxVariable}`}></Box>+ </Body>);expect(findAvailableVariables({ ...data, startingInstanceId: "boxId" })@@ -856,9 +862,9 @@ test("find masked variables", () => {const bodyVariable = new Variable("myVariable", "");const boxVariable = new Variable("myVariable", "");const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" vars={expression`${boxVariable}`}></$.Box>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" vars={expression`${boxVariable}`}></Box>+ </Body>);expect(findAvailableVariables({ ...data, startingInstanceId: "boxId" })@@ -873,9 +879,9 @@ test("find global variables", () => {const boxVariable = new Variable("boxVariable", "");const data = renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId" vars={expression`${boxVariable}`}></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId" vars={expression`${boxVariable}`}></Box>+ </Body></ws.root>);data.instances.delete(ROOT_INSTANCE_ID);@@ -894,13 +900,13 @@ test("find global variables in slots", () => {const boxVariable = new Variable("boxVariable", "");const data = renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Slot ws:id="slotId">- <$.Fragment ws:id="fragmentId">- <$.Box ws:id="boxId" vars={expression`${boxVariable}`}></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Slot ws:id="slotId">+ <Fragment ws:id="fragmentId">+ <Box ws:id="boxId" vars={expression`${boxVariable}`}></Box>+ </Fragment>+ </Slot>+ </Body></ws.root>);data.instances.delete(ROOT_INSTANCE_ID);@@ -915,9 +921,9 @@ test("find global variables in slots", () => {test("find legacy global variables with missing scope", () => {const data = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId"></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId"></Box>+ </Body>);data.dataSources.set("legacyGlobalVariableId", {id: "legacyGlobalVariableId",@@ -1087,16 +1093,16 @@ test("find unset variable names", () => {body: expression`thirteen`,});const data = renderData(- <$.Body ws:id="body" data-prop={expression`two`}>- <$.Box ws:id="box" data-prop={expression`three`}>- <$.Text+ <Body ws:id="body" data-prop={expression`two`}>+ <Box ws:id="box" data-prop={expression`three`}>+ <Textws:id="text"data-variables={expression`${resourceVariable}`}data-resource={resourceProp}data-action={new ActionValue(["five"], expression`four + five`)}- >{expression`one`}</$.Text>- </$.Box>- </$.Body>+ >{expression`one`}</Text>+ </Box>+ </Body>);expect(findUnsetVariableNames({ startingInstanceId: "body", ...data })@@ -1120,11 +1126,11 @@ test("restore tree variables in children", () => {const bodyVariable = new Variable("one", "one value of body");const boxVariable = new Variable("one", "one value of box");const data = renderData(- <$.Body ws:id="bodyId" data-vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" data-vars={expression`${boxVariable}`}>- <$.Text ws:id="textId">{expression`one`}</$.Text>- </$.Box>- </$.Body>+ <Body ws:id="bodyId" data-vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" data-vars={expression`${boxVariable}`}>+ <Text ws:id="textId">{expression`one`}</Text>+ </Box>+ </Body>);rebindTreeVariablesMutable({startingInstanceId: "boxId",@@ -1147,16 +1153,16 @@ test("restore tree variables in props", () => {const oneBox = new Variable("one", "one value of box");const twoBox = new Variable("two", "two value of box");const data = renderData(- <$.Body ws:id="bodyId" data-body-vars={expression`${oneBody}`}>- <$.Box+ <Body ws:id="bodyId" data-body-vars={expression`${oneBody}`}>+ <Boxws:id="boxId"data-box-vars={expression`${oneBox} ${twoBox}`}data-one={expression`one`}data-action={new ActionValue(["one"], expression`one + two + three`)}>- <$.Text ws:id="text" data-two={expression`one + two + three`}></$.Text>- </$.Box>- </$.Body>+ <Text ws:id="text" data-two={expression`one + two + three`}></Text>+ </Box>+ </Body>);rebindTreeVariablesMutable({startingInstanceId: "boxId",@@ -1197,17 +1203,17 @@ test("rebind tree variables in props and children", () => {const bodyVariable = new Variable("one", "one value of body");const boxVariable = new Variable("one", "one value of box");const data = renderData(- <$.Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" data-box-vars={expression`${boxVariable}`}>- <$.Text+ <Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" data-box-vars={expression`${boxVariable}`}>+ <Textws:id="textId"data-text-vars={expression`${bodyVariable}`}data-action={new ActionValue([], expression`${bodyVariable}`)}>{expression`${bodyVariable}`}- </$.Text>- </$.Box>- </$.Body>+ </Text>+ </Box>+ </Body>);rebindTreeVariablesMutable({startingInstanceId: "boxId",@@ -1238,11 +1244,11 @@ test("preserve nested variables with the same name when rebind", () => {const bodyVariable = new Variable("one", "one value of body");const textVariable = new Variable("one", "one value of box");const data = renderData(- <$.Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>- <$.Text ws:id="textId" data-text-vars={expression`${textVariable}`}>+ <Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>+ <Text ws:id="textId" data-text-vars={expression`${textVariable}`}>{expression`${textVariable}`}- </$.Text>- </$.Body>+ </Text>+ </Body>);rebindTreeVariablesMutable({startingInstanceId: "bodyId",@@ -1278,15 +1284,15 @@ test("restore tree variables in resources", () => {body: expression`one + 2`,});const data = renderData(- <$.Body ws:id="bodyId" data-vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" data-vars={expression`${boxVariable}`}>- <$.Text+ <Body ws:id="bodyId" data-vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" data-vars={expression`${boxVariable}`}>+ <Textws:id="text"data-vars={expression`${resourceVariable}`}data-resource={resourceProp}- ></$.Text>- </$.Box>- </$.Body>+ ></Text>+ </Box>+ </Body>);rebindTreeVariablesMutable({startingInstanceId: "boxId",@@ -1336,15 +1342,15 @@ test("rebind tree variables in resources", () => {body: expression`${bodyVariable}`,});const data = renderData(- <$.Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" data-box-vars={expression`${boxVariable}`}>- <$.Text+ <Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" data-box-vars={expression`${boxVariable}`}>+ <Textws:id="textId"data-text-vars={expression`${resourceVariable}`}data-action={resourceProp}- ></$.Text>- </$.Box>- </$.Body>+ ></Text>+ </Box>+ </Body>);rebindTreeVariablesMutable({startingInstanceId: "boxId",@@ -1380,9 +1386,9 @@ test("rebind global variables in resources", () => {const globalVariable = new Variable("globalVariable", "");const data = renderData(<ws.root ws:id={ROOT_INSTANCE_ID} data-vars={expression`${globalVariable}`}>- <$.Body ws:id="bodyId">- <$.Text ws:id="textId">{expression`globalVariable`}</$.Text>- </$.Body>+ <Body ws:id="bodyId">+ <Text ws:id="textId">{expression`globalVariable`}</Text>+ </Body></ws.root>);data.instances.delete(ROOT_INSTANCE_ID);@@ -1405,9 +1411,9 @@ test("preserve other variables when rebind", () => {const bodyVariable = new Variable("globalVariable", "");const textVariable = new Variable("textVariable", "");const data = renderData(- <$.Body ws:id="bodyId" data-vars={expression`${bodyVariable}`}>- <$.Text ws:id="textId">{expression`${textVariable}`}</$.Text>- </$.Body>+ <Body ws:id="bodyId" data-vars={expression`${bodyVariable}`}>+ <Text ws:id="textId">{expression`${textVariable}`}</Text>+ </Body>);rebindTreeVariablesMutable({startingInstanceId: "bodyId",@@ -1428,13 +1434,13 @@ test("preserve other variables when rebind", () => {test("prevent rebinding tree variables from slots", () => {const bodyVariable = new Variable("myVariable", "one value of body");const data = renderData(- <$.Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>- <$.Slot ws:id="slotId">- <$.Fragment ws:id="fragmentId">- <$.Box ws:id="boxId">{expression`myVariable`}</$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>+ <Slot ws:id="slotId">+ <Fragment ws:id="fragmentId">+ <Box ws:id="boxId">{expression`myVariable`}</Box>+ </Fragment>+ </Slot>+ </Body>);rebindTreeVariablesMutable({startingInstanceId: "boxId",@@ -1450,7 +1456,7 @@ test("prevent rebinding with nested collection item", () => {const collectionItem = new Parameter("collectionITem");const nestedCollectionItem = new Parameter("collectionITem");const data = renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.collection ws:id="collectionId" data={[]} item={collectionItem}><ws.collectionws:id="nestedCollectionId"@@ -1462,7 +1468,7 @@ test("prevent rebinding with nested collection item", () => {</ws.element></ws.collection></ws.collection>- </$.Body>+ </Body>);expect(Array.from(data.dataSources.values())).toEqual([expect.objectContaining({ scopeInstanceId: "collectionId" }),@@ -1507,14 +1513,14 @@ test("prevent rebinding with nested collection item", () => {test("delete variable and unset it in expressions", () => {const bodyVariable = new Variable("bodyVariable", "one value of body");const data = renderData(- <$.Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>- <$.Box+ <Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>+ <Boxws:id="boxId"data-action={new ActionValue([], expression`${bodyVariable}`)}>{expression`${bodyVariable}`}- </$.Box>- </$.Body>+ </Box>+ </Body>);expect(Array.from(data.dataSources.values())).toEqual([expect.objectContaining({ scopeInstanceId: "bodyId" }),@@ -1542,11 +1548,11 @@ test("delete data variable payload reuses mutable cleanup semantics", () => {headers: [{ name: "auth", value: expression`${bodyVariable}` }],});const data = renderData(- <$.Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" data-box-vars={expression`${resourceVariable}`}>+ <Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" data-box-vars={expression`${resourceVariable}`}>{expression`${bodyVariable}`}- </$.Box>- </$.Body>+ </Box>+ </Body>);const [bodyVariableId] = data.dataSources.keys();const pages = createDefaultPages({ rootInstanceId: "bodyId" });@@ -1656,13 +1662,13 @@ test("delete variable and unset it in resources", () => {body: expression`${bodyVariable}`,});const data = renderData(- <$.Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>- <$.Box+ <Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>+ <Boxws:id="boxId"data-box-vars={expression`${resourceVariable}`}data-resource={resourceProp}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);expect(Array.from(data.dataSources.values())).toEqual([expect.objectContaining({ scopeInstanceId: "bodyId" }),@@ -1692,11 +1698,11 @@ test("rebind expressions with parent variable when delete variable on child", ()const bodyVariable = new Variable("myVariable", "one value of body");const boxVariable = new Variable("myVariable", "one value of body");const data = renderData(- <$.Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" data-box-vars={expression`${boxVariable}`}>- <$.Text ws:id="textId">{expression`${boxVariable}`}</$.Text>- </$.Box>- </$.Body>+ <Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" data-box-vars={expression`${boxVariable}`}>+ <Text ws:id="textId">{expression`${boxVariable}`}</Text>+ </Box>+ </Body>);expect(Array.from(data.dataSources.values())).toEqual([expect.objectContaining({ scopeInstanceId: "bodyId" }),@@ -1714,15 +1720,15 @@ test("prevent rebinding with variables outside of slot content scope", () => {const bodyVariable = new Variable("myVariable", "one value of body");const boxVariable = new Variable("myVariable", "one value of body");const data = renderData(- <$.Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>- <$.Slot>- <$.Fragment>- <$.Box ws:id="boxId" data-box-vars={expression`${boxVariable}`}>- <$.Text ws:id="textId">{expression`${boxVariable}`}</$.Text>- </$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>+ <Slot>+ <Fragment>+ <Box ws:id="boxId" data-box-vars={expression`${boxVariable}`}>+ <Text ws:id="textId">{expression`${boxVariable}`}</Text>+ </Box>+ </Fragment>+ </Slot>+ </Body>);expect(Array.from(data.dataSources.values())).toEqual([expect.objectContaining({ scopeInstanceId: "bodyId" }),@@ -1750,12 +1756,12 @@ test("unset global variables on all pages when delete", () => {pages,...renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>- <$.Body ws:id="homeBodyId">- <$.Text ws:id="homeTextId">{expression`${globalVariable}`}</$.Text>- </$.Body>- <$.Body ws:id="aboutBodyId">- <$.Text ws:id="aboutTextId">{expression`${globalVariable}`}</$.Text>- </$.Body>+ <Body ws:id="homeBodyId">+ <Text ws:id="homeTextId">{expression`${globalVariable}`}</Text>+ </Body>+ <Body ws:id="aboutBodyId">+ <Text ws:id="aboutTextId">{expression`${globalVariable}`}</Text>+ </Body></ws.root>),};@@ -1775,9 +1781,9 @@ test("unset legacy global variables with missing scope when delete", () => {const data = {pages: createDefaultPages({ rootInstanceId: "homeBodyId" }),...renderData(- <$.Body ws:id="homeBodyId">- <$.Text ws:id="homeTextId"></$.Text>- </$.Body>+ <Body ws:id="homeBodyId">+ <Text ws:id="homeTextId"></Text>+ </Body>),};data.pages.pages.set("aboutPage", {@@ -1830,13 +1836,13 @@ test("unset global variables in slots when delete", () => {pages: createDefaultPages({ rootInstanceId: "bodyId" }),...renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>- <$.Body ws:id="bodyId">- <$.Slot ws:id="slotId">- <$.Fragment ws:id="fragmentId">- <$.Text ws:id="textId">{expression`${globalVariable}`}</$.Text>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="bodyId">+ <Slot ws:id="slotId">+ <Fragment ws:id="fragmentId">+ <Text ws:id="textId">{expression`${globalVariable}`}</Text>+ </Fragment>+ </Slot>+ </Body></ws.root>),};@@ -1854,7 +1860,7 @@ test("unset body variables in page meta when delete", () => {const data = {pages: createDefaultPages({ rootInstanceId: "bodyId" }),...renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}></$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}></Body>),};expect(data.dataSources.size).toEqual(1);@@ -1888,8 +1894,8 @@ test("unset global variables in all pages meta when delete", () => {pages: createDefaultPages({ rootInstanceId: "homeBodyId" }),...renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>- <$.Body ws:id="homeBodyId"></$.Body>- <$.Body ws:id="aboutBodyId"></$.Body>+ <Body ws:id="homeBodyId"></Body>+ <Body ws:id="aboutBodyId"></Body></ws.root>),};@@ -1936,19 +1942,19 @@ test("find variable usages by instance", () => {const data = {pages: createDefaultPages({ rootInstanceId: "bodyId" }),...renderData(- <$.Body+ <Bodyws:id="bodyId"vars={expression`${bodyVariable}`}data-prop={expression`${bodyVariable} + "test"`}>- <$.Box+ <Boxws:id="boxId"vars={expression`${boxVariable}`}data-prop={expression`${boxVariable} + ${bodyVariable}`}>- <$.Text ws:id="textId">{expression`${bodyVariable}`}</$.Text>- </$.Box>- </$.Body>+ <Text ws:id="textId">{expression`${bodyVariable}`}</Text>+ </Box>+ </Body>),};const bodyVariableId = [...data.dataSources.values()].find(@@ -1975,12 +1981,12 @@ test("find variable usages from root includes all pages", () => {pages: createDefaultPages({ rootInstanceId: "homeBodyId" }),...renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>- <$.Body ws:id="homeBodyId">- <$.Box ws:id="homeBoxId" data-prop={expression`${globalVariable}`} />- </$.Body>- <$.Body ws:id="aboutBodyId">- <$.Box ws:id="aboutBoxId" data-prop={expression`${globalVariable}`} />- </$.Body>+ <Body ws:id="homeBodyId">+ <Box ws:id="homeBoxId" data-prop={expression`${globalVariable}`} />+ </Body>+ <Body ws:id="aboutBodyId">+ <Box ws:id="aboutBoxId" data-prop={expression`${globalVariable}`} />+ </Body></ws.root>),};@@ -2012,7 +2018,7 @@ test("find variable usages in page meta", () => {const data = {pages: createDefaultPages({ rootInstanceId: "bodyId" }),...renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}></$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}></Body>),};const [bodyVariableId] = data.dataSources.keys();@@ -2040,13 +2046,13 @@ test("find variable usages counts unique instances not expressions", () => {const data = {pages: createDefaultPages({ rootInstanceId: "bodyId" }),...renderData(- <$.Body+ <Bodyws:id="bodyId"vars={expression`${bodyVariable}`}data-prop1={expression`${bodyVariable}`}data-prop2={expression`${bodyVariable}`}data-prop3={expression`${bodyVariable}`}- ></$.Body>+ ></Body>),};const [bodyVariableId] = data.dataSources.keys();@@ -2068,11 +2074,11 @@ test("finds and deletes unused data variables in one runtime mutation", () => {const data = {pages: createDefaultPages({ rootInstanceId: "bodyId" }),...renderData(- <$.Body+ <Bodyws:id="bodyId"vars={expression`${usedVariable};${unusedVariable}`}data-prop={expression`${usedVariable}`}- ></$.Body>+ ></Body>),};const usedVariableId = [...data.dataSources.values()].find(@@ -2111,11 +2117,11 @@ test("delete unused data variables is a noop when all variables are used", () =>const data = {pages: createDefaultPages({ rootInstanceId: "bodyId" }),...renderData(- <$.Body+ <Bodyws:id="bodyId"vars={expression`${usedVariable}`}data-prop={expression`${usedVariable}`}- ></$.Body>+ ></Body>),};diff --git a/packages/project-build/src/runtime/fragment.test.tsx b/packages/project-build/src/runtime/fragment.test.tsxindex 90c0c4c548..07d5da77a9 100644--- a/packages/project-build/src/runtime/fragment.test.tsx+++ b/packages/project-build/src/runtime/fragment.test.tsx@@ -23,7 +23,7 @@ import {type WebstudioData,} from "@webstudio-is/sdk";import {- $,+ createTemplateComponentFixture,ws,css,renderData,@@ -38,6 +38,15 @@ import {} from "@webstudio-is/template";import { findAvailableVariables } from "./data";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const CodeText = createTemplateComponentFixture("CodeText");+const Fragment = createTemplateComponentFixture("Fragment");+const HtmlEmbed = createTemplateComponentFixture("HtmlEmbed");+const Paragraph = createTemplateComponentFixture("Paragraph");+const Slot = createTemplateComponentFixture("Slot");+const Text = createTemplateComponentFixture("Text");+const stripIndent = (value: string) => {const lines = value.replace(/^\n|\n\s*$/g, "").split("\n");const indent = Math.min(@@ -95,11 +104,11 @@ const toCss = (data: WebstudioData) => {};test("copies a fragment for a target instance and maps root children", () => {- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const data = renderData(<Body ws:id="bodyId"></Body>);const fragment = renderTemplate(- <$.Box ws:id="boxId">- <$.Paragraph ws:id="paragraphId">Hello</$.Paragraph>- </$.Box>+ <Box ws:id="boxId">+ <Paragraph ws:id="paragraphId">Hello</Paragraph>+ </Box>);const ids = ["boxCopyId", "paragraphCopyId"];@@ -133,13 +142,11 @@ test("copies a fragment for a target instance and maps root children", () => {test("merges multiple copied fragments and preserves requested roots", () => {const first = renderTemplate(- <$.Box ws:id="box">- <$.Text ws:id="text">Hello</$.Text>- </$.Box>- );- const second = renderTemplate(- <$.Paragraph ws:id="paragraph">World</$.Paragraph>+ <Box ws:id="box">+ <Text ws:id="text">Hello</Text>+ </Box>);+ const second = renderTemplate(<Paragraph ws:id="paragraph">World</Paragraph>);const fragment = mergeWebstudioFragments(["box", "paragraph"],@@ -160,8 +167,8 @@ test("merges multiple copied fragments and preserves requested roots", () => {test("filters multi-root paste ids to unique ids present in fragment roots", () => {const fragment = renderTemplate(<>- <$.Box ws:id="box"></$.Box>- <$.Paragraph ws:id="paragraph"></$.Paragraph>+ <Box ws:id="box"></Box>+ <Paragraph ws:id="paragraph"></Paragraph></>);@@ -265,7 +272,7 @@ test("prevents pasting a portal fragment into one of its preserved children", ()});test("includes assets referenced by copied variable values", () => {- const data = createStub(<$.Box ws:id="boxId" />);+ const data = createStub(<Box ws:id="boxId" />);data.assets.set("post", {id: "post",projectId: "source-project",@@ -314,14 +321,14 @@ const insertStyles = ({test("extract the instance by id and all its descendants including slot instances", () => {const data = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Slot>- <$.Fragment></$.Fragment>- </$.Slot>- </$.Box>- <$.Text ws:id="textId"></$.Text>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">+ <Slot>+ <Fragment></Fragment>+ </Slot>+ </Box>+ <Text ws:id="textId"></Text>+ </Body>);const { instances } = extractWebstudioFragment(data, "boxId");expect(instances).toEqual([@@ -332,13 +339,13 @@ test("extract the instance by id and all its descendants including slot instance});test("insert instances with slots", () => {- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const data = renderData(<Body ws:id="bodyId"></Body>);const fragment = renderTemplate(- <$.Slot ws:id="slotId">- <$.Fragment ws:id="fragmentId">- <$.Box ws:id="boxId"></$.Box>- </$.Fragment>- </$.Slot>+ <Slot ws:id="slotId">+ <Fragment ws:id="fragmentId">+ <Box ws:id="boxId"></Box>+ </Fragment>+ </Slot>);expect(data.instances.size).toEqual(1);insertWebstudioFragmentCopy({@@ -366,11 +373,11 @@ test("insert instances with slots", () => {});test("remap token selections in inserted slot content", () => {- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const data = renderData(<Body ws:id="bodyId"></Body>);const fragment = renderTemplate(- <$.Slot ws:id="slotId">- <$.Fragment ws:id="fragmentId">- <$.HtmlEmbed+ <Slot ws:id="slotId">+ <Fragment ws:id="fragmentId">+ <HtmlEmbedws:id="iconId"ws:tokens={[token(@@ -381,8 +388,8 @@ test("remap token selections in inserted slot content", () => {),]}/>- </$.Fragment>- </$.Slot>+ </Fragment>+ </Slot>);insertWebstudioFragmentCopy({@@ -401,8 +408,8 @@ test("remap token selections in inserted slot content", () => {});test("preserves legacy HtmlEmbed code when copying internal fragments", () => {- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);- const fragment = renderTemplate(<$.HtmlEmbed code="<div><span></div>" />);+ const data = renderData(<Body ws:id="bodyId"></Body>);+ const fragment = renderTemplate(<HtmlEmbed code="<div><span></div>" />);insertWebstudioFragmentCopy({data,@@ -421,8 +428,8 @@ test("preserves legacy HtmlEmbed code when copying internal fragments", () => {});test("moves legacy Code Text properties into copied text content", () => {- const data = renderData(<$.Body ws:id="bodyId" />);- const fragment = renderTemplate(<$.CodeText code="const answer = 42;" />);+ const data = renderData(<Body ws:id="bodyId" />);+ const fragment = renderTemplate(<CodeText code="const answer = 42;" />);insertWebstudioFragmentCopy({data,@@ -445,15 +452,15 @@ test("moves legacy Code Text properties into copied text content", () => {});test("insert instances with multiple roots", () => {- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const data = renderData(<Body ws:id="bodyId"></Body>);const fragment = renderTemplate(<>- <$.Box>- <$.Text></$.Text>- </$.Box>- <$.Box>- <$.Text></$.Text>- </$.Box>+ <Box>+ <Text></Text>+ </Box>+ <Box>+ <Text></Text>+ </Box></>);expect(data.instances.size).toEqual(1);@@ -474,10 +481,10 @@ test("should add :root local styles", () => {color: red;`}>- <$.Body></$.Body>+ <Body></Body></ws.root>);- const newProject = createStub(<$.Body></$.Body>);+ const newProject = createStub(<Body></Body>);const fragment = extractWebstudioFragment(oldProject, ROOT_INSTANCE_ID);insertWebstudioFragmentCopy({data: newProject,@@ -504,7 +511,7 @@ test("should merge :root local styles", () => {color: red;`}>- <$.Body></$.Body>+ <Body></Body></ws.root>);const newProject = createStub(@@ -514,7 +521,7 @@ test("should merge :root local styles", () => {font-size: medium;`}>- <$.Body></$.Body>+ <Body></Body></ws.root>);const fragment = extractWebstudioFragment(oldProject, ROOT_INSTANCE_ID);@@ -544,7 +551,7 @@ test("does not conflict when a breakpoint id is remapped during insertion", () =color: red;`}>- <$.Body></$.Body>+ <Body></Body></ws.root>);const target = createStub(@@ -554,7 +561,7 @@ test("does not conflict when a breakpoint id is remapped during insertion", () =color: blue;`}>- <$.Body></$.Body>+ <Body></Body></ws.root>);const sourceBreakpoint = source.breakpoints.values().next().value;@@ -590,14 +597,14 @@ test("does not conflict when a breakpoint id is remapped during insertion", () =test("should copy local styles of duplicated instance", () => {const project = createStub(- <$.Body>- <$.Box+ <Body>+ <Boxws:id="boxId"ws:style={css`color: red;`}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);const fragment = extractWebstudioFragment(project, "boxId");insertWebstudioFragmentCopy({@@ -646,11 +653,11 @@ test("should copy local styles of duplicated instance", () => {describe("props", () => {test("extract all props bound to fragment instances", () => {const data = renderData(- <$.Body ws:id="bodyId" data-body="">- <$.Box ws:id="boxId" data-box="">- <$.Text ws:id="textId" data-text=""></$.Text>- </$.Box>- </$.Body>+ <Body ws:id="bodyId" data-body="">+ <Box ws:id="boxId" data-box="">+ <Text ws:id="textId" data-text=""></Text>+ </Box>+ </Body>);const { props } = extractWebstudioFragment(data, "boxId");expect(props).toEqual([@@ -660,11 +667,11 @@ describe("props", () => {});test("insert props with new ids", () => {- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const data = renderData(<Body ws:id="bodyId"></Body>);const fragment = renderTemplate(- <$.Box ws:id="boxId" data-box="">- <$.Text ws:id="textId" data-text=""></$.Text>- </$.Box>+ <Box ws:id="boxId" data-box="">+ <Text ws:id="textId" data-text=""></Text>+ </Box>);insertWebstudioFragmentCopy({data,@@ -685,15 +692,15 @@ describe("props", () => {});test("preserve ids when insert props from slots", () => {- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const data = renderData(<Body ws:id="bodyId"></Body>);const fragment = renderTemplate(- <$.Slot>- <$.Fragment>- <$.Box ws:id="boxId" data-box="">- <$.Text ws:id="textId" data-text=""></$.Text>- </$.Box>- </$.Fragment>- </$.Slot>+ <Slot>+ <Fragment>+ <Box ws:id="boxId" data-box="">+ <Text ws:id="textId" data-text=""></Text>+ </Box>+ </Fragment>+ </Slot>);insertWebstudioFragmentCopy({data,@@ -718,9 +725,9 @@ describe("variables", () => {test("extract variable", () => {const boxVariable = new Variable("Box Variable", "");const data = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId" vars={expression`${boxVariable}`}></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId" vars={expression`${boxVariable}`}></Box>+ </Body>);const fragment = extractWebstudioFragment(data, "boxId");expect(fragment.dataSources).toEqual([@@ -737,8 +744,8 @@ describe("variables", () => {test("unset variable outside of scope", () => {const bodyVariable = new Variable("Body Variable", "");const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Box+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Boxws:id="boxId"vars={expression`${bodyVariable}`}action={@@ -746,8 +753,8 @@ describe("variables", () => {}>{expression`${bodyVariable}`}- </$.Box>- </$.Body>+ </Box>+ </Body>);const fragment = extractWebstudioFragment(data, "boxId");expect(fragment.dataSources).toEqual([]);@@ -783,16 +790,16 @@ describe("variables", () => {test("insert variables with new ids", () => {const boxParameter = new Parameter("My Parameter");- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const data = renderData(<Body ws:id="bodyId"></Body>);const fragment = renderTemplate(- <$.Box+ <Boxws:id="boxId"vars={expression`${boxParameter}`}action={new ActionValue([], expression`${boxParameter}`)}parameter={boxParameter}>{expression`${boxParameter}`}- </$.Box>+ </Box>);insertWebstudioFragmentCopy({data,@@ -831,20 +838,20 @@ describe("variables", () => {test("preserve ids when insert variables from portals", () => {const boxParameter = new Parameter("My Parameter");- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const data = renderData(<Body ws:id="bodyId"></Body>);const fragment = renderTemplate(- <$.Slot>- <$.Fragment>- <$.Box+ <Slot>+ <Fragment>+ <Boxws:id="boxId"vars={expression`${boxParameter}`}action={new ActionValue([], expression`${boxParameter}`)}parameter={boxParameter}>{expression`${boxParameter}`}- </$.Box>- </$.Fragment>- </$.Slot>+ </Box>+ </Fragment>+ </Slot>);insertWebstudioFragmentCopy({data,@@ -883,8 +890,8 @@ describe("variables", () => {test("restore unset variables when insert fragment", () => {const bodyVariable = new Variable("Body Variable", "");const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Box+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Boxws:id="boxId"vars={expression`${bodyVariable} + unknownVariable`}action={@@ -892,8 +899,8 @@ describe("variables", () => {}>{expression`${bodyVariable}`}- </$.Box>- </$.Body>+ </Box>+ </Body>);const fragment = extractWebstudioFragment(data, "boxId");insertWebstudioFragmentCopy({@@ -936,9 +943,9 @@ describe("resources", () => {body: expression`${boxVariable}`,});const data = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId" vars={expression`${resourceVariable}`}></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId" vars={expression`${resourceVariable}`}></Box>+ </Body>);const fragment = extractWebstudioFragment(data, "boxId");expect(fragment.dataSources).toEqual([@@ -965,9 +972,9 @@ describe("resources", () => {body: expression`${bodyVariable}`,});const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" vars={expression`${resourceVariable}`}></$.Box>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" vars={expression`${resourceVariable}`}></Box>+ </Body>);const fragment = extractWebstudioFragment(data, "boxId");expect(fragment.dataSources).toEqual([@@ -993,9 +1000,9 @@ describe("resources", () => {body: expression`${bodyVariable}`,});const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" vars={expression`${resourceVariable}`}></$.Box>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" vars={expression`${resourceVariable}`}></Box>+ </Body>);const fragment = extractWebstudioFragment(data, "boxId");insertWebstudioFragmentCopy({@@ -1035,9 +1042,9 @@ describe("resources", () => {body: expression`${boxVariable}`,});const data = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId" resource={resourceProp}></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId" resource={resourceProp}></Box>+ </Body>);const fragment = extractWebstudioFragment(data, "boxId");expect(fragment.dataSources).toEqual([@@ -1063,9 +1070,9 @@ describe("resources", () => {body: expression`${bodyVariable}`,});const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" resource={resourceProp}></$.Box>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" resource={resourceProp}></Box>+ </Body>);const fragment = extractWebstudioFragment(data, "boxId");expect(fragment.dataSources).toEqual([]);@@ -1089,9 +1096,9 @@ describe("resources", () => {body: expression`${bodyVariable}`,});const data = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}>- <$.Box ws:id="boxId" resource={resourceProp}></$.Box>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}>+ <Box ws:id="boxId" resource={resourceProp}></Box>+ </Body>);const fragment = extractWebstudioFragment(data, "boxId");insertWebstudioFragmentCopy({@@ -1137,13 +1144,13 @@ describe("resources", () => {headers: [{ name: "auth", value: expression`${boxVariable}` }],body: expression`${boxVariable}`,});- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const data = renderData(<Body ws:id="bodyId"></Body>);const fragment = renderTemplate(- <$.Box+ <Boxws:id="boxId"action={resourceProp}vars={expression`${resourceVariable}`}- ></$.Box>+ ></Box>);insertWebstudioFragmentCopy({data,@@ -1204,17 +1211,17 @@ describe("resources", () => {headers: [{ name: "auth", value: expression`${boxVariable}` }],body: expression`${boxVariable}`,});- const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const data = renderData(<Body ws:id="bodyId"></Body>);const fragment = renderTemplate(- <$.Slot ws:id="slotId">- <$.Fragment ws:id="fragmentId">- <$.Box+ <Slot ws:id="slotId">+ <Fragment ws:id="fragmentId">+ <Boxws:id="boxId"action={resourceProp}vars={expression`${resourceVariable}`}- ></$.Box>- </$.Fragment>- </$.Slot>+ ></Box>+ </Fragment>+ </Slot>);insertWebstudioFragmentCopy({data,diff --git a/packages/project-build/src/runtime/html.test.tsx b/packages/project-build/src/runtime/html.test.tsxindex 403b3f50a4..e897962129 100644--- a/packages/project-build/src/runtime/html.test.tsx+++ b/packages/project-build/src/runtime/html.test.tsx@@ -1,8 +1,17 @@import { expect, test, describe } from "vitest";-import { $, css, renderTemplate, token, ws } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ css,+ renderTemplate,+ token,+ ws,+} from "@webstudio-is/template";import type { WebstudioFragment } from "@webstudio-is/sdk";import { generateFragmentFromHtml as _generateFragmentFromHtml } from "./html";+const HtmlEmbed = createTemplateComponentFixture("HtmlEmbed");+const Image = createTemplateComponentFixture("Image");+// Wrapper that strips skippedSelectors for tests that only compare fragment shapeconst generateFragmentFromHtml = (html: string) => {const { skippedSelectors: _skipped, ...fragment } =@@ -304,7 +313,7 @@ test("generate nested css math functions as unparsed local styles", () => {test("script as html embed", () => {expect(generateFragmentFromHtml(`<script>a;</script>`)).toEqual(renderTemplate(- <$.HtmlEmbed+ <HtmlEmbedws:label="Script"clientOnly={true}code={`<script>a;</script>`}@@ -315,7 +324,7 @@ test("script as html embed", () => {test("style as html embed", () => {expect(generateFragmentFromHtml(`<style>a;</style>`)).toEqual(- renderTemplate(<$.HtmlEmbed code={`<style>a;</style>`} ws:label="Style" />)+ renderTemplate(<HtmlEmbed code={`<style>a;</style>`} ws:label="Style" />));});@@ -381,7 +390,7 @@ test("generate Image component instead of img element", () => {).toEqual(renderTemplate(<ws.element ws:tag="div">- <$.Image src="./my-url" />+ <Image src="./my-url" /></ws.element>));@@ -583,7 +592,7 @@ describe("style tag to tokens", () => {).toEqual(renderTemplate(<>- <$.HtmlEmbed+ <HtmlEmbedws:label="Style"code={`<style>#hero { color: red; }</style>`}/>@@ -710,7 +719,7 @@ describe("style tag to tokens", () => {).toEqual(renderTemplate(<>- <$.HtmlEmbed+ <HtmlEmbedws:label="Style"code={`<style>div { color: red; }</style>`}/>@@ -1005,7 +1014,7 @@ describe("style tag to tokens", () => {).toEqual(renderTemplate(<>- <$.HtmlEmbed+ <HtmlEmbedws:label="Script"clientOnly={true}code={`<script>console.log("hi");</script>`}diff --git a/packages/project-build/src/runtime/insert-target.test.tsx b/packages/project-build/src/runtime/insert-target.test.tsxindex 773cd9f27f..29b27373f9 100644--- a/packages/project-build/src/runtime/insert-target.test.tsx+++ b/packages/project-build/src/runtime/insert-target.test.tsx@@ -1,5 +1,10 @@import { describe, expect, test } from "vitest";-import { $, ws, renderData, renderTemplate } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ ws,+ renderData,+ renderTemplate,+} from "@webstudio-is/template";import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import {@@ -13,17 +18,23 @@ import {import { getComponentTemplates } from "./component-templates";import { builderRuntimeContext } from "./context";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const List = createTemplateComponentFixture("List");+const ListItem = createTemplateComponentFixture("ListItem");+const Paragraph = createTemplateComponentFixture("Paragraph");+const emptyProps = new Map();describe("insert target", () => {test("resolves default target after a selected textual container", () => {const data = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.element ws:id="div" ws:tag="div">text</ws.element><ws.element ws:id="span" ws:tag="span"></ws.element>- </$.Body>+ </Body>);expect(@@ -38,9 +49,9 @@ describe("insert target", () => {test("finds the first valid html tag for an element target", () => {const data = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.element ws:id="list" ws:tag="ul"></ws.element>- </$.Body>+ </Body>);expect(@@ -55,13 +66,13 @@ describe("insert target", () => {test("finds closest content-model-compatible insertion target", () => {const data = renderData(- <$.Body ws:id="body">- <$.List ws:id="list">- <$.ListItem ws:id="item"></$.ListItem>- </$.List>- </$.Body>+ <Body ws:id="body">+ <List ws:id="list">+ <ListItem ws:id="item"></ListItem>+ </List>+ </Body>);- const fragment = renderTemplate(<$.Paragraph ws:id="paragraph" />);+ const fragment = renderTemplate(<Paragraph ws:id="paragraph" />);expect(findClosestInsertTarget({@@ -76,7 +87,7 @@ describe("insert target", () => {});test("keeps explicit matching target", () => {- const data = renderData(<$.Body ws:id="body"></$.Body>);+ const data = renderData(<Body ws:id="body"></Body>);const fragment = renderTemplate(<ws.element ws:id="element" ws:tag="section" />);@@ -95,11 +106,11 @@ describe("insert target", () => {test("does not restore an incompatible explicit paste target", () => {const data = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.element ws:id="button" ws:tag="button" />- </$.Body>+ </Body>);- const fragment = renderTemplate(<$.ListItem ws:id="item" />);+ const fragment = renderTemplate(<ListItem ws:id="item" />);expect(resolveFragmentInsertTarget({@@ -115,7 +126,7 @@ describe("insert target", () => {});test("reports global root target", () => {- const data = renderData(<$.Body ws:id="body"></$.Body>);+ const data = renderData(<Body ws:id="body"></Body>);const fragment = renderTemplate(<ws.element ws:id="element" ws:tag="section" />);@@ -138,7 +149,7 @@ describe("insert target", () => {});test("finds default div tag for body insertion", () => {- const data = renderData(<$.Body ws:id="body"></$.Body>);+ const data = renderData(<Body ws:id="body"></Body>);expect(findElementTagForInsertTarget({@@ -152,10 +163,10 @@ describe("insert target", () => {test("normalizes after position to the next sibling index", () => {const data = renderData(- <$.Body ws:id="body">- <$.Box ws:id="first"></$.Box>- <$.Box ws:id="second"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="first"></Box>+ <Box ws:id="second"></Box>+ </Body>);expect(@@ -176,7 +187,7 @@ describe("insert target", () => {});test("normalizes after position on root selection to end", () => {- const data = renderData(<$.Body ws:id="body"></$.Body>);+ const data = renderData(<Body ws:id="body"></Body>);expect(resolveInsertTargetPosition({@@ -193,11 +204,11 @@ describe("insert target", () => {test("resolves component target with template-aware matching", () => {const data = renderData(- <$.Body ws:id="body">- <$.List ws:id="list">- <$.ListItem ws:id="item"></$.ListItem>- </$.List>- </$.Body>+ <Body ws:id="body">+ <List ws:id="list">+ <ListItem ws:id="item"></ListItem>+ </List>+ </Body>);expect(@@ -220,9 +231,9 @@ describe("insert target", () => {test("resolves element target with matching html tag", () => {const data = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.element ws:id="list" ws:tag="ul"></ws.element>- </$.Body>+ </Body>);expect(@@ -245,7 +256,7 @@ describe("insert target", () => {});test("reports missing resolved target", () => {- const fragment = renderTemplate(<$.Paragraph ws:id="paragraph" />);+ const fragment = renderTemplate(<Paragraph ws:id="paragraph" />);let didReportMissingTarget = false;expect(diff --git a/packages/project-build/src/runtime/instances.test.ts b/packages/project-build/src/runtime/instances.test.tsindex 59e251fcda..b18e193081 100644--- a/packages/project-build/src/runtime/instances.test.ts+++ b/packages/project-build/src/runtime/instances.test.ts@@ -53,6 +53,7 @@ import {moveInstances,replaceTextInput,serializeTextNodes,+ setInstanceName,setInstanceLabel,setInstanceTag,setTextContent,@@ -68,7 +69,7 @@ import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";const runtimeContext = { createId: () => "generated" };-test("rejects duplicate names and confirms source-backed template deletion", () => {+test("keeps template names separate from labels and confirms source-backed changes", () => {const block = createInstance("block", blockComponent, [{ type: "id", value: "templates" },]);@@ -76,8 +77,12 @@ test("rejects duplicate names and confirms source-backed template deletion", (){ type: "id", value: "hero" },{ type: "id", value: "card" },]);- const hero = { ...createInstance("hero", "Box"), label: "Hero" };- const card = createInstance("card", "Box");+ const hero = {+ ...createInstance("hero", "Box"),+ name: "Hero",+ label: "Featured hero",+ };+ const card = { ...createInstance("card", "Box"), name: "Card" };const source: Prop = {id: "src",instanceId: block.id,@@ -93,11 +98,17 @@ test("rejects duplicate names and confirms source-backed template deletion", ()]);expect(() =>- setInstanceLabel(+ setInstanceName({ instances, props: new Map([[source.id, source]]) },- { instanceId: card.id, label: "Hero" }+ { instanceId: card.id, name: "Hero" })).toThrow("Template name must be unique");+ expect(+ setInstanceLabel(+ { instances, props: new Map([[source.id, source]]) },+ { instanceId: card.id, label: "Hero" }+ ).result+ ).toMatchObject({ label: "Hero" });expect(() =>deleteInstances({diff --git a/packages/project-build/src/runtime/instances.ts b/packages/project-build/src/runtime/instances.tsindex ddafb685df..9084754bc5 100644--- a/packages/project-build/src/runtime/instances.ts+++ b/packages/project-build/src/runtime/instances.ts@@ -1,5 +1,6 @@import {blockTemplateComponent,+ assignUniqueBlockTemplateNamesMutable,elementComponent,findChildReferenceIndex,findParentInstanceReference,@@ -83,10 +84,10 @@ import {} from "./style-utils";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import { mapAttributeNames } from "@webstudio-is/content-engine/jsx-attributes";+import { isMdxTemplateComponentName } from "@webstudio-is/content-engine/mdx";import equal from "fast-deep-equal";import { z } from "zod";import {- assignUniqueBlockTemplateNamesMutable,type BlockTemplateNameConfirmation,findBlockTemplateNameCollision,getBlockTemplateNameConfirmation,@@ -97,7 +98,7 @@ const throwDuplicateBlockTemplateName = ({path,}: {name: string;- path: "component" | "label" | "tag";+ path: "component" | "label" | "name" | "tag";}): never =>throwBuilderValidationError("Template name must be unique", [{@@ -137,6 +138,7 @@ export const requireBlockTemplateNameConfirmation = ({| "instanceSelector"| "label"| "mode"+ | "name"| "tag";}) => {if (required === undefined || equal(required, confirm)) {@@ -270,6 +272,12 @@ export const setInstanceLabelInput = z.object({templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});+export const setInstanceNameInput = z.object({+ instanceId: z.string(),+ name: z.string(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),+});+export const updateTextInstanceInput = z.object({instanceId: z@@ -1190,17 +1198,18 @@ export const createInstanceMovePatches = ({continue;}if (parent.instance.id !== nextParent.id) {- const previousLabel = instance.label;+ const previousName = instance.name;assignUniqueBlockTemplateNamesMutable({instanceIds: [instance.id],parent: nextParent,instances: mutableInstances,+ components: componentMetas.keys(),});- if (instance.label !== previousLabel && instance.label !== undefined) {+ if (instance.name !== previousName && instance.name !== undefined) {patches.push({- op: previousLabel === undefined ? "add" : "replace",- path: [instance.id, "label"],- value: instance.label,+ op: previousName === undefined ? "add" : "replace",+ path: [instance.id, "name"],+ value: instance.name,});}}@@ -1605,6 +1614,7 @@ export const createInstanceClonePayload = ({instanceIds: [clonedRootId],parent: targetParent,instances: instancesWithClones,+ components: componentMetas.keys(),});const propPatches = createPropClonePatches({nextIdById,@@ -1925,6 +1935,7 @@ const moveInstanceToParentMutable = (instanceIds: [rootInstanceId],parent: newParent,instances: data.instances,+ components: componentMetas.keys(),});}if (dropTarget.position === "end") {@@ -2112,6 +2123,7 @@ export const wrapInstance = (instanceIds: [wrapperInstanceId],parent: parentInstance,instances: nextInstances,+ components: componentMetas.keys(),});const wrapperSelector = [wrapperInstanceId, ...parentItem.instanceSelector];const isSatisfying = isTreeSatisfyingContentModel({@@ -2191,6 +2203,7 @@ export const wrapInstance = (parent: nextParentInstance,replacedInstanceIds: [instanceId],instances: nextInstances,+ components: componentMetas.keys(),});const wrapperSelector = [wrapperInstanceId,@@ -2422,6 +2435,7 @@ const unwrapInstanceMutable = ({replacedInstanceIds:parentInstance.children.length === 0 ? [parentInstance.id] : [],instances,+ components: componentMetas.keys(),});if (parentInstance.children.length === 0) {instances.delete(parentItem.instance.id);@@ -2946,6 +2960,7 @@ export const unwrapInstance = (replacedInstanceIds:nextParentInstance.children.length === 0 ? [parentInstanceId] : [],instances: nextInstances,+ components: componentMetas.keys(),});}const nextInstanceSelector = [instanceId, ...input.instanceSelector.slice(2)];@@ -2960,11 +2975,11 @@ export const unwrapInstance = (}const patches: BuilderPatchChange["patches"] = [];- if (nextSelectedInstance.label !== selectedInstance.label) {+ if (nextSelectedInstance.name !== selectedInstance.name) {patches.push({- op: selectedInstance.label === undefined ? "add" : "replace",- path: [instanceId, "label"],- value: nextSelectedInstance.label,+ op: selectedInstance.name === undefined ? "add" : "replace",+ path: [instanceId, "name"],+ value: nextSelectedInstance.name,});}if (nextParentInstance.children.length === 0) {@@ -3203,7 +3218,9 @@ export const setInstanceLabel = (: [instance];const prospectiveInstances = new Map(instances);- for (const targetInstance of targetInstances) {+ for (const targetInstance of targetInstances.filter(+ ({ name }) => name === undefined+ )) {prospectiveInstances.set(targetInstance.id, { ...targetInstance, label });}for (const targetInstance of targetInstances) {@@ -3219,18 +3236,23 @@ export const setInstanceLabel = (});}}- requireBlockTemplateNameConfirmation({- required: getBlockTemplateNameConfirmation({- changes: targetInstances.map((targetInstance) => ({- instance: targetInstance,- nextInstance: prospectiveInstances.get(targetInstance.id),- })),- instances,- props: state.props?.values() ?? [],- }),- confirm: input.templateNameConfirmation,- path: "label",- });+ const legacyTemplates = targetInstances.filter(+ ({ name }) => name === undefined+ );+ if (legacyTemplates.length > 0) {+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: legacyTemplates.map((targetInstance) => ({+ instance: targetInstance,+ nextInstance: prospectiveInstances.get(targetInstance.id),+ })),+ instances,+ props: state.props?.values() ?? [],+ }),+ confirm: input.templateNameConfirmation,+ path: "label",+ });+ }const patches: BuilderPatchChange["patches"] = [];for (const targetInstance of targetInstances) {@@ -3254,6 +3276,77 @@ export const setInstanceLabel = (});};+export const setInstanceName = (+ state: Pick<BuilderState, "instances"> & Partial<Pick<BuilderState, "props">>,+ input: z.infer<typeof setInstanceNameInput>+) => {+ const instances = getRequiredInstances(state);+ const instance = instances.get(input.instanceId);+ if (instance === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ const parent = findParentInstanceReference(instances, instance.id)?.instance;+ if (parent?.component !== blockTemplateComponent) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Only direct Content Block templates have an MDX name"+ );+ }++ const name = input.name.trim();+ if (isMdxTemplateComponentName(name) === false) {+ return throwBuilderValidationError(+ "Template name must be a PascalCase JavaScript identifier",+ [+ {+ code: "invalid_template_name",+ path: ["name"],+ message:+ "Use a name such as PromotionCard. Spaces and punctuation are not allowed.",+ constraint: "javascript_component_identifier",+ example: "PromotionCard",+ },+ ]+ );+ }++ const nextInstance = { ...instance, name };+ const collision = findBlockTemplateNameCollision({+ instance,+ nextInstance,+ instances,+ });+ if (collision !== undefined) {+ return throwDuplicateBlockTemplateName({+ name: collision.name,+ path: "name",+ });+ }+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: [{ instance, nextInstance }],+ instances,+ props: state.props?.values() ?? [],+ }),+ confirm: input.templateNameConfirmation,+ path: "name",+ });++ const patches: BuilderPatchChange["patches"] = [];+ if (instance.name !== name) {+ patches.push({+ op: instance.name === undefined ? "add" : "replace",+ path: [instance.id, "name"],+ value: name,+ });+ }+ return createRuntimeMutation({+ payload: compactBuilderPatchPayload([{ namespace: "instances", patches }]),+ result: { instanceId: instance.id, name },+ invalidatesNamespaces: ["instances"],+ });+};+export const deleteInstances = (state: TreeMutationState,input: z.infer<typeof deleteInstancesInput>diff --git a/packages/project-build/src/runtime/jsx/bindings.ts b/packages/project-build/src/runtime/jsx/bindings.tsindex 1862896961..7ed37a9d85 100644--- a/packages/project-build/src/runtime/jsx/bindings.ts+++ b/packages/project-build/src/runtime/jsx/bindings.ts@@ -1,5 +1,4 @@import {- $,ActionValue,AssetValue,PageValue,@@ -7,13 +6,15 @@ import {PlaceholderValue,ResourceValue,Variable,- createProxy,expression,parseTemplateCss,token,ws,} from "@webstudio-is/template";import { hasUnsupportedCssTemplateRules } from "@webstudio-is/css-data";+import { getComponentByJsxName, getComponentJsxName } from "@webstudio-is/sdk";+import { componentsById } from "@webstudio-is/sdk-components-registry/components";+import { isMdxTemplateComponentName } from "@webstudio-is/content-engine/mdx";const css = (strings: TemplateStringsArray, ...values: string[]) => {const source = String.raw({ raw: strings }, ...values);@@ -25,11 +26,31 @@ const css = (strings: TemplateStringsArray, ...values: string[]) => {return parseTemplateCss(source);};+const directComponentBindings = Object.fromEntries(+ Array.from(componentsById.keys()).flatMap((candidate) => {+ const jsxName = getComponentJsxName({+ component: candidate,+ components: componentsById.keys(),+ });+ if (+ jsxName === "Fragment" ||+ isMdxTemplateComponentName(jsxName) === false+ ) {+ return [];+ }+ const component = getComponentByJsxName({+ name: jsxName,+ components: componentsById.keys(),+ });+ const componentObject =+ component === undefined ? undefined : componentsById.get(component);+ return componentObject === undefined ? [] : [[jsxName, componentObject]];+ })+);+const componentBindings = {- $,+ ...directComponentBindings,ws,- radix: createProxy("@webstudio-is/sdk-components-react-radix:"),- animation: createProxy("@webstudio-is/sdk-components-animation:"),};const helperBindings = {@@ -50,28 +71,21 @@ export const webstudioJsxRuntimeBindings = {...helperBindings,};-export const webstudioJsxComponentNamespaces = new Set(- Object.keys(componentBindings)-);+export const webstudioJsxRootNames = new Set(Object.keys(componentBindings));++export const webstudioJsxCompilerPrimitiveNames = new Set(Object.keys(ws));const listFormatter = new Intl.ListFormat("en", {style: "long",type: "conjunction",});-const webstudioJsxComponentNamespaceNames = listFormatter.format(- Object.keys(componentBindings)-);-const webstudioJsxHelperNames = listFormatter.format(Object.keys(helperBindings));-export const webstudioJsxBindingGuidance = `component namespaces ${webstudioJsxComponentNamespaceNames} and value helpers ${webstudioJsxHelperNames}`;--export const webstudioJsxAnimationGuidance =- "animation is a component namespace such as <animation.AnimateChildren>; it is not a callable CSS keyframes helper.";+export const webstudioJsxBindingGuidance = `lowercase HTML elements, unique direct component identifiers, compiler primitives from ws, and value helpers ${webstudioJsxHelperNames}`;export const webstudioJsxFragmentInputDescription =- `Webstudio JSX fragment. Use ${webstudioJsxBindingGuidance}. ${webstudioJsxAnimationGuidance} ` ++ `Webstudio JSX fragment. Use ${webstudioJsxBindingGuidance}. ` +'Do not access host globals or dynamic code APIs such as process, globalThis, eval, Function, or constructor. Use Webstudio prop names such as class and for, not React aliases className or htmlFor. Use ws:style={css`...`} for Webstudio-native styles, or style={{ padding: 24 }} for React-style object syntax that is converted into editable Webstudio styles. Use Webstudio actions such as onClick={new ActionValue(["event"], expression`console.log(event)`)}; do not pass JavaScript functions such as onClick={() => ...}. Plain prop values must be JSON-compatible: use 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. Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template; use insert-component when you want Webstudio to apply one registered component template automatically. Do not set ws:id; ids are generated by the runtime. The JSX is converted locally before the mutation request is sent.';diff --git a/packages/project-build/src/runtime/jsx/errors.ts b/packages/project-build/src/runtime/jsx/errors.tsindex ac2dc3d8db..7ba061877d 100644--- a/packages/project-build/src/runtime/jsx/errors.ts+++ b/packages/project-build/src/runtime/jsx/errors.ts@@ -26,8 +26,7 @@ export const throwWebstudioJsxValidationError = (path: ["fragment"],message: "Invalid Webstudio JSX fragment",constraint,- example:- '<ws.element ws:tag="section"><ws.element ws:tag="h2">Title</ws.element></ws.element>',+ example: "<section><h2>Title</h2></section>",...(detail === undefined? {}: { detail: sanitizeValidationDetail(detail) }),diff --git a/packages/project-build/src/runtime/jsx/fragment.server.test.ts b/packages/project-build/src/runtime/jsx/fragment.server.test.tsnew file mode 100644index 0000000000..2f56a2f476--- /dev/null+++ b/packages/project-build/src/runtime/jsx/fragment.server.test.ts@@ -0,0 +1,38 @@+// Locks the public JSX component and intrinsic-element spellings at the+// server evaluator boundary.+import { expect, test } from "vitest";+import { evaluateWebstudioJsxFragment } from "./fragment.server";++test("uses intrinsic tags and direct component identifiers", async () => {+ const fragment = await evaluateWebstudioJsxFragment(+ '<section><Heading tag="h2">Title</Heading></section>'+ );++ expect(fragment.instances).toMatchObject([+ { component: "ws:element", tag: "section" },+ { component: "Heading" },+ ]);+ expect(fragment.props).toContainEqual(+ expect.objectContaining({+ instanceId: fragment.instances[1]?.id,+ name: "tag",+ value: "h2",+ })+ );+});++test("uses a stable prefix for namespaced component-name collisions", async () => {+ const fragment = await evaluateWebstudioJsxFragment("<RadixCheckbox />");++ expect(fragment.instances).toMatchObject([+ {+ component: "@webstudio-is/sdk-components-react-radix:Checkbox",+ },+ ]);+});++test("rejects component member syntax", async () => {+ await expect(+ evaluateWebstudioJsxFragment("<Library.Card />")+ ).rejects.toThrow("JSX component namespaces are not supported");+});diff --git a/packages/project-build/src/runtime/jsx/fragment.server.ts b/packages/project-build/src/runtime/jsx/fragment.server.tsindex 5c7cb8ff32..ac28f32fb4 100644--- a/packages/project-build/src/runtime/jsx/fragment.server.ts+++ b/packages/project-build/src/runtime/jsx/fragment.server.ts@@ -1,16 +1,16 @@import { createId, type WebstudioFragment } from "@webstudio-is/sdk";import { renderTemplate } from "@webstudio-is/template";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { componentIds } from "@webstudio-is/sdk-components-registry/components";import {- webstudioJsxAnimationGuidance,webstudioJsxBindingGuidance,webstudioJsxRuntimeBindings,} from "./bindings";import { evaluateJsx } from "./evaluate.server";import { getErrorMessage } from "./errors";+import { inspectWebstudioJsxFragmentSyntax } from "./syntax";const templateValidationMessagePrefixes = [- "Do not use raw HTML tag","Do not use React fragment shorthand","Invalid JSX component","Invalid JSX prop",@@ -34,19 +34,21 @@ const createWebstudioJsxFragmentIdFactory = () => {export const evaluateWebstudioJsxFragment = async (source: string): Promise<WebstudioFragment> => {+ inspectWebstudioJsxFragmentSyntax(source);const createId = createWebstudioJsxFragmentIdFactory();return evaluateJsx<WebstudioFragment>({source,createModule: (jsx) =>- `exports.default = __renderTemplate(<>${jsx}</>, __createWebstudioJsxFragmentId, [], { allowManualIds: false, componentMetas: __componentMetas });`,+ `exports.default = __renderTemplate(<>${jsx}</>, __createWebstudioJsxFragmentId, [], { allowManualIds: false, componentIds: __componentIds, componentMetas: __componentMetas });`,globals: {__createWebstudioJsxFragmentId: createId,+ __componentIds: componentIds,__componentMetas: componentMetas,__renderTemplate: renderTemplate,...webstudioJsxRuntimeBindings,},parseErrorMessage: (error) =>- `Could not parse JSX fragment. Pass Webstudio JSX such as <$.Box><$.Heading>Title</$.Heading></$.Box>. ${getErrorMessage(+ `Could not parse JSX fragment. Pass Webstudio JSX such as <section><Heading tag="h2">Title</Heading></section>. ${getErrorMessage(error)}`,evaluationErrorMessage: (error) => {@@ -54,11 +56,7 @@ export const evaluateWebstudioJsxFragment = async (if (isTemplateValidationMessage(message)) {return message;}- const animationGuidance =- message === "animation is not a function"- ? ` ${webstudioJsxAnimationGuidance}`- : "";- return `Could not evaluate JSX fragment. Use ${webstudioJsxBindingGuidance}.${animationGuidance} ${message}`;+ return `Could not evaluate JSX fragment. Use ${webstudioJsxBindingGuidance}. ${message}`;},missingResultMessage: "JSX fragment did not produce Webstudio data.",});diff --git a/packages/project-build/src/runtime/jsx/index.ts b/packages/project-build/src/runtime/jsx/index.tsindex cf485d6b3c..ad32f068a6 100644--- a/packages/project-build/src/runtime/jsx/index.ts+++ b/packages/project-build/src/runtime/jsx/index.ts@@ -1,12 +1,10 @@import { webstudioFragment, type WebstudioFragment } from "@webstudio-is/sdk";import { evaluateWebstudioJsxFragment } from "./fragment.server";-import { inspectWebstudioJsxFragmentSyntax } from "./syntax";export { isLikelyWebstudioJsxFragment } from "./utils";export const parseWebstudioJsxFragment = async (source: string): Promise<WebstudioFragment> => {- inspectWebstudioJsxFragmentSyntax(source);const fragment = await evaluateWebstudioJsxFragment(source);return webstudioFragment.parse(fragment);};diff --git a/packages/project-build/src/runtime/jsx/syntax.ts b/packages/project-build/src/runtime/jsx/syntax.tsindex 3d6142233e..b8d8ef2518 100644--- a/packages/project-build/src/runtime/jsx/syntax.ts+++ b/packages/project-build/src/runtime/jsx/syntax.ts@@ -1,6 +1,9 @@import { Parser } from "acorn";import jsx from "acorn-jsx";-import { webstudioJsxBindingGuidance } from "./bindings";+import {+ webstudioJsxBindingGuidance,+ webstudioJsxCompilerPrimitiveNames,+} from "./bindings";import { getErrorMessage, throwWebstudioJsxValidationError } from "./errors";const JsxParser = Parser.extend(jsx());@@ -212,12 +215,26 @@ export const inspectWebstudioJsxFragmentSyntax = (source: string) => {? " Every opening element must use the same closing tag or end with />. Fragment parsing is stateless, so refresh cannot repair unmatched JSX.": "";return throwWebstudioJsxValidationError(- `Could not parse JSX fragment. Pass Webstudio JSX such as <$.Box><$.Heading>Title</$.Heading></$.Box>. ${message}${recovery}`,+ `Could not parse JSX fragment. Pass Webstudio JSX such as <section><Heading tag="h2">Title</Heading></section>. ${message}${recovery}`,"valid_webstudio_jsx_syntax",message);}const error = visitAst(ast, (node, context) => {+ if (node.type === "JSXMemberExpression") {+ const name = getJsxElementName(node);+ const [namespace, primitive, nested] = name?.split(".") ?? [];+ if (namespace !== "ws" || nested !== undefined) {+ return `JSX component namespaces are not supported. Use the direct component identifier for "${name}".`;+ }+ if (+ nested === undefined &&+ primitive !== undefined &&+ webstudioJsxCompilerPrimitiveNames.has(primitive) === false+ ) {+ return `Component "ws:${primitive}" does not exist. The "ws:" namespace contains Webstudio core components, not HTML tag shorthands. In JSX, use a lowercase HTML element such as <${primitive}>.`;+ }+ }if (node.type === "ImportExpression" || node.type === "Import") {return `Do not use dynamic import() in JSX fragments. JSX fragments are declarative Webstudio project data; use ${webstudioJsxBindingGuidance}.`;}diff --git a/packages/project-build/src/runtime/jsx/utils.ts b/packages/project-build/src/runtime/jsx/utils.tsindex b6e2706532..ea244c52d0 100644--- a/packages/project-build/src/runtime/jsx/utils.ts+++ b/packages/project-build/src/runtime/jsx/utils.ts@@ -1,13 +1,11 @@-import { webstudioJsxComponentNamespaces } from "./bindings";+import { webstudioJsxRootNames } from "./bindings";import { getWebstudioJsxFragmentFirstElementName } from "./syntax";export const isLikelyWebstudioJsxFragment = (source: string) => {try {const name = getWebstudioJsxFragmentFirstElementName(source);const namespace = name?.split(".").at(0);- return (- namespace !== undefined && webstudioJsxComponentNamespaces.has(namespace)- );+ return namespace !== undefined && webstudioJsxRootNames.has(namespace);} catch {return false;}diff --git a/packages/project-build/src/runtime/matcher.test.tsx b/packages/project-build/src/runtime/matcher.test.tsxindex 5c7eb70f28..b503a1c08e 100644--- a/packages/project-build/src/runtime/matcher.test.tsx+++ b/packages/project-build/src/runtime/matcher.test.tsx@@ -1,21 +1,32 @@import { describe, expect, test, vi } from "vitest";-import { $, renderData, renderTemplate, ws } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+ renderTemplate,+ ws,+} from "@webstudio-is/template";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import {findClosestInstanceMatchingFragment,getFragmentContentModelWarnings,} from "./matcher";+const Body = createTemplateComponentFixture("Body");+const Button = createTemplateComponentFixture("Button");+const List = createTemplateComponentFixture("List");+const ListItem = createTemplateComponentFixture("ListItem");+const Text = createTemplateComponentFixture("Text");+describe("findClosestInstanceMatchingFragment", () => {test("finds closest list with list item fragment", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.List ws:id="list">- <$.ListItem ws:id="listitem"></$.ListItem>- </$.List>- </$.Body>+ <Body ws:id="body">+ <List ws:id="list">+ <ListItem ws:id="listitem"></ListItem>+ </List>+ </Body>);- const fragment = renderTemplate(<$.ListItem ws:id="new"></$.ListItem>);+ const fragment = renderTemplate(<ListItem ws:id="new"></ListItem>);expect(findClosestInstanceMatchingFragment({metas: componentMetas,@@ -47,11 +58,11 @@ describe("findClosestInstanceMatchingFragment", () => {test("finds button parent with button fragment", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Button ws:id="button"></$.Button>- </$.Body>+ <Body ws:id="body">+ <Button ws:id="button"></Button>+ </Body>);- const fragment = renderTemplate(<$.Button ws:id="new"></$.Button>);+ const fragment = renderTemplate(<Button ws:id="new"></Button>);expect(findClosestInstanceMatchingFragment({metas: componentMetas,@@ -65,14 +76,14 @@ describe("findClosestInstanceMatchingFragment", () => {test("finds button parent with button and text fragment", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Button ws:id="button"></$.Button>- </$.Body>+ <Body ws:id="body">+ <Button ws:id="button"></Button>+ </Body>);const fragment = renderTemplate(<>- <$.Button ws:id="new-button"></$.Button>- <$.Text ws:id="new-text"></$.Text>+ <Button ws:id="new-button"></Button>+ <Text ws:id="new-text"></Text></>);expect(@@ -88,8 +99,8 @@ describe("findClosestInstanceMatchingFragment", () => {test("reports first placement error", () => {const onError = vi.fn();- const { instances, props } = renderData(<$.Body ws:id="body"></$.Body>);- const fragment = renderTemplate(<$.ListItem ws:id="listitem"></$.ListItem>);+ const { instances, props } = renderData(<Body ws:id="body"></Body>);+ const fragment = renderTemplate(<ListItem ws:id="listitem"></ListItem>);findClosestInstanceMatchingFragment({metas: componentMetas,instances,@@ -105,9 +116,9 @@ describe("findClosestInstanceMatchingFragment", () => {test("allows fragment-internal warnings without allowing new placement violations", () => {const { instances, props } = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.element ws:id="button" ws:tag="button" />- </$.Body>+ </Body>);const legacyFragment = renderTemplate(<ws.element ws:id="legacy-button" ws:tag="button">diff --git a/packages/project-build/src/runtime/mdx-asset-references.ts b/packages/project-build/src/runtime/mdx-asset-references.tsindex f37980cd82..b85141d56d 100644--- a/packages/project-build/src/runtime/mdx-asset-references.ts+++ b/packages/project-build/src/runtime/mdx-asset-references.ts@@ -1,3 +1,7 @@+/**+ * Maps MDX asset references between persisted asset ids and stable authored+ * paths so materialization and later source edits agree on the same asset.+ */import { createCanonicalAssetPath } from "@webstudio-is/content-engine/mdx";import {createAssetFolderHierarchy,diff --git a/packages/project-build/src/runtime/mdx-authored-content.test.ts b/packages/project-build/src/runtime/mdx-authored-content.test.tsindex 052660b316..c3ee894b40 100644--- a/packages/project-build/src/runtime/mdx-authored-content.test.ts+++ b/packages/project-build/src/runtime/mdx-authored-content.test.ts@@ -3,6 +3,7 @@ import {discoverMdxBodyAssetReferences,parseMdxDocument,serializeMdxDocument,+ type MdxDocument,} from "@webstudio-is/content-engine/mdx";import {elementComponent,@@ -17,6 +18,7 @@ import {serializeMdxAuthoredContent,serializeMdxTemplateInsertion,} from "./mdx-authored-content";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";const identity: ContentBlockExternalContentIdentity = {blockInstanceId: "block",@@ -76,6 +78,120 @@ const createCodeTextFragment = (theme = "github-light"): WebstudioFragment => ({});describe("MDX authored content", () => {+ test("materializes and round-trips exact registered component JSX", async () => {+ const source =+ "<PromotionCard><Heading>Launch offer</Heading></PromotionCard>\n";+ const document = await parseMdxDocument({ source });+ const metas = new Map([+ ["PromotionCard", { label: "Promotion card" }],+ ["Heading", { label: "Heading" }],+ ]);+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ metas,+ });++ expect(root.fragment.instances).toEqual([+ expect.objectContaining({ component: "Heading" }),+ expect.objectContaining({+ component: "PromotionCard",+ children: [{ type: "id", value: expect.any(String) }],+ }),+ ]);+ await expect(+ serializeMdxAuthoredContent({ root, fragment: root.fragment })+ ).resolves.toBe(source);+ });++ test("materializes static props on an exact registered component", async () => {+ const source = '<Heading tag="h2">Test</Heading>\n';+ const document = await parseMdxDocument({ source });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ metas: componentMetas,+ });++ expect(root.fragment.instances).toEqual([+ expect.objectContaining({ component: "Heading" }),+ ]);+ expect(root.fragment.props).toEqual([+ expect.objectContaining({ name: "tag", type: "string", value: "h2" }),+ ]);+ await expect(+ serializeMdxAuthoredContent({ root, fragment: root.fragment })+ ).resolves.toBe(source);+ });++ test("treats a legacy template node without syntax metadata as self-closing", async () => {+ const document: MdxDocument = {+ frontmatter: { properties: {} },+ children: [+ {+ type: "template",+ name: "Card",+ props: [],+ children: [],+ mdxMode: "flow",+ },+ ],+ };+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ templates: [+ {+ type: "resolved-template",+ reference: {+ type: "resolved-template",+ path: [0],+ templateName: "Card",+ templateInstanceId: "card-template",+ props: [],+ },+ fragment: {+ children: [{ type: "id", value: "card" }],+ instances: [+ {+ type: "instance",+ id: "card",+ component: elementComponent,+ tag: "section",+ children: [{ type: "text", value: "Template default" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ },+ editablePropNames: [],+ jsxPropContext: htmlJsxPropContext,+ propNameMappings: [],+ ignoredJsxPropNames: [],+ },+ ],+ diagnostics: [],+ dependencies: { templateNames: ["Card"], templates: [] },+ },+ });++ expect(root.fragment.instances[0]?.children).toEqual([+ { type: "text", value: "Template default" },+ ]);+ await expect(+ serializeMdxAuthoredContent({ root, fragment: root.fragment })+ ).resolves.toBe("<Card />\n");+ });+test("rejects a canvas edit prepared from a stale Asset document", async () => {const document = await parseMdxDocument({ source: "Original\n" });const root = materializeMdxAuthoredContent({@@ -473,7 +589,7 @@ describe("MDX authored content", () => {).resolves.toBe("######\n\n-\n");});- test("serializes a lossless template insertion as Markdown", async () => {+ test("preserves the selected template identity for a lossless insertion", async () => {const fragment: WebstudioFragment = {children: [{ type: "id", value: "heading" }],instances: [@@ -482,6 +598,7 @@ describe("MDX authored content", () => {id: "heading",component: elementComponent,tag: "h1",+ name: "Heading1",label: "Heading 1",children: [{ type: "text", value: "Test" }],},@@ -501,10 +618,123 @@ describe("MDX authored content", () => {await serializeMdxTemplateInsertion({identity,fragment,- templateName: "Heading 1",+ templateName: "Heading1",}))- ).toBe("# Test\n");+ ).toBe("<Heading1>Test</Heading1>\n");+ });++ test("keeps a default generic element template insertion as Markdown", async () => {+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "paragraph" }],+ instances: [+ {+ type: "instance",+ id: "paragraph",+ component: elementComponent,+ tag: "p",+ label: "Editable text template",+ children: [{ type: "text", value: "Editable template content" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };++ expect(+ serializeMdxDocument(+ await serializeMdxTemplateInsertion({+ identity,+ fragment,+ pristineFragment: structuredClone(fragment),+ templateName: "Editable text template",+ htmlTags: [{ instanceId: "paragraph", tag: "p" }],+ })+ )+ ).toBe("Editable template content\n");+ });++ test.each(["Image", "CodeText"])(+ "keeps a matching custom template named %s ahead of component fallback",+ async (templateName) => {+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "custom" }],+ instances: [+ {+ type: "instance",+ id: "custom",+ component: elementComponent,+ tag: "section",+ children: [{ type: "text", value: "Custom content" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };++ expect(+ serializeMdxDocument(+ await serializeMdxTemplateInsertion({+ identity,+ fragment,+ templateName,+ })+ )+ ).toBe(`<${templateName}>Custom content</${templateName}>\n`);+ }+ );++ test("rejects an immediate descendant edit that cannot be serialized", async () => {+ const pristineFragment: WebstudioFragment = {+ children: [{ type: "id", value: "card" }],+ instances: [+ {+ type: "instance",+ id: "card",+ component: elementComponent,+ tag: "section",+ children: [{ type: "id", value: "unknown" }],+ },+ {+ type: "instance",+ id: "unknown",+ component: "Unknown",+ children: [{ type: "text", value: "Template default" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };+ const edited = structuredClone(pristineFragment);+ edited.instances[1]!.children = [{ type: "text", value: "Immediate edit" }];++ await expect(+ serializeMdxTemplateInsertion({+ identity,+ fragment: edited,+ pristineFragment,+ templateName: "Card",+ htmlTags: [{ instanceId: "card", tag: "section" }],+ })+ ).rejects.toThrow("cannot be represented losslessly in MDX");});test("serializes Markdown-compatible Image props as an image", async () => {@@ -558,7 +788,7 @@ describe("MDX authored content", () => {templateName: "Image",}))- ).toBe('\n');+ ).toBe('<Image src="/hero.png" alt="Hero" title="Cover" />\n');});test("uses JSX when an Image has props Markdown cannot express", async () => {@@ -605,7 +835,7 @@ describe("MDX authored content", () => {templateName: "Image",}))- ).toBe('<ws.element ws:name="Image" src="/hero.png" width="640" />\n');+ ).toBe('<Image src="/hero.png" width="640" />\n');});test("uses canonical JSX names in a generic template insertion", async () => {@@ -645,7 +875,7 @@ describe("MDX authored content", () => {templateName: "Widget",}))- ).toBe('<ws.element ws:name="Widget" className="featured" />\n');+ ).toBe('<Widget className="featured" />\n');});test("preserves unknown component props in a generic template insertion", async () => {@@ -685,10 +915,10 @@ describe("MDX authored content", () => {templateName: "Widget",}))- ).toBe('<ws.element ws:name="Widget" for="custom-target" />\n');+ ).toBe('<Widget for="custom-target" />\n');});- test("rebases a styled template insertion as a template reference", async () => {+ test("preserves edits made before a template insertion is materialized", async () => {const document = await parseMdxDocument({ source: "" });const root = materializeMdxAuthoredContent({identity,@@ -704,7 +934,7 @@ describe("MDX authored content", () => {component: elementComponent,tag: "h1",label: "Styled Heading",- children: [{ type: "text", value: "Test" }],+ children: [{ type: "text", value: "Default" }],},],props: [@@ -713,7 +943,7 @@ describe("MDX authored content", () => {instanceId: "heading",name: "title",type: "string",- value: "Updated",+ value: "Original",},],assets: [],@@ -733,7 +963,29 @@ describe("MDX authored content", () => {},],};+ const pristineFragment = structuredClone(fragment);+ const heading = fragment.instances[0];+ const title = fragment.props[0];+ if (heading === undefined || title?.type !== "string") {+ throw new Error("Expected the inserted heading defaults");+ }+ heading.children = [{ type: "text", value: "Test" }];+ title.value = "Updated";+ expect(+ serializeMdxDocument(+ await rebaseMdxAuthoredContent({+ root,+ fragment,+ latest: document,+ insertedTemplates: new Map([+ ["heading", { templateName: "Styled Heading", pristineFragment }],+ ]),+ })+ )+ ).toBe(+ '<ws.element ws:name="Styled Heading" title="Updated">Test</ws.element>\n'+ );expect(serializeMdxDocument(await rebaseMdxAuthoredContent({@@ -748,6 +1000,54 @@ describe("MDX authored content", () => {);});+ test("rebases a fresh empty template insertion as self-closing", async () => {+ const document = await parseMdxDocument({ source: "" });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "heading" }],+ instances: [+ {+ type: "instance",+ id: "heading",+ component: elementComponent,+ tag: "h1",+ children: [],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };++ expect(+ serializeMdxDocument(+ await rebaseMdxAuthoredContent({+ root,+ fragment,+ latest: document,+ insertedTemplates: new Map([+ [+ "heading",+ {+ templateName: "Heading1",+ pristineFragment: structuredClone(fragment),+ },+ ],+ ]),+ })+ )+ ).toBe("<Heading1 />\n");+ });+test("serializes explicitly configured Code Text presentation as JSX", async () => {const document = await serializeMdxTemplateInsertion({identity,@@ -756,11 +1056,11 @@ describe("MDX authored content", () => {});expect(serializeMdxDocument(document)).toBe(- '<ws.element ws:name="CodeText" language="javascript" theme="github-light">const ready = true;</ws.element>\n'+ '<CodeText language="javascript" theme="github-light">const ready = true;</CodeText>\n');});- test("serializes Code Text without presentation props as fenced Markdown", async () => {+ test("preserves Code Text template identity without presentation props", async () => {const fragment = createCodeTextFragment();fragment.props = [];const code = fragment.instances[0]?.children[0];@@ -775,7 +1075,9 @@ describe("MDX authored content", () => {templateName: "CodeText",});- expect(serializeMdxDocument(document)).toBe("```\na = 1\nb=2\nc=5\n```\n");+ expect(serializeMdxDocument(document)).toBe(+ "<CodeText>a = 1\nb=2\nc=5</CodeText>\n"+ );});test("serializes the legacy Code Text code property as text content", async () => {@@ -925,7 +1227,7 @@ describe("MDX authored content", () => {});expect(serializeMdxDocument(document)).toBe(- '<ws.element ws:name="CodeText" tabIndex="2" hidden="false">const ready = true;</ws.element>\n'+ '<CodeText tabIndex="2" hidden="false">const ready = true;</CodeText>\n');});@@ -965,7 +1267,7 @@ describe("MDX authored content", () => {});expect(await serializeMdxAuthoredContent({ root, fragment })).toContain(- '<ws.element ws:name="CodeText" language="javascript" theme="nord">const ready = true;</ws.element>'+ '<CodeText language="javascript" theme="nord">const ready = true;</CodeText>');});@@ -991,7 +1293,7 @@ describe("MDX authored content", () => {fragment: withClass,});expect(jsxSource).toBe(- '<ws.element ws:name="CodeText" className="example">const ready = true;</ws.element>\n'+ '<CodeText className="example">const ready = true;</CodeText>\n');const jsx = await parseMdxDocument({ source: jsxSource });@@ -1041,10 +1343,10 @@ describe("MDX authored content", () => {expect(await serializeMdxAuthoredContent({ root: jsxRoot, fragment: reset })- ).toBe("```\nconst ready = true;\n```\n");+ ).toBe("<CodeText>const ready = true;</CodeText>\n");});- test("persists a newly authored prop on an existing template reference", async () => {+ test("persists a newly authored prop without copying inherited defaults", async () => {const document = await parseMdxDocument({source: '<ws.element ws:name="CodeText">const ready = true;</ws.element>',});@@ -1088,12 +1390,10 @@ describe("MDX authored content", () => {serializeMdxDocument(reconcileMdxAuthoredContent({ root, fragment: next }))- ).toBe(- '<ws.element ws:name="CodeText" language="javascript" theme="nord">const ready = true;</ws.element>\n'- );+ ).toBe('<CodeText theme="nord">const ready = true;</CodeText>\n');});- test("switches a Code Text template reference to a fence after resetting presentation props", async () => {+ test("keeps a named Code Text reference after resetting presentation props", async () => {const document = await parseMdxDocument({source:'<ws.element ws:name="CodeText" language="javascript" theme="github-light">const ready = true;</ws.element>',@@ -1139,7 +1439,7 @@ describe("MDX authored content", () => {serializeMdxDocument(reconcileMdxAuthoredContent({ root, fragment: next }))- ).toBe("```\nconst ready = true;\n```\n");+ ).toBe("<CodeText>const ready = true;</CodeText>\n");});test("materializes deterministic nested Markdown and MDX elements", async () => {@@ -1184,8 +1484,7 @@ describe("MDX authored content", () => {});test("round-trips typed static props on generic MDX elements", async () => {- const source =- '<ws.element ws:tag="input" tabIndex="2" hidden="false" />\n';+ const source = '<input tabIndex="2" hidden="false" />\n';const document = await parseMdxDocument({ source });const root = materializeMdxAuthoredContent({identity,@@ -1719,9 +2018,20 @@ describe("MDX authored content", () => {next.instances.find(({ id }) => id === "template-heading")!.children = [{ type: "text", value: "Changed internal" },];- expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow(- "Expanded template internals"- );+ expect(+ reconcileMdxAuthoredContent({ root, fragment: next }).children[0]+ ).toMatchObject({+ type: "template",+ name: "Card",+ selfClosing: false,+ children: [+ {+ type: "element",+ tag: "h2",+ children: [{ type: "text", value: "Changed internal" }],+ },+ ],+ });expect(reconcileMdxAuthoredContent({@@ -1809,7 +2119,7 @@ describe("MDX authored content", () => {classProp.value = "new";expect(await serializeMdxAuthoredContent({ root, fragment: next })).toBe(- '<ws.element ws:name="Card" className="new" />\n'+ '<Card className="new" />\n');});@@ -1875,7 +2185,7 @@ describe("MDX authored content", () => {});expect(await serializeMdxAuthoredContent({ root, fragment: next })).toBe(- '<ws.element ws:name="Card" className="new" />\n'+ '<Card className="new" />\n');const invalid = structuredClone(root.fragment);diff --git a/packages/project-build/src/runtime/mdx-authored-content.ts b/packages/project-build/src/runtime/mdx-authored-content.tsindex ba77c0efd0..7bb701a91a 100644--- a/packages/project-build/src/runtime/mdx-authored-content.ts+++ b/packages/project-build/src/runtime/mdx-authored-content.ts@@ -1,3 +1,7 @@+/**+ * Converts authored MDX nodes to editable Webstudio instances and reconciles+ * instance edits back into MDX without treating generated instance ids as source.+ */import equal from "fast-deep-equal";import { elementsByTag } from "@webstudio-is/html-data";import type { AssetValueReference } from "@webstudio-is/content-engine";@@ -13,22 +17,32 @@ import {} from "@webstudio-is/content-engine/mdx";import {assertUniqueAttributeNames,+ getInstancePropName,mapAttributeNames,} from "@webstudio-is/content-engine/jsx-attributes";import {elementComponent,+ getComponentByJsxName,+ getContentBlockMdxTemplateDescriptor,+ getDefaultContentBlockTemplateName,getStyleDeclKey,+ type ContentBlockDiagnostic,type ContentBlockExternalContentIdentity,type Instance,type Prop,type WebstudioFragment,+ type WsComponentMeta,} from "@webstudio-is/sdk";import {createMdxScopeIdGenerator,+ getMdxPropBinding,+ getMdxPropEligibility,+ resolveMdxPropCollisions,type MaterializedMdxTemplate,type MdxJsxPropContext,type MdxTemplateMaterialization,} from "./mdx-materialization";+import { getContentModeCapabilities } from "./content-mode-permissions";import { createEmptyWebstudioFragment } from "./component-template";import {createWebstudioDataFromFragment,@@ -36,6 +50,8 @@ import {} from "./fragment";import {getDerivedMdxComponentPropIds,+ getMdxNamedTemplateSyntax,+ hasMdxComponentAdapter,materializeMdxComponent,normalizeMdxComponentProps,serializeMdxComponent,@@ -64,15 +80,25 @@ type AuthoredComponentProvenance = Readonly<{type: "component";path: readonly number[];instanceId: Instance["id"];+ ignoredInstancePropNames: readonly string[];+ namedJsx?: Readonly<{+ jsxPropContext: MdxJsxPropContext;+ ignoredJsxPropNames: readonly string[];+ }>;assetProps: AuthoredElementProvenance["assetProps"];}>;type TemplateProvenance = Readonly<{type: "template";+ binding: "semantic" | "named";+ templateName: string;+ overridesTemplateChildren: boolean;+ overlaysTemplateChildren: boolean;path: readonly number[];instanceId: Instance["id"];editableTextChildren: boolean;editablePropNames: readonly string[];+ authoredPropNames: readonly string[];jsxPropContext: MdxJsxPropContext;propNameMappings: readonly Readonly<{jsxPropName: string;@@ -81,6 +107,18 @@ type TemplateProvenance = Readonly<{preservedJsxPropNames?: readonly string[];ignoredJsxPropNames: readonly string[];expandedInstanceIds: readonly Instance["id"][];+ htmlTags: readonly Readonly<{+ instanceId: Instance["id"];+ tag: string;+ }>[];+ overlaidDescendants: readonly Readonly<{+ instanceId: Instance["id"];+ path: readonly number[];+ kind: "element" | "component";+ componentPropNames: readonly string[];+ ignoredInstancePropNames: readonly string[];+ assetProps: AuthoredElementProvenance["assetProps"];+ }>[];assetProps: AuthoredElementProvenance["assetProps"];namespaceKeys: readonly Readonly<{namespace: UnsupportedNamespace;@@ -185,6 +223,8 @@ export type MaterializedMdxAuthoredContentRoot = Readonly<{document: MdxDocument;resolvedFrontmatter?: Readonly<Record<string, unknown>>;provenance: MdxAuthoredContentProvenance;+ /** Optional so roots created by older API consumers remain serializable. */+ diagnostics?: readonly ContentBlockDiagnostic[];assetReferenceValues?: ReadonlyMap<string, string>;}>;@@ -208,17 +248,34 @@ const isMdxValueEqual = (left: unknown, right: unknown): boolean => {) {const leftRecord = left as Record<string, unknown>;const rightRecord = right as Record<string, unknown>;+ const bothTemplates =+ leftRecord.type === "template" && rightRecord.type === "template";const keys = new Set([...Object.keys(leftRecord),...Object.keys(rightRecord),]);keys.delete("sourceRange");- return Array.from(keys).every(- (key) =>+ return Array.from(keys).every((key) => {+ if (bothTemplates && key === "syntax") {+ return (+ (leftRecord.syntax ?? "ws-element") ===+ (rightRecord.syntax ?? "ws-element")+ );+ }+ if (bothTemplates && key === "selfClosing") {+ const leftChildren = leftRecord.children as readonly unknown[];+ const rightChildren = rightRecord.children as readonly unknown[];+ return (+ (leftRecord.selfClosing ?? leftChildren.length === 0) ===+ (rightRecord.selfClosing ?? rightChildren.length === 0)+ );+ }+ return (key in leftRecord &&key in rightRecord &&isMdxValueEqual(leftRecord[key], rightRecord[key])- );+ );+ });}return false;};@@ -321,7 +378,9 @@ const mergeLocalNode = ({const mutableFields = ["tag","name",+ "syntax","mdxMode",+ "selfClosing","markdownListItem","preserveTextWhitespace",] as const;@@ -341,7 +400,7 @@ const getNodeShape = (node: MdxAuthoredNode) => {return `${node.type}:${node.syntax}:${node.tag}`;}if (node.type === "template") {- return `${node.type}:${node.name}`;+ return `${node.type}:${node.syntax ?? "ws-element"}:${node.name}`;}return node.type;};@@ -642,12 +701,54 @@ const getSingleTemplateRootId = (template: MaterializedMdxTemplate) => {return template.fragment.children[0].value;};+const isSelfClosingTemplateNode = (+ node: Extract<MdxAuthoredNode, { type: "template" }>+) => node.selfClosing ?? node.children.length === 0;++const getSourcePropName = ({+ node,+ source,+ fallback,+}: {+ node: MdxAuthoredNode;+ source:+ | Readonly<{ nodePath: readonly number[]; propIndex: number }>+ | undefined;+ fallback: string;+}) => {+ let sourceNode = node;+ for (const childIndex of source?.nodePath ?? []) {+ if (+ sourceNode.type === "text" ||+ sourceNode.type === "comment" ||+ sourceNode.type === "opaque"+ ) {+ return fallback;+ }+ const child = sourceNode.children[childIndex];+ if (child === undefined) {+ return fallback;+ }+ sourceNode = child;+ }+ if (+ source === undefined ||+ sourceNode.type === "text" ||+ sourceNode.type === "comment" ||+ sourceNode.type === "opaque"+ ) {+ return fallback;+ }+ return sourceNode.props[source.propIndex]?.name ?? fallback;+};+export const materializeMdxAuthoredContent = ({identity,document,templateMaterialization,assetReferences = [],assetReferenceValues,+ metas,createUnresolvedTemplateInstance,}: {identity: ContentBlockExternalContentIdentity;@@ -655,12 +756,14 @@ export const materializeMdxAuthoredContent = ({templateMaterialization: MdxTemplateMaterialization;assetReferences?: readonly AssetValueReference[];assetReferenceValues?: ReadonlyMap<string, string>;+ metas?: Map<Instance["component"], WsComponentMeta>;createUnresolvedTemplateInstance?: (input: {markerId: string;templateName: string;}) => Instance;}): MaterializedMdxAuthoredContentRoot => {const fragment = createEmptyWebstudioFragment();+ const diagnostics: ContentBlockDiagnostic[] = [];const nodes: MdxAuthoredContentProvenance["nodes"][number][] = [];const templatesByPath = new Map(templateMaterialization.templates.map((template) => [@@ -691,11 +794,8 @@ export const materializeMdxAuthoredContent = ({if (node.type === "opaque") {continue;}- if (node.type === "template") {- const template = templatesByPath.get(pathKey(path));- if (template === undefined) {- continue;- }+ const template = templatesByPath.get(pathKey(path));+ if (template !== undefined) {if (template.type === "unresolved-template") {const placeholder = createUnresolvedTemplateInstance?.({markerId: template.markerId,@@ -708,22 +808,367 @@ export const materializeMdxAuthoredContent = ({continue;}const rootId = getSingleTemplateRootId(template);- mergeTemplateFragment(fragment, template.fragment);- const rootInstance = fragment.instances.find(({ id }) => id === rootId);- if (rootInstance === undefined) {+ const sourceRootInstance = template.fragment.instances.find(+ ({ id }) => id === rootId+ );+ if (sourceRootInstance === undefined) {throw new Error("Resolved MDX template root is missing");}- const editableTextChildren = rootInstance.children.every(+ const editableTextChildren = sourceRootInstance.children.every((child) => child.type === "text");- if (- editableTextChildren &&- node.children.length > 0 &&- node.children.every(- (child) => child.type === "text" || child.type === "comment"- )- ) {- rootInstance.children = visit(node.children, path);+ const overridesTemplateChildren =+ node.type === "element" ||+ (node.type === "template" &&+ isSelfClosingTemplateNode(node) === false);+ let overlaysTemplateChildren = false;+ let overlaidDescendants: TemplateProvenance["overlaidDescendants"] = [];+ let resolvedFragment = template.fragment;+ if (overridesTemplateChildren) {+ resolvedFragment = structuredClone(template.fragment);+ const rootInstance = resolvedFragment.instances.find(+ ({ id }) => id === rootId+ );+ if (rootInstance === undefined) {+ throw new Error("Resolved MDX template root is missing");+ }+ const templateData =+ createWebstudioDataFromFragment(resolvedFragment);+ const reservedIds = new Set([+ ...resolvedFragment.instances.map(({ id }) => id),+ ...resolvedFragment.props.map(({ id }) => id),+ ...resolvedFragment.assets.map(({ id }) => id),+ ...resolvedFragment.dataSources.map(({ id }) => id),+ ...resolvedFragment.resources.map(({ id }) => id),+ ...resolvedFragment.breakpoints.map(({ id }) => id),+ ...resolvedFragment.styleSources.map(({ id }) => id),+ ]);+ const nextScopedId = createMdxScopeIdGenerator({ identity, path });+ const createOverlayId = () => {+ let id = nextScopedId();+ while (reservedIds.has(id)) {+ id = nextScopedId();+ }+ reservedIds.add(id);+ return id;+ };+ const overlayCapabilities =+ metas === undefined+ ? undefined+ : getContentModeCapabilities({+ instances: templateData.instances,+ metas,+ props: templateData.props,+ styleSources: templateData.styleSources,+ styleSourceSelections: templateData.styleSourceSelections,+ styles: templateData.styles,+ breakpoints: templateData.breakpoints,+ contentRootIds: new Set([rootId]),+ });+ const htmlTags = new Map(+ (+ template.htmlTags ??+ resolvedFragment.instances.flatMap((instance) =>+ instance.tag === undefined+ ? []+ : [{ instanceId: instance.id, tag: instance.tag }]+ )+ ).map(({ instanceId, tag }) => [instanceId, tag])+ );+ const matchedDescendants: Array<+ TemplateProvenance["overlaidDescendants"][number]+ > = [];+ const overlayDiagnostics: ContentBlockDiagnostic[] = [];+ const overlayChildren = (+ authoredNodes: readonly MdxAuthoredNode[],+ instanceChildren: Instance["children"],+ parentNodePath: readonly number[]+ ): boolean => {+ const authoredChildren: Array<{+ child: MdxAuthoredNode;+ path: number[];+ textNodes?: Array<Extract<MdxAuthoredNode, { type: "text" }>>;+ }> = [];+ authoredNodes.forEach((child, index) => {+ if (child.type === "comment") {+ return;+ }+ if (child.type === "text") {+ const previous = authoredChildren.at(-1);+ if (previous?.textNodes !== undefined) {+ previous.textNodes.push(child);+ return;+ }+ authoredChildren.push({+ child,+ path: [...parentNodePath, index],+ textNodes: [child],+ });+ return;+ }+ authoredChildren.push({+ child,+ path: [...parentNodePath, index],+ });+ });+ if (authoredChildren.length !== instanceChildren.length) {+ return false;+ }+ const nextInstanceChildren: Instance["children"] = [];+ for (const [index, authored] of authoredChildren.entries()) {+ const instanceChild = instanceChildren[index];+ if (authored.child.type === "text") {+ if (instanceChild?.type !== "text") {+ return false;+ }+ nextInstanceChildren.push(+ ...(authored.textNodes ?? [authored.child]).map(+ ({ value }) => ({ type: "text" as const, value })+ )+ );+ continue;+ }+ if (+ authored.child.type === "opaque" ||+ instanceChild?.type !== "id"+ ) {+ return false;+ }+ const instance = templateData.instances.get(instanceChild.value);+ if (instance === undefined) {+ return false;+ }+ const adapted = materializeMdxComponent(authored.child);+ let authoredProps: readonly MdxAuthoredProp[];+ let propBindings:+ | readonly Readonly<{+ prop: MdxAuthoredProp;+ source?: Readonly<{+ nodePath: readonly number[];+ propIndex: number;+ }>;+ requiresAssetReference?: boolean;+ }>[]+ | undefined;+ let authoredGrandchildren: readonly MdxAuthoredNode[] | undefined;+ let kind: "element" | "component";+ let authoredJsxPropNames: readonly string[];+ let componentPropNames: readonly string[];+ if (adapted?.component === instance.component) {+ kind = "component";+ authoredProps = adapted.props.map(({ prop }) => prop);+ authoredJsxPropNames = adapted.props.map(({ prop, source }) =>+ getSourcePropName({+ node: authored.child,+ source,+ fallback: prop.name,+ })+ );+ propBindings = adapted.props;+ componentPropNames = Object.keys(+ metas?.get(instance.component)?.props ?? {}+ );+ } else if (+ authored.child.type === "element" &&+ authored.child.tag ===+ (htmlTags.get(instance.id) ?? instance.tag)+ ) {+ kind = "element";+ componentPropNames = Object.keys(+ metas?.get(instance.component)?.props ?? {}+ );+ const declaredComponentPropNames = new Set(componentPropNames);+ authoredProps = mapAttributeNames({+ attributes: authored.child.props,+ direction: "jsx-to-instance",+ acceptsHtmlAttributes: true,+ componentPropNames: declaredComponentPropNames,+ });+ authoredJsxPropNames = authored.child.props.map(+ ({ name }) => name+ );+ authoredGrandchildren = authored.child.children;+ } else {+ return false;+ }+ const assetProps: AuthoredElementProvenance["assetProps"][number][] =+ [];+ const ignoredInstancePropNames: string[] = [];+ authoredProps.forEach((prop, propIndex) => {+ const existing = Array.from(templateData.props.values()).find(+ (candidate) =>+ candidate.instanceId === instance.id &&+ candidate.name === prop.name+ );+ const source = propBindings?.[propIndex]?.source;+ const assetReference = assetReferenceByPath.get(+ getMdxPropValuePathKey({+ nodePath:+ source === undefined+ ? authored.path+ : [...authored.path, ...source.nodePath],+ propIndex: source?.propIndex ?? propIndex,+ })+ );+ if (+ propBindings?.[propIndex]?.requiresAssetReference === true &&+ assetReference === undefined+ ) {+ if (existing !== undefined) {+ templateData.props.delete(existing.id);+ }+ return;+ }+ let nextProp: Prop;+ if (+ overlayCapabilities !== undefined &&+ instance.component !== elementComponent+ ) {+ const binding =+ assetReference === undefined+ ? getMdxPropBinding({+ capabilities: overlayCapabilities,+ instance,+ prop,+ existingType:+ existing?.type === "string" ||+ existing?.type === "number" ||+ existing?.type === "boolean"+ ? existing.type+ : undefined,+ jsxPropName: authoredJsxPropNames[propIndex],+ })+ : getMdxPropEligibility({+ capabilities: overlayCapabilities,+ instance,+ prop: { name: prop.name, type: "asset" },+ jsxPropName: authoredJsxPropNames[propIndex],+ }).editable+ ? {+ type: "asset" as const,+ value: assetReference.assetId,+ }+ : undefined;+ if (binding === undefined) {+ const propName =+ authoredJsxPropNames[propIndex] ?? prop.name;+ const eligibility = getMdxPropEligibility({+ capabilities: overlayCapabilities,+ instance,+ prop: {+ name: prop.name,+ type:+ existing?.type === "number" ||+ existing?.type === "boolean"+ ? existing.type+ : "string",+ },+ jsxPropName: propName,+ });+ ignoredInstancePropNames.push(prop.name);+ overlayDiagnostics.push({+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ templateName: template.reference.templateName,+ propName,+ reason:+ eligibility.editable === false+ ? eligibility.reason+ : "incompatible",+ sourceRange: authored.child.sourceRange,+ });+ return;+ }+ nextProp = {+ id: existing?.id ?? createOverlayId(),+ instanceId: instance.id,+ name: prop.name,+ ...binding,+ required: existing?.required,+ };+ } else {+ nextProp = createLiteralProp({+ id: existing?.id ?? createOverlayId(),+ instanceId: instance.id,+ prop,+ assetId: assetReference?.assetId,+ type:+ authored.child.type === "element"+ ? getHtmlAttributeType({+ tag: authored.child.tag,+ name: prop.name,+ })+ : undefined,+ });+ }+ templateData.props.set(nextProp.id, nextProp);+ if (+ assetReference !== undefined &&+ typeof prop.value === "string"+ ) {+ assetProps.push({+ propId: nextProp.id,+ assetId: assetReference.assetId,+ authoredValue: prop.value,+ });+ }+ });+ matchedDescendants.push({+ instanceId: instance.id,+ path: authored.path,+ kind,+ componentPropNames,+ ignoredInstancePropNames,+ assetProps,+ });+ if (authoredGrandchildren !== undefined) {+ if (+ overlayChildren(+ authoredGrandchildren,+ instance.children,+ authored.path+ ) === false+ ) {+ return false;+ }+ } else if (adapted !== undefined) {+ instance.children = adapted.children;+ }+ nextInstanceChildren.push(instanceChild);+ }+ instanceChildren.splice(+ 0,+ instanceChildren.length,+ ...nextInstanceChildren+ );+ return true;+ };+ overlaysTemplateChildren =+ node.type === "template" &&+ node.children.length > 0 &&+ template.reference.componentChildren === undefined &&+ overlayChildren(node.children, rootInstance.children, path);+ if (overlaysTemplateChildren === false) {+ matchedDescendants.length = 0;+ rootInstance.children =+ template.reference.componentChildren ??+ visit(node.children, path);+ } else {+ diagnostics.push(...overlayDiagnostics);+ }+ overlaidDescendants = matchedDescendants;+ resolvedFragment = extractWebstudioFragment(templateData, rootId);+ }+ mergeTemplateFragment(fragment, resolvedFragment);+ const mergedRootInstance = fragment.instances.find(+ ({ id }) => id === rootId+ );+ if (mergedRootInstance === undefined) {+ throw new Error("Resolved MDX template root is missing");}const ignored = new Set(template.ignoredJsxPropNames);const instancePropNameByJsxName = new Map(@@ -741,9 +1186,16 @@ export const materializeMdxAuthoredContent = ({]);const assetProps: AuthoredElementProvenance["assetProps"][number][] =[];- node.props.forEach((prop, propIndex) => {+ template.reference.props.forEach((prop, propIndex) => {+ const propBinding = template.reference.propBindings?.[propIndex];const assetReference = assetReferenceByPath.get(- getMdxPropValuePathKey({ nodePath: path, propIndex })+ getMdxPropValuePathKey({+ nodePath:+ propBinding?.source === undefined+ ? path+ : [...path, ...propBinding.source.nodePath],+ propIndex: propBinding?.source?.propIndex ?? propIndex,+ }));if (assetReference === undefined) {return;@@ -770,9 +1222,18 @@ export const materializeMdxAuthoredContent = ({});nodes.push({type: "template",+ binding: node.type === "element" ? "semantic" : "named",+ templateName: template.reference.templateName,+ overridesTemplateChildren,+ overlaysTemplateChildren,path,instanceId: rootId,editableTextChildren,+ authoredPropNames: template.reference.props.flatMap(({ name }) => {+ const instancePropName =+ instancePropNameByJsxName.get(name) ?? name;+ return ignored.has(name) ? [] : [instancePropName];+ }),editablePropNames: Array.from(editablePropNames).filter((name) =>Array.from(instancePropNameByJsxName).some(@@ -784,10 +1245,18 @@ export const materializeMdxAuthoredContent = ({propNameMappings: template.propNameMappings,preservedJsxPropNames: template.preservedJsxPropNames,ignoredJsxPropNames: template.ignoredJsxPropNames,- expandedInstanceIds: template.fragment.instances.map(({ id }) => id),+ expandedInstanceIds: resolvedFragment.instances.map(({ id }) => id),+ htmlTags:+ template.htmlTags ??+ resolvedFragment.instances.flatMap((instance) =>+ instance.tag === undefined+ ? []+ : [{ instanceId: instance.id, tag: instance.tag }]+ ),+ overlaidDescendants,assetProps,namespaceKeys: unsupportedNamespaces.flatMap((namespace) =>- template.fragment[namespace].map((record) => ({+ resolvedFragment[namespace].map((record) => ({namespace,key: getNamespaceRecordKey(namespace, record),}))@@ -796,24 +1265,164 @@ export const materializeMdxAuthoredContent = ({children.push({ type: "id", value: rootId });continue;}-- const materializedComponent = materializeMdxComponent(node);+ const registeredComponent =+ node.type === "template" && node.syntax === "jsx" && metas !== undefined+ ? getComponentByJsxName({+ name: node.name,+ components: metas.keys(),+ })+ : undefined;+ const materializedComponent = materializeMdxComponent(+ node,+ registeredComponent+ );if (materializedComponent !== undefined) {+ const isDirectRegisteredComponent =+ "authoredChildren" in materializedComponent;const createId = createMdxScopeIdGenerator({ identity, path });const instanceId = createId();- fragment.instances.push({+ const instance: Instance = {type: "instance",id: instanceId,component: materializedComponent.component,- children: materializedComponent.children,- });+ children:+ "authoredChildren" in materializedComponent+ ? visit(node.children, path)+ : materializedComponent.children,+ };+ fragment.instances.push(instance);+ const componentData =+ metas === undefined+ ? undefined+ : createWebstudioDataFromFragment({+ ...createEmptyWebstudioFragment(),+ children: [{ type: "id", value: instanceId }],+ instances: [instance],+ });+ const componentCapabilities =+ componentData === undefined || metas === undefined+ ? undefined+ : getContentModeCapabilities({+ instances: componentData.instances,+ metas,+ props: componentData.props,+ styleSources: componentData.styleSources,+ styleSourceSelections: componentData.styleSourceSelections,+ styles: componentData.styles,+ breakpoints: componentData.breakpoints,+ contentRootIds: new Set([instanceId]),+ });+ const namedJsxNode =+ node.type === "template" && node.syntax === "jsx" ? node : undefined;+ const declaredJsxPropNames = new Set(+ Object.keys(metas?.get(instance.component)?.props ?? {})+ );+ const htmlTag =+ componentCapabilities?.htmlTagsByInstanceId.get(instanceId);+ // Both built-in adapters render an HTML element and accept global HTML+ // attributes independently of whether component metadata is available.+ const acceptsHtmlAttributes = true;+ const declaredInstancePropNames = new Set(+ Array.from(declaredJsxPropNames, (jsxPropName) =>+ getInstancePropName({+ jsxPropName,+ componentPropNames: declaredJsxPropNames,+ acceptsHtmlAttributes,+ })+ )+ );+ const namedJsxProps =+ namedJsxNode === undefined+ ? []+ : namedJsxNode.props.map((prop) => ({+ ...prop,+ name: getInstancePropName({+ jsxPropName: prop.name,+ componentPropNames: declaredJsxPropNames,+ acceptsHtmlAttributes,+ }),+ }));+ const conflictingPropIndexes =+ namedJsxNode === undefined+ ? new Set<number>()+ : resolveMdxPropCollisions({+ authoredProps: namedJsxNode.props,+ mappedProps: namedJsxProps,+ componentPropNames: declaredJsxPropNames,+ acceptsHtmlAttributes,+ canUseProp: (index) => {+ if (componentCapabilities === undefined) {+ return true;+ }+ const authoredProp = namedJsxNode.props[index];+ const instanceProp = namedJsxProps[index];+ return (+ authoredProp !== undefined &&+ instanceProp !== undefined &&+ getMdxPropBinding({+ capabilities: componentCapabilities,+ instance,+ prop: instanceProp,+ jsxPropName: authoredProp.name,+ }) !== undefined+ );+ },+ }).conflictingPropIndexes;const assetProps: AuthoredElementProvenance["assetProps"][number][] =[];+ const ignoredJsxPropNames = new Set<string>();+ const ignoredInstancePropNameByJsxName = new Map<string, string>();+ const acceptedInstancePropNames = new Set<string>();+ if (namedJsxNode !== undefined) {+ for (const index of conflictingPropIndexes) {+ const authoredProp = namedJsxNode.props[index];+ const instanceProp = namedJsxProps[index];+ if (authoredProp === undefined || instanceProp === undefined) {+ continue;+ }+ ignoredJsxPropNames.add(authoredProp.name);+ ignoredInstancePropNameByJsxName.set(+ authoredProp.name,+ instanceProp.name+ );+ diagnostics.push({+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ templateName: materializedComponent.component,+ propName: authoredProp.name,+ reason: "incompatible",+ sourceRange: authoredProp.sourceRange ?? node.sourceRange,+ });+ }+ }for (const {prop,source,requiresAssetReference,} of materializedComponent.props) {+ const sourcePropIndex =+ source?.nodePath.length === 0 ? source.propIndex : undefined;+ if (+ sourcePropIndex !== undefined &&+ conflictingPropIndexes.has(sourcePropIndex)+ ) {+ continue;+ }+ const instanceProp =+ namedJsxNode === undefined+ ? prop+ : {+ ...prop,+ name: getInstancePropName({+ jsxPropName: prop.name,+ componentPropNames: declaredJsxPropNames,+ acceptsHtmlAttributes,+ }),+ };const propId = createId();const assetReference =source === undefined@@ -827,26 +1436,130 @@ export const materializeMdxAuthoredContent = ({if (requiresAssetReference && assetReference === undefined) {continue;}- fragment.props.push(- createLiteralProp({+ const jsxPropName = getSourcePropName({+ node,+ source,+ fallback: prop.name,+ });+ let materializedProp: Prop;+ if (componentCapabilities === undefined) {+ materializedProp = createLiteralProp({id: propId,instanceId,- prop,+ prop: instanceProp,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+ ? getMdxPropBinding({+ capabilities: componentCapabilities,+ instance,+ prop: instanceProp,+ jsxPropName,+ })+ : getMdxPropEligibility({+ capabilities: componentCapabilities,+ instance,+ prop: { name: instanceProp.name, type: "asset" },+ jsxPropName,+ }).editable+ ? { type: "asset" as const, value: assetReference.assetId }+ : undefined);+ if (binding === undefined) {+ const eligibility = getMdxPropEligibility({+ capabilities: componentCapabilities,+ instance,+ prop: { name: instanceProp.name, type: "string" },+ jsxPropName,+ });+ ignoredJsxPropNames.add(jsxPropName);+ ignoredInstancePropNameByJsxName.set(+ jsxPropName,+ instanceProp.name+ );+ diagnostics.push({+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ templateName: materializedComponent.component,+ propName: jsxPropName,+ reason:+ eligibility.editable === false+ ? eligibility.reason+ : "incompatible",+ sourceRange:+ sourcePropIndex === undefined+ ? node.sourceRange+ : (namedJsxNode?.props[sourcePropIndex]?.sourceRange ??+ node.sourceRange),+ });+ continue;+ }+ materializedProp = {+ id: propId,+ instanceId,+ name: instanceProp.name,+ ...binding,+ };+ }+ fragment.props.push(materializedProp);+ componentData?.props.set(materializedProp.id, materializedProp);+ acceptedInstancePropNames.add(materializedProp.name);if (assetReference !== undefined && typeof prop.value === "string") {assetProps.push({- propId,+ propId: materializedProp.id,assetId: assetReference.assetId,authoredValue: prop.value,});}}- nodes.push({ type: "component", path, instanceId, assetProps });+ nodes.push({+ type: "component",+ path,+ instanceId,+ ignoredInstancePropNames: Array.from(+ new Set(+ Array.from(ignoredInstancePropNameByJsxName.values()).filter(+ (name) => acceptedInstancePropNames.has(name) === false+ )+ )+ ),+ ...(namedJsxNode === undefined+ ? {}+ : {+ namedJsx: {+ jsxPropContext: {+ acceptsHtmlAttributes,+ componentPropNames: Array.from(declaredInstancePropNames),+ htmlTag,+ propTypes: [],+ },+ ignoredJsxPropNames: Array.from(ignoredJsxPropNames),+ },+ }),+ assetProps,+ });children.push({ type: "id", value: instanceId });continue;}+ if (node.type === "template") {+ continue;+ }const createId = createMdxScopeIdGenerator({ identity, path });const instanceId = createId();@@ -905,6 +1618,7 @@ export const materializeMdxAuthoredContent = ({fragment,document,provenance: { nodes, unresolvedTemplates },+ diagnostics,assetReferenceValues,};};@@ -1059,6 +1773,17 @@ export const adoptMdxAuthoredContentFragment = ({assetProps: mapAssetProps(node.assetProps),expandedInstanceIds:node.expandedInstanceIds.map(mapInstanceId),+ htmlTags: node.htmlTags.map(({ instanceId, tag }) => ({+ instanceId: mapInstanceId(instanceId),+ tag,+ })),+ overlaidDescendants: node.overlaidDescendants.map(+ (descendant) => ({+ ...descendant,+ instanceId: mapInstanceId(descendant.instanceId),+ assetProps: mapAssetProps(descendant.assetProps),+ })+ ),namespaceKeys: node.namespaceKeys.map((entry) => {const key = namespaceKeys.get(`${entry.namespace}:${entry.key}`@@ -1307,6 +2032,58 @@ export const reconcileMdxAuthoredContent = ({};indexOriginal(root.document.children, []);+ const templatesExpandedToAuthoredChildren = new Set<Instance["id"]>();+ for (const provenance of root.provenance.nodes) {+ if (provenance.type !== "template") {+ continue;+ }+ if (provenance.overlaysTemplateChildren) {+ templatesExpandedToAuthoredChildren.add(provenance.instanceId);+ continue;+ }+ const originalNode = originalNodeByPath.get(pathKey(provenance.path));+ if (+ originalNode?.type !== "template" ||+ isSelfClosingTemplateNode(originalNode) === false+ ) {+ continue;+ }+ const originalRoot = originalInstanceById.get(provenance.instanceId);+ const nextRoot = instanceById.get(provenance.instanceId);+ if (originalRoot === undefined || nextRoot === undefined) {+ continue;+ }+ const rootShellChanged =+ equal({ ...nextRoot, children: originalRoot.children }, originalRoot) ===+ false;+ if (rootShellChanged) {+ continue;+ }+ const descendantIds = provenance.expandedInstanceIds.filter(+ (id) => id !== provenance.instanceId+ );+ const childrenChanged =+ equal(nextRoot.children, originalRoot.children) === false;+ const descendantInstancesChanged = descendantIds.some(+ (id) =>+ equal(instanceById.get(id), originalInstanceById.get(id)) === false+ );+ const descendantPropsChanged = descendantIds.some(+ (id) =>+ equal(+ propsByInstanceId.get(id) ?? [],+ originalPropsByInstanceId.get(id) ?? []+ ) === false+ );+ if (+ childrenChanged ||+ descendantInstancesChanged ||+ descendantPropsChanged+ ) {+ templatesExpandedToAuthoredChildren.add(provenance.instanceId);+ }+ }+const templateByExpandedInstanceId = new Map(root.provenance.nodes.flatMap((node) =>node.type === "template"@@ -1314,6 +2091,25 @@ export const reconcileMdxAuthoredContent = ({: []));+ const htmlTagByExpandedInstanceId = new Map(+ root.provenance.nodes.flatMap((node) =>+ node.type === "template"+ ? node.htmlTags.map(({ instanceId, tag }) => [instanceId, tag] as const)+ : []+ )+ );+ const overlaidDescendantById = new Map(+ root.provenance.nodes.flatMap((node) =>+ node.type === "template"+ ? node.overlaidDescendants.map(+ (descendant) => [descendant.instanceId, descendant] as const+ )+ : []+ )+ );+ const overlaidDescendantPaths = new Set(+ Array.from(overlaidDescendantById.values(), ({ path }) => pathKey(path))+ );const templateInternalIds = new Set(templateByExpandedInstanceId.keys());const derivedTemplatePropIds = new Set<Prop["id"]>();for (const node of root.provenance.nodes) {@@ -1376,11 +2172,15 @@ export const reconcileMdxAuthoredContent = ({next !== undefined &&next.children.every((child) => child.type === "text") &&equal({ ...next, children: original.children }, original);+ const expandsToAuthoredChildren =+ template !== undefined &&+ templatesExpandedToAuthoredChildren.has(template.instanceId);if (templateInternalIds.has(original.id) &&(template?.type !== "template" ||deletedTemplateRootIds.has(template.instanceId) === false) &&- isEditableTemplateText === false+ isEditableTemplateText === false &&+ expandsToAuthoredChildren === false) {if (next === undefined || !equal(next, original)) {throw new Error(@@ -1399,9 +2199,19 @@ export const reconcileMdxAuthoredContent = ({);for (const prop of fragment.props) {const original = originalPropsById.get(prop.id);+ const owningTemplate =+ original === undefined+ ? undefined+ : templateByExpandedInstanceId.get(original.instanceId);+ const isAuthoredChildProp =+ original !== undefined &&+ owningTemplate !== undefined &&+ original.instanceId !== owningTemplate.instanceId &&+ templatesExpandedToAuthoredChildren.has(owningTemplate.instanceId);if (original !== undefined &&templateInternalIds.has(original.instanceId) &&+ isAuthoredChildProp === false &&!editableTemplatePropIds.has(prop.id) &&!derivedTemplatePropIds.has(prop.id) &&!equal(prop, original)@@ -1423,8 +2233,16 @@ export const reconcileMdxAuthoredContent = ({}}for (const original of root.fragment.props) {+ const owningTemplate = templateByExpandedInstanceId.get(+ original.instanceId+ );+ const isAuthoredChildProp =+ owningTemplate !== undefined &&+ original.instanceId !== owningTemplate.instanceId &&+ templatesExpandedToAuthoredChildren.has(owningTemplate.instanceId);if (templateInternalIds.has(original.instanceId) &&+ isAuthoredChildProp === false &&deletedTemplateRootIds.has(templateByExpandedInstanceId.get(original.instanceId)?.instanceId ?? "") === false &&@@ -1482,15 +2300,52 @@ export const reconcileMdxAuthoredContent = ({if (serializedInstanceIds.has(instanceId)) {throw new Error(`Authored MDX instance "${instanceId}" is reused`);}- for (const expandedId of provenance.expandedInstanceIds) {- serializedInstanceIds.add(expandedId);+ const expandsToAuthoredChildren =+ templatesExpandedToAuthoredChildren.has(instanceId);+ if (expandsToAuthoredChildren) {+ serializedInstanceIds.add(instanceId);+ } else {+ for (const expandedId of provenance.expandedInstanceIds) {+ serializedInstanceIds.add(expandedId);+ }}const original = originalNodeByPath.get(pathKey(provenance.path));- if (original?.type !== "template") {+ if (+ original === undefined ||+ (original.type !== "template" && original.type !== "element") ||+ (provenance.binding === "semantic") !== (original.type === "element")+ ) {throw new Error("Authored MDX template provenance is invalid");}+ const ignoredJsxPropNames = new Set(provenance.ignoredJsxPropNames);+ const instancePropNameByJsxName = new Map(+ provenance.propNameMappings.map((mapping) => [+ mapping.jsxPropName,+ mapping.instancePropName,+ ])+ );+ const componentPropNames = new Set(+ provenance.jsxPropContext.componentPropNames+ );+ const toInstancePropName = (jsxPropName: string) =>+ instancePropNameByJsxName.get(jsxPropName) ??+ getInstancePropName({+ jsxPropName,+ acceptsHtmlAttributes:+ provenance.jsxPropContext.acceptsHtmlAttributes,+ componentPropNames,+ });+ const authoredPropNames = new Set(provenance.authoredPropNames);+ const originalEditablePropsByName = new Map(+ (originalPropsByInstanceId.get(instanceId) ?? [])+ .filter((prop) => isEditableTemplateProp({ provenance, prop }))+ .map((prop) => [prop.name, prop])+ );const editableProps = (propsByInstanceId.get(instanceId) ?? []).filter(- (prop) => isEditableTemplateProp({ provenance, prop })+ (prop) =>+ isEditableTemplateProp({ provenance, prop }) &&+ (authoredPropNames.has(prop.name) ||+ equal(originalEditablePropsByName.get(prop.name), prop) === false));if (new Set(editableProps.map(({ name }) => name)).size !==@@ -1502,18 +2357,6 @@ export const reconcileMdxAuthoredContent = ({...provenance.editablePropNames,...editableProps.map(({ name }) => name),]);- const instancePropNameByJsxName = new Map(- provenance.propNameMappings.map((mapping) => [- mapping.jsxPropName,- mapping.instancePropName,- ])- );- const toInstancePropName = (jsxPropName: string) =>- instancePropNameByJsxName.get(jsxPropName) ?? jsxPropName;- const ignoredJsxPropNames = new Set(provenance.ignoredJsxPropNames);- const componentPropNames = new Set(- provenance.jsxPropContext.componentPropNames- );const authoredJsxPropNameByInstanceName = new Map(provenance.propNameMappings.flatMap((mapping) =>provenance.preservedJsxPropNames?.includes(mapping.jsxPropName)@@ -1533,6 +2376,12 @@ export const reconcileMdxAuthoredContent = ({componentPropNames,}).map((mapping) => [mapping.instancePropName, mapping.name]));+ const nextInstancePropNameByJsxName = new Map(+ Array.from(+ jsxPropNameByInstanceName,+ ([instancePropName, jsxPropName]) => [jsxPropName, instancePropName]+ )+ );const toJsxName = (instancePropName: string) => {const jsxPropName =authoredJsxPropNameByInstanceName.get(instancePropName) ??@@ -1557,9 +2406,21 @@ export const reconcileMdxAuthoredContent = ({assetReferenceValues: root.assetReferenceValues,});const nextByName = new Map(nextEditable.map((prop) => [prop.name, prop]));+ const nextInstancePropNames = new Set(nextByName.keys());+ const boundOriginalInstancePropNames = new Set(+ original.props.flatMap((prop) =>+ ignoredJsxPropNames.has(prop.name)+ ? []+ : [toInstancePropName(prop.name)]+ )+ );const props = original.props.flatMap((prop) => {if (ignoredJsxPropNames.has(prop.name)) {- return [prop];+ const instancePropName = toInstancePropName(prop.name);+ return boundOriginalInstancePropNames.has(instancePropName) &&+ nextInstancePropNames.has(instancePropName) === false+ ? []+ : [prop];}const instancePropName = toInstancePropName(prop.name);if (editableNames.has(instancePropName) === false) {@@ -1580,87 +2441,465 @@ export const reconcileMdxAuthoredContent = ({const normalizedProps = normalizeMdxComponentProps({instance,props,- instanceProps: editableProps,+ instanceProps: propsByInstanceId.get(instanceId) ?? [],});assertUniqueAttributeNames(normalizedProps);let children = original.children;const originalInstance = originalInstanceById.get(instanceId);if (- provenance.editableTextChildren &&- originalInstance !== undefined &&- (original.children.length > 0 ||- equal(instance.children, originalInstance.children) === false)+ expandsToAuthoredChildren ||+ provenance.overridesTemplateChildren ||+ (provenance.editableTextChildren &&+ originalInstance !== undefined &&+ (original.children.length > 0 ||+ equal(instance.children, originalInstance.children) === false))) {children = reconcileChildren({original: original.children,children: instance.children,- mode: original.mdxMode,+ mode:+ original.type === "element"+ ? getChildrenMode({ original, tag: original.tag })+ : original.mdxMode,active,});- if (children.length === 0) {- throw new Error(- "Empty template text cannot be represented losslessly in MDX"- );- }}if (- provenance.namespaceKeys.length === 0 &&+ provenance.binding === "semantic" &&normalizedProps.every(({ name }) =>ignoredJsxPropNames.has(name) === false &&- editableNames.has(toInstancePropName(name))+ editableNames.has(+ instancePropNameByJsxName.get(name) ??+ nextInstancePropNameByJsxName.get(name) ??+ name+ ))) {const componentNode = serializeMdxComponent({instance,props: nextEditable,- instanceProps: editableProps,+ instanceProps: propsByInstanceId.get(instanceId) ?? [],original,});if (componentNode !== undefined) {return componentNode;}+ const componentFallback = serializeMdxComponentFallback({+ instance,+ props: nextEditable,+ instanceProps: propsByInstanceId.get(instanceId) ?? [],+ templateName: provenance.templateName,+ mdxMode: mode,+ });+ if (componentFallback !== undefined) {+ return componentFallback;+ }+ }+ if (original.type === "element") {+ if (+ original.syntax === "markdown" &&+ equal(normalizedProps, original.props) === false+ ) {+ return {+ type: "template",+ syntax: getMdxNamedTemplateSyntax({+ templateName: provenance.templateName,+ component: instance.component,+ }),+ selfClosing: false,+ name: provenance.templateName,+ props: normalizedProps,+ children,+ mdxMode: getChildrenMode({ original, tag: original.tag }),+ sourceRange: original.sourceRange,+ };+ }+ return { ...original, props: normalizedProps, children };+ }+ if (expandsToAuthoredChildren) {+ return {+ ...original,+ selfClosing: false,+ props: normalizedProps,+ children,+ mdxMode:+ mode === "text" ||+ (provenance.editableTextChildren && children.length > 0)+ ? "text"+ : original.mdxMode,+ };}return mode === "text" ||(provenance.editableTextChildren && children.length > 0)? { ...original, props: normalizedProps, children, mdxMode: "text" }: { ...original, props: normalizedProps, children };}+ const owningTemplate = templateByExpandedInstanceId.get(instanceId);+ const isExpandedTemplateDescendant =+ owningTemplate !== undefined &&+ owningTemplate.instanceId !== instanceId &&+ templatesExpandedToAuthoredChildren.has(owningTemplate.instanceId);+ if (isExpandedTemplateDescendant) {+ const originalInstance = originalInstanceById.get(instanceId);+ if (+ originalInstance === undefined ||+ originalInstance.component !== instance.component ||+ originalInstance.label !== instance.label+ ) {+ throw new Error(+ "Template descendant metadata cannot be represented losslessly in MDX"+ );+ }+ const descendantProvenance = overlaidDescendantById.get(instanceId);+ const originalNode =+ descendantProvenance === undefined+ ? undefined+ : originalNodeByPath.get(pathKey(descendantProvenance.path));+ if (+ originalNode !== undefined &&+ (originalNode.type === "text" ||+ originalNode.type === "comment" ||+ originalNode.type === "opaque")+ ) {+ throw new Error("Overlaid template descendant provenance is invalid");+ }+ const originalProps = originalPropsByInstanceId.get(instanceId) ?? [];+ const currentProps = propsByInstanceId.get(instanceId) ?? [];+ // Removing a descendant prop resets its authored override and lets the+ // current template default apply again on the next materialization.+ const originalPropsById = new Map(+ originalProps.map((prop) => [prop.id, prop])+ );+ const originalComponent =+ descendantProvenance?.kind === "component" && originalNode !== undefined+ ? materializeMdxComponent(originalNode)+ : undefined;+ if (+ descendantProvenance?.kind === "component" &&+ originalComponent?.component !== instance.component+ ) {+ throw new Error("Overlaid template component provenance is invalid");+ }+ const originalAuthoredProps =+ originalNode === undefined+ ? []+ : descendantProvenance?.kind === "component"+ ? (originalComponent?.props.map(({ prop }) => prop) ?? [])+ : mapAttributeNames({+ attributes: originalNode.props,+ direction: "jsx-to-instance",+ acceptsHtmlAttributes: true,+ componentPropNames: new Set(+ descendantProvenance?.componentPropNames ?? []+ ),+ });+ const ignoredInstancePropNames = new Set(+ descendantProvenance?.ignoredInstancePropNames ?? []+ );+ for (const prop of currentProps) {+ if (+ ignoredInstancePropNames.has(prop.name) &&+ equal(originalPropsById.get(prop.id), prop) === false+ ) {+ throw new Error(+ "Ignored template descendant props cannot be represented losslessly in MDX"+ );+ }+ }+ const authoredPropNames = new Set(+ originalAuthoredProps.flatMap(({ name }) =>+ ignoredInstancePropNames.has(name) ? [] : [name]+ )+ );+ const changedProps = currentProps.filter(+ (prop) =>+ ignoredInstancePropNames.has(prop.name) === false &&+ (authoredPropNames.has(prop.name) ||+ equal(originalPropsById.get(prop.id), prop) === false)+ );+ const editableAuthoredProps = toAuthoredProps({+ original: originalAuthoredProps.filter(+ ({ name }) => ignoredInstancePropNames.has(name) === false+ ),+ props: changedProps,+ assetProps: descendantProvenance?.assetProps,+ assetReferenceValues: root.assetReferenceValues,+ });+ const editableAuthoredPropsByName = new Map(+ editableAuthoredProps.map((prop) => [prop.name, prop])+ );+ const authoredProps = originalAuthoredProps.flatMap((prop) => {+ if (ignoredInstancePropNames.has(prop.name)) {+ return [prop];+ }+ const next = editableAuthoredPropsByName.get(prop.name);+ editableAuthoredPropsByName.delete(prop.name);+ return next === undefined ? [] : [next];+ });+ authoredProps.push(...editableAuthoredPropsByName.values());+ if (serializedInstanceIds.has(instanceId)) {+ throw new Error(`Authored MDX instance "${instanceId}" is reused`);+ }+ serializedInstanceIds.add(instanceId);+ if (descendantProvenance?.kind === "component") {+ const componentNode =+ originalNode?.type === "template" ||+ (authoredProps.length === 0 && instance.children.length === 0)+ ? serializeMdxComponentFallback({+ instance,+ props: authoredProps,+ instanceProps: currentProps,+ templateName:+ originalNode?.type === "template"+ ? originalNode.name+ : undefined,+ mdxMode:+ originalNode?.type === "template"+ ? originalNode.mdxMode+ : mode,+ })+ : (serializeMdxComponent({+ instance,+ props: authoredProps,+ instanceProps: currentProps,+ original: originalNode,+ }) ??+ serializeMdxComponentFallback({+ instance,+ props: authoredProps,+ instanceProps: currentProps,+ mdxMode: mode,+ }));+ if (componentNode === undefined) {+ throw new Error(+ `Template component descendant "${instanceId}" cannot be represented losslessly in MDX`+ );+ }+ return componentNode;+ }+ const tag =+ instance.component === elementComponent+ ? instance.tag+ : (htmlTagByExpandedInstanceId.get(instanceId) ?? instance.tag);+ if (tag === undefined) {+ throw new Error(+ `Template descendant "${instanceId}" has no deterministic HTML tag`+ );+ }+ active.add(instanceId);+ const children = reconcileChildren({+ original: originalNode?.children ?? [],+ children: instance.children,+ mode:+ elementsByTag[tag]?.children.includes("phrasing") === true+ ? "text"+ : "flow",+ active,+ });+ active.delete(instanceId);+ const props = mapAttributeNames({+ attributes: authoredProps,+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: true,+ componentPropNames: new Set(+ descendantProvenance?.componentPropNames ?? []+ ),+ });+ return {+ type: "element",+ syntax: "mdx",+ tag,+ props,+ children,+ mdxMode: getInsertedNodeMode(instance.children),+ };+ }const instanceProps = propsByInstanceId.get(instanceId) ?? [];- const authoredComponentProps =+ const componentProvenance =+ provenance?.type === "component" ? provenance : undefined;+ const originalComponentNode =+ componentProvenance === undefined+ ? undefined+ : originalNodeByPath.get(pathKey(componentProvenance.path));+ const originalComponent =+ originalComponentNode === undefined+ ? undefined+ : materializeMdxComponent(originalComponentNode);+ const originalComponentProps =+ originalComponent?.component === instance.component+ ? originalComponent.props.map(({ prop }) => prop)+ : [];+ const namedJsxProvenance = componentProvenance?.namedJsx;+ const namedJsxComponentPropNames = new Set(+ namedJsxProvenance?.jsxPropContext.componentPropNames ?? []+ );+ const toNamedJsxInstancePropName = (jsxPropName: string) =>+ namedJsxProvenance === undefined+ ? jsxPropName+ : getInstancePropName({+ jsxPropName,+ acceptsHtmlAttributes:+ namedJsxProvenance.jsxPropContext.acceptsHtmlAttributes,+ componentPropNames: namedJsxComponentPropNames,+ });+ const ignoredJsxPropNames = new Set(+ namedJsxProvenance?.ignoredJsxPropNames ?? []+ );+ const ignoredInstancePropNames = new Set(+ componentProvenance?.ignoredInstancePropNames ?? []+ );+ if (instanceProps.some(({ name }) => ignoredInstancePropNames.has(name))) {+ throw new Error(+ "Ignored authored component props cannot be represented losslessly in MDX"+ );+ }+ const editableAuthoredComponentProps =instance.component === elementComponent? []: toAuthoredProps({- original: [],+ original:+ namedJsxProvenance === undefined+ ? originalComponentProps.filter(+ ({ name }) => ignoredInstancePropNames.has(name) === false+ )+ : originalComponentProps.flatMap((prop) =>+ ignoredJsxPropNames.has(prop.name)+ ? []+ : [+ {+ ...prop,+ name: toNamedJsxInstancePropName(prop.name),+ },+ ]+ ),props: instanceProps,- assetProps:- provenance?.type === "component"- ? provenance.assetProps- : undefined,+ assetProps: componentProvenance?.assetProps,assetReferenceValues: root.assetReferenceValues,});- const componentNode =+ const editableAuthoredComponentPropsByName = new Map(+ editableAuthoredComponentProps.map((prop) => [prop.name, prop])+ );+ const authoredComponentProps =instance.component === elementComponent+ ? []+ : namedJsxProvenance !== undefined+ ? editableAuthoredComponentProps+ : originalComponentProps+ .flatMap((prop) => {+ if (ignoredInstancePropNames.has(prop.name)) {+ return [prop];+ }+ const next = editableAuthoredComponentPropsByName.get(+ prop.name+ );+ editableAuthoredComponentPropsByName.delete(prop.name);+ return next === undefined ? [] : [next];+ })+ .concat(...editableAuthoredComponentPropsByName.values());+ const preferComponentReference =+ instance.children.length === 0 &&+ instanceProps.length === 0 &&+ (componentProvenance === undefined ||+ originalComponentNode?.type === "template");+ let genericNamedJsxChildren: readonly MdxAuthoredNode[] | undefined;+ if (+ namedJsxProvenance !== undefined &&+ hasMdxComponentAdapter(instance.component) === false+ ) {+ active.add(instanceId);+ genericNamedJsxChildren = reconcileChildren({+ original:+ originalComponentNode?.type === "template"+ ? originalComponentNode.children+ : [],+ children: instance.children,+ mode:+ originalComponentNode?.type === "template"+ ? originalComponentNode.mdxMode+ : mode,+ active,+ });+ active.delete(instanceId);+ }+ const componentNode =+ instance.component === elementComponent ||+ preferComponentReference ||+ namedJsxProvenance !== undefined? undefined: serializeMdxComponent({instance,props: authoredComponentProps,instanceProps,- original:- provenance?.type === "component"- ? originalNodeByPath.get(pathKey(provenance.path))- : undefined,+ original: originalComponentNode,});const serializedComponent =componentNode ??- (provenance?.type === "component"- ? serializeMdxComponentFallback({- instance,- props: authoredComponentProps,- instanceProps,- })- : undefined);- if (serializedComponent !== undefined) {+ serializeMdxComponentFallback({+ instance,+ props: authoredComponentProps,+ instanceProps,+ templateName:+ originalComponentNode?.type === "template"+ ? originalComponentNode.name+ : undefined,+ mdxMode:+ originalComponentNode?.type === "template"+ ? originalComponentNode.mdxMode+ : mode,+ jsxPropContext: namedJsxProvenance?.jsxPropContext,+ children: genericNamedJsxChildren,+ });+ const sourcePreservingComponent =+ namedJsxProvenance === undefined ||+ serializedComponent === undefined ||+ originalComponentNode?.type !== "template" ||+ serializedComponent.type !== "template"+ ? serializedComponent+ : (() => {+ const nextPropsByInstanceName = new Map(+ serializedComponent.props.map((prop) => [+ toNamedJsxInstancePropName(prop.name),+ prop,+ ])+ );+ const nextInstancePropNames = new Set(+ nextPropsByInstanceName.keys()+ );+ const boundOriginalInstancePropNames = new Set(+ originalComponentNode.props.flatMap((prop) =>+ ignoredJsxPropNames.has(prop.name)+ ? []+ : [toNamedJsxInstancePropName(prop.name)]+ )+ );+ const props = originalComponentNode.props.flatMap((prop) => {+ if (ignoredJsxPropNames.has(prop.name)) {+ const instancePropName = toNamedJsxInstancePropName(prop.name);+ return boundOriginalInstancePropNames.has(instancePropName) &&+ nextInstancePropNames.has(instancePropName) === false+ ? []+ : [prop];+ }+ const instancePropName = toNamedJsxInstancePropName(prop.name);+ const next = nextPropsByInstanceName.get(instancePropName);+ nextPropsByInstanceName.delete(instancePropName);+ return next === undefined ? [] : [{ ...next, name: prop.name }];+ });+ props.push(...nextPropsByInstanceName.values());+ assertUniqueAttributeNames(props);+ return {+ ...serializedComponent,+ name: originalComponentNode.name,+ props,+ sourceRange: originalComponentNode.sourceRange,+ selfClosing:+ serializedComponent.children.length === 0+ ? originalComponentNode.selfClosing+ : serializedComponent.selfClosing,+ };+ })();+ if (sourcePreservingComponent !== undefined) {if (serializedInstanceIds.has(instanceId)) {throw new Error(`Authored MDX instance "${instanceId}" is reused`);}@@ -1673,7 +2912,7 @@ export const reconcileMdxAuthoredContent = ({throw new Error("Authored MDX component provenance is invalid");}serializedInstanceIds.add(instanceId);- return serializedComponent;+ return sourcePreservingComponent;}if (instance.component !== elementComponent || instance.tag === undefined) {throw new Error(@@ -1791,11 +3030,13 @@ export const reconcileMdxAuthoredContent = ({return { key: entry?.key, node };}const provenance = provenanceById.get(child.value);+ const authoredPath =+ provenance?.path ?? overlaidDescendantById.get(child.value)?.path;return {key:- provenance === undefined+ authoredPath === undefined? undefined- : `node:${pathKey(provenance.path)}`,+ : `node:${pathKey(authoredPath)}`,node: toNode(child.value, mode, active),};});@@ -1811,12 +3052,14 @@ export const reconcileMdxAuthoredContent = ({originalPath === undefined? undefined: provenanceByPath.get(originalPath);+ const isOverlaidDescendant =+ originalPath !== undefined && overlaidDescendantPaths.has(originalPath);const key =node.type === "text"? `text:${index}`- : provenance === undefined+ : provenance === undefined && isOverlaidDescendant === false? undefined- : `node:${pathKey(provenance.path)}`;+ : `node:${originalPath}`;if (key !== undefined && surviving.has(key)) {anchorsByKey.set(key, pending);pending = [];@@ -1984,12 +3227,122 @@ export const serializeMdxTemplateInsertion = async ({fragment,templateName,assetReferenceValues,+ inheritTemplateDefaults = false,+ pristineFragment,+ htmlTags = [],}: {identity: ContentBlockExternalContentIdentity;fragment: WebstudioFragment;templateName: string;assetReferenceValues?: ReadonlyMap<string, string>;-}) => {+ inheritTemplateDefaults?: boolean;+ pristineFragment?: WebstudioFragment;+ htmlTags?: readonly Readonly<{+ instanceId: Instance["id"];+ tag: string;+ }>[];+}): Promise<MdxDocument> => {+ const root = fragment.children[0];+ const rootInstance =+ root?.type === "id"+ ? fragment.instances.find(({ id }) => id === root.value)+ : undefined;+ const pristineRoot = pristineFragment?.children[0];+ const pristineRootId =+ pristineRoot?.type === "id" ? pristineRoot.value : undefined;+ const rootTemplateDescriptor =+ rootInstance === undefined+ ? undefined+ : getContentBlockMdxTemplateDescriptor(rootInstance);+ const isDefaultElementTemplate =+ rootInstance?.component === elementComponent &&+ rootTemplateDescriptor?.kind === "element" &&+ (templateName === getDefaultContentBlockTemplateName(rootInstance) ||+ (rootInstance.name === undefined && rootInstance.label === templateName));+ const canInheritTemplateDefaults =+ isDefaultElementTemplate === false &&+ (inheritTemplateDefaults ||+ (pristineFragment !== undefined &&+ root?.type === "id" &&+ pristineRootId === root.value &&+ equal(+ {+ ...fragment,+ props: fragment.props.filter(+ ({ instanceId }) => instanceId !== root.value+ ),+ // Asset records are immutable inputs. A newly selected root Asset is+ // represented by its authored reference, not by expanding children.+ assets: [],+ },+ {+ ...pristineFragment,+ props: pristineFragment.props.filter(+ ({ instanceId }) => instanceId !== root.value+ ),+ assets: [],+ }+ )));+ if (canInheritTemplateDefaults) {+ if (+ fragment.children.length !== 1 ||+ root?.type !== "id" ||+ rootInstance === undefined+ ) {+ throw new Error("Inserted template must have exactly one root instance");+ }+ const currentRootProps = fragment.props.filter(+ ({ instanceId }) => instanceId === root.value+ );+ const pristineRootProps =+ pristineFragment?.props.filter(+ ({ instanceId }) => instanceId === root.value+ ) ?? [];+ const pristineRootPropsById = new Map(+ pristineRootProps.map((prop) => [prop.id, prop])+ );+ const changedRootProps = currentRootProps.filter(+ (prop) => equal(pristineRootPropsById.get(prop.id), prop) === false+ );+ const authoredRootProps = toAuthoredProps({+ original: [],+ props: changedRootProps,+ assetReferenceValues,+ });+ const componentReference = serializeMdxComponentFallback({+ instance: rootInstance,+ props: authoredRootProps,+ instanceProps: currentRootProps,+ templateName,+ });+ const tag =+ htmlTags.find(({ instanceId }) => instanceId === root.value)?.tag ??+ rootInstance.tag;+ const props =+ componentReference?.props ??+ mapAttributeNames({+ attributes: authoredRootProps,+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: tag !== undefined,+ });+ return {+ frontmatter: { properties: {} },+ children: [+ {+ type: "template",+ syntax: getMdxNamedTemplateSyntax({+ templateName,+ component: rootInstance.component,+ }),+ selfClosing: true,+ name: templateName,+ props,+ children: [],+ mdxMode: "flow",+ },+ ],+ };+ }const emptyDocument: MdxDocument = {frontmatter: { properties: {} },children: [],@@ -2004,11 +3357,130 @@ export const serializeMdxTemplateInsertion = async ({},assetReferenceValues,});+ const pristinePropsById = new Map(+ pristineFragment?.props.map((prop) => [prop.id, prop]) ?? []+ );+ const htmlTagByInstanceId = new Map(+ htmlTags.map(({ instanceId, tag }) => [instanceId, tag])+ );+ const serializableProps = fragment.props.filter(+ (prop) => equal(pristinePropsById.get(prop.id), prop) === false+ );+ const serializableAssetIds = new Set(+ serializableProps.flatMap((prop) =>+ prop.type === "asset" ? [prop.value] : []+ )+ );+ const serializableFragment =+ pristineFragment === undefined+ ? fragment+ : {+ ...fragment,+ instances: fragment.instances.map((instance) => {+ const tag = htmlTagByInstanceId.get(instance.id) ?? instance.tag;+ return tag === undefined ||+ hasMdxComponentAdapter(instance.component)+ ? instance+ : { ...instance, component: elementComponent, tag };+ }),+ props: serializableProps,+ assets: fragment.assets.filter(({ id }) =>+ serializableAssetIds.has(id)+ ),+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };try {- return preferMarkdownSyntax(- reconcileMdxAuthoredContent({ root: emptyRoot, fragment })+ const authored = await preferMarkdownSyntax(+ reconcileMdxAuthoredContent({+ root: emptyRoot,+ fragment: serializableFragment,+ }));- } catch {+ const rootNode =+ authored.children.length === 1 ? authored.children[0] : undefined;+ if (+ rootNode === undefined ||+ rootNode.type === "text" ||+ rootNode.type === "comment" ||+ rootNode.type === "opaque"+ ) {+ throw new Error("Inserted template root cannot be represented in MDX");+ }+ if (+ isDefaultElementTemplate &&+ rootNode.type === "element" &&+ rootNode.syntax === "markdown"+ ) {+ return authored;+ }+ const rootChild = fragment.children[0];+ const rootInstance =+ rootChild?.type === "id"+ ? fragment.instances.find(({ id }) => id === rootChild.value)+ : undefined;+ const rootInstanceProps =+ rootInstance === undefined+ ? []+ : fragment.props.filter(+ ({ instanceId }) => instanceId === rootInstance.id+ );+ const componentReference =+ rootInstance === undefined+ ? undefined+ : serializeMdxComponentFallback({+ instance: rootInstance,+ props: toAuthoredProps({+ original: [],+ props: rootInstanceProps,+ assetReferenceValues,+ }),+ instanceProps: rootInstanceProps,+ templateName,+ });+ const props =+ componentReference?.props ??+ mapAttributeNames({+ attributes: rootNode.props,+ direction: "instance-to-jsx",+ acceptsHtmlAttributes:+ rootNode.type === "element" || rootInstance?.tag !== undefined,+ });+ const children = componentReference?.children ?? rootNode.children;+ return {+ ...authored,+ children: [+ {+ type: "template" as const,+ syntax: getMdxNamedTemplateSyntax({+ templateName,+ component: rootInstance?.component,+ }),+ selfClosing: componentReference?.selfClosing ?? false,+ name: templateName,+ props,+ children,+ mdxMode:+ componentReference?.mdxMode ??+ (rootNode.type === "element" && rootNode.syntax === "mdx"+ ? rootNode.mdxMode+ : rootNode.type === "template"+ ? rootNode.mdxMode+ : elementsByTag[rootNode.tag]?.children.includes("phrasing") ===+ true+ ? ("text" as const)+ : ("flow" as const)),+ },+ ],+ };+ } catch (error) {+ if (pristineFragment !== undefined) {+ throw error;+ }const rootChild = fragment.children[0];const rootInstance =rootChild?.type === "id"@@ -2034,7 +3506,13 @@ export const serializeMdxTemplateInsertion = async ({if (componentFallback !== undefined) {return {frontmatter: { properties: {} },- children: [componentFallback],+ children: [+ {+ ...componentFallback,+ selfClosing: componentFallback.children.length === 0,+ name: templateName,+ },+ ],};}const props =@@ -2067,6 +3545,11 @@ export const serializeMdxTemplateInsertion = async ({children: [{type: "template" as const,+ syntax: getMdxNamedTemplateSyntax({+ templateName,+ component: rootInstance?.component,+ }),+ selfClosing: children.length === 0,name: templateName,props,children,@@ -2078,18 +3561,32 @@ export const serializeMdxTemplateInsertion = async ({}};+export type MdxTemplateInsertion = Readonly<{+ templateName: string;+ pristineFragment: WebstudioFragment;+ htmlTags?: readonly Readonly<{+ instanceId: Instance["id"];+ tag: string;+ }>[];+}>;+const reconcileMdxAuthoredContentWithTemplateInsertions = async ({root,fragment,+ insertedTemplates,insertedTemplateNames,}: {root: MaterializedMdxAuthoredContentRoot;fragment: WebstudioFragment;- insertedTemplateNames: ReadonlyMap<string, string>;+ insertedTemplates: ReadonlyMap<Instance["id"], MdxTemplateInsertion>;+ insertedTemplateNames: ReadonlyMap<Instance["id"], string>;}) => {- if (insertedTemplateNames.size === 0) {+ if (insertedTemplates.size === 0 && insertedTemplateNames.size === 0) {return preferMarkdownSyntax(- reconcileMdxAuthoredContent({ root, fragment })+ reconcileMdxAuthoredContent({+ root,+ fragment: omitTransientEmptyMarkdownDrafts({ root, fragment }),+ }));}const fragmentData = createWebstudioDataFromFragment(fragment);@@ -2098,7 +3595,9 @@ const reconcileMdxAuthoredContentWithTemplateInsertions = async ({if (child.type !== "id") {return [];}- const templateName = insertedTemplateNames.get(child.value);+ const insertion = insertedTemplates.get(child.value);+ const templateName =+ insertion?.templateName ?? insertedTemplateNames.get(child.value);if (templateName === undefined) {return [];}@@ -2112,6 +3611,11 @@ const reconcileMdxAuthoredContentWithTemplateInsertions = async ({fragment: insertionFragment,templateName,assetReferenceValues: root.assetReferenceValues,+ inheritTemplateDefaults:+ insertion !== undefined &&+ equal(insertionFragment, insertion.pristineFragment),+ pristineFragment: insertion?.pristineFragment,+ htmlTags: insertion?.htmlTags,}).then((document) => ({rootInstanceId: child.value,fragment: insertionFragment,@@ -2122,7 +3626,10 @@ const reconcileMdxAuthoredContentWithTemplateInsertions = async ({);if (insertions.length === 0) {return preferMarkdownSyntax(- reconcileMdxAuthoredContent({ root, fragment })+ reconcileMdxAuthoredContent({+ root,+ fragment: omitTransientEmptyMarkdownDrafts({ root, fragment }),+ }));}@@ -2203,7 +3710,7 @@ const reconcileMdxAuthoredContentWithTemplateInsertions = async ({} as WebstudioFragment;const reconciled = reconcileMdxAuthoredContent({root,- fragment: normalized,+ fragment: omitTransientEmptyMarkdownDrafts({ root, fragment: normalized }),});const insertionByMarker = new Map(insertions.map((insertion) => [@@ -2233,6 +3740,7 @@ export const rebaseMdxAuthoredContent = async ({latest,latestRevision,latestIsLocal = false,+ insertedTemplates = new Map(),insertedTemplateNames = new Map(),}: {root: MaterializedMdxAuthoredContentRoot;@@ -2240,7 +3748,9 @@ export const rebaseMdxAuthoredContent = async ({latest: MdxDocument;latestRevision?: string;latestIsLocal?: boolean;- insertedTemplateNames?: ReadonlyMap<string, string>;+ insertedTemplates?: ReadonlyMap<Instance["id"], MdxTemplateInsertion>;+ /** @deprecated Use insertedTemplates to preserve pristine template defaults. */+ insertedTemplateNames?: ReadonlyMap<Instance["id"], string>;}) => {if ((latestRevision !== undefined &&@@ -2254,7 +3764,8 @@ export const rebaseMdxAuthoredContent = async ({}const local = await reconcileMdxAuthoredContentWithTemplateInsertions({root,- fragment: omitTransientEmptyMarkdownDrafts({ root, fragment }),+ fragment,+ insertedTemplates,insertedTemplateNames,});return preferMarkdownSyntax(diff --git a/packages/project-build/src/runtime/mdx-component-adapters.ts b/packages/project-build/src/runtime/mdx-component-adapters.tsindex f433220d19..f88443f88b 100644--- a/packages/project-build/src/runtime/mdx-component-adapters.ts+++ b/packages/project-build/src/runtime/mdx-component-adapters.ts@@ -1,11 +1,23 @@+/**+ * Defines the component-specific conversions that preserve Markdown semantics+ * and static props when moving between MDX nodes and Webstudio instances.+ */import {createMdxCodeBlock,+ isMdxTemplateComponentName,readMdxCodeBlock,type MdxAuthoredNode,type MdxAuthoredProp,+ type MdxMode,} from "@webstudio-is/content-engine/mdx";import { mapAttributeNames } from "@webstudio-is/content-engine/jsx-attributes";-import type { Instance, Prop } from "@webstudio-is/sdk";+import {+ getContentBlockMdxTemplateDescriptor,+ getHtmlTagFromInstance,+ type Instance,+ type Prop,+ type WsComponentMeta,+} from "@webstudio-is/sdk";type MaterializedComponentProp = Readonly<{prop: MdxAuthoredProp;@@ -30,6 +42,9 @@ type MdxComponentAdapter = Readonly<{original?: MdxAuthoredNode;}) => MdxAuthoredNode | undefined;fromMdx: (node: MdxAuthoredNode) => MaterializedComponent | undefined;+ fromNamedMdx?: (+ node: Extract<MdxAuthoredNode, { type: "template" }>+ ) => MaterializedComponent | undefined;}>;const codeTextComponent = "CodeText";@@ -47,6 +62,14 @@ const getStringProps = (props: readonly MdxAuthoredProp[]) => {return values;};+const materializeNamedProps = (+ props: readonly MdxAuthoredProp[]+): MaterializedComponentProp[] =>+ props.map((prop, propIndex) => ({+ prop,+ source: { nodePath: [], propIndex },+ }));+const codeTextAdapter: MdxComponentAdapter = {component: codeTextComponent,toMdx: ({ instance, props }) => {@@ -94,9 +117,30 @@ const codeTextAdapter: MdxComponentAdapter = {: [{ prop: { name: "language", value: code.language } }],};},+ fromNamedMdx: (node) => {+ if (node.children.some(({ type }) => type !== "text")) {+ return;+ }+ return {+ children: node.children.flatMap((child) =>+ child.type === "text"+ ? [{ type: "text" as const, value: child.value }]+ : []+ ),+ props: materializeNamedProps(node.props),+ };+ },};const readMdxImage = (node: MdxAuthoredNode) => {+ if (+ node.type === "element" &&+ node.syntax === "markdown" &&+ node.tag === "img" &&+ node.children.length === 0+ ) {+ return { image: node, nodePath: [] } as const;+ }if (node.type !== "element" ||node.syntax !== "markdown" ||@@ -115,7 +159,7 @@ const readMdxImage = (node: MdxAuthoredNode) => {) {return;}- return image;+ return { image, nodePath: [0] } as const;};const getDerivedImageAssetPropIds = (instanceProps: readonly Prop[]) => {@@ -180,7 +224,7 @@ export const normalizeMdxComponentProps = ({const imageAdapter: MdxComponentAdapter = {component: imageComponent,- toMdx: ({ instance, props, instanceProps }) => {+ toMdx: ({ instance, props, instanceProps, original }) => {if (instance.children.length > 0) {return;}@@ -203,29 +247,32 @@ const imageAdapter: MdxComponentAdapter = {if (title !== undefined) {imageProps.push({ name: "title", value: title });}+ const image = {+ type: "element" as const,+ syntax: "mdx" as const,+ tag: "img",+ props: imageProps,+ children: [],+ mdxMode: "text" as const,+ };+ if (original?.type === "element" && original.tag === "img") {+ return image;+ }return {type: "element",syntax: "mdx",tag: "p",props: [],- children: [- {- type: "element",- syntax: "mdx",- tag: "img",- props: imageProps,- children: [],- mdxMode: "text",- },- ],+ children: [image],mdxMode: "flow",};},fromMdx: (node) => {- const image = readMdxImage(node);- if (image === undefined) {+ const result = readMdxImage(node);+ if (result === undefined) {return;}+ const { image, nodePath } = result;const props: MaterializedComponentProp[] = [];const names = new Set<string>();for (const [propIndex, prop] of image.props.entries()) {@@ -240,14 +287,14 @@ const imageAdapter: MdxComponentAdapter = {if (prop.value !== "") {props.push({prop,- source: { nodePath: [0], propIndex },+ source: { nodePath, propIndex },});}}const sourceIndex = image.props.findIndex(({ name }) => name === "src");const source = image.props[sourceIndex];if (sourceIndex !== -1 && typeof source?.value === "string") {- const sourceLocation = { nodePath: [0], propIndex: sourceIndex };+ const sourceLocation = { nodePath, propIndex: sourceIndex };for (const name of ["width", "height"] as const) {props.push({prop: { name, value: source.value },@@ -268,6 +315,33 @@ const imageAdapter: MdxComponentAdapter = {}return { children: [], props };},+ fromNamedMdx: (node) => {+ if (node.children.length > 0) {+ return;+ }+ const materializedProps: MaterializedComponentProp[] =+ materializeNamedProps(node.props);+ const sourceIndex = materializedProps.findIndex(+ ({ prop }) => prop.name === "src" && typeof prop.value === "string"+ );+ const source = materializedProps[sourceIndex]?.prop;+ if (sourceIndex === -1 || typeof source?.value !== "string") {+ return { children: [], props: materializedProps };+ }+ const names = new Set(materializedProps.map(({ prop }) => prop.name));+ const sourceLocation = { nodePath: [], propIndex: sourceIndex };+ for (const name of ["width", "height", "alt"] as const) {+ if (names.has(name)) {+ continue;+ }+ materializedProps.push({+ prop: { name, value: source.value },+ source: sourceLocation,+ requiresAssetReference: true,+ });+ }+ return { children: [], props: materializedProps };+ },};const componentAdapters = new Map<Instance["component"], MdxComponentAdapter>([@@ -275,6 +349,82 @@ const componentAdapters = new Map<Instance["component"], MdxComponentAdapter>([[imageAdapter.component, imageAdapter],]);+export const hasMdxComponentAdapter = (component: Instance["component"]) =>+ componentAdapters.has(component);++export const getMdxNamedTemplateSyntax = ({+ templateName,+}: {+ templateName: string;+ component?: Instance["component"];+}) =>+ isMdxTemplateComponentName(templateName)+ ? ("jsx" as const)+ : ("ws-element" as const);++export const getMdxNamedTemplateComponentBinding = ({+ instance,+ node,+}: {+ instance: Instance;+ node: Extract<MdxAuthoredNode, { type: "template" }>;+}) => componentAdapters.get(instance.component)?.fromNamedMdx?.(node);++export const getMdxStandardTemplateBinding = (node: MdxAuthoredNode) => {+ const adapted = materializeMdxComponent(node);+ if (adapted !== undefined) {+ return {+ key: `component:${adapted.component}`,+ props: adapted.props.map(({ prop }) => prop),+ propBindings: adapted.props.map(({ source, requiresAssetReference }) => ({+ source,+ requiresAssetReference,+ })),+ componentChildren: adapted.children,+ };+ }+ if (node.type === "element") {+ return {+ key: `element:${node.tag}`,+ props: node.props,+ propBindings: undefined,+ componentChildren: undefined,+ };+ }+};++export const getMdxStandardTemplateKeyForInstance = ({+ instance,+ metas,+ props,+ htmlTagsByInstanceId,+}: {+ instance: Instance;+ metas: ReadonlyMap<Instance["component"], WsComponentMeta>;+ props?: ReadonlyMap<Prop["id"], Prop>;+ htmlTagsByInstanceId?: ReadonlyMap<Instance["id"], string>;+}) => {+ if (componentAdapters.has(instance.component)) {+ return `component:${instance.component}`;+ }+ const tag = getHtmlTagFromInstance({+ instance,+ metas,+ props,+ htmlTagsByInstanceId,+ });+ const descriptor = getContentBlockMdxTemplateDescriptor({+ component: instance.component,+ tag,+ });+ if (descriptor !== undefined) {+ return descriptor.resolutionKey;+ }+ if (tag !== undefined) {+ return `element:${tag}`;+ }+};+export const serializeMdxComponent = ({instance,props,@@ -295,15 +445,44 @@ export const serializeMdxComponentFallback = ({props,instanceProps,templateName,+ mdxMode,+ jsxPropContext,+ children: authoredChildren,}: {instance: Instance;props: readonly MdxAuthoredProp[];instanceProps: readonly Prop[];templateName?: string;-}): MdxAuthoredNode | undefined => {+ mdxMode?: MdxMode;+ jsxPropContext?: Readonly<{+ acceptsHtmlAttributes: boolean;+ componentPropNames: readonly string[];+ }>;+ children?: readonly MdxAuthoredNode[];+}): Extract<MdxAuthoredNode, { type: "template" }> | undefined => {const adapter = componentAdapters.get(instance.component);if (adapter === undefined) {- return;+ if (templateName === undefined || authoredChildren === undefined) {+ return;+ }+ const children = authoredChildren ?? [];+ return {+ type: "template",+ syntax: "jsx",+ selfClosing: children.length === 0,+ name: templateName,+ props: mapAttributeNames({+ attributes: props,+ direction: "instance-to-jsx",+ acceptsHtmlAttributes: jsxPropContext?.acceptsHtmlAttributes ?? false,+ componentPropNames:+ jsxPropContext === undefined+ ? undefined+ : new Set(jsxPropContext.componentPropNames),+ }),+ children,+ mdxMode: mdxMode ?? "flow",+ };}const authoredProps: MdxAuthoredProp[] = [];const propNames = new Set<string>();@@ -338,18 +517,49 @@ export const serializeMdxComponentFallback = ({}return {type: "template",+ syntax: getMdxNamedTemplateSyntax({+ templateName: templateName ?? adapter.component,+ component: instance.component,+ }),+ selfClosing: children.length === 0,name: templateName ?? adapter.component,props: mapAttributeNames({attributes: authoredProps,direction: "instance-to-jsx",- acceptsHtmlAttributes: true,+ acceptsHtmlAttributes: jsxPropContext?.acceptsHtmlAttributes ?? true,+ componentPropNames:+ jsxPropContext === undefined+ ? undefined+ : new Set(jsxPropContext.componentPropNames),}),children,- mdxMode: children.length === 0 ? "flow" : "text",+ mdxMode: children.length === 0 ? (mdxMode ?? "flow") : "text",};};-export const materializeMdxComponent = (node: MdxAuthoredNode) => {+export const materializeMdxComponent = (+ node: MdxAuthoredNode,+ registeredComponent?: Instance["component"]+) => {+ if (node.type === "template") {+ if (node.syntax !== "jsx") {+ return;+ }+ const adapter = componentAdapters.get(node.name);+ const component = adapter?.fromNamedMdx?.(node);+ 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()) {const component = adapter.fromMdx(node);if (component !== undefined) {diff --git a/packages/project-build/src/runtime/mdx-diagnostics.ts b/packages/project-build/src/runtime/mdx-diagnostics.tsindex d7e8010412..0d06db99b0 100644--- a/packages/project-build/src/runtime/mdx-diagnostics.ts+++ b/packages/project-build/src/runtime/mdx-diagnostics.ts@@ -1,3 +1,7 @@+/**+ * Translates parser and rendered content-model failures into source-located+ * Content Block diagnostics that Builder and MCP consumers can display.+ */import {createMdxSourceDiagnostics,type MdxAuthoredNode,diff --git a/packages/project-build/src/runtime/mdx-materialization.test.ts b/packages/project-build/src/runtime/mdx-materialization.test.tsindex 13382ac2d1..e28c6dad22 100644--- a/packages/project-build/src/runtime/mdx-materialization.test.ts+++ b/packages/project-build/src/runtime/mdx-materialization.test.ts@@ -978,7 +978,7 @@ describe("materializeMdxTemplates", () => {classProp.value = "changed";expect(await serializeMdxAuthoredContent({ root, fragment: next })).toBe(- '<ws.element ws:name="Card" class="legacy" className="changed" />\n'+ '<Card class="legacy" className="changed" />\n');});@@ -1041,7 +1041,7 @@ describe("materializeMdxTemplates", () => {classProp.value = "changed";expect(await serializeMdxAuthoredContent({ root, fragment: next })).toBe(- '<ws.element ws:name="Card" class="changed" className />\n'+ '<Card class="changed" className />\n');});diff --git a/packages/project-build/src/runtime/mdx-materialization.ts b/packages/project-build/src/runtime/mdx-materialization.tsindex 9b61783b67..504251d5ed 100644--- a/packages/project-build/src/runtime/mdx-materialization.ts+++ b/packages/project-build/src/runtime/mdx-materialization.ts@@ -1,3 +1,7 @@+/**+ * Clones resolved Content Block templates into runtime fragments, applies+ * authored MDX props and children, and records their source provenance.+ */import hash from "@emotion/hash";import { migrateCodeTextPropMutable } from "@webstudio-is/project-migrations";import type { AssetValueReference } from "@webstudio-is/content-engine";@@ -40,7 +44,7 @@ import { getHtmlAttributeType } from "./html-attribute-utils";import { parseMdxStaticProp, type MdxStaticPropType } from "./mdx-static-props";import { getMdxPropValuePathKey } from "./mdx-asset-references";-const getMdxPropEligibility = ({+export const getMdxPropEligibility = ({capabilities,instance,prop,@@ -83,7 +87,7 @@ const getMdxPropEligibility = ({: ({ editable: false, reason: "incompatible" } as const);};-const getMdxPropBinding = ({+export const getMdxPropBinding = ({capabilities,instance,prop,@@ -118,6 +122,53 @@ const getMdxPropBinding = ({}};+export const resolveMdxPropCollisions = ({+ authoredProps,+ mappedProps,+ componentPropNames,+ acceptsHtmlAttributes,+ canUseProp,+}: {+ authoredProps: readonly MdxAuthoredProp[];+ mappedProps: readonly MdxAuthoredProp[];+ componentPropNames: ReadonlySet<string>;+ acceptsHtmlAttributes: boolean;+ canUseProp: (index: number) => boolean;+}) => {+ const propIndexesByInstanceName = new Map<string, number[]>();+ for (const [index, prop] of mappedProps.entries()) {+ const indexes = propIndexesByInstanceName.get(prop.name) ?? [];+ indexes.push(index);+ propIndexesByInstanceName.set(prop.name, indexes);+ }+ const conflictingPropIndexes = new Set<number>();+ const collidedInstancePropNames = new Set<string>();+ for (const [instancePropName, indexes] of propIndexesByInstanceName) {+ if (indexes.length < 2) {+ continue;+ }+ collidedInstancePropNames.add(instancePropName);+ const canonicalJsxName = getJsxPropName({+ instancePropName,+ componentPropNames,+ acceptsHtmlAttributes,+ });+ const orderedIndexes = indexes.toSorted((left, right) => {+ const leftIsCanonical = authoredProps[left]?.name === canonicalJsxName;+ const rightIsCanonical = authoredProps[right]?.name === canonicalJsxName;+ return Number(rightIsCanonical) - Number(leftIsCanonical);+ });+ const selectedIndex =+ orderedIndexes.find((index) => canUseProp(index)) ?? orderedIndexes[0];+ for (const index of indexes) {+ if (index !== selectedIndex) {+ conflictingPropIndexes.add(index);+ }+ }+ }+ return { conflictingPropIndexes, collidedInstancePropNames };+};+export type MdxJsxPropContext = Readonly<{acceptsHtmlAttributes: boolean;componentPropNames: readonly string[];@@ -141,6 +192,10 @@ export type MaterializedMdxTemplate =}>[];preservedJsxPropNames?: readonly string[];ignoredJsxPropNames: readonly string[];+ htmlTags?: readonly Readonly<{+ instanceId: Instance["id"];+ tag: string;+ }>[];}>| Readonly<{type: "unresolved-template";@@ -373,43 +428,23 @@ export const materializeMdxTemplates = async ({acceptsHtmlAttributes,}),}));- const propIndexesByInstanceName = new Map<string, number[]>();- for (const [index, prop] of mappedReferenceProps.entries()) {- const indexes = propIndexesByInstanceName.get(prop.name) ?? [];- indexes.push(index);- propIndexesByInstanceName.set(prop.name, indexes);- }- const conflictingPropIndexes = new Set<number>();- const collidedInstancePropNames = new Set<string>();- for (const [instancePropName, indexes] of propIndexesByInstanceName) {- if (indexes.length < 2) {- continue;- }- collidedInstancePropNames.add(instancePropName);- const canonicalJsxName = getJsxPropName({- instancePropName,+ const { conflictingPropIndexes, collidedInstancePropNames } =+ resolveMdxPropCollisions({+ authoredProps: reference.props,+ mappedProps: mappedReferenceProps,componentPropNames: declaredJsxPropNames,acceptsHtmlAttributes,- });- const orderedIndexes = indexes.toSorted((left, right) => {- const leftIsCanonical =- reference.props[left]?.name === canonicalJsxName;- const rightIsCanonical =- reference.props[right]?.name === canonicalJsxName;- return Number(rightIsCanonical) - Number(leftIsCanonical);- });- const existingProp = findProp(- materializedData.props.values(),- materializedRootId,- instancePropName- );- const selectedIndex =- orderedIndexes.find((index) => {+ canUseProp: (index) => {const authoredProp = reference.props[index];const instanceProp = mappedReferenceProps[index];if (authoredProp === undefined || instanceProp === undefined) {return false;}+ const existingProp = findProp(+ materializedData.props.values(),+ materializedRootId,+ instanceProp.name+ );return (getMdxPropBinding({capabilities,@@ -424,13 +459,8 @@ export const materializeMdxTemplates = async ({: undefined,}) !== undefined);- }) ?? orderedIndexes[0];- for (const index of indexes) {- if (index !== selectedIndex) {- conflictingPropIndexes.add(index);- }- }- }+ },+ });const propNameMappings: Array<{jsxPropName: string;instancePropName: string;@@ -474,12 +504,25 @@ export const materializeMdxTemplates = async ({);}const existingProp = canonicalExistingProp ?? aliasedExistingProp;+ const propBinding = reference.propBindings?.[index];const assetReference = assetReferenceByPath.get(getMdxPropValuePathKey({- nodePath: reference.path,- propIndex: index,+ nodePath:+ propBinding?.source === undefined+ ? reference.path+ : [...reference.path, ...propBinding.source.nodePath],+ propIndex: propBinding?.source?.propIndex ?? index,}));+ if (+ propBinding?.requiresAssetReference === true &&+ assetReference === undefined+ ) {+ if (existingProp !== undefined) {+ materializedData.props.delete(existingProp.id);+ }+ continue;+ }const rawBinding =assetReference !== undefined? ({ type: "asset", value: assetReference.assetId } as const)@@ -487,6 +530,7 @@ export const materializeMdxTemplates = async ({? ({ type: "boolean", value: true } as const): ({ type: "string", value: authoredProp.value } as const);if (+ instancePropName === "code" &&migrateCodeTextPropMutable({instance: rootInstance,prop: createPropValue({@@ -665,10 +709,14 @@ export const materializeMdxTemplates = async ({}}+ const materializedFragment = extractWebstudioFragment(+ materializedData,+ materializedRootId+ );materializedTemplates.push({type: "resolved-template",reference,- fragment: extractWebstudioFragment(materializedData, materializedRootId),+ fragment: materializedFragment,editablePropNames,jsxPropContext: {acceptsHtmlAttributes,@@ -686,6 +734,14 @@ export const materializeMdxTemplates = async ({: [];}),ignoredJsxPropNames: Array.from(ignoredJsxPropNames),+ htmlTags: materializedFragment.instances.flatMap((instance) => {+ const tag = getHtmlTagFromInstance({+ instance,+ metas,+ props: materializedData.props,+ });+ return tag === undefined ? [] : [{ instanceId: instance.id, tag }];+ }),});}return {diff --git a/packages/project-build/src/runtime/mdx-paste.test.ts b/packages/project-build/src/runtime/mdx-paste.test.tsindex 5afd67f5eb..0a11edf7f0 100644--- a/packages/project-build/src/runtime/mdx-paste.test.ts+++ b/packages/project-build/src/runtime/mdx-paste.test.ts@@ -9,6 +9,7 @@ import type { BuilderState } from "../state/builder-state";import { executeBuilderRuntimeOperation } from "./registry";import type { BuilderRuntimeMutation } from "./mutation";import type { MdxPasteResult } from "./mdx-paste";+import { InvalidMdxTemplateStructureError } from "./mdx-template-resolution";const createState = (): BuilderState => ({pages: createDefaultPages({ rootInstanceId: "block" }),@@ -91,4 +92,66 @@ describe("instances.insertMdxText", () => {})).rejects.toMatchObject({ code: "BAD_REQUEST" });});++ test("inserts Markdown outside a Content Block without template resolution", async () => {+ const state = createState();+ const instances = state.instances;+ const root = instances?.get("block");+ if (root === undefined || instances === undefined) {+ throw new Error("Expected root instance");+ }+ root.component = elementComponent;+ root.tag = "main";+ root.children = [];+ instances.delete("templates");+ instances.delete("hero");++ const mutation = await executeBuilderRuntimeOperation<+ BuilderRuntimeMutation<MdxPasteResult>+ >({+ id: "instances.insertMdxText",+ state,+ input: { parentInstanceId: "block", source: "# Heading" },+ context: { createId: createId(), projectId: "project" },+ });++ expect(mutation.result.rootInstanceIds).toHaveLength(1);+ expect(mutation.result.diagnostics).toEqual([]);+ });++ test.each([+ ["without", 0],+ ["with multiple", 2],+ ])(+ "rejects insertion into a block %s Templates containers",+ async (_, count) => {+ const state = createState();+ const instances = state.instances;+ const block = instances?.get("block");+ if (block === undefined || instances === undefined) {+ throw new Error("Expected Content Block");+ }+ if (count === 0) {+ block.children = [];+ instances.delete("templates");+ } else {+ block.children.push({ type: "id", value: "templates-2" });+ instances.set("templates-2", {+ type: "instance",+ id: "templates-2",+ component: blockTemplateComponent,+ children: [],+ });+ }++ await expect(+ executeBuilderRuntimeOperation({+ id: "instances.insertMdxText",+ state,+ input: { parentInstanceId: "block", source: "# Heading" },+ context: { createId: createId(), projectId: "project" },+ })+ ).rejects.toBeInstanceOf(InvalidMdxTemplateStructureError);+ }+ );});diff --git a/packages/project-build/src/runtime/mdx-paste.ts b/packages/project-build/src/runtime/mdx-paste.tsindex 8d32c6521d..f236aa1635 100644--- a/packages/project-build/src/runtime/mdx-paste.ts+++ b/packages/project-build/src/runtime/mdx-paste.ts@@ -1,3 +1,7 @@+/**+ * Handles one-time insertion of pasted MDX into a Content Block by using the+ * same template resolution and materialization rules as an MDX-backed source.+ */import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";import {blockComponent,@@ -22,7 +26,10 @@ import {} from "./instances";import { materializeMdxAuthoredContent } from "./mdx-authored-content";import { materializeMdxTemplates } from "./mdx-materialization";-import { resolveMdxTemplates } from "./mdx-template-resolution";+import {+ assertMdxTemplateStructure,+ resolveMdxTemplates,+} from "./mdx-template-resolution";import type { BuilderRuntimeMutation } from "./mutation";export const insertMdxTextInput = z.object({@@ -114,8 +121,12 @@ export const insertMdxText = async ({document,identity,instances: data.instances,+ props: data.props,metas: componentMetas,});+ if (destinationBlock !== undefined) {+ assertMdxTemplateStructure(resolution);+ }const templateMaterialization = await materializeMdxTemplates({identity,resolution,@@ -127,6 +138,7 @@ export const insertMdxText = async ({identity,document,templateMaterialization,+ metas: componentMetas,});const mutation = insertFragment(state,@@ -146,7 +158,10 @@ export const insertMdxText = async ({...mutation.result,parentInstanceId:mutation.result.parentInstanceId ?? input.parentInstanceId,- diagnostics: [...templateMaterialization.diagnostics],+ diagnostics: [+ ...templateMaterialization.diagnostics,+ ...(authored.diagnostics ?? []),+ ],},};};diff --git a/packages/project-build/src/runtime/mdx-source.test.ts b/packages/project-build/src/runtime/mdx-source.test.tsindex a8a94b229c..21973cdd99 100644--- a/packages/project-build/src/runtime/mdx-source.test.ts+++ b/packages/project-build/src/runtime/mdx-source.test.ts@@ -1,56 +1,2320 @@import { describe, expect, test } from "vitest";+import { serializeMdxDocument } from "@webstudio-is/content-engine/mdx";import {type Asset,blockComponent,blockTemplateComponent,+ elementComponent,type ContentBlockExternalContentIdentity,type WebstudioData,} from "@webstudio-is/sdk";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";-import { serializeMdxAuthoredContent } from "./mdx-authored-content";+import {+ rebaseMdxAuthoredContent,+ serializeMdxAuthoredContent,+ serializeMdxTemplateInsertion,+} from "./mdx-authored-content";+import { extractWebstudioFragment } from "./fragment";import { materializeMdxSource } from "./mdx-source";+import { InvalidMdxTemplateStructureError } from "./mdx-template-resolution";++const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:revision",+ contentRef: "article.mdx",+ format: "mdx",+ renderScope: "page",+};++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: [],+ },+ ],+ ]),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+};++const createSourceData = () => structuredClone(data);++const addCardTemplate = (sourceData: Omit<WebstudioData, "pages">) => {+ sourceData.instances.set("card", {+ type: "instance",+ id: "card",+ component: elementComponent,+ tag: "section",+ label: "Card",+ children: [{ type: "id", value: "default-content" }],+ });+ sourceData.instances.set("default-content", {+ type: "instance",+ id: "default-content",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Template default" }],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "card",+ });+};++const createAssetSourceData = () => {+ const sourceData = createSourceData();+ sourceData.assetFolders = new Map();+ sourceData.assets = new Map<string, Asset>([+ [+ "article",+ {+ id: "article",+ projectId: "project",+ type: "file",+ format: "mdx",+ name: "article_hash.mdx",+ filename: "article",+ size: 0,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: {},+ },+ ],+ [+ "hero",+ {+ id: "hero",+ projectId: "project",+ type: "image",+ format: "png",+ name: "hero_hash.png",+ filename: "hero",+ size: 0,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: "Mountain sunrise",+ meta: { width: 1600, height: 900 },+ },+ ],+ ]);+ return sourceData;+};++describe("materializeMdxSource", () => {+ test.each([+ ["without", 0],+ ["with multiple", 2],+ ])("rejects a Content Block %s Templates containers", async (_, count) => {+ const sourceData = createSourceData();+ const block = sourceData.instances.get("block");+ if (block === undefined) {+ throw new Error("Expected Content Block");+ }+ if (count === 0) {+ block.children = [];+ sourceData.instances.delete("templates");+ } else {+ block.children.push({ type: "id", value: "templates-2" });+ sourceData.instances.set("templates-2", {+ type: "instance",+ id: "templates-2",+ component: blockTemplateComponent,+ children: [],+ });+ }++ await expect(+ materializeMdxSource({+ source: "# Heading\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ })+ ).rejects.toBeInstanceOf(InvalidMdxTemplateStructureError);+ });++ test("materializes and preserves component-style JSX template syntax", async () => {+ const sourceData = createSourceData();+ sourceData.instances.set("card", {+ type: "instance",+ id: "card",+ component: elementComponent,+ tag: "section",+ label: "Card",+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "card",+ });++ const result = await materializeMdxSource({+ source: "<Card>Content</Card>\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ expect(result.root.fragment.instances).toEqual([+ expect.objectContaining({+ tag: "section",+ children: [{ type: "text", value: "Content" }],+ }),+ ]);+ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe("<Card>Content</Card>\n");+ });++ test("keeps a semantic custom template with a reserved component name addressable after an edit", async () => {+ const sourceData = createSourceData();+ sourceData.instances.set("heading", {+ type: "instance",+ id: "heading",+ component: elementComponent,+ tag: "h1",+ label: "Image",+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "heading",+ });+ const result = await materializeMdxSource({+ source: "# Hello\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const fragment = structuredClone(result.root.fragment);+ const heading = fragment.instances.find(({ tag }) => tag === "h1");+ if (heading === undefined) {+ throw new Error("Expected heading");+ }+ fragment.props.push({+ id: "heading-title",+ instanceId: heading.id,+ name: "title",+ type: "string",+ value: "Greeting",+ });++ const source = await serializeMdxAuthoredContent({+ root: result.root,+ fragment,+ });+ expect(source).toBe('<Image title="Greeting">Hello</Image>\n');++ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ expect(reloaded.diagnostics).toEqual([]);+ expect(reloaded.root.fragment.instances).toEqual([+ expect.objectContaining({ tag: "h1" }),+ ]);+ });++ test("replaces custom template defaults with explicit JSX children", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ const source = `<Card>+ ## Launch offer+</Card>+`;++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const card = result.root.fragment.instances.find(+ (instance) => instance.tag === "section"+ );+ const heading = result.root.fragment.instances.find(+ (instance) => instance.tag === "h2"+ );+ if (card === undefined || heading === undefined) {+ throw new Error("Expected Card and authored heading instances");+ }++ expect(card.children).toEqual([{ type: "id", value: heading.id }]);+ expect(heading.children).toEqual([{ type: "text", value: "Launch offer" }]);+ expect(+ result.root.fragment.instances.some(+ (instance) => instance.id === "default-content"+ )+ ).toBe(false);+ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe(source);+ });++ test("keeps custom template defaults for self-closing JSX", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);++ const result = await materializeMdxSource({+ source: "<Card />\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const card = result.root.fragment.instances.find(+ (instance) => instance.tag === "section"+ );+ const defaultContent = result.root.fragment.instances.find(+ (instance) => instance.tag === "p"+ );+ if (card === undefined || defaultContent === undefined) {+ throw new Error("Expected Card template default instances");+ }++ expect(card.children).toEqual([{ type: "id", value: defaultContent.id }]);+ expect(defaultContent.children).toEqual([+ { type: "text", value: "Template default" },+ ]);+ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe("<Card />\n");+ });++ test("treats paired empty JSX as an explicit empty child override", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);++ const result = await materializeMdxSource({+ source: "<Card></Card>\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const card = result.root.fragment.instances.find(+ (instance) => instance.tag === "section"+ );++ expect(card?.children).toEqual([]);+ expect(+ result.root.fragment.instances.some((instance) => instance.tag === "p")+ ).toBe(false);+ const serialized = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ });+ const reparsed = await materializeMdxSource({+ source: serialized,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ expect(serialized).toContain("<Card>");+ expect(serialized).not.toContain("<Card />");+ expect(+ reparsed.root.fragment.instances.find(+ (instance) => instance.tag === "section"+ )?.children+ ).toEqual([]);+ });++ test("persists edits to inherited descendants as explicit JSX children", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ sourceData.styleSources.set("paragraph-style", {+ type: "local",+ id: "paragraph-style",+ });+ sourceData.styleSourceSelections.set("default-content", {+ instanceId: "default-content",+ values: ["paragraph-style"],+ });+ const result = await materializeMdxSource({+ source: "<Card />\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const edited = structuredClone(result.root.fragment);+ const paragraph = edited.instances.find((instance) => instance.tag === "p");+ if (paragraph === undefined) {+ throw new Error("Expected inherited paragraph");+ }+ paragraph.children = [{ type: "text", value: "Edited content" }];++ const source = serializeMdxDocument(+ await rebaseMdxAuthoredContent({+ root: result.root,+ fragment: edited,+ latest: result.root.document,+ })+ );+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(source).toContain("<Card>");+ expect(source).not.toContain("<Card />");+ expect(+ reloaded.root.fragment.instances.find((instance) => instance.tag === "p")+ ?.children+ ).toEqual([{ type: "text", value: "Edited content" }]);+ const reloadedParagraph = reloaded.root.fragment.instances.find(+ ({ tag }) => tag === "p"+ );+ expect(reloaded.root.fragment.styleSourceSelections).toContainEqual({+ instanceId: reloadedParagraph?.id,+ values: [expect.stringMatching(/^mdx-/)],+ });++ const editedAgain = structuredClone(reloaded.root.fragment);+ const paragraphAgain = editedAgain.instances.find(({ tag }) => tag === "p");+ if (paragraphAgain === undefined) {+ throw new Error("Expected overlaid paragraph");+ }+ paragraphAgain.children = [{ type: "text", value: "Edited again" }];+ const sourceAfterSecondEdit = await serializeMdxAuthoredContent({+ root: reloaded.root,+ fragment: editedAgain,+ });+ const reloadedAgain = await materializeMdxSource({+ source: sourceAfterSecondEdit,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const finalParagraph = reloadedAgain.root.fragment.instances.find(+ ({ tag }) => tag === "p"+ );+ expect(finalParagraph?.children).toEqual([+ { type: "text", value: "Edited again" },+ ]);+ expect(reloadedAgain.root.fragment.styleSourceSelections).toContainEqual({+ instanceId: finalParagraph?.id,+ values: [expect.stringMatching(/^mdx-/)],+ });+ });++ test("persists tag edits to inherited element descendants", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ const result = await materializeMdxSource({+ source: "<Card />\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const edited = structuredClone(result.root.fragment);+ const paragraph = edited.instances.find(({ tag }) => tag === "p");+ if (paragraph === undefined) {+ throw new Error("Expected inherited paragraph");+ }+ paragraph.tag = "h3";++ const source = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: edited,+ });+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(source).toContain("### Template default");+ expect(+ reloaded.root.fragment.instances.find(({ tag }) => tag === "h3")+ ).toBeDefined();+ });++ test("preserves a component descendant while authoring inherited content", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ const button = sourceData.instances.get("default-content");+ if (button === undefined) {+ throw new Error("Expected Card content");+ }+ sourceData.instances.set(button.id, {+ ...button,+ component: "Button",+ tag: undefined,+ children: [{ type: "text", value: "Template action" }],+ });+ sourceData.styleSources.set("button-style", {+ type: "local",+ id: "button-style",+ });+ sourceData.styleSourceSelections.set(button.id, {+ instanceId: button.id,+ values: ["button-style"],+ });++ const result = await materializeMdxSource({+ source: "<Card />\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const edited = structuredClone(result.root.fragment);+ const editedButton = edited.instances.find(+ ({ component }) => component === "Button"+ );+ if (editedButton === undefined) {+ throw new Error("Expected inherited Button");+ }+ editedButton.children = [{ type: "text", value: "Authored action" }];++ const source = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: edited,+ });+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const reloadedButton = reloaded.root.fragment.instances.find(+ ({ component }) => component === "Button"+ );++ expect(source).toContain("<Card>");+ expect(source).toContain("<button>Authored action</button>");+ expect(reloadedButton?.children).toEqual([+ { type: "text", value: "Authored action" },+ ]);+ expect(reloaded.root.fragment.styleSourceSelections).toContainEqual({+ instanceId: reloadedButton?.id,+ values: [expect.stringMatching(/^mdx-/)],+ });+ });++ test("preserves a composite template edit made before its first save", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ sourceData.styleSources.set("paragraph-style", {+ type: "local",+ id: "paragraph-style",+ });+ sourceData.styleSourceSelections.set("default-content", {+ instanceId: "default-content",+ values: ["paragraph-style"],+ });+ const pristineFragment = extractWebstudioFragment(sourceData, "card");+ const edited = structuredClone(pristineFragment);+ const paragraph = edited.instances.find(+ ({ id }) => id === "default-content"+ );+ if (paragraph === undefined) {+ throw new Error("Expected inserted Card content");+ }+ paragraph.children = [{ type: "text", value: "Immediate edit" }];+ const empty = await materializeMdxSource({+ source: "",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ const source = serializeMdxDocument(+ await rebaseMdxAuthoredContent({+ root: empty.root,+ fragment: edited,+ latest: empty.root.document,+ insertedTemplates: new Map([+ ["card", { templateName: "Card", pristineFragment }],+ ]),+ })+ );+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const reloadedParagraph = reloaded.root.fragment.instances.find(+ ({ tag }) => tag === "p"+ );++ expect(source).toContain("<Card>");+ expect(source).toContain("Immediate edit");+ expect(reloadedParagraph?.children).toEqual([+ { type: "text", value: "Immediate edit" },+ ]);+ expect(reloaded.root.fragment.styleSourceSelections).toContainEqual({+ instanceId: reloadedParagraph?.id,+ values: [expect.stringMatching(/^mdx-/)],+ });+ });++ test("preserves default Image Assets during an unrelated first-save edit", async () => {+ const sourceData = createAssetSourceData();+ addCardTemplate(sourceData);+ const card = sourceData.instances.get("card");+ if (card === undefined) {+ throw new Error("Expected Card template");+ }+ sourceData.instances.set("default-image", {+ type: "instance",+ id: "default-image",+ component: "Image",+ children: [],+ });+ card.children.push({ type: "id", value: "default-image" });+ for (const name of ["src", "width", "height", "alt"] as const) {+ sourceData.props.set(`default-image-${name}`, {+ id: `default-image-${name}`,+ instanceId: "default-image",+ name,+ type: "asset",+ value: "hero",+ });+ }+ const pristineFragment = extractWebstudioFragment(sourceData, "card");+ const edited = structuredClone(pristineFragment);+ const paragraph = edited.instances.find(+ ({ id }) => id === "default-content"+ );+ if (paragraph === undefined) {+ throw new Error("Expected inserted Card content");+ }+ paragraph.children = [{ type: "text", value: "Immediate edit" }];+ const empty = await materializeMdxSource({+ source: "",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ const source = serializeMdxDocument(+ await rebaseMdxAuthoredContent({+ root: empty.root,+ fragment: edited,+ latest: empty.root.document,+ insertedTemplates: new Map([+ ["card", { templateName: "Card", pristineFragment }],+ ]),+ })+ );+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const image = reloaded.root.fragment.instances.find(+ ({ component }) => component === "Image"+ );++ expect(source).toContain("Immediate edit");+ expect(source).toContain("<Image />");+ expect(reloaded.root.fragment.props).toContainEqual(+ expect.objectContaining({+ instanceId: image?.id,+ name: "src",+ type: "asset",+ value: "hero",+ })+ );+ });++ test("keeps template defaults inherited after an immediate root prop edit", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ const pristineFragment = extractWebstudioFragment(sourceData, "card");+ const edited = structuredClone(pristineFragment);+ edited.props.push({+ id: "card-title",+ instanceId: "card",+ name: "title",+ type: "string",+ value: "Edited title",+ });+ const empty = await materializeMdxSource({+ source: "",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ const source = serializeMdxDocument(+ await rebaseMdxAuthoredContent({+ root: empty.root,+ fragment: edited,+ latest: empty.root.document,+ insertedTemplates: new Map([+ ["card", { templateName: "Card", pristineFragment }],+ ]),+ })+ );+ const defaultContent = sourceData.instances.get("default-content");+ if (defaultContent === undefined) {+ throw new Error("Expected Card default content");+ }+ defaultContent.children = [+ { type: "text", value: "Updated template default" },+ ];+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(source).toBe('<Card title="Edited title" />\n');+ expect(+ reloaded.root.fragment.instances.find(({ tag }) => tag === "p")?.children+ ).toEqual([{ type: "text", value: "Updated template default" }]);+ });++ test("treats a removed fresh-insertion root prop as inheriting the template default", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ sourceData.props.set("card-title", {+ id: "card-title",+ instanceId: "card",+ name: "title",+ type: "string",+ value: "Template title",+ });+ const pristineFragment = extractWebstudioFragment(sourceData, "card");+ const edited = structuredClone(pristineFragment);+ edited.props = edited.props.filter(({ name }) => name !== "title");+ const empty = await materializeMdxSource({+ source: "",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ const source = serializeMdxDocument(+ await rebaseMdxAuthoredContent({+ root: empty.root,+ fragment: edited,+ latest: empty.root.document,+ insertedTemplates: new Map([+ ["card", { templateName: "Card", pristineFragment }],+ ]),+ })+ );+ const templateTitle = sourceData.props.get("card-title");+ if (templateTitle?.type !== "string") {+ throw new Error("Expected Card title");+ }+ templateTitle.value = "Updated template title";+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const card = reloaded.root.fragment.instances.find(+ ({ tag }) => tag === "section"+ );++ expect(source).toBe("<Card />\n");+ expect(reloaded.root.fragment.props).toContainEqual(+ expect.objectContaining({+ instanceId: card?.id,+ name: "title",+ value: "Updated template title",+ })+ );+ });++ test("keeps authored descendant props and comments in a template overlay", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ sourceData.props.set("default-title", {+ id: "default-title",+ instanceId: "default-content",+ name: "title",+ type: "string",+ value: "Template title",+ });+ sourceData.styleSources.set("paragraph-style", {+ type: "local",+ id: "paragraph-style",+ });+ sourceData.styleSourceSelections.set("default-content", {+ instanceId: "default-content",+ values: ["paragraph-style"],+ });+ const source = `<Card>+ <ws.element ws:tag="p" title="Authored title">A{/* note */}B</ws.element>+</Card>+`;+ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ const serialized = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ });+ const reloaded = await materializeMdxSource({+ source: serialized,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const paragraph = reloaded.root.fragment.instances.find(+ ({ tag }) => tag === "p"+ );++ expect(serialized).toContain('title="Authored title"');+ expect(serialized).toContain("{/* note */}");+ expect(reloaded.root.fragment.props).toContainEqual(+ expect.objectContaining({+ instanceId: paragraph?.id,+ name: "title",+ value: "Authored title",+ })+ );+ expect(reloaded.root.fragment.styleSourceSelections).toContainEqual({+ instanceId: paragraph?.id,+ values: [expect.stringMatching(/^mdx-/)],+ });+ expect(paragraph?.children).toEqual([+ { type: "text", value: "A" },+ { type: "text", value: "B" },+ ]);+ });++ test.each([+ ["an authored override", ' title="Authored title"'],+ ["an inherited value", ""],+ ])(+ "resets %s on an overlaid descendant to the current template default",+ async (_, authoredTitle) => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ sourceData.props.set("default-title", {+ id: "default-title",+ instanceId: "default-content",+ name: "title",+ type: "string",+ value: "Template title",+ });+ const source = `<Card>+ <ws.element ws:tag="p"${authoredTitle}>Authored content</ws.element>+</Card>+`;+ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const reset = structuredClone(result.root.fragment);+ reset.props = reset.props.filter(({ name }) => name !== "title");++ const serialized = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: reset,+ });+ const templateTitle = sourceData.props.get("default-title");+ if (templateTitle === undefined || templateTitle.type !== "string") {+ throw new Error("Expected template title");+ }+ templateTitle.value = "Updated template title";+ const reloaded = await materializeMdxSource({+ source: serialized,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const paragraph = reloaded.root.fragment.instances.find(+ ({ tag }) => tag === "p"+ );++ expect(serialized).not.toContain("title=");+ expect(reloaded.root.fragment.props).toContainEqual(+ expect.objectContaining({+ instanceId: paragraph?.id,+ name: "title",+ value: "Updated template title",+ })+ );+ }+ );++ test("resets Markdown Image descendant props to current template defaults", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ const paragraph = sourceData.instances.get("default-content");+ if (paragraph === undefined) {+ throw new Error("Expected Card default content");+ }+ paragraph.children = [{ type: "id", value: "default-image" }];+ sourceData.instances.set("default-image", {+ type: "instance",+ id: "default-image",+ component: "Image",+ children: [],+ });+ sourceData.props.set("default-image-src", {+ id: "default-image-src",+ instanceId: "default-image",+ name: "src",+ type: "string",+ value: "https://example.com/template.png",+ });+ sourceData.props.set("default-image-alt", {+ id: "default-image-alt",+ instanceId: "default-image",+ name: "alt",+ type: "string",+ value: "Template image",+ });+ const result = await materializeMdxSource({+ source: `<Card>+ +</Card>+`,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const reset = structuredClone(result.root.fragment);+ const image = reset.instances.find(+ ({ component }) => component === "Image"+ );+ reset.props = reset.props.filter(+ ({ instanceId }) => instanceId !== image?.id+ );++ const source = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: reset,+ });+ const defaultSource = sourceData.props.get("default-image-src");+ const defaultAlt = sourceData.props.get("default-image-alt");+ if (defaultSource?.type !== "string" || defaultAlt?.type !== "string") {+ throw new Error("Expected Image template defaults");+ }+ defaultSource.value = "https://example.com/updated.png";+ defaultAlt.value = "Updated template image";+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const reloadedImage = reloaded.root.fragment.instances.find(+ ({ component }) => component === "Image"+ );+ const reloadedImageProps = reloaded.root.fragment.props.filter(+ ({ instanceId }) => instanceId === reloadedImage?.id+ );++ expect(source).toContain("<Image />");+ expect(reloadedImageProps).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "src",+ value: "https://example.com/updated.png",+ }),+ expect.objectContaining({+ name: "alt",+ value: "Updated template image",+ }),+ ])+ );+ });++ test("round-trips an authored Asset Image through a styled composite descendant", async () => {+ const sourceData = createAssetSourceData();+ addCardTemplate(sourceData);+ const image = sourceData.instances.get("default-content");+ if (image === undefined) {+ throw new Error("Expected Card default content");+ }+ sourceData.instances.set(image.id, {+ ...image,+ children: [{ type: "id", value: "default-link" }],+ });+ sourceData.instances.set("default-link", {+ type: "instance",+ id: "default-link",+ component: elementComponent,+ tag: "a",+ children: [{ type: "id", value: "default-image" }],+ });+ sourceData.instances.set("default-image", {+ type: "instance",+ id: "default-image",+ component: "Image",+ children: [],+ });+ sourceData.styleSources.set("image-style", {+ type: "local",+ id: "image-style",+ });+ sourceData.styleSourceSelections.set("default-image", {+ instanceId: "default-image",+ values: ["image-style"],+ });+ const source = `<Card>+ [](/gallery)+</Card>+`;+ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const edited = structuredClone(result.root.fragment);+ const authoredImage = edited.instances.find(+ ({ component }) => component === "Image"+ );+ if (authoredImage === undefined) {+ throw new Error("Expected overlaid Image");+ }+ edited.props.push({+ id: "image-class",+ instanceId: authoredImage.id,+ name: "class",+ type: "string",+ value: "featured",+ });++ const serialized = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: edited,+ });+ const reloaded = await materializeMdxSource({+ source: serialized,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const reloadedImage = reloaded.root.fragment.instances.find(+ ({ component }) => component === "Image"+ );++ expect(serialized).toContain(+ '<Image src="./hero.png" alt="Mountain sunrise" className="featured" />'+ );+ expect(serialized).not.toMatch(/(?:width|height)="\.\/hero\.png"/);+ expect(reloaded.root.fragment.styleSourceSelections).toContainEqual({+ instanceId: reloadedImage?.id,+ values: [expect.stringMatching(/^mdx-/)],+ });+ expect(+ reloaded.root.fragment.props.filter(+ ({ instanceId }) => instanceId === reloadedImage?.id+ )+ ).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: "src", type: "asset", value: "hero" }),+ expect.objectContaining({+ name: "width",+ type: "asset",+ value: "hero",+ }),+ expect.objectContaining({+ name: "height",+ type: "asset",+ value: "hero",+ }),+ ])+ );+ });++ test("applies nested component prop permissions inside a composite template", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ const image = sourceData.instances.get("default-content");+ if (image === undefined) {+ throw new Error("Expected Card default content");+ }+ sourceData.instances.set(image.id, {+ ...image,+ component: "Image",+ tag: undefined,+ children: [],+ });+ sourceData.props.set("image-optimize", {+ id: "image-optimize",+ instanceId: image.id,+ name: "optimize",+ type: "boolean",+ value: true,+ });+ sourceData.props.set("image-quality", {+ id: "image-quality",+ instanceId: image.id,+ name: "quality",+ type: "number",+ value: 60,+ });+ const source = `<Card>+ <Image src="https://example.com/hero.png" alt="Hero" optimize="false" quality="80" />+</Card>+`;++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const materializedImage = result.root.fragment.instances.find(+ ({ component }) => component === "Image"+ );+ const imageProps = result.root.fragment.props.filter(+ ({ instanceId }) => instanceId === materializedImage?.id+ );++ expect(imageProps).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: "optimize", value: true }),+ expect.objectContaining({ name: "quality", value: 60 }),+ ])+ );+ expect(result.diagnostics).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "optimize",+ reason: "design-only",+ }),+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "quality",+ reason: "design-only",+ }),+ ])+ );+ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe(source);+ });++ test("discards diagnostics from a composite overlay that does not match", async () => {+ const sourceData = createSourceData();+ addCardTemplate(sourceData);+ const image = sourceData.instances.get("default-content");+ const card = sourceData.instances.get("card");+ if (image === undefined || card === undefined) {+ throw new Error("Expected Card template");+ }+ sourceData.instances.set(image.id, {+ ...image,+ component: "Image",+ tag: undefined,+ children: [],+ });+ sourceData.instances.set("default-copy", {+ type: "instance",+ id: "default-copy",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Template copy" }],+ });+ card.children.push({ type: "id", value: "default-copy" });+ const source = `<Card>+ <Image src="https://example.com/hero.png" alt="Hero" optimize="false" />+ ## Different shape+</Card>+`;++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "ignored-template-prop",+ templateName: "Image",+ propName: "optimize",+ reason: "design-only",+ }),+ ]);+ });++ test("replaces CodeText template defaults with fenced code", async () => {+ const sourceData = createSourceData();+ sourceData.instances.set("code", {+ type: "instance",+ id: "code",+ component: "CodeText",+ label: "Code Block",+ children: [{ type: "text", value: "templateDefault()" }],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "code",+ });+ const source = "```js\nauthoredCode()\n```\n";++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const code = result.root.fragment.instances.find(+ (instance) => instance.component === "CodeText"+ );+ if (code === undefined) {+ throw new Error("Expected CodeText template instance");+ }++ expect(code.children).toEqual([{ type: "text", value: "authoredCode()" }]);+ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe(source);+ });++ test.each([+ [+ "a semantic fence",+ "Code Block",+ "```javascript\nhello()\n```\n",+ [["language", "javascript"]],+ ],+ [+ "named JSX",+ "CodeText",+ '<CodeText language="javascript" theme="github-light">hello()</CodeText>\n',+ [+ ["language", "javascript"],+ ["theme", "dracula"],+ ],+ ],+ ] as const)(+ "preserves explicit CodeText global defaults from %s over template defaults",+ async (_, templateName, source, expectedProps) => {+ const sourceData = createSourceData();+ sourceData.instances.set("code", {+ type: "instance",+ id: "code",+ component: "CodeText",+ label: templateName,+ children: [{ type: "text", value: "templateDefault()" }],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "code",+ });+ sourceData.props.set("code-language", {+ id: "code-language",+ instanceId: "code",+ name: "language",+ type: "string",+ value: "python",+ });+ sourceData.props.set("code-theme", {+ id: "code-theme",+ instanceId: "code",+ name: "theme",+ type: "string",+ value: "dracula",+ });++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const serialized = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ });+ const reloaded = await materializeMdxSource({+ source: serialized,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(serialized).toBe(source);+ expect(reloaded.root.fragment.props).toEqual(+ expect.arrayContaining(+ expectedProps.map(([name, value]) =>+ expect.objectContaining({ name, value })+ )+ )+ );+ if (templateName === "CodeText") {+ expect(result.diagnostics).toContainEqual(+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "theme",+ reason: "design-only",+ })+ );+ }+ }+ );++ test("round-trips styled semantic CodeText without duplicating content", async () => {+ const sourceData = createSourceData();+ sourceData.instances.set("code", {+ type: "instance",+ id: "code",+ component: "CodeText",+ label: "Code Block",+ children: [{ type: "text", value: "templateDefault()" }],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "code",+ });+ sourceData.styleSources.set("code-style", {+ type: "local",+ id: "code-style",+ });+ sourceData.styleSourceSelections.set("code", {+ instanceId: "code",+ values: ["code-style"],+ });+ sourceData.breakpoints.set("base", { id: "base", label: "Base" });+ sourceData.styles.set("code-style:base:color", {+ breakpointId: "base",+ styleSourceId: "code-style",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ const source = "```js\nauthoredCode()\n```\n";+ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const edited = structuredClone(result.root.fragment);+ const code = edited.instances.find(+ ({ component }) => component === "CodeText"+ );+ if (code === undefined) {+ throw new Error("Expected CodeText");+ }+ code.children = [{ type: "text", value: "changedCode()" }];++ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe(source);+ await expect(+ serializeMdxAuthoredContent({ root: result.root, fragment: edited })+ ).resolves.toBe("```js\nchangedCode()\n```\n");+ });++ test("keeps the CodeText template when an edit requires JSX", async () => {+ const sourceData = createSourceData();+ sourceData.instances.set("code", {+ type: "instance",+ id: "code",+ component: "CodeText",+ label: "Code Block",+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "code",+ });+ const result = await materializeMdxSource({+ source: "```js\nauthoredCode()\n```\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const edited = structuredClone(result.root.fragment);+ const code = edited.instances.find(+ ({ component }) => component === "CodeText"+ );+ if (code === undefined) {+ throw new Error("Expected CodeText");+ }+ edited.props.push({+ id: "code-class",+ instanceId: code.id,+ name: "class",+ type: "string",+ value: "featured",+ });++ const source = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: edited,+ });+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(source).toContain('ws:name="Code Block"');+ expect(source).toContain('className="featured"');+ expect(+ reloaded.root.fragment.instances.find(+ ({ component }) => component === "CodeText"+ )+ ).toBeDefined();+ });++ test("keeps named CodeText JSX instead of collapsing it to Markdown", async () => {+ const sourceData = createSourceData();+ sourceData.instances.set("code", {+ type: "instance",+ id: "code",+ component: "CodeText",+ label: "CodeText",+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "code",+ });+ const source = "<CodeText>authoredCode()</CodeText>\n";++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe(source);+ });++ test("round-trips adapter JSX without requiring a matching template", async () => {+ const sourceData = createSourceData();+ const source = `<CodeText className="example">const ready = true;</CodeText>++Before <Image src="https://example.com/hero.png" alt="Hero" className="featured" /> after.+`;++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(result.diagnostics).toEqual([]);+ expect(+ result.root.fragment.instances.map(({ component }) => component)+ ).toEqual(expect.arrayContaining(["CodeText", "Image"]));+ expect(result.root.fragment.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: "class", value: "example" }),+ expect.objectContaining({ name: "class", value: "featured" }),+ ])+ );+ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe(source);++ const reloaded = await materializeMdxSource({+ source: await serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ }),+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ expect(reloaded.diagnostics).toEqual([]);+ expect(+ reloaded.root.fragment.instances.map(({ component }) => component)+ ).toEqual(expect.arrayContaining(["CodeText", "Image"]));+ });++ test.each([false, true])(+ "resolves built-in JSX alias collisions with template=%s",+ async (withTemplate) => {+ const sourceData = createSourceData();+ if (withTemplate) {+ sourceData.instances.set("image-template", {+ type: "instance",+ id: "image-template",+ component: "Image",+ label: "Image",+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "image-template",+ });+ }+ const source =+ '<Image class="legacy" className="canonical" alt="Example" />\n';++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const classProp = result.root.fragment.props.find(+ ({ name }) => name === "class"+ );++ expect(classProp).toMatchObject({ value: "canonical" });+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "ignored-template-prop",+ templateName: "Image",+ propName: "class",+ reason: "incompatible",+ sourceRange: {+ start: { line: 1, column: 8, offset: 7 },+ end: { line: 1, column: 22, offset: 21 },+ },+ }),+ ]);+ expect(+ await serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).toBe(source);++ const withoutClass = structuredClone(result.root.fragment);+ withoutClass.props = withoutClass.props.filter(+ ({ id }) => id !== classProp?.id+ );+ expect(+ await serializeMdxAuthoredContent({+ root: result.root,+ fragment: withoutClass,+ })+ ).toBe('<Image alt="Example" />\n');++ if (classProp?.type !== "string") {+ throw new Error("Expected Image class prop");+ }+ classProp.value = "changed";+ expect(+ await serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).toBe('<Image class="legacy" className="changed" alt="Example" />\n');+ }+ );++ test("applies component prop permissions to adapter JSX without a template", async () => {+ const sourceData = createSourceData();+ const source =+ '<Image src="https://example.com/hero.png" alt="Hero" optimize="false" quality="80" />\n';++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const image = result.root.fragment.instances.find(+ ({ component }) => component === "Image"+ );+ const propNames = result.root.fragment.props.flatMap((prop) =>+ prop.instanceId === image?.id ? [prop.name] : []+ );++ expect(propNames).toEqual(expect.arrayContaining(["src", "alt"]));+ expect(propNames).not.toEqual(+ expect.arrayContaining(["optimize", "quality"])+ );+ expect(result.diagnostics).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ code: "ignored-template-prop",+ templateName: "Image",+ propName: "optimize",+ reason: "design-only",+ }),+ expect.objectContaining({+ code: "ignored-template-prop",+ templateName: "Image",+ propName: "quality",+ reason: "design-only",+ }),+ ])+ );+ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe(source);+ });++ test("applies a semantic template added after adapter JSX was authored", async () => {+ const sourceData = createSourceData();+ const source = '<CodeText className="example">authoredCode()</CodeText>\n';+ const untemplated = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ expect(untemplated.diagnostics).toEqual([]);++ sourceData.instances.set("code", {+ type: "instance",+ id: "code",+ component: "CodeText",+ label: "Code Block",+ children: [{ type: "text", value: "templateDefault()" }],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "code",+ });+ sourceData.styleSources.set("code-style", {+ type: "local",+ id: "code-style",+ });+ sourceData.styleSourceSelections.set("code", {+ instanceId: "code",+ values: ["code-style"],+ });++ const templated = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const code = templated.root.fragment.instances.find(+ ({ component }) => component === "CodeText"+ );++ expect(code?.children).toEqual([{ type: "text", value: "authoredCode()" }]);+ expect(templated.root.fragment.styleSourceSelections).toContainEqual({+ instanceId: code?.id,+ values: [expect.stringMatching(/^mdx-/)],+ });+ await expect(+ serializeMdxAuthoredContent({+ root: templated.root,+ fragment: templated.root.fragment,+ })+ ).resolves.toBe(source);+ });++ test("materializes Markdown through a matching template and serializes it as Markdown", async () => {+ const sourceData: Omit<WebstudioData, "pages"> = {+ ...createSourceData(),+ styleSources: new Map([+ ["heading-style", { type: "local", id: "heading-style" }],+ ]),+ styleSourceSelections: new Map([+ ["heading", { instanceId: "heading", values: ["heading-style"] }],+ ]),+ styles: new Map([+ [+ "heading-style:base:color",+ {+ breakpointId: "base",+ styleSourceId: "heading-style",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ ]),+ props: new Map([+ [+ "heading-title",+ {+ id: "heading-title",+ instanceId: "heading",+ name: "title",+ type: "string",+ value: "Inherited template title",+ },+ ],+ ]),+ };+ sourceData.instances.set("heading", {+ type: "instance",+ id: "heading",+ component: elementComponent,+ tag: "h1",+ label: "Heading 1",+ children: [{ type: "id", value: "template-mark" }],+ });+ sourceData.instances.set("template-mark", {+ type: "instance",+ id: "template-mark",+ component: elementComponent,+ tag: "span",+ children: [{ type: "text", value: "Template text" }],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "heading",+ });++ const result = await materializeMdxSource({+ source: "# Existing heading\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(result.root.fragment.instances).toEqual([+ expect.objectContaining({+ component: elementComponent,+ tag: "h1",+ children: [{ type: "text", value: "Existing heading" }],+ }),+ ]);+ expect(result.root.fragment.styleSourceSelections).toHaveLength(1);+ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe("# Existing heading\n");+ });++ test("keeps the selected template identity when semantic candidates duplicate", async () => {+ const sourceData = createSourceData();+ for (const [id, label] of [+ ["primary-heading", "Primary heading"],+ ["secondary-heading", "Secondary heading"],+ ] as const) {+ sourceData.instances.set(id, {+ type: "instance",+ id,+ component: elementComponent,+ tag: "h1",+ label,+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: id,+ });+ }+ sourceData.styleSources.set("primary-style", {+ type: "local",+ id: "primary-style",+ });+ sourceData.styleSourceSelections.set("primary-heading", {+ instanceId: "primary-heading",+ values: ["primary-style"],+ });+ const document = await serializeMdxTemplateInsertion({+ identity,+ templateName: "Primary heading",+ fragment: {+ children: [{ type: "id", value: "inserted-heading" }],+ instances: [+ {+ type: "instance",+ id: "inserted-heading",+ component: elementComponent,+ tag: "h1",+ children: [{ type: "text", value: "Selected" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ },+ });+ const source = serializeMdxDocument(document);+ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const heading = result.root.fragment.instances.find(+ (instance) => instance.tag === "h1"+ );++ expect(source).toContain('ws:name="Primary heading"');+ expect(result.diagnostics).toEqual([]);+ expect(result.root.fragment.styleSourceSelections).toContainEqual({+ instanceId: heading?.id,+ values: [expect.stringMatching(/^mdx-/)],+ });++ const savedSource = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ });+ const reloaded = await materializeMdxSource({+ source: savedSource,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const reloadedHeading = reloaded.root.fragment.instances.find(+ (instance) => instance.tag === "h1"+ );+ expect(savedSource).toBe(source);+ expect(reloaded.root.fragment.styleSourceSelections).toContainEqual({+ instanceId: reloadedHeading?.id,+ values: [expect.stringMatching(/^mdx-/)],+ });++ for (const [instanceId, value] of [+ ["primary-heading", "Primary updated"],+ ["secondary-heading", "Secondary updated"],+ ] as const) {+ sourceData.props.set(`${instanceId}-title`, {+ id: `${instanceId}-title`,+ instanceId,+ name: "title",+ type: "string",+ value,+ });+ }+ const rematerialized = await materializeMdxSource({+ source: savedSource,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const rematerializedHeading = rematerialized.root.fragment.instances.find(+ (instance) => instance.tag === "h1"+ );+ expect(rematerialized.root.fragment.props).toContainEqual(+ expect.objectContaining({+ instanceId: rematerializedHeading?.id,+ name: "title",+ value: "Primary updated",+ })+ );+ });-const identity: ContentBlockExternalContentIdentity = {- blockInstanceId: "block",- assetId: "article",- revision: "sha256:revision",- contentRef: "article.mdx",- format: "mdx",- renderScope: "page",-};+ test("keeps new semantic-template props by switching to explicit MDX", async () => {+ const sourceData = createSourceData();+ sourceData.instances.set("heading", {+ type: "instance",+ id: "heading",+ component: elementComponent,+ tag: "h1",+ label: "Heading 1",+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "heading",+ });+ sourceData.styleSources.set("heading-style", {+ type: "local",+ id: "heading-style",+ });+ sourceData.styleSourceSelections.set("heading", {+ instanceId: "heading",+ values: ["heading-style"],+ });+ const result = await materializeMdxSource({+ source: "# Existing heading\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const edited = structuredClone(result.root.fragment);+ const heading = edited.instances.find((instance) => instance.tag === "h1");+ if (heading === undefined) {+ throw new Error("Expected heading");+ }+ edited.props.push({+ id: "authored-title",+ instanceId: heading.id,+ name: "title",+ type: "string",+ value: "Authored title",+ });-const data: Omit<WebstudioData, "pages"> = {- instances: new Map([- [- "block",- {- type: "instance",- id: "block",- component: blockComponent,- children: [{ type: "id", value: "templates" }],- },- ],- [- "templates",+ const source = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: edited,+ });+ sourceData.instances.set("other-heading", {+ type: "instance",+ id: "other-heading",+ component: elementComponent,+ tag: "h1",+ label: "Other heading",+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "other-heading",+ });+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(source).toContain('ws:name="Heading 1"');+ expect(source).toContain('title="Authored title"');+ expect(reloaded.diagnostics).toEqual([]);+ const reloadedHeading = reloaded.root.fragment.instances.find(+ ({ tag }) => tag === "h1"+ );+ expect(reloaded.root.fragment.styleSourceSelections).toContainEqual({+ instanceId: reloadedHeading?.id,+ values: [expect.stringMatching(/^mdx-/)],+ });+ expect(reloaded.root.fragment.props).toContainEqual(+ expect.objectContaining({ name: "title", value: "Authored title" })+ );++ const changed = structuredClone(reloaded.root.fragment);+ const changedTitle = changed.props.find(({ name }) => name === "title");+ if (changedTitle?.type !== "string") {+ throw new Error("Expected authored heading title");+ }+ changedTitle.value = "Updated title";+ const changedSource = await serializeMdxAuthoredContent({+ root: reloaded.root,+ fragment: changed,+ });+ expect(changedSource).toContain('ws:name="Heading 1"');+ expect(changedSource).toContain('title="Updated title"');++ const changedReloaded = await materializeMdxSource({+ source: changedSource,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const removed = structuredClone(changedReloaded.root.fragment);+ removed.props = removed.props.filter(({ name }) => name !== "title");+ const removedSource = await serializeMdxAuthoredContent({+ root: changedReloaded.root,+ fragment: removed,+ });+ expect(removedSource).toContain('ws:name="Heading 1"');+ expect(removedSource).not.toContain("title=");+ const removedReloaded = await materializeMdxSource({+ source: removedSource,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ expect(+ removedReloaded.root.fragment.props.some(({ name }) => name === "title")+ ).toBe(false);+ });++ test("uses styled Image templates for nested Markdown images", async () => {+ const sourceData = createAssetSourceData();+ sourceData.instances.set("image-template", {+ type: "instance",+ id: "image-template",+ component: "Image",+ label: "Image",+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "image-template",+ });+ sourceData.styleSources.set("image-style", {+ type: "local",+ id: "image-style",+ });+ sourceData.styleSourceSelections.set("image-template", {+ instanceId: "image-template",+ values: ["image-style"],+ });+ sourceData.breakpoints.set("base", { id: "base", label: "Base" });+ sourceData.styles.set("image-style:base:width", {+ breakpointId: "base",+ styleSourceId: "image-style",+ property: "width",+ value: { type: "unit", value: 100, unit: "%" },+ });+ const source = `++Before [](/gallery) and .++- ++| Image |+| --- |+|  |+`;++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const images = result.root.fragment.instances.filter(+ ({ component }) => component === "Image"+ );++ expect(images).toHaveLength(5);+ for (const image of images) {+ expect(result.root.fragment.styleSourceSelections).toContainEqual(+ expect.objectContaining({ instanceId: image.id })+ );+ expect(+ result.root.fragment.props.filter(+ ({ instanceId }) => instanceId === image.id+ )+ ).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "src",+ type: "asset",+ value: "hero",+ }),+ expect.objectContaining({+ name: "width",+ type: "asset",+ value: "hero",+ }),+ expect.objectContaining({+ name: "height",+ type: "asset",+ value: "hero",+ }),+ ])+ );+ }+ const serialized = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ });+ const reloaded = await materializeMdxSource({+ source: serialized,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ expect(+ reloaded.root.fragment.instances.filter(+ ({ component }) => component === "Image"+ )+ ).toHaveLength(5);+ expect(serialized.match(/\.\/hero\.png/g)).toHaveLength(5);++ const edited = structuredClone(result.root.fragment);+ const firstImage = images[0];+ if (firstImage === undefined) {+ throw new Error("Expected first Image");+ }+ const alt = edited.props.find(+ (prop) => prop.instanceId === firstImage.id && prop.name === "alt"+ );+ if (alt?.type !== "string") {+ throw new Error("Expected authored Image alt text");+ }+ alt.value = "Changed alt";+ await expect(+ serializeMdxAuthoredContent({ root: result.root, fragment: edited })+ ).resolves.toContain("");+ });++ test("keeps the Image template when an edit requires JSX", async () => {+ const sourceData = createSourceData();+ sourceData.instances.set("image-template", {+ type: "instance",+ id: "image-template",+ component: "Image",+ label: "Image",+ children: [],+ });+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "image-template",+ });+ const result = await materializeMdxSource({+ source: "Before  after.\n",+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const edited = structuredClone(result.root.fragment);+ const image = edited.instances.find(+ ({ component }) => component === "Image"+ );+ if (image === undefined) {+ throw new Error("Expected Image");+ }+ edited.props.push({+ id: "image-class",+ instanceId: image.id,+ name: "class",+ type: "string",+ value: "featured",+ });++ const source = await serializeMdxAuthoredContent({+ root: result.root,+ fragment: edited,+ });+ const reloaded = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(source).toBe(+ 'Before <Image src="https://example.com/hero.png" alt="Hero" className="featured" /> after.\n'+ );+ expect(+ reloaded.root.fragment.instances.find(+ ({ component }) => component === "Image"+ )+ ).toBeDefined();+ });++ test("does not turn an external Image URL into derived Asset props", async () => {+ const sourceData = createSourceData();+ sourceData.instances.set("image-template", {+ type: "instance",+ id: "image-template",+ component: "Image",+ label: "Image",+ children: [],+ });+ for (const name of ["width", "height", "alt"] as const) {+ sourceData.props.set(`image-${name}`, {+ id: `image-${name}`,+ instanceId: "image-template",+ name,+ type: "string",+ value: "template default",+ });+ }+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "image-template",+ });+ const source = "\n";++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });++ expect(+ result.root.fragment.props.map(({ name, type, value }) => ({+ name,+ type,+ value,+ }))+ ).toEqual([{- type: "instance",- id: "templates",- component: blockTemplateComponent,- children: [],+ name: "src",+ type: "string",+ value: "https://example.com/hero.png",},- ],- ]),- props: new Map(),- dataSources: new Map(),- resources: new Map(),- styleSources: new Map(),- styleSourceSelections: new Map(),- styles: new Map(),- breakpoints: new Map(),- assets: new Map(),-};+ ]);+ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe(source);+ });++ test("keeps unresolved relative Image sources literal without derived Asset props", async () => {+ const sourceData = createAssetSourceData();+ sourceData.instances.set("image-template", {+ type: "instance",+ id: "image-template",+ component: "Image",+ label: "Image",+ children: [],+ });+ for (const name of ["width", "height", "alt"] as const) {+ sourceData.props.set(`image-${name}`, {+ id: `image-${name}`,+ instanceId: "image-template",+ name,+ type: "string",+ value: "template default",+ });+ }+ sourceData.instances.get("templates")?.children.push({+ type: "id",+ value: "image-template",+ });+ const source = `++<Image src="./missing-jsx.png" />+`;++ const result = await materializeMdxSource({+ source,+ identity,+ data: sourceData,+ metas: componentMetas,+ projectId: "project",+ });+ const propsBySource = new Map(+ result.root.fragment.instances.flatMap((instance) => {+ if (instance.component !== "Image") {+ return [];+ }+ const props = result.root.fragment.props.filter(+ ({ instanceId }) => instanceId === instance.id+ );+ const src = props.find(({ name }) => name === "src");+ return src?.type === "string" ? [[src.value, props] as const] : [];+ })+ );++ const markdownProps = propsBySource+ .get("./missing-markdown.png")+ ?.map(({ name, type, value }) => ({ name, type, value }));+ expect(markdownProps).toHaveLength(2);+ expect(markdownProps).toEqual(+ expect.arrayContaining([+ { name: "src", type: "string", value: "./missing-markdown.png" },+ { name: "alt", type: "string", value: "Authored alt" },+ ])+ );+ expect(+ propsBySource+ .get("./missing-jsx.png")+ ?.map(({ name, type, value }) => ({ name, type, value }))+ ).toEqual([{ name: "src", type: "string", value: "./missing-jsx.png" }]);+ expect(result.root.fragment.assets).toEqual([]);+ await expect(+ serializeMdxAuthoredContent({+ root: result.root,+ fragment: result.root.fragment,+ })+ ).resolves.toBe(source);+ });-describe("materializeMdxSource", () => {test("uses the shared recovery result and materializes valid siblings", async () => {const result = await materializeMdxSource({source: "# Hello\n\n{dangerous()}\n\nAfter",@@ -165,8 +2429,7 @@ featureImage:test("serializes an Asset selected on an inserted Image template", async () => {const sourceData: Omit<WebstudioData, "pages"> = {- ...data,- instances: new Map(data.instances),+ ...createSourceData(),assetFolders: new Map(),assets: new Map<string, Asset>([[@@ -244,7 +2507,7 @@ featureImage:root: result.root,fragment,});- expect(source).toBe("\n");+ expect(source).toBe('<Image src="./hero.png" />\n');const customized = structuredClone(fragment);customized.props.push({@@ -259,9 +2522,7 @@ featureImage:root: result.root,fragment: customized,})- ).toBe(- '<ws.element ws:name="Image" src="./hero.png" className="hero" />\n'- );+ ).toBe('<Image src="./hero.png" className="hero" />\n');const reloaded = await materializeMdxSource({source,@@ -293,7 +2554,7 @@ featureImage:root: reloaded.root,fragment: reset,});- expect(resetSource).toBe("![]()\n");+ expect(resetSource).toBe("<Image />\n");const resetReloaded = await materializeMdxSource({source: resetSource,identity,diff --git a/packages/project-build/src/runtime/mdx-source.ts b/packages/project-build/src/runtime/mdx-source.tsindex 97418915b8..4a8ee7ec59 100644--- a/packages/project-build/src/runtime/mdx-source.ts+++ b/packages/project-build/src/runtime/mdx-source.ts@@ -1,3 +1,7 @@+/**+ * Orchestrates the complete MDX source pipeline: parse, resolve templates and+ * assets, materialize editable instances, and combine source diagnostics.+ */import {discoverNamedMdxAssetReferences,parseMdxDocumentRecovering,@@ -26,7 +30,10 @@ import {} from "./mdx-diagnostics";import { createMdxAssetReferenceValues } from "./mdx-asset-references";import { materializeMdxTemplates } from "./mdx-materialization";-import { resolveMdxTemplates } from "./mdx-template-resolution";+import {+ assertMdxTemplateStructure,+ resolveMdxTemplates,+} from "./mdx-template-resolution";const emptyMdxDocument: MdxDocument = {frontmatter: { properties: {} },@@ -68,8 +75,10 @@ export const materializeMdxSource = async ({document,identity,instances: data.instances,+ props: data.props,metas,});+ assertMdxTemplateStructure(resolution);const sourceAsset = data.assets.get(identity.assetId);const hierarchy = createAssetFolderHierarchy(data.assetFolders ?? new Map());const getNamedAsset = (asset: Asset) => ({@@ -98,6 +107,7 @@ export const materializeMdxSource = async ({document,templateMaterialization: templates,assetReferences,+ metas,assetReferenceValues:sourceAsset === undefined? undefined@@ -145,6 +155,7 @@ export const materializeMdxSource = async ({diagnostics: parsedSource.diagnostics,}),...templates.diagnostics,+ ...(authoredRoot.diagnostics ?? []),...createMdxContentModelDiagnostics({ root, metas }),],};diff --git a/packages/project-build/src/runtime/mdx-static-props.ts b/packages/project-build/src/runtime/mdx-static-props.tsindex ccd4e6c117..3949dafdc8 100644--- a/packages/project-build/src/runtime/mdx-static-props.ts+++ b/packages/project-build/src/runtime/mdx-static-props.ts@@ -1,3 +1,7 @@+/**+ * Converts the primitive static prop values allowed in authored MDX to and+ * from persisted Webstudio props without evaluating JavaScript expressions.+ */import type { MdxAuthoredProp } from "@webstudio-is/content-engine/mdx";import type { Prop } from "@webstudio-is/sdk";diff --git a/packages/project-build/src/runtime/mdx-template-migration.test.ts b/packages/project-build/src/runtime/mdx-template-migration.test.tsindex 05ee1ef7b5..c76ac84d25 100644--- a/packages/project-build/src/runtime/mdx-template-migration.test.ts+++ b/packages/project-build/src/runtime/mdx-template-migration.test.ts@@ -45,7 +45,7 @@ describe("MDX template migration", () => {test("previews nested AST renames while preserving frontmatter and comments", async () => {const plan = await planMdxTemplateMigration({projectId: "project",- migration: { type: "rename", from: "Card", to: "Feature Card" },+ migration: { type: "rename", from: "Card", to: "FeatureCard" },files,});@@ -64,8 +64,8 @@ describe("MDX template migration", () => {});expect(document.children[1]).toMatchObject({type: "template",- name: "Feature Card",- children: [{ type: "template", name: "Feature Card" }],+ name: "FeatureCard",+ children: [{ type: "template", name: "FeatureCard" }],});expect(document.children[2]).toMatchObject({type: "template",@@ -73,7 +73,78 @@ describe("MDX template migration", () => {});});- test("omits the complete matching subtree and reports invalid files", async () => {+ test("renames JSX references and rejects incompatible names", async () => {+ const file = {+ ...files[0],+ source: "<Card><Card /></Card>",+ };+ const jsxPlan = await planMdxTemplateMigration({+ projectId: "project",+ migration: { type: "rename", from: "Card", to: "FeatureCard" },+ files: [file],+ });+ expect(jsxPlan.files[0]?.source).toBe(+ "<FeatureCard>\n <FeatureCard />\n</FeatureCard>\n"+ );++ await expect(+ planMdxTemplateMigration({+ projectId: "project",+ migration: { type: "rename", from: "Card", to: "Feature Card" },+ files: [file],+ })+ ).rejects.toThrow("valid PascalCase MDX name");+ });++ test("migrates every reference because template names take precedence", async () => {+ const file = {+ ...files[0],+ source: `<Image src="hero.png" alt="Hero" />++<ws.element ws:name="Image" />`,+ };+ const renamePlan = await planMdxTemplateMigration({+ projectId: "project",+ migration: { type: "rename", from: "Image", to: "Photo" },+ files: [file],+ });+ const renamed = await parseMdxDocument({+ source: renamePlan.files[0]?.source ?? "",+ });++ expect(renamePlan).toMatchObject({ updateCount: 2, changedFileCount: 1 });+ expect(renamed.children).toMatchObject([+ { type: "template", name: "Photo", syntax: "jsx" },+ { type: "template", name: "Photo", syntax: "jsx" },+ ]);++ const removePlan = await planMdxTemplateMigration({+ projectId: "project",+ migration: { type: "remove", name: "Image" },+ files: [file],+ });+ const removed = await parseMdxDocument({+ source: removePlan.files[0]?.source ?? "",+ });++ expect(removePlan).toMatchObject({ omissionCount: 2, changedFileCount: 1 });+ expect(removed.children).toEqual([]);+ });++ test.each(["Image", "CodeText"])(+ "uses canonical JSX when renaming a template to %s",+ async (reservedName) => {+ const plan = await planMdxTemplateMigration({+ projectId: "project",+ migration: { type: "rename", from: "Card", to: reservedName },+ files: [{ ...files[0], source: "<Card />" }],+ });++ expect(plan.files[0]?.source).toBe(`<${reservedName} />\n`);+ }+ );++ test("removes nested matching references and reports invalid files", async () => {const plan = await planMdxTemplateMigration({projectId: "project",migration: { type: "remove", name: "Card" },@@ -85,10 +156,10 @@ describe("MDX template migration", () => {expect(plan).toMatchObject({updateCount: 0,- omissionCount: 1,+ omissionCount: 2,changedFileCount: 1,files: [- { assetId: "article", omissionCount: 1, diagnostics: [] },+ { assetId: "article", omissionCount: 2, diagnostics: [] },{assetId: "invalid",changed: false,@@ -102,4 +173,36 @@ describe("MDX template migration", () => {expect.objectContaining({ type: "template", name: "Other" }),]);});++ test("removes template wrappers without discarding authored children", async () => {+ const plan = await planMdxTemplateMigration({+ projectId: "project",+ migration: { type: "remove", name: "Card" },+ files: [+ {+ ...files[0],+ source: "<Card>Before <Other /> after</Card>",+ },+ ],+ });++ expect(plan).toMatchObject({ omissionCount: 1, changedFileCount: 1 });+ await expect(+ parseMdxDocument({ source: plan.files[0]?.source ?? "" })+ ).resolves.toMatchObject({+ children: [+ {+ type: "element",+ tag: "p",+ children: [{ type: "text", value: "Before" }],+ },+ { type: "template", name: "Other" },+ {+ type: "element",+ tag: "p",+ children: [{ type: "text", value: "after" }],+ },+ ],+ });+ });});diff --git a/packages/project-build/src/runtime/mdx-template-migration.ts b/packages/project-build/src/runtime/mdx-template-migration.tsindex 6c27fdaaa3..f53aaf371a 100644--- a/packages/project-build/src/runtime/mdx-template-migration.ts+++ b/packages/project-build/src/runtime/mdx-template-migration.ts@@ -1,4 +1,10 @@+/**+ * Plans and confirms explicit batch rewrites of authored MDX references after+ * custom templates are renamed or removed; normal template resolution does not+ * depend on this migration.+ */import {+ isMdxTemplateComponentName,parseMdxDocument,serializeMdxDocument,type MdxAuthoredNode,@@ -80,11 +86,6 @@ const updateNodes = ((migration.type === "rename"? node.name === migration.from: node.name === migration.name);- if (node.type === "template" && matches && migration.type === "remove") {- omissionCount += 1;- changed = true;- continue;- }if (node.type === "text" ||node.type === "comment" ||@@ -96,12 +97,21 @@ const updateNodes = (const children = updateNodes(node.children, migration);updateCount += children.updateCount;omissionCount += children.omissionCount;+ if (node.type === "template" && matches && migration.type === "remove") {+ // Removing a template reference removes only its wrapper. Authored+ // children remain in place; self-closing references have none to retain.+ omissionCount += 1;+ changed = true;+ nextNodes.push(...children.nodes);+ continue;+ }if (node.type === "template" && matches && migration.type === "rename") {updateCount += 1;changed = true;nextNodes.push({...node,name: migration.to,+ syntax: "jsx",children: children.nodes,});continue;@@ -202,6 +212,12 @@ export const planMdxTemplateMigration = async ({confirmationScope?: Readonly<Record<string, unknown>>;confirmationTtlMs?: number;}): Promise<MdxTemplateMigrationPlan> => {+ if (+ migration.type === "rename" &&+ isMdxTemplateComponentName(migration.to) === false+ ) {+ throw new Error("Renamed template must use a valid PascalCase MDX name");+ }if (files.length > mdxTemplateMigrationFileLimit) {throw new Error("MDX template migration is limited to 100 files");}diff --git a/packages/project-build/src/runtime/mdx-template-resolution.test.ts b/packages/project-build/src/runtime/mdx-template-resolution.test.tsindex 2301fa0b5b..4d3f0810f9 100644--- a/packages/project-build/src/runtime/mdx-template-resolution.test.ts+++ b/packages/project-build/src/runtime/mdx-template-resolution.test.ts@@ -1,9 +1,14 @@import { describe, expect, test } from "vitest";import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import { coreTemplates } from "@webstudio-is/sdk-components-registry/core-templates";+import { componentIds } from "@webstudio-is/sdk-components-registry/components";+import { renderTemplate } from "@webstudio-is/template";import {blockComponent,blockTemplateComponent,+ contentBlockMdxTemplateDescriptors,elementComponent,+ getContentBlockMdxTemplateDescriptor,type ContentBlockExternalContentIdentity,type Instance,type Instances,@@ -26,11 +31,41 @@ const identity: ContentBlockExternalContentIdentity = {renderScope: "route:/hello",};-const metas = new Map<string, WsComponentMeta>([+const metas: ReadonlyMap<string, WsComponentMeta> = new Map([["Card", { label: "Card" }],["Badge", { label: "Badge" }],]);+const standardMdxSource = `# Heading 1+## Heading 2+### Heading 3+#### Heading 4+##### Heading 5+###### Heading 6++Paragraph with *emphasis*, **strong**, ~~strikethrough~~, \`inline code\`, and [a link](https://example.com).${" "}+Next line.++> Blockquote++- [x] Task item+- List item++1. Ordered item++---++| Header | Value |+| --- | --- |+| Cell | Value |++++\`\`\`js+code()+\`\`\`+`;+const createInstances = (): Instances =>new Map([[@@ -65,6 +100,734 @@ const createInstances = (): Instances =>]);describe("resolveMdxTemplates", () => {+ test("reaches every standard template through authored Markdown", async () => {+ const instances = createInstances();+ const templates = instances.get("templates");+ if (templates === undefined) {+ throw new Error("Expected Templates container");+ }+ templates.children = [];+ for (const descriptor of contentBlockMdxTemplateDescriptors) {+ const id = `template-${descriptor.resolutionKey}`;+ templates.children.push({ type: "id", value: id });+ instances.set(+ id,+ createInstance(+ id,+ descriptor.kind === "element"+ ? elementComponent+ : descriptor.component,+ descriptor.kind === "element" ? { tag: descriptor.tag } : {}+ )+ );+ }+ const document = await parseMdxDocument({ source: standardMdxSource });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas,+ });+ const resolvedTemplateIds = new Set(+ result.references.flatMap((reference) =>+ reference.type === "resolved-template"+ ? [reference.templateInstanceId]+ : []+ )+ );++ expect(result.diagnostics).toEqual([]);+ expect(+ contentBlockMdxTemplateDescriptors+ .map(({ resolutionKey }) => resolutionKey)+ .filter((key) => resolvedTemplateIds.has(`template-${key}`) === false)+ ).toEqual([]);+ });++ test("resolves authored Markdown through the actual core templates", async () => {+ const template = coreTemplates[blockComponent];+ if (template === undefined) {+ throw new Error("Expected the core Content Block template");+ }+ const fragment = renderTemplate(template.template, undefined, [], {+ componentIds,+ });+ const instances = new Map(+ fragment.instances.map((instance) => [instance.id, instance])+ );+ const block = fragment.instances.find(+ ({ component }) => component === blockComponent+ );+ const templates = fragment.instances.find(+ ({ component }) => component === blockTemplateComponent+ );+ if (block === undefined || templates === undefined) {+ throw new Error("Expected the core Content Block containers");+ }+ const expectedTemplateIds = new Set(+ templates.children.flatMap((child) => {+ const instance =+ child.type === "id" ? instances.get(child.value) : undefined;+ return instance !== undefined &&+ getContentBlockMdxTemplateDescriptor(instance) !== undefined+ ? [instance.id]+ : [];+ })+ );+ const document = await parseMdxDocument({ source: standardMdxSource });++ const result = resolveMdxTemplates({+ document,+ identity: { ...identity, blockInstanceId: block.id },+ instances,+ metas,+ });+ const resolvedTemplateIds = new Set(+ result.references.flatMap((reference) =>+ reference.type === "resolved-template"+ ? [reference.templateInstanceId]+ : []+ )+ );++ expect(result.diagnostics).toEqual([]);+ expect(+ Array.from(expectedTemplateIds).filter(+ (templateId) => resolvedTemplateIds.has(templateId) === false+ )+ ).toEqual([]);+ const codeTemplate = fragment.instances.find(+ ({ component }) => component === "CodeText"+ );+ expect(+ result.references.find(+ (reference) =>+ reference.type === "resolved-template" &&+ reference.templateInstanceId === codeTemplate?.id+ )?.templateName+ ).toBe("CodeText");++ const componentNameDocument = await parseMdxDocument({+ source: "<CodeText />\n",+ });+ expect(+ resolveMdxTemplates({+ document: componentNameDocument,+ identity: { ...identity, blockInstanceId: block.id },+ instances,+ metas,+ }).references+ ).toEqual([+ expect.objectContaining({+ type: "resolved-template",+ templateName: "CodeText",+ templateInstanceId: codeTemplate?.id,+ }),+ ]);++ for (const component of ["Image", "CodeText"]) {+ const templateInstance = fragment.instances.find(+ (instance) => instance.component === component+ );+ const templateName = templateInstance?.name ?? component;+ const legacyDocument = await parseMdxDocument({+ source: `<ws.element ws:name="${templateName}" />\n`,+ });+ expect(+ resolveMdxTemplates({+ document: legacyDocument,+ identity: { ...identity, blockInstanceId: block.id },+ instances,+ metas,+ }).references+ ).toEqual([+ expect.objectContaining({+ type: "resolved-template",+ templateName,+ templateInstanceId: templateInstance?.id,+ }),+ ]);+ }+ });++ test("resolves component-style JSX by its direct template name", async () => {+ const document = await parseMdxDocument({+ source: '<Card tone="quiet">Content</Card>',+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances: createInstances(),+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "resolved-template",+ path: [0],+ templateName: "Card",+ templateInstanceId: "card",+ }),+ ]);+ expect(document.children[0]).toMatchObject({+ type: "template",+ syntax: "jsx",+ name: "Card",+ });+ });++ test("reads a legacy label alias and resolves it to the stable name", async () => {+ const instances = createInstances();+ const card = instances.get("card");+ if (card === undefined) {+ throw new Error("Expected card template");+ }+ card.name = "Card";+ card.label = "Promotion Card";+ const document = await parseMdxDocument({+ source: '<ws.element ws:name="Promotion Card" />\n',+ });++ expect(+ resolveMdxTemplates({ document, identity, instances, metas }).references+ ).toEqual([+ expect.objectContaining({+ type: "resolved-template",+ templateName: "Card",+ templateInstanceId: "card",+ }),+ ]);+ });++ test("lets a canonical name win over another template's legacy label alias", async () => {+ const instances = createInstances();+ const card = instances.get("card");+ const templates = instances.get("templates");+ if (card === undefined || templates === undefined) {+ throw new Error("Expected card and templates");+ }+ card.name = "Card";+ card.label = "PromotionCard";+ instances.set("promotion", {+ ...createInstance("promotion", "Badge"),+ name: "PromotionCard",+ });+ templates.children.push({ type: "id", value: "promotion" });++ const document = await parseMdxDocument({ source: "<PromotionCard />\n" });+ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas,+ });++ expect(result.diagnostics).toEqual([]);+ expect(result.references).toEqual([+ expect.objectContaining({+ type: "resolved-template",+ templateName: "PromotionCard",+ templateInstanceId: "promotion",+ }),+ ]);+ });++ test("lets a stable template name shadow the registered component fallback", async () => {+ const instances = createInstances();+ instances.set(+ "reserved-image-name",+ createInstance("reserved-image-name", elementComponent, {+ label: "Image",+ tag: "p",+ })+ );+ instances.get("templates")?.children.push({+ type: "id",+ value: "reserved-image-name",+ });+ const document = await parseMdxDocument({+ source: '<Image src="https://example.com/image.png" alt="Example" />\n',+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "resolved-template",+ templateInstanceId: "reserved-image-name",+ }),+ ]);+ expect(result.diagnostics).toEqual([]);++ const explicitNamed = await parseMdxDocument({+ source: '<ws.element ws:name="Image" />\n',+ });+ expect(+ resolveMdxTemplates({+ document: explicitNamed,+ identity,+ instances,+ metas,+ }).references+ ).toEqual([+ expect.objectContaining({+ type: "resolved-template",+ templateInstanceId: "reserved-image-name",+ }),+ ]);+ });++ test("resolves templates nested inside a direct registered component", async () => {+ const instances = createInstances();+ instances.set(+ "heading-2",+ createInstance("heading-2", elementComponent, { tag: "h2" })+ );+ instances.get("templates")?.children.push({+ type: "id",+ value: "heading-2",+ });+ const document = await parseMdxDocument({+ source: "<Box><h2>Nested</h2><Missing /></Box>\n",+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas: new Map([...metas, ["Box", { label: "Box" }]]),+ });++ 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",+ }),+ ]);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ templateName: "Missing",+ }),+ ]);+ });++ test.each([+ ["without a same-named template", false],+ ["with a same-named custom template", true],+ ] as const)(+ "resolves component-like JSX by the normal template precedence %s",+ async (_description, withSameNamedTemplate) => {+ const instances = createInstances();+ if (withSameNamedTemplate) {+ instances.set(+ "reserved-image-name",+ createInstance("reserved-image-name", elementComponent, {+ label: "Image",+ tag: "p",+ })+ );+ instances.get("templates")?.children.push({+ type: "id",+ value: "reserved-image-name",+ });+ }+ const document = await parseMdxDocument({+ source: "<Image>Caption</Image>\n",+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining(+ withSameNamedTemplate+ ? {+ type: "resolved-template",+ templateInstanceId: "reserved-image-name",+ }+ : { type: "unresolved-template", templateName: "Image" }+ ),+ ]);+ expect(result.diagnostics).toEqual(+ [+ expect.objectContaining(+ withSameNamedTemplate+ ? {}+ : { code: "unresolved-template", templateName: "Image" }+ ),+ ].filter(() => withSameNamedTemplate === false)+ );+ }+ );++ test.each(["Image", "CodeText"])(+ "keeps a missing legacy %s template unresolved",+ async (templateName) => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="${templateName}" />\n`,+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances: createInstances(),+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "unresolved-template",+ path: [0],+ templateName,+ }),+ ]);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ templateName,+ }),+ ]);+ }+ );++ test("resolves existing Markdown after a matching template is added", async () => {+ const source = "# Existing heading\n";+ const document = await parseMdxDocument({ source });+ const instances = createInstances();++ expect(+ resolveMdxTemplates({ document, identity, instances, metas }).references+ ).toEqual([]);++ instances.set(+ "heading",+ createInstance("heading", elementComponent, {+ label: "Heading 1",+ tag: "h1",+ })+ );+ instances.get("templates")?.children.push({+ type: "id",+ value: "heading",+ });++ const resolved = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas,+ });+ expect(resolved.references).toEqual([+ expect.objectContaining({+ type: "resolved-template",+ path: [0],+ templateName: "Heading 1",+ templateInstanceId: "heading",+ }),+ ]);+ expect(document.children[0]).toMatchObject({+ type: "element",+ syntax: "markdown",+ tag: "h1",+ });+ });++ test("matches Markdown to normal components by their rendered HTML tags", async () => {+ const instances = createInstances();+ instances.set(+ "heading-component",+ createInstance("heading-component", "Heading", {+ label: "Component heading",+ })+ );+ instances.get("templates")?.children.push({+ type: "id",+ value: "heading-component",+ });+ for (const [id, component, label] of [+ ["paragraph-component", "Paragraph", "Component paragraph"],+ ["link-component", "Link", "Component link"],+ ] as const) {+ instances.set(id, createInstance(id, component, { label }));+ instances.get("templates")?.children.push({ type: "id", value: id });+ }+ const props = new Map([+ [+ "heading-tag",+ {+ id: "heading-tag",+ instanceId: "heading-component",+ name: "tag",+ type: "string" as const,+ value: "h2",+ },+ ],+ ]);+ const componentMetas = new Map(metas);+ componentMetas.set("Heading", {+ label: "Heading",+ presetStyle: { h1: [], h2: [] },+ });+ componentMetas.set("Paragraph", {+ label: "Paragraph",+ presetStyle: { p: [] },+ });+ componentMetas.set("Link", {+ label: "Link",+ presetStyle: { a: [] },+ });+ const document = await parseMdxDocument({+ source: "## Heading\n\nParagraph with [link](/docs).\n",+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ props,+ metas: componentMetas,+ });++ expect(result.references).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: "resolved-template",+ path: [0],+ templateName: "Component heading",+ templateInstanceId: "heading-component",+ }),+ expect.objectContaining({+ type: "resolved-template",+ path: [1],+ templateName: "Component paragraph",+ templateInstanceId: "paragraph-component",+ }),+ expect.objectContaining({+ type: "resolved-template",+ templateName: "Component link",+ templateInstanceId: "link-component",+ }),+ ])+ );+ });++ test("does not resolve Markdown through a template with a dynamic tag", async () => {+ const instances = createInstances();+ const templates = instances.get("templates");+ if (templates === undefined) {+ throw new Error("Expected Templates container");+ }+ instances.set(+ "dynamic-heading",+ createInstance("dynamic-heading", "DynamicHeading", {+ label: "Dynamic Heading",+ })+ );+ templates.children.push({ type: "id", value: "dynamic-heading" });+ const props = new Map([+ [+ "dynamic-heading-tag",+ {+ id: "dynamic-heading-tag",+ instanceId: "dynamic-heading",+ name: "tag",+ type: "expression" as const,+ value: '"h1"',+ mode: "read" as const,+ },+ ],+ ]);+ const componentMetas = new Map(metas);+ componentMetas.set("DynamicHeading", { presetStyle: { h1: [] } });+ const document = await parseMdxDocument({ source: "# Heading\n" });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ props,+ metas: componentMetas,+ });++ expect(result.references).toEqual([]);+ });++ test("matches ordered and unordered Markdown to the List component tag", async () => {+ const instances = createInstances();+ const templates = instances.get("templates");+ if (templates === undefined) {+ throw new Error("Expected Templates container");+ }+ instances.set(+ "list",+ createInstance("list", "List", { label: "Authored List" })+ );+ templates.children.push({ type: "id", value: "list" });+ const props = new Map();+ const componentMetas = new Map(metas);+ componentMetas.set("List", {+ presetStyle: { ol: [], ul: [] },+ props: {+ ordered: {+ type: "boolean",+ control: "boolean",+ required: false,+ },+ },+ renderedTag: {+ prop: "ordered",+ values: { true: "ol", false: "ul" },+ default: "ul",+ },+ });+ const resolve = async (source: string) =>+ resolveMdxTemplates({+ document: await parseMdxDocument({ source }),+ identity,+ instances,+ props,+ metas: componentMetas,+ });++ expect((await resolve("- Default unordered\n")).references).toEqual([+ expect.objectContaining({ templateInstanceId: "list" }),+ ]);+ props.set("ordered", {+ id: "ordered",+ instanceId: "list",+ name: "ordered",+ type: "boolean" as const,+ value: false,+ });+ expect((await resolve("- Explicit unordered\n")).references).toEqual([+ expect.objectContaining({ templateInstanceId: "list" }),+ ]);+ props.set("ordered", { ...props.get("ordered")!, value: true });+ expect((await resolve("1. Ordered\n")).references).toEqual([+ expect.objectContaining({ templateInstanceId: "list" }),+ ]);+ props.set("ordered", {+ id: "ordered",+ instanceId: "list",+ name: "ordered",+ type: "expression" as const,+ value: "$ws$dataSource$ordered",+ });+ expect((await resolve("1. Dynamic\n")).references).toEqual([]);+ });++ test("does not resolve templates from malformed multiple containers", async () => {+ const instances = createInstances();+ instances.get("block")?.children.push({+ type: "id",+ value: "templates-2",+ });+ instances.set(+ "templates-2",+ createInstance("templates-2", blockTemplateComponent, {+ children: [{ type: "id", value: "heading" }],+ })+ );+ instances.set(+ "heading",+ createInstance("heading", elementComponent, {+ label: "Heading 1",+ tag: "h1",+ })+ );+ const document = await parseMdxDocument({ source: "# Heading\n" });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas,+ });++ expect(result.references).toEqual([]);+ expect(result.templateNames).toEqual([]);+ expect(result.templateStructure).toEqual({+ status: "invalid",+ reason: "multiple-containers",+ containerIds: ["templates", "templates-2"],+ });+ });++ test("warns and uses the semantic fallback for ambiguous standard templates", async () => {+ const instances = createInstances();+ for (const id of ["first-heading", "second-heading"]) {+ instances.set(+ id,+ createInstance(id, elementComponent, { label: id, tag: "h1" })+ );+ instances.get("templates")?.children.push({ type: "id", value: id });+ }+ const document = await parseMdxDocument({ source: "# Heading\n" });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas,+ });++ expect(result.references).toEqual([]);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "ambiguous-template",+ semanticKey: "element:h1",+ templateNames: ["first-heading", "second-heading"],+ sourceRange: expect.objectContaining({}),+ }),+ ]);+ });++ test("does not resolve adapted component internals through semantic templates", async () => {+ const instances = createInstances();+ instances.set(+ "inline-code",+ createInstance("inline-code", elementComponent, {+ label: "Inline Code",+ tag: "code",+ })+ );+ instances.get("templates")?.children.push({+ type: "id",+ value: "inline-code",+ });+ const document = await parseMdxDocument({+ source: "```ts\nconst ready = true;\n```\n",+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas,+ });++ expect(result.references).toEqual([]);+ expect(result.diagnostics).toEqual([]);+ });+test("resolves exact displayed names from the direct flat Templates list", async () => {const document = await parseMdxDocument({source: `<ws.element ws:name="Hero Card" tone="quiet" />@@ -89,6 +852,13 @@ describe("resolveMdxTemplates", () => {props: [expect.objectContaining({ name: "tone", value: "quiet" })],templateInstanceId: "hero",}),+ expect.objectContaining({+ type: "resolved-template",+ path: [1],+ templateName: "Hero Card",+ props: [],+ templateInstanceId: "hero",+ }),expect.objectContaining({type: "resolved-template",path: [1, 0],@@ -174,8 +944,8 @@ describe("resolveMdxTemplates", () => {]);expect(result.diagnostics).toEqual([expect.objectContaining({- code: "unresolved-template",- templateName: "Hero Card",+ code: "ambiguous-template",+ semanticKey: "name:Hero Card",}),]);expect(result.templateNames).toEqual(["Hero Card", "Card", "Hero Card"]);diff --git a/packages/project-build/src/runtime/mdx-template-resolution.ts b/packages/project-build/src/runtime/mdx-template-resolution.tsindex b1c85dc138..bd2fb83b2e 100644--- a/packages/project-build/src/runtime/mdx-template-resolution.ts+++ b/packages/project-build/src/runtime/mdx-template-resolution.ts@@ -1,18 +1,31 @@+/**+ * Matches authored Markdown and JSX nodes to the current Content Block+ * templates, leaving unmatched nodes available for their semantic fallback.+ */import type {MdxAuthoredProp,MdxAuthoredNode,MdxDocument,} from "@webstudio-is/content-engine/mdx";import {- getInstanceName,+ findContentBlockTemplateContainers,+ getContentBlockTemplateName,+ getComponentByJsxName,+ getHtmlTagsFromProps,type ContentBlockDiagnostic,type ContentBlockExternalContentIdentity,type ContentBlockSourceRange,type Instance,type Instances,+ type Prop,type WsComponentMeta,} from "@webstudio-is/sdk";import { findBlockTemplates } from "./block";+import {+ getMdxNamedTemplateComponentBinding,+ getMdxStandardTemplateKeyForInstance,+ getMdxStandardTemplateBinding,+} from "./mdx-component-adapters";export type MdxTemplateReference = Readonly<{path: readonly number[];@@ -24,6 +37,14 @@ export type MdxTemplateReference = Readonly<{type: "resolved-template";templateInstanceId: Instance["id"];props: readonly MdxAuthoredProp[];+ propBindings?: readonly Readonly<{+ source?: Readonly<{+ nodePath: readonly number[];+ propIndex: number;+ }>;+ requiresAssetReference?: boolean;+ }>[];+ componentChildren?: Instance["children"];}>| Readonly<{type: "unresolved-template";@@ -31,33 +52,113 @@ export type MdxTemplateReference = Readonly<{);export type MdxTemplateResolution = Readonly<{+ /** Present on resolver output; optional for callers that persist old inputs. */+ templateStructure?:+ | Readonly<{ status: "valid"; containerId: Instance["id"] }>+ | Readonly<{+ status: "invalid";+ reason: "missing-container" | "multiple-containers";+ containerIds: readonly Instance["id"][];+ }>;templateNames: readonly string[];references: readonly MdxTemplateReference[];diagnostics: readonly ContentBlockDiagnostic[];}>;+export class InvalidMdxTemplateStructureError extends Error {+ name = "InvalidMdxTemplateStructureError";+ readonly containerCount: number;++ constructor(containerCount: number) {+ super(+ `Content Block has ${containerCount} Templates containers; exactly one is required`+ );+ this.containerCount = containerCount;+ }+}++export const assertMdxTemplateContainerCount = (containerCount: number) => {+ if (containerCount !== 1) {+ throw new InvalidMdxTemplateStructureError(containerCount);+ }+};++export const assertMdxTemplateStructure = (+ resolution: Pick<MdxTemplateResolution, "templateStructure">+) => {+ if (resolution.templateStructure?.status === "invalid") {+ assertMdxTemplateContainerCount(+ resolution.templateStructure.containerIds.length+ );+ }+};+export const resolveMdxTemplates = ({document,identity,instances,+ props,metas,}: {document: MdxDocument;identity: ContentBlockExternalContentIdentity;instances: Instances;+ props?: ReadonlyMap<Prop["id"], Prop>;metas: ReadonlyMap<Instance["component"], WsComponentMeta>;}): MdxTemplateResolution => {+ const blockInstance = instances.get(identity.blockInstanceId);+ const templateContainers =+ blockInstance === undefined+ ? []+ : findContentBlockTemplateContainers({ blockInstance, instances });+ const templateStructure: MdxTemplateResolution["templateStructure"] =+ templateContainers.length === 0+ ? {+ status: "invalid",+ reason: "missing-container",+ containerIds: [],+ }+ : templateContainers.length === 1+ ? { status: "valid", containerId: templateContainers[0].id }+ : {+ status: "invalid",+ reason: "multiple-containers",+ containerIds: templateContainers.map(({ id }) => id),+ };+ const htmlTagsByInstanceId =+ props === undefined ? undefined : getHtmlTagsFromProps(props);const templateIdsByName = new Map<string, Instance["id"][]>();+ const legacyTemplateIdsByLabel = new Map<string, Instance["id"][]>();+ const templateIdsByStandardKey = new Map<string, Instance["id"][]>();+ const templateNameById = new Map<Instance["id"], string>();const templateNames: string[] = [];for (const [template] of findBlockTemplates({anchor: [identity.blockInstanceId],instances,}) ?? []) {- const name = getInstanceName({ instance: template, metas });+ const name = getContentBlockTemplateName(template);templateNames.push(name);+ templateNameById.set(template.id, name);const templateIds = templateIdsByName.get(name) ?? [];templateIds.push(template.id);templateIdsByName.set(name, templateIds);+ if (template.name !== undefined && template.label !== undefined) {+ const legacyTemplateIds =+ legacyTemplateIdsByLabel.get(template.label) ?? [];+ legacyTemplateIds.push(template.id);+ legacyTemplateIdsByLabel.set(template.label, legacyTemplateIds);+ }+ const standardKey = getMdxStandardTemplateKeyForInstance({+ instance: template,+ metas,+ props,+ htmlTagsByInstanceId,+ });+ if (standardKey !== undefined) {+ const standardIds = templateIdsByStandardKey.get(standardKey) ?? [];+ standardIds.push(template.id);+ templateIdsByStandardKey.set(standardKey, standardIds);+ }}const references: MdxTemplateReference[] = [];@@ -70,17 +171,113 @@ export const resolveMdxTemplates = ({for (const [index, node] of nodes.entries()) {const path = [...parentPath, index];if (node.type === "template") {- const templateIds = templateIdsByName.get(node.name);+ const standard = getMdxStandardTemplateBinding(node);+ const templateIds =+ templateIdsByName.get(node.name) ??+ (node.syntax !== "jsx"+ ? legacyTemplateIdsByLabel.get(node.name)+ : undefined);+ if ((templateIds?.length ?? 0) > 1) {+ references.push({+ type: "unresolved-template",+ path,+ templateName: node.name,+ sourceRange: node.sourceRange,+ });+ diagnostics.push({+ code: "ambiguous-template",+ severity: "warning",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ semanticKey: `name:${node.name}`,+ templateNames: templateIds!.map(+ (templateId) => templateNameById.get(templateId) ?? node.name+ ),+ sourceRange: node.sourceRange,+ });+ continue;+ }if (templateIds?.length === 1) {+ const templateInstance = instances.get(templateIds[0]);+ const componentBinding =+ templateInstance === undefined+ ? undefined+ : getMdxNamedTemplateComponentBinding({+ instance: templateInstance,+ node,+ });references.push({type: "resolved-template",path,- templateName: node.name,- props: node.props,+ templateName: templateNameById.get(templateIds[0]) ?? node.name,+ props:+ componentBinding?.props.map(({ prop }) => prop) ?? node.props,+ propBindings: componentBinding?.props.map(+ ({ source, requiresAssetReference }) => ({+ source,+ requiresAssetReference,+ })+ ),templateInstanceId: templateIds[0],sourceRange: node.sourceRange,});} else {+ const standardTemplateIds =+ standard === undefined+ ? undefined+ : templateIdsByStandardKey.get(standard.key);+ if (+ standard?.key.startsWith("component:") === true &&+ standardTemplateIds?.length === 1+ ) {+ const templateInstanceId = standardTemplateIds[0];+ references.push({+ type: "resolved-template",+ path,+ templateName:+ templateNameById.get(templateInstanceId) ?? standard.key,+ props: standard.props,+ propBindings: standard.propBindings,+ componentChildren: standard.componentChildren,+ templateInstanceId,+ sourceRange: node.sourceRange,+ });+ continue;+ }+ if (+ standard?.key.startsWith("component:") === true &&+ (standardTemplateIds?.length ?? 0) > 1+ ) {+ diagnostics.push({+ code: "ambiguous-template",+ severity: "warning",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ semanticKey: standard.key,+ templateNames: standardTemplateIds!.map(+ (templateId) => templateNameById.get(templateId) ?? standard.key+ ),+ sourceRange: node.sourceRange,+ });+ continue;+ }+ 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,@@ -101,6 +298,43 @@ export const resolveMdxTemplates = ({// and publication omits it, so descendant references are not actionable.continue;}+ } else {+ const standard = getMdxStandardTemplateBinding(node);+ const templateIds =+ standard === undefined+ ? undefined+ : templateIdsByStandardKey.get(standard.key);+ if (standard !== undefined && templateIds?.length === 1) {+ const templateInstanceId = templateIds[0];+ references.push({+ type: "resolved-template",+ path,+ templateName:+ templateNameById.get(templateInstanceId) ?? standard.key,+ props: standard.props,+ propBindings: standard.propBindings,+ componentChildren: standard.componentChildren,+ templateInstanceId,+ sourceRange: node.sourceRange,+ });+ } else if (standard !== undefined && (templateIds?.length ?? 0) > 1) {+ diagnostics.push({+ code: "ambiguous-template",+ severity: "warning",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ semanticKey: standard.key,+ templateNames: templateIds!.map(+ (templateId) => templateNameById.get(templateId) ?? standard.key+ ),+ sourceRange: node.sourceRange,+ });+ }+ if (standard?.key.startsWith("component:")) {+ continue;+ }}if (@@ -114,5 +348,5 @@ export const resolveMdxTemplates = ({};visit(document.children, []);- return { templateNames, references, diagnostics };+ return { templateStructure, templateNames, references, diagnostics };};diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.tsindex 186275c7f8..614bc36104 100644--- a/packages/project-build/src/runtime/output-schemas.ts+++ b/packages/project-build/src/runtime/output-schemas.ts@@ -639,6 +639,7 @@ export const runtimeOutputSchemas = {instanceIds: stringArray,label: z.string(),}),+ "instances.setName": looseObject({ instanceId: id, name: z.string() }),"styles.getDeclarations": looseObject({declarations: z.array(declarationSummary),...outputPage,diff --git a/packages/project-build/src/runtime/page-copy.test.tsx b/packages/project-build/src/runtime/page-copy.test.tsxindex 3fe62746b7..50c68e7e63 100644--- a/packages/project-build/src/runtime/page-copy.test.tsx+++ b/packages/project-build/src/runtime/page-copy.test.tsx@@ -41,7 +41,7 @@ import {updatePageTemplate,} from "./page-copy";import {- $,+ createTemplateComponentFixture,css,expression,Parameter,@@ -51,6 +51,11 @@ import {} from "@webstudio-is/template";import { applyBuilderPatchTransactions } from "../state/patch";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Fragment = createTemplateComponentFixture("Fragment");+const Slot = createTemplateComponentFixture("Slot");+const createNanoId = () => createId("nano");const { deduplicateName, deduplicatePath, joinPath } = pageCopyTesting;@@ -177,7 +182,7 @@ const createConflictingRootStyleProjects = () => {color: red;`}>- <$.Body ws:id="source-body"></$.Body>+ <Body ws:id="source-body"></Body></ws.root>),pages: sourcePages,@@ -190,7 +195,7 @@ const createConflictingRootStyleProjects = () => {color: blue;`}>- <$.Body ws:id="target-body"></$.Body>+ <Body ws:id="target-body"></Body></ws.root>),pages: createDefaultPages({@@ -871,13 +876,13 @@ describe("insert page copy", () => {test("preserves slot content ids when duplicating page", () => {const dataWithoutPages = renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slotId">- <$.Fragment ws:id="fragmentId">- <$.Box ws:id="boxId"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>+ <Body ws:id="bodyId">+ <Slot ws:id="slotId">+ <Fragment ws:id="fragmentId">+ <Box ws:id="boxId"></Box>+ </Fragment>+ </Slot>+ </Body>);const data = getWebstudioDataStub({...dataWithoutPages,@@ -1123,7 +1128,7 @@ describe("insert page copy", () => {test("replace variables in page copy meta", () => {const bodyVariable = new Variable("bodyVariable", "");const dataWithoutPage = renderData(- <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}></$.Body>+ <Body ws:id="bodyId" vars={expression`${bodyVariable}`}></Body>);const [variableId] = dataWithoutPage.dataSources.keys();const variableIdentifier = encodeDataVariableId(variableId);@@ -1256,9 +1261,9 @@ describe("insert page copy", () => {}),...renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">{expression`${globalVariable}`}</$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">{expression`${globalVariable}`}</Box>+ </Body></ws.root>),};@@ -1294,9 +1299,9 @@ describe("insert page copy", () => {}),...renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">{expression`${globalVariable}`}</$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">{expression`${globalVariable}`}</Box>+ </Body></ws.root>,// generate different ids in source and data projectscreateNanoId@@ -1309,7 +1314,7 @@ describe("insert page copy", () => {}),...renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>- <$.Body ws:id="anotherBodyId"></$.Body>+ <Body ws:id="anotherBodyId"></Body></ws.root>,// generate different ids in source and data projectscreateNanoId@@ -1346,9 +1351,9 @@ describe("insert page copy", () => {}),...renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">{expression`${globalVariable}`}</$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="boxId">{expression`${globalVariable}`}</Box>+ </Body></ws.root>,// generate different ids in source and data projectscreateNanoId@@ -1360,7 +1365,7 @@ describe("insert page copy", () => {rootInstanceId: "anotherBodyId",}),// generate different ids in source and data projects- ...renderData(<$.Body ws:id="anotherBodyId"></$.Body>, createNanoId),+ ...renderData(<Body ws:id="anotherBodyId"></Body>, createNanoId),};insertPageCopyMutable({source: { data: sourceData, pageId: sourceData.pages.homePageId },@@ -1387,9 +1392,9 @@ describe("insert page copy", () => {test("delete page system in favor of global one", () => {const pageSystemVariable = new Parameter("system");const dataWithoutPages = renderData(- <$.Body ws:id="bodyId" vars={expression`${pageSystemVariable}`}>- <$.Box ws:id="boxId">{expression`${pageSystemVariable}`}</$.Box>- </$.Body>+ <Body ws:id="bodyId" vars={expression`${pageSystemVariable}`}>+ <Box ws:id="boxId">{expression`${pageSystemVariable}`}</Box>+ </Body>);const [pageSystemVariableId] = dataWithoutPages.dataSources.keys();const data = {@@ -1426,9 +1431,9 @@ describe("insert page copy", () => {test("insert page from template with transformed metadata", () => {const templateVariable = new Variable("templateVariable", "");const dataWithoutPages = renderData(- <$.Body ws:id="templateBodyId" vars={expression`${templateVariable}`}>- <$.Box ws:id="boxId">{expression`${templateVariable}`}</$.Box>- </$.Body>+ <Body ws:id="templateBodyId" vars={expression`${templateVariable}`}>+ <Box ws:id="boxId">{expression`${templateVariable}`}</Box>+ </Body>);const [templateVariableId] = dataWithoutPages.dataSources.keys();const templateVariableIdentifier = encodeDataVariableId(templateVariableId);diff --git a/packages/project-build/src/runtime/pre-publish-audit.test.tsx b/packages/project-build/src/runtime/pre-publish-audit.test.tsxindex 0556e543d6..56e43ada87 100644--- a/packages/project-build/src/runtime/pre-publish-audit.test.tsx+++ b/packages/project-build/src/runtime/pre-publish-audit.test.tsx@@ -7,12 +7,25 @@ import {type Pages,} from "@webstudio-is/sdk";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";-import { $, renderData, ws } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+ ws,+} from "@webstudio-is/template";import {formatPrePublishAuditFinding,runPrePublishAudit,} from "./pre-publish-audit";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const CodeText = createTemplateComponentFixture("CodeText");+const Heading = createTemplateComponentFixture("Heading");+const Link = createTemplateComponentFixture("Link");+const Paragraph = createTemplateComponentFixture("Paragraph");+const Text = createTemplateComponentFixture("Text");+const Video = createTemplateComponentFixture("Video");+const createPages = (page: Page): Pages => {const rootFolder: Folder = {id: ROOT_FOLDER_ID,@@ -56,13 +69,13 @@ const runAudit = ({test("warns without blocking legacy invalid HTML", () => {const { instances, props } = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.element ws:tag="button">- <$.Heading ws:id="heading" ws:tag="h3">+ <Heading ws:id="heading" ws:tag="h3">Legacy accordion trigger- </$.Heading>+ </Heading></ws.element>- </$.Body>+ </Body>);const findings = runAudit({ instances, props });@@ -88,14 +101,14 @@ test("warns without blocking legacy invalid HTML", () => {test("allows valid publishable pages and ignores invalid drafts", () => {const { instances, props } = renderData(<>- <$.Body ws:id="body">- <$.Paragraph>Valid paragraph</$.Paragraph>- </$.Body>- <$.Body ws:id="draft-body">- <$.Paragraph>- <$.Heading ws:tag="h2">Invalid draft heading</$.Heading>- </$.Paragraph>- </$.Body>+ <Body ws:id="body">+ <Paragraph>Valid paragraph</Paragraph>+ </Body>+ <Body ws:id="draft-body">+ <Paragraph>+ <Heading ws:tag="h2">Invalid draft heading</Heading>+ </Paragraph>+ </Body></>);const pages = createPages(marketEdgePage);@@ -120,11 +133,11 @@ test("allows valid publishable pages and ignores invalid drafts", () => {test("allows valid legacy CodeText children", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.CodeText>- <$.Text ws:tag="span">Legacy code text</$.Text>- </$.CodeText>- </$.Body>+ <Body ws:id="body">+ <CodeText>+ <Text ws:tag="span">Legacy code text</Text>+ </CodeText>+ </Body>);expect(runAudit({ instances, props })).toEqual([]);@@ -132,14 +145,14 @@ test("allows valid legacy CodeText children", () => {test("allows Video inside a Div with valid children", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box>- <$.Video>+ <Body ws:id="body">+ <Box>+ <Video><ws.element ws:tag="source" /><ws.element ws:tag="track" />- </$.Video>- </$.Box>- </$.Body>+ </Video>+ </Box>+ </Body>);expect(runAudit({ instances, props })).toEqual([]);@@ -147,13 +160,13 @@ test("allows Video inside a Div with valid children", () => {test("reports the Link constraint for Video inside a Div", () => {const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Link>- <$.Box>- <$.Video ws:id="video" controls />- </$.Box>- </$.Link>- </$.Body>+ <Body ws:id="body">+ <Link>+ <Box>+ <Video ws:id="video" controls />+ </Box>+ </Link>+ </Body>);expect(runAudit({ instances, props })).toEqual([@@ -173,11 +186,11 @@ test("reports the Link constraint for Video inside a Div", () => {test("warns about unknown element tags without throwing", () => {const { instances, props } = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.element ws:id="custom" ws:tag="custom-element">- <$.Paragraph>Custom element content</$.Paragraph>+ <Paragraph>Custom element content</Paragraph></ws.element>- </$.Body>+ </Body>);expect(runAudit({ instances, props })).toEqual([@@ -198,9 +211,9 @@ test("warns about unknown element tags without throwing", () => {test("allows legacy components with unknown tags", () => {const { instances, props } = renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.element ws:id="legacy" ws:tag="legacy-element" />- </$.Body>+ </Body>);const legacyInstance = instances.get("legacy");if (legacyInstance === undefined) {@@ -212,7 +225,7 @@ test("allows legacy components with unknown tags", () => {});test("blocks publishing when required audit input is unavailable", () => {- const { instances, props } = renderData(<$.Body ws:id="body"></$.Body>);+ const { instances, props } = renderData(<Body ws:id="body"></Body>);const findings = runPrePublishAudit({pages: undefined,@@ -235,7 +248,7 @@ test("blocks publishing when required audit input is unavailable", () => {});test("includes existing resource integrity checks in the audit pipeline", () => {- const { instances, props } = renderData(<$.Body ws:id="body"></$.Body>);+ const { instances, props } = renderData(<Body ws:id="body"></Body>);const findings = runPrePublishAudit({pages: createPages(marketEdgePage),instances,@@ -272,7 +285,7 @@ test("includes existing resource integrity checks in the audit pipeline", () =>});test("includes Content Block source integrity checks in the audit pipeline", () => {- const { instances, props } = renderData(<$.Body ws:id="body"></$.Body>);+ const { instances, props } = renderData(<Body ws:id="body"></Body>);instances.set("block", {type: "instance",id: "block",diff --git a/packages/project-build/src/runtime/published-mdx.test.ts b/packages/project-build/src/runtime/published-mdx.test.tsindex bba788d605..eac1648f97 100644--- a/packages/project-build/src/runtime/published-mdx.test.ts+++ b/packages/project-build/src/runtime/published-mdx.test.ts@@ -10,6 +10,7 @@ import {materializePublishedMdx,type PublishedMdxRoot,} from "./published-mdx";+import { InvalidMdxTemplateStructureError } from "./mdx-template-resolution";const revision = (value: string) => `sha256:${value.repeat(64)}` as const;@@ -26,26 +27,26 @@ const createData = ({type: "instance",id: "block",component: "ws:block",- children: withTemplate ? [{ type: "id", value: "templates" }] : [],+ children: [{ type: "id", value: "templates" }],};- const instances: Instance[] = [block];+ const instances: Instance[] = [+ block,+ {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: withTemplate ? [{ type: "id", value: "hero" }] : [],+ },+ ];if (withTemplate) {- instances.push(- {- type: "instance",- id: "templates",- component: "ws:block-template",- children: [{ type: "id", value: "hero" }],- },- {- type: "instance",- id: "hero",- component: "ws:element",- tag: "section",- label: "Hero",- children: [{ type: "text", value: "Template body" }],- }- );+ instances.push({+ type: "instance",+ id: "hero",+ component: "ws:element",+ tag: "section",+ label: "Hero",+ children: [{ type: "text", value: "Template body" }],+ });}return {instances: new Map(instances.map((instance) => [instance.id, instance])),@@ -126,6 +127,47 @@ describe("published MDX materialization", () => {expect(getFragmentText(result.roots[0].fragment)).toContain("Published");});+ test("rejects publication with multiple Templates containers", async () => {+ const data = createData({ withTemplate: true });+ const block = data.instances.get("block");+ if (block === undefined) {+ throw new Error("Expected Content Block");+ }+ block.children.push({ type: "id", value: "templates-2" });+ data.instances.set("templates-2", {+ type: "instance",+ id: "templates-2",+ component: "ws:block-template",+ children: [],+ });++ await expect(+ materializePublishedMdx({+ route: "/blog/article",+ data,+ artifact: createArtifact([{ id: "article", source: "# Published" }]),+ metas: new Map(),+ projectId: "project",+ })+ ).rejects.toBeInstanceOf(InvalidMdxTemplateStructureError);+ });++ test("rejects publication without a Templates container", async () => {+ const data = createData({});+ data.instances.get("block")!.children = [];+ data.instances.delete("templates");++ await expect(+ materializePublishedMdx({+ route: "/blog/article",+ data,+ artifact: createArtifact([{ id: "article", source: "# Published" }]),+ metas: new Map(),+ projectId: "project",+ })+ ).rejects.toBeInstanceOf(InvalidMdxTemplateStructureError);+ });+test("resolves referenced document frontmatter for the designed shell", async () => {const artifact = createArtifact([{@@ -403,6 +445,110 @@ featureImage:expect(result.roots).toHaveLength(21);});+ test("publishes named JSX with its authored children", async () => {+ const data = createData({ withTemplate: true });+ const hero = data.instances.get("hero");+ if (hero === undefined) {+ throw new Error("Expected Hero template instance");+ }+ hero.children = [{ type: "id", value: "template-default" }];+ data.instances.set("template-default", {+ type: "instance",+ id: "template-default",+ component: "ws:element",+ tag: "p",+ children: [{ type: "text", value: "Template body" }],+ });+ const result = await materializePublishedMdx({+ route: "/",+ data,+ artifact: createArtifact([+ { id: "article", source: "<Hero>Published body</Hero>" },+ ]),+ metas: new Map(),+ projectId: "project",+ });++ expect(getFragmentText(result.roots[0].fragment)).toContain(+ "Published body"+ );+ expect(getFragmentText(result.roots[0].fragment)).not.toContain(+ "Template body"+ );+ });++ test("materializes one MDX Asset through each Content Block's template scope", async () => {+ const data = createData({});+ data.instances.get("block")!.children = [+ { type: "id", value: "templates-a" },+ ];+ data.instances.set("templates-a", {+ type: "instance",+ id: "templates-a",+ component: "ws:block-template",+ children: [{ type: "id", value: "heading-a" }],+ });+ data.instances.set("heading-a", {+ type: "instance",+ id: "heading-a",+ component: "ws:element",+ tag: "h1",+ label: "First scope heading",+ children: [],+ });+ data.instances.set("block-b", {+ type: "instance",+ id: "block-b",+ component: "ws:block",+ children: [{ type: "id", value: "templates-b" }],+ });+ data.instances.set("templates-b", {+ type: "instance",+ id: "templates-b",+ component: "ws:block-template",+ children: [{ type: "id", value: "heading-b" }],+ });+ data.instances.set("heading-b", {+ type: "instance",+ id: "heading-b",+ component: "ws:element",+ tag: "h1",+ label: "Second scope heading",+ children: [],+ });+ data.props.set("source-b", {+ id: "source-b",+ instanceId: "block-b",+ name: "src",+ type: "asset",+ value: "article",+ });++ const result = await materializePublishedMdx({+ route: "/",+ data,+ artifact: createArtifact([{ id: "article", source: "# Shared\n" }]),+ metas: new Map(),+ projectId: "project",+ });++ expect(+ result.roots.map((root) => ({+ blockInstanceId: root.identity.blockInstanceId,+ labels: root.fragment.instances.map(({ label }) => label),+ }))+ ).toEqual([+ {+ blockInstanceId: "block",+ labels: ["First scope heading"],+ },+ {+ blockInstanceId: "block-b",+ labels: ["Second scope heading"],+ },+ ]);+ });+test("omits an unresolved template subtree and keeps valid siblings", async () => {const result = await materializePublishedMdx({route: "/",@@ -575,6 +721,104 @@ featureImage:);});+ test("keeps Asset bindings when a published Markdown image uses a template", async () => {+ const source = "\n";+ const document = await parseMdxDocument({ source });+ const data = createData({});+ data.instances.get("block")!.children = [+ { type: "id", value: "templates" },+ ];+ data.instances.set("templates", {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: [{ type: "id", value: "image-template" }],+ });+ data.instances.set("image-template", {+ type: "instance",+ id: "image-template",+ component: "Image",+ label: "Image",+ children: [],+ });+ const result = await materializePublishedMdx({+ route: "/",+ data,+ artifact: createArtifact([{ id: "article", source }], {+ article: discoverMdxBodyAssetReferences({+ document,+ sourcePath: "article.mdx",+ assetIdsByPath: new Map([["images/hero.png", "hero-image"]]),+ }),+ }),+ metas: new Map(),+ projectId: "project",+ });++ expect(+ result.roots[0].fragment.props.map(({ name, type, value }) => ({+ name,+ type,+ value,+ }))+ ).toEqual(+ ["src", "width", "height", "alt"].map((name) => ({+ name,+ type: "asset",+ value: "hero-image",+ }))+ );+ });++ test("keeps Asset bindings for a published named Image template", async () => {+ const source = '<Image src="./images/hero.png" />\n';+ const document = await parseMdxDocument({ source });+ const data = createData({});+ data.instances.get("block")!.children = [+ { type: "id", value: "templates" },+ ];+ data.instances.set("templates", {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: [{ type: "id", value: "image-template" }],+ });+ data.instances.set("image-template", {+ type: "instance",+ id: "image-template",+ component: "Image",+ label: "Image",+ children: [],+ });+ const result = await materializePublishedMdx({+ route: "/",+ data,+ artifact: createArtifact([{ id: "article", source }], {+ article: discoverMdxBodyAssetReferences({+ document,+ sourcePath: "article.mdx",+ assetIdsByPath: new Map([["images/hero.png", "hero-image"]]),+ }),+ }),+ metas: new Map(),+ projectId: "project",+ });++ expect(+ result.roots[0].fragment.props.map(({ name, type, value }) => ({+ name,+ type,+ value,+ }))+ ).toEqual(+ ["src", "width", "height", "alt"].map((name) => ({+ name,+ type: "asset",+ value: "hero-image",+ }))+ );+ });+test("warns for a missing source but recovers unsafe authored content", async () => {const missing = await materializePublishedMdx({route: "/",diff --git a/packages/project-build/src/runtime/published-mdx.ts b/packages/project-build/src/runtime/published-mdx.tsindex b69f03b893..de2bd319a5 100644--- a/packages/project-build/src/runtime/published-mdx.ts+++ b/packages/project-build/src/runtime/published-mdx.ts@@ -1,3 +1,7 @@+/**+ * Materializes MDX Assets for published builds with the same template and+ * Asset-reference behavior used by the Builder runtime.+ */import {parseMdxDocumentRecovering,type MdxDocument,@@ -35,7 +39,10 @@ import {materializeMdxTemplates,type MdxTemplateDependency,} from "./mdx-materialization";-import { resolveMdxTemplates } from "./mdx-template-resolution";+import {+ assertMdxTemplateStructure,+ resolveMdxTemplates,+} from "./mdx-template-resolution";import {createMdxContentModelDiagnostics,createMdxDiagnostics,@@ -113,7 +120,7 @@ export const getUnsafeDynamicPublishedMdxDiagnostic = ({}};-const publishedMdxMaterializerRevision = 1;+const publishedMdxMaterializerRevision = 2;export const createPublishedMdxMaterializationCache = () => ({documents: new Map<@@ -178,11 +185,14 @@ const createDependencyRevision = async ({identity,nestedDocuments,assetReferences: [...assetReferences]- .map(({ assetId, suffix }) => ({ assetId, suffix }))+ .map(({ path, assetId, suffix, structured }) => ({+ path,+ assetId,+ suffix,+ structured,+ })).sort((left, right) =>- `${left.assetId}${left.suffix ?? ""}`.localeCompare(- `${right.assetId}${right.suffix ?? ""}`- )+ JSON.stringify(left).localeCompare(JSON.stringify(right))),assetDependencies: [...assetDependencies].sort((left, right) =>left.id.localeCompare(right.id)@@ -409,31 +419,35 @@ export const materializePublishedMdx = async ({continue;}const document = parsed.document;+ const assetReferences =+ artifact.assetValueReferences?.[candidate._id] ?? [];const resolution = resolveMdxTemplates({document,identity,instances: data.instances,+ props: data.props,metas,});+ assertMdxTemplateStructure(resolution);const templates = await materializeMdxTemplates({identity,resolution,data,metas,projectId,+ assetReferences,});const referencedTemplateNames = Array.from(new Set(resolution.references.map((reference) => reference.templateName)));- const assetReferences =- artifact.assetValueReferences?.[candidate._id] ?? [];const materialized = materializeMdxAuthoredContent({identity,document,templateMaterialization: templates,assetReferences,+ metas,});if (materialized.fragment.instances.length > contentEngineLimits.mdxNodes ||@@ -449,6 +463,9 @@ export const materializePublishedMdx = async ({for (const diagnostic of templates.diagnostics) {warnings.push({ route, diagnostic });}+ for (const diagnostic of materialized.diagnostics ?? []) {+ warnings.push({ route, diagnostic });+ }for (const diagnostic of createMdxContentModelDiagnostics({root: materialized,metas,diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.tsindex 2b7ae7b475..7a97d56a4b 100644--- a/packages/project-build/src/runtime/registry.test.ts+++ b/packages/project-build/src/runtime/registry.test.ts@@ -2416,6 +2416,7 @@ describe("builder runtime registry", () => {["instances.updateTextTree", {}],["instances.setTag", {}],["instances.setLabel", {}],+ ["instances.setName", {}],["styles.updateDeclarations", { updates: {} }],["styles.deleteDeclarations", { deletions: {} }],["styles.updateSelectedDeclarations", { updates: {} }],diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.tsindex 9d2344614a..a6dfee4cc1 100644--- a/packages/project-build/src/runtime/registry.ts+++ b/packages/project-build/src/runtime/registry.ts@@ -18,6 +18,7 @@ import {import { pageCopyNamespaces } from "../contracts/namespaces";import { builderRuntimeContext, type BuilderRuntimeContext } from "./context";import { z } from "zod";+import { isMdxTemplateComponentName } from "@webstudio-is/content-engine/mdx";import * as assets from "./assets";import * as assetResources from "./asset-resources";import * as bindingVerification from "./binding-verification";@@ -374,7 +375,10 @@ const contentBlockTemplateMigrationInput = z.object({z.object({type: z.literal("rename"),from: z.string().min(1),- to: z.string().min(1),+ to: z+ .string()+ .min(1)+ .refine(isMdxTemplateComponentName, "Use a PascalCase MDX name"),}),z.object({ type: z.literal("remove"), name: z.string().min(1) }),]),@@ -1718,6 +1722,17 @@ export const builderRuntimeOperations = [instances.setInstanceLabelInput,({ state, input }) => instances.setInstanceLabel(state, input)),+ runtimeOperation(+ "instances.setName",+ api("set-instance-name", "setInstanceName", "edit"),+ mutationContract({+ readNamespaces: ["instances", "props"],+ writeNamespaces: ["instances"],+ retryOnConflict: true,+ }),+ instances.setInstanceNameInput,+ ({ state, input }) => instances.setInstanceName(state, input)+ ),runtimeOperation("styles.getDeclarations",api("get-styles", "getStyleDeclarations"),diff --git a/packages/project-build/src/template.tsx b/packages/project-build/src/template.tsxindex 0fc3fbe870..8c9703af7f 100644--- a/packages/project-build/src/template.tsx+++ b/packages/project-build/src/template.tsx@@ -4,8 +4,9 @@ import {type Pages,type WebstudioData,} from "@webstudio-is/sdk";-import { coreTemplates } from "@webstudio-is/sdk/core-templates";-import { css, renderData, ws } from "@webstudio-is/template";+import { coreTemplates } from "@webstudio-is/sdk-components-registry/core-templates";+import { componentIds } from "@webstudio-is/sdk-components-registry/components";+import { css, renderData } from "@webstudio-is/template";import { createRootFolder } from "./shared/pages-utils";export const createPages = (): WebstudioData => {@@ -21,10 +22,9 @@ export const createPages = (): WebstudioData => {const data = renderData(<>{/* home page body */}- <ws.element ws:tag="body" ws:id={homeBodyId}></ws.element>+ <body ws:id={homeBodyId} />{/* not found page body */}- <ws.element- ws:tag="body"+ <bodyws:id={notFoundBodyId}ws:style={css`display: flex;@@ -33,9 +33,8 @@ export const createPages = (): WebstudioData => {background-color: #fff;`}>- <ws.element ws:tag="div">- <ws.element- ws:tag="div"+ <div>+ <divws:style={css`position: relative;text-align: center;@@ -45,9 +44,8 @@ export const createPages = (): WebstudioData => {letter-spacing: -0.05em;`}>- <ws.element ws:tag="div">404</ws.element>- <ws.element- ws:tag="div"+ <div>404</div>+ <divws:style={css`position: absolute;inset: 0 -0.125rem 0 0.125rem;@@ -55,9 +53,8 @@ export const createPages = (): WebstudioData => {`}>404- </ws.element>- <ws.element- ws:tag="div"+ </div>+ <divws:style={css`position: absolute;inset: 0 0.125rem 0 -0.125rem;@@ -65,9 +62,8 @@ export const createPages = (): WebstudioData => {`}>404- </ws.element>- <ws.element- ws:tag="div"+ </div>+ <divws:style={css`position: absolute;top: 50%;@@ -76,10 +72,9 @@ export const createPages = (): WebstudioData => {background-color: #fff;height: 0.375rem;`}- ></ws.element>- </ws.element>- <ws.element- ws:tag="p"+ />+ </div>+ <pws:style={css`margin-top: 1.5rem;font-weight: 700;@@ -89,13 +84,14 @@ export const createPages = (): WebstudioData => {`}>PAGE NOT FOUND- </ws.element>- </ws.element>+ </p>+ </div>{coreTemplates.builtWithWebstudio.template}- </ws.element>+ </body></>,() => createId("nano"),- breakpoints+ breakpoints,+ { componentIds });const pages: Pages = {diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.tsindex 1af6e23341..ce10547e3b 100644--- a/packages/protocol/src/builder-api/operation-docs.ts+++ b/packages/protocol/src/builder-api/operation-docs.ts@@ -344,7 +344,7 @@ const curatedPublicApiOperationDocumentation = [description:"Insert authored/styled Webstudio JSX with components, text, props, tokens, and styles. The CLI converts the JSX string to structured Webstudio data before mutation.",examples: [- 'MCP tool: insert-fragment {"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\'section\' />"}',+ 'MCP tool: insert-fragment {"parentInstanceId":"parent-id","fragment":"<section />"}',],},{diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsxindex 3e00280030..ffe0e87717 100644--- a/packages/react-sdk/src/component-generator.test.tsx+++ b/packages/react-sdk/src/component-generator.test.tsx@@ -10,14 +10,13 @@ import {type WsComponentMeta,} from "@webstudio-is/sdk";import {- $,+ createTemplateComponentFixture,ActionValue,AssetValue,PageValue,Parameter,ResourceValue,Variable,- createProxy,expression,renderData,ws,@@ -27,6 +26,23 @@ import {generateWebstudioComponent,} from "./component-generator";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Button = createTemplateComponentFixture("Button");+const Form = createTemplateComponentFixture("Form");+const Fragment = createTemplateComponentFixture("Fragment");+const HeadSlot = createTemplateComponentFixture("HeadSlot");+const Heading = createTemplateComponentFixture("Heading");+const Image = createTemplateComponentFixture("Image");+const Input = createTemplateComponentFixture("Input");+const Label = createTemplateComponentFixture("Label");+const Tabs = createTemplateComponentFixture("Tabs");+const TabsContent = createTemplateComponentFixture("TabsContent");+const TabsList = createTemplateComponentFixture("TabsList");+const TabsTrigger = createTemplateComponentFixture("TabsTrigger");+const Text = createTemplateComponentFixture("Text");+const Vimeo = createTemplateComponentFixture("Vimeo");+const virtualRoot = "/component-generator-test";const virtualConfig = `${virtualRoot}/tsconfig.json`;const virtualFile = `${virtualRoot}/virtual.tsx`;@@ -96,7 +112,7 @@ test("generate jsx element with children and without them", () => {indexesWithinAncestors: new Map(),metas: new Map(),children: [{ type: "id", value: "body" }],- ...renderData(<$.Body ws:id="body">Children</$.Body>),+ ...renderData(<Body ws:id="body">Children</Body>),})).toEqual(validateJSX(@@ -114,7 +130,7 @@ test("generate jsx element with children and without them", () => {indexesWithinAncestors: new Map(),metas: new Map(),children: [{ type: "id", value: "image" }],- ...renderData(<$.Image ws:id="image"></$.Image>),+ ...renderData(<Image ws:id="image"></Image>),})).toEqual(validateJSX(@@ -125,8 +141,13 @@ test("generate jsx element with children and without them", () => {);});-test("generate jsx element with namespaces components", () => {- const library = createProxy("@webstudio-is/library:");+test("generate jsx element with a namespaced component", () => {+ const LibraryBody = createTemplateComponentFixture(+ "@webstudio-is/library:Body"+ );+ const LibraryImage = createTemplateComponentFixture(+ "@webstudio-is/library:Image"+ );expect(generateJsxChildren({scope: createScope(),@@ -134,7 +155,7 @@ test("generate jsx element with namespaces components", () => {indexesWithinAncestors: new Map(),metas: new Map(),children: [{ type: "id", value: "body" }],- ...renderData(<library.Body ws:id="body"></library.Body>),+ ...renderData(<LibraryBody ws:id="body"></LibraryBody>),})).toEqual(validateJSX(@@ -150,7 +171,7 @@ test("generate jsx element with namespaces components", () => {indexesWithinAncestors: new Map(),metas: new Map(),children: [{ type: "id", value: "image" }],- ...renderData(<library.Image ws:id="image"></library.Image>),+ ...renderData(<LibraryImage ws:id="image"></LibraryImage>),})).toEqual(validateJSX(@@ -169,7 +190,7 @@ test("generate jsx element with literal props", () => {indexesWithinAncestors: new Map(),metas: new Map(),children: [{ type: "id", value: "body" }],- ...renderData(<$.Body ws:id="body" string="string" number={0}></$.Body>),+ ...renderData(<Body ws:id="body" string="string" number={0}></Body>),})).toEqual(validateJSX(@@ -188,11 +209,11 @@ test("generate jsx element with literal props", () => {metas: new Map(),children: [{ type: "id", value: "image" }],...renderData(- <$.Image+ <Imagews:id="image"boolean={true}stringArray={["value1", "value2"]}- ></$.Image>+ ></Image>),})).toEqual(@@ -207,7 +228,7 @@ test("generate jsx element with literal props", () => {});test("deduplicates duplicate instance props when generating jsx", () => {- const data = renderData(<$.Image ws:id="image" width={100}></$.Image>);+ const data = renderData(<Image ws:id="image" width={100}></Image>);const widthProp = Array.from(data.props.values()).find((prop) => prop.instanceId === "image" && prop.name === "width");@@ -248,11 +269,11 @@ test("ignore asset and page props", () => {metas: new Map(),children: [{ type: "id", value: "box" }],...renderData(- <$.Box+ <Boxws:id="box"page={new PageValue("pageId")}asset={new AssetValue("assetId")}- ></$.Box>+ ></Box>),})).toEqual(@@ -274,12 +295,12 @@ test("generate jsx element with data sources and action", () => {metas: new Map(),children: [{ type: "id", value: "box" }],...renderData(- <$.Box+ <Boxws:id="box"variable={expression`${variable}`}expression={expression`${variable} + 1`}onChange={new ActionValue(["value"], expression`${variable} = value`)}- ></$.Box>+ ></Box>),})).toEqual(@@ -305,7 +326,7 @@ test("generate jsx element with condition based on show prop", () => {indexesWithinAncestors: new Map(),metas: new Map(),children: [{ type: "id", value: "box" }],- ...renderData(<$.Box ws:id="box" data-ws-show={true}></$.Box>),+ ...renderData(<Box ws:id="box" data-ws-show={true}></Box>),})).toEqual(validateJSX(@@ -321,7 +342,7 @@ test("generate jsx element with condition based on show prop", () => {indexesWithinAncestors: new Map(),metas: new Map(),children: [{ type: "id", value: "box" }],- ...renderData(<$.Box ws:id="box" data-ws-show={false}></$.Box>),+ ...renderData(<Box ws:id="box" data-ws-show={false}></Box>),})).toEqual("");const condition = new Variable("condition", false);@@ -333,7 +354,7 @@ test("generate jsx element with condition based on show prop", () => {metas: new Map(),children: [{ type: "id", value: "box" }],...renderData(- <$.Box ws:id="box" data-ws-show={expression`${condition}`}></$.Box>+ <Box ws:id="box" data-ws-show={expression`${condition}`}></Box>),})).toEqual(@@ -486,10 +507,10 @@ test("generate jsx children with nested instances", () => {usedDataSources: new Map(),indexesWithinAncestors: new Map(),...renderData(- <$.Form ws:id="form" prop="value">- <$.Input></$.Input>- <$.Button></$.Button>- </$.Form>+ <Form ws:id="form" prop="value">+ <Input></Input>+ <Button></Button>+ </Form>),})).toEqual(@@ -506,7 +527,9 @@ test("generate jsx children with nested instances", () => {});test("deduplicate base and namespaced components with same short name", () => {- const radix = createProxy("@webstudio-is/sdk-component-react-radix:");+ const RadixButton = createTemplateComponentFixture(+ "@webstudio-is/sdk-component-react-radix:Button"+ );expect(generateJsxChildren({scope: createScope(),@@ -518,10 +541,10 @@ test("deduplicate base and namespaced components with same short name", () => {usedDataSources: new Map(),indexesWithinAncestors: new Map(),...renderData(- <$.Fragment>- <$.Button ws:id="button1"></$.Button>- <radix.Button ws:id="button2"></radix.Button>- </$.Fragment>+ <Fragment>+ <Button ws:id="button1"></Button>+ <RadixButton ws:id="button2"></RadixButton>+ </Fragment>),})).toEqual(@@ -544,8 +567,8 @@ test("generate collection component as map", () => {indexesWithinAncestors: new Map(),...renderData(<ws.collection ws:id="list" data={expression`${data}`} item={element}>- <$.Label></$.Label>- <$.Button aria-label={expression`${element}`}></$.Button>+ <Label></Label>+ <Button aria-label={expression`${element}`}></Button></ws.collection>),})@@ -589,8 +612,8 @@ test("generate collection component with itemKey", () => {item={element}itemKey={key}>- <$.Label>{expression`${key}`}</$.Label>- <$.Button aria-label={expression`${element}`}></$.Button>+ <Label>{expression`${key}`}</Label>+ <Button aria-label={expression`${element}`}></Button></ws.collection>),})@@ -629,14 +652,14 @@ test("generate component with variables and actions", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="body">- <$.Input+ <Body ws:id="body">+ <Inputvalue={expression`${variable}`}onChange={new ActionValue(["value"], expression`${variable} = value`)}/>- </$.Body>+ </Body>),})).toEqual(@@ -667,7 +690,7 @@ test("merge classes if no className", () => {rootInstanceId: "body",parameters: [],metas: new Map(),- ...renderData(<$.Body ws:id="body"></$.Body>),+ ...renderData(<Body ws:id="body"></Body>),})).toEqual(validateJSX(@@ -690,7 +713,7 @@ test("add classes and merge classes", () => {rootInstanceId: "body",parameters: [],metas: new Map(),- ...renderData(<$.Body ws:id="body" className='cls2 "cls3"'></$.Body>),+ ...renderData(<Body ws:id="body" className='cls2 "cls3"'></Body>),})).toEqual(validateJSX(@@ -713,7 +736,7 @@ test("add classes", () => {rootInstanceId: "body",parameters: [],metas: new Map(),- ...renderData(<$.Body ws:id="body" className='cls2 "cls3"'></$.Body>),+ ...renderData(<Body ws:id="body" className='cls2 "cls3"'></Body>),})).toEqual(validateJSX(@@ -728,7 +751,7 @@ test("add classes", () => {});test("merges class aliases when generating jsx", () => {- const data = renderData(<$.Body ws:id="body" className="standard"></$.Body>);+ const data = renderData(<Body ws:id="body" className="standard"></Body>);data.props.set("duplicate-class", {id: "duplicate-class",instanceId: "body",@@ -775,7 +798,7 @@ test.each("keeps the last value when %s and %s map to the same JSX prop",(standardName, jsxName) => {const generate = (attributes: [name: string, value: string][]) => {- const data = renderData(<$.Body ws:id="body"></$.Body>);+ const data = renderData(<Body ws:id="body"></Body>);const instance = data.instances.get("body");if (instance === undefined) {throw new Error("Expected Body instance");@@ -832,10 +855,10 @@ test("add bind classes and merge classes", () => {parameters: [],metas: new Map(),...renderData(- <$.Body+ <Bodyws:id="body"className={expression`${hasClass2} ? 'cls2' : ''`}- ></$.Body>+ ></Body>),})).toEqual(@@ -863,13 +886,13 @@ test("avoid generating collection parameter variable as state", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.collectionws:id="list"data={expression`${data}`}item={element}></ws.collection>- </$.Body>+ </Body>),})).toEqual(@@ -899,11 +922,11 @@ test("avoid generating collection parameter variable as state", () => {test("generate both page system and global system variables when present", () => {const system = new Parameter("system");const data = renderData(- <$.Body+ <Bodyws:id="body"data-page={expression`${system}.params.slug`}data-global={expression`$ws$system.params.slug`}- ></$.Body>+ ></Body>);expect(data.dataSources.size).toEqual(1);const [pageSystemVariableId] = data.dataSources.keys();@@ -964,11 +987,11 @@ test("generate resources loading", () => {parameters: [],metas: new Map(),...renderData(- <$.Body+ <Bodyws:id="body"data-data={expression`${dataVariable}`}data-resource={expression`${dataResource}`}- ></$.Body>+ ></Body>),})).toEqual(@@ -997,11 +1020,11 @@ test("avoid generating unused variables", () => {headers: [],});const data = renderData(- <$.Body+ <Bodyws:id="body"data-used={expression`${usedVariable}`}data-unused={expression`${unusedVariable} ${unusedParameter} ${unusedResource}`}- ></$.Body>+ ></Body>);expect(Array.from(data.props.values())).toEqual([expect.objectContaining({ name: "data-used" }),@@ -1047,9 +1070,9 @@ test("avoid generating descendant component", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.descendant></ws.descendant>- </$.Body>+ </Body>),})).toMatchInlineSnapshot(`@@ -1073,14 +1096,14 @@ test("generate conditional collection", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.collectionws:id="list"data-ws-show={expression`${condition}`}data={[]}item={collectionItem}></ws.collection>- </$.Body>+ </Body>),})).toMatchInlineSnapshot(`@@ -1119,7 +1142,7 @@ test("generate conditional body", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="body" data-ws-show={expression`${condition}`}></$.Body>+ <Body ws:id="body" data-ws-show={expression`${condition}`}></Body>),})).toMatchInlineSnapshot(`@@ -1169,11 +1192,11 @@ test("generate resource prop with configured form method", () => {],]),...renderData(- <$.Body ws:id="body">- <$.Form ws:id="form1" action={myResource}></$.Form>- <$.Form ws:id="form2" action={anotherResource}></$.Form>- <$.Form ws:id="form3" action={myResource} method="get"></$.Form>- </$.Body>+ <Body ws:id="body">+ <Form ws:id="form1" action={myResource}></Form>+ <Form ws:id="form2" action={anotherResource}></Form>+ <Form ws:id="form3" action={myResource} method="get"></Form>+ </Body>),})).toMatchInlineSnapshot(`@@ -1204,14 +1227,14 @@ test("skip unsafe properties", () => {parameters: [],metas: new Map(),...renderData(- <$.Body+ <Bodyws:id="body"{...{"": "unsafe","1-numeric-unsafe": "unsafe","click.prevent": "unsafe",}}- ></$.Body>+ ></Body>),})).toEqual(@@ -1236,14 +1259,14 @@ test("variable names can be js identifiers", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="body">- <$.Input+ <Body ws:id="body">+ <Inputvalue={expression`${variable}`}onChange={new ActionValue(["value"], expression`${variable} = value`)}/>- </$.Body>+ </Body>),})).toEqual(@@ -1266,7 +1289,7 @@ test("variable names can be js identifiers", () => {});test("renders nothing if only templates are present in block", () => {- const BlockTemplate = ws["block-template"];+ const BlockTemplate = ws.blockTemplate;expect(generateWebstudioComponent({classesMap: new Map(),@@ -1276,13 +1299,13 @@ test("renders nothing if only templates are present in block", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.block ws:id="block"><BlockTemplate>- <$.Box>Test</$.Box>+ <Box>Test</Box></BlockTemplate></ws.block>- </$.Body>+ </Body>),})).toEqual(@@ -1298,7 +1321,7 @@ test("renders nothing if only templates are present in block", () => {});test("renders only block children", () => {- const BlockTemplate = ws["block-template"];+ const BlockTemplate = ws.blockTemplate;expect(generateWebstudioComponent({@@ -1309,14 +1332,14 @@ test("renders only block children", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.block ws:id="block"><BlockTemplate>- <$.Box>Test</$.Box>+ <Box>Test</Box></BlockTemplate>- <$.Box>Child0</$.Box>+ <Box>Child0</Box></ws.block>- </$.Body>+ </Body>),})).toEqual(@@ -1344,9 +1367,9 @@ test("generate unset variables as undefined", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="body">- <$.Box>{expression`a + b`}</$.Box>- </$.Body>+ <Body ws:id="body">+ <Box>{expression`a + b`}</Box>+ </Body>),})).toEqual(@@ -1368,9 +1391,9 @@ test("generate global variables", () => {const rootVariable = new Variable("rootVariable", "root");const data = renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${rootVariable}`}>- <$.Body ws:id="body">- <$.Box>{expression`${rootVariable}`}</$.Box>- </$.Body>+ <Body ws:id="body">+ <Box>{expression`${rootVariable}`}</Box>+ </Body></ws.root>);data.instances.delete(ROOT_INSTANCE_ID);@@ -1404,9 +1427,9 @@ test("ignore unused global variables", () => {const rootVariable = new Variable("rootVariable", "root");const data = renderData(<ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${rootVariable}`}>- <$.Body ws:id="body">- <$.Box></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box></Box>+ </Body></ws.root>);data.instances.delete(ROOT_INSTANCE_ID);@@ -1446,20 +1469,20 @@ test("generate prop with index within ancestor", () => {["TabsContent", { indexWithinAncestor: "Tabs" }],]),...renderData(- <$.Body ws:id="body">- <$.Tabs>- <$.TabsList>- <$.TabsTrigger></$.TabsTrigger>- <$.Box>- <$.TabsTrigger></$.TabsTrigger>- </$.Box>- </$.TabsList>- <$.Box>- <$.TabsContent></$.TabsContent>- </$.Box>- <$.TabsContent></$.TabsContent>- </$.Tabs>- </$.Body>+ <Body ws:id="body">+ <Tabs>+ <TabsList>+ <TabsTrigger></TabsTrigger>+ <Box>+ <TabsTrigger></TabsTrigger>+ </Box>+ </TabsList>+ <Box>+ <TabsContent></TabsContent>+ </Box>+ <TabsContent></TabsContent>+ </Tabs>+ </Body>),})).toEqual(@@ -1491,7 +1514,7 @@ test("generate prop with index within ancestor", () => {});test("ignore ws:block-template when generate index attribute", () => {- const BlockTemplate = ws["block-template"];+ const BlockTemplate = ws.blockTemplate;expect(generateWebstudioComponent({classesMap: new Map(),@@ -1503,17 +1526,17 @@ test("ignore ws:block-template when generate index attribute", () => {["TabsTrigger", { indexWithinAncestor: "Tabs" }],]),...renderData(- <$.Body ws:id="bodyId">- <$.Tabs>+ <Body ws:id="bodyId">+ <Tabs><BlockTemplate>- <$.TabsTrigger></$.TabsTrigger>+ <TabsTrigger></TabsTrigger></BlockTemplate>- <$.Box>- <$.TabsTrigger></$.TabsTrigger>- </$.Box>- <$.TabsTrigger></$.TabsTrigger>- </$.Tabs>- </$.Body>+ <Box>+ <TabsTrigger></TabsTrigger>+ </Box>+ <TabsTrigger></TabsTrigger>+ </Tabs>+ </Body>),})).toEqual(@@ -1623,17 +1646,17 @@ test("renders pre-materialized dynamic Content Block candidates without loading"test("renders a Content Block shell with candidate frontmatter and body", () => {const document = new Parameter("document");const Block = ws.block;- const BlockBody = ws["content-block-body"];+ const BlockBody = ws.contentBlockBody;const data = renderData(- <$.Body ws:id="page">+ <Body ws:id="page"><Block ws:id="block" document={document}>- <$.Heading ws:id="title">+ <Heading ws:id="title">{expression`${document}.frontmatter.title`}- </$.Heading>+ </Heading><BlockBody ws:id="content" />- <$.Text ws:id="footer">Designed footer</$.Text>+ <Text ws:id="footer">Designed footer</Text></Block>- </$.Body>+ </Body>);data.instances.set("article-body", {type: "instance",@@ -1685,7 +1708,7 @@ test("render empty component when no instances found", () => {rootInstanceId: "",parameters: [],metas: new Map(),- ...renderData(<$.Body ws:id="bodyId"></$.Body>),+ ...renderData(<Body ws:id="bodyId"></Body>),})).toEqual(validateJSX(@@ -1708,9 +1731,9 @@ test("render tag property on components", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="spanId" ws:tag="span"></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box ws:id="spanId" ws:tag="span"></Box>+ </Body>),})).toEqual(@@ -1737,14 +1760,14 @@ test("converts instance attributes when tag enables HTML attributes", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="bodyId">- <$.Box+ <Body ws:id="bodyId">+ <Boxws:id="labelId"ws:tag="label"tabindex={0}readonly={true}- ></$.Box>- </$.Body>+ ></Box>+ </Body>),})).toEqual(@@ -1773,11 +1796,11 @@ test("render ws:element component with div tag by default", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element id="element1"><ws.element id="element2"></ws.element></ws.element>- </$.Body>+ </Body>),})).toEqual(@@ -1807,11 +1830,11 @@ test("render ws:element component with ws:tag", () => {parameters: [],metas: new Map(),...renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.element ws:tag="p" id="paragraph"><ws.element ws:tag="span" id="span"></ws.element></ws.element>- </$.Body>+ </Body>),})).toEqual(@@ -1887,13 +1910,13 @@ test("convert attributes to react compatible when render ws:element", () => {parameters: [],metas: new Map([[elementComponent, { presetStyle: { div: [] } }]]),...renderData(- <$.Body ws:id="bodyId">+ <Body ws:id="bodyId"><ws.elementclass="my-class"for="my-id"autocomplete="off"></ws.element>- </$.Body>+ </Body>),})).toEqual(@@ -1922,9 +1945,9 @@ test("convert attributes to react compatible when render components with tags",parameters: [],metas: new Map([["Box", { presetStyle: { div: [] } }]]),...renderData(- <$.Body ws:id="bodyId">- <$.Box class="my-class" for="my-id" autocomplete="off"></$.Box>- </$.Body>+ <Body ws:id="bodyId">+ <Box class="my-class" for="my-id" autocomplete="off"></Box>+ </Body>),})).toEqual(@@ -1963,9 +1986,9 @@ test("ignore props similar to standard attributes when react components defines],]),...renderData(- <$.Body ws:id="bodyId">- <$.Vimeo autoplay={true}></$.Vimeo>- </$.Body>+ <Body ws:id="bodyId">+ <Vimeo autoplay={true}></Vimeo>+ </Body>),})).toEqual(@@ -1992,13 +2015,9 @@ test("only converts the universal class alias on components without tags", () =>parameters: [],metas: new Map([["HeadSlot", {}]]),...renderData(- <$.Body ws:id="bodyId">- <$.HeadSlot- class="my-class"- for="my-id"- autocomplete="off"- ></$.HeadSlot>- </$.Body>+ <Body ws:id="bodyId">+ <HeadSlot class="my-class" for="my-id" autocomplete="off"></HeadSlot>+ </Body>),})).toEqual(diff --git a/packages/sdk-cli/src/generate-stories.test.ts b/packages/sdk-cli/src/generate-stories.test.tsxsimilarity index 57%rename from packages/sdk-cli/src/generate-stories.test.tsrename to packages/sdk-cli/src/generate-stories.test.tsxindex 5ffe1d2e46..71652a58f1 100644--- a/packages/sdk-cli/src/generate-stories.test.ts+++ b/packages/sdk-cli/src/generate-stories.test.tsx@@ -1,4 +1,3 @@-import { createElement } from "react";import {mkdir,mkdtemp,@@ -9,7 +8,7 @@ import {} from "node:fs/promises";import path from "node:path";import { afterEach, describe, expect, test } from "vitest";-import { $, type TemplateMeta } from "@webstudio-is/template";+import type { TemplateMeta } from "@webstudio-is/template";import type { WsComponentMeta } from "@webstudio-is/sdk";import { generateStories } from "./generate-stories";@@ -66,6 +65,13 @@ const labelMeta: WsComponentMeta = {props: {},};+const Box = () => null;+Box.displayName = "Box";+const BaseLabel = () => null;+BaseLabel.displayName = "Label";+const RadixLabel = () => null;+RadixLabel.displayName = "Label";+describe("generateStories", () => {test("generates stories from explicit package-local templates and metas", async () => {const root = await createTempPackage({@@ -78,12 +84,15 @@ describe("generateStories", () => {process.chdir(root);await generateStories({packageName: "@webstudio-is/sdk-components-react",- templates: {- Box: {- category: "general",- template: createElement($.Box, undefined, "Explicit story"),- } satisfies TemplateMeta,- },+ components: { Box },+ templates: [+ {+ meta: {+ category: "general",+ template: <Box />,+ } satisfies TemplateMeta,+ },+ ],metas: {Box: boxMeta,},@@ -94,6 +103,28 @@ describe("generateStories", () => {).resolves.toContain('title: "Components/Box"');});+ test("rejects templates that resolve to the same story name", async () => {+ const root = await createTempPackage({+ packageJson: {+ name: "@webstudio-is/sdk-components-react",+ type: "module",+ },+ });++ process.chdir(root);+ await expect(+ generateStories({+ packageName: "@webstudio-is/sdk-components-react",+ components: { Box },+ templates: [+ { meta: { category: "general", template: <Box /> } },+ { meta: { category: "general", template: <Box /> } },+ ],+ metas: { Box: boxMeta },+ })+ ).rejects.toThrow('Story name "Box" is generated more than once');+ });+test("imports default components from the base package even when local metas share the short name", async () => {const root = await createTempPackage({packageJson: {@@ -105,18 +136,28 @@ describe("generateStories", () => {process.chdir(root);await generateStories({packageName: "@webstudio-is/sdk-components-react-radix",- templates: {- BaseLabel: {- category: "general",- template: createElement($.Label, undefined, "Base label"),- } satisfies TemplateMeta,- },+ components: { Label: RadixLabel },+ templates: [+ {+ storyName: "BaseLabel",+ meta: {+ category: "general",+ template: <BaseLabel />,+ } satisfies TemplateMeta,+ },+ ],metas: {Label: {...labelMeta,label: "Radix Label",},},+ namespaceComponents: new Map([+ [+ "@webstudio-is/sdk-components-react/components",+ { Box, Label: BaseLabel },+ ],+ ]),namespaceMetas: new Map([["@webstudio-is/sdk-components-react/components",@@ -137,4 +178,35 @@ describe("generateStories", () => {);expect(story).not.toContain('from "../components"');});++ test("keeps namespaced component identity in generated stories", async () => {+ const root = await createTempPackage({+ packageJson: {+ name: "@webstudio-is/sdk-components-react-radix",+ type: "module",+ },+ });++ process.chdir(root);+ await generateStories({+ packageName: "@webstudio-is/sdk-components-react-radix",+ components: { Label: RadixLabel },+ templates: [+ {+ meta: {+ category: "general",+ template: <RadixLabel />,+ },+ },+ ],+ metas: { Label: labelMeta },+ namespaceMetas: new Map([+ ["@webstudio-is/sdk-components-react/components", { Box: boxMeta }],+ ]),+ });++ await expect(+ readFile(path.join(root, "src/__generated__/label.stories.tsx"), "utf8")+ ).resolves.toContain('import { Label as Label } from "../components";');+ });});diff --git a/packages/sdk-cli/src/generate-stories.ts b/packages/sdk-cli/src/generate-stories.tsindex 90aca7762e..5cff50baec 100644--- a/packages/sdk-cli/src/generate-stories.ts+++ b/packages/sdk-cli/src/generate-stories.ts@@ -16,6 +16,12 @@ import {import { generateWebstudioComponent } from "@webstudio-is/react-sdk";import { renderTemplate, type TemplateMeta } from "@webstudio-is/template";+export type StoryTemplate = {+ meta: TemplateMeta;+ /** Overrides only the generated Storybook file and export name. */+ storyName?: string;+};+const WS_NAMESPACE = "ws";const BASE_NAMESPACE = "@webstudio-is/sdk-components-react/components";@@ -97,14 +103,18 @@ export { Story as ${name} }export const generateStories = async ({packageName,+ components,templates,metas,+ namespaceComponents = new Map(),namespaceMetas = new Map(),outputDir = "src/__generated__",}: {packageName: string;- templates: Record<string, TemplateMeta>;+ components: Record<string, object>;+ templates: readonly StoryTemplate[];metas: Record<string, WsComponentMeta>;+ namespaceComponents?: Map<string, Record<string, object>>;namespaceMetas?: Map<string, Record<string, WsComponentMeta>>;outputDir?: string;}) => {@@ -115,14 +125,49 @@ export const generateStories = async ({`Cannot generate stories for ${packageName} from package ${packageJson.name}`);}- const templatesMap = new Map<string, TemplateMeta>(Object.entries(templates));const metasMap = new Map<string, WsComponentMeta>(Object.entries(metas));const storiesDir = join(cwd(), outputDir);await mkdir(storiesDir, { recursive: true });- for (const [name, meta] of templatesMap) {+ const componentIds = new Map<object, Instance["component"]>();+ const registerComponents = (+ namespace: string,+ registeredComponents: Record<string, object>+ ) => {+ for (const [name, component] of Object.entries(registeredComponents)) {+ const componentId =+ namespace === BASE_NAMESPACE ||+ namespace === "@webstudio-is/sdk-components-react"+ ? name+ : `${namespace}:${name}`;+ componentIds.set(component, componentId);+ }+ };+ registerComponents(packageName, components);+ for (const [namespace, components] of namespaceComponents) {+ registerComponents(namespace, components);+ }++ const storyNameByFile = new Map<string, string>();+ for (const { meta, storyName } of templates) {const rootInstanceId = "root";- const data = renderTemplate(meta.template);+ const data = renderTemplate(meta.template, undefined, [], { componentIds });+ const rootComponent = data.instances[0]?.component;+ if (rootComponent === undefined) {+ throw Error("A story template must have a component at its root");+ }+ const [, componentName] = parseComponentName(rootComponent);+ const name = storyName ?? componentName;+ const storyFile = `${kebabCase(name)}.stories.tsx`;+ const existingName = storyNameByFile.get(storyFile);+ if (existingName !== undefined) {+ throw new Error(+ existingName === name+ ? `Story name "${name}" is generated more than once`+ : `Story names "${existingName}" and "${name}" generate the same file`+ );+ }+ storyNameByFile.set(storyFile, name);const instances: Instances = new Map([[rootInstanceId,@@ -217,9 +262,6 @@ export const generateStories = async ({});content += getStoriesExports(name, cssText);- await writeFile(- join(storiesDir, kebabCase(name) + ".stories.tsx"),- content- );+ await writeFile(join(storiesDir, storyFile), content);}};diff --git a/packages/sdk-components-animation/package.json b/packages/sdk-components-animation/package.jsonindex f7948a61c5..80a770abec 100644--- a/packages/sdk-components-animation/package.json+++ b/packages/sdk-components-animation/package.json@@ -19,6 +19,11 @@"types": "./lib/types/components.d.ts","import": "./lib/components.js"},+ "./components": {+ "webstudio": "./src/components.ts",+ "types": "./lib/types/components.d.ts",+ "import": "./lib/components.js"+ },"./metas": {"webstudio": "./src/metas.ts","types": "./lib/types/metas.d.ts",@@ -53,6 +58,7 @@"@webstudio-is/icons": "workspace:*","@webstudio-is/react-sdk": "workspace:*","@webstudio-is/sdk": "workspace:*",+ "@webstudio-is/sdk-components-react": "workspace:*","change-case": "^5.4.4","nanostores": "^0.11.3","react-error-boundary": "^5.0.0",@@ -66,7 +72,6 @@"@webstudio-is/design-system": "workspace:*","@webstudio-is/generate-arg-types": "workspace:*","@webstudio-is/sdk-cli": "workspace:^",- "@webstudio-is/sdk-components-react": "workspace:*","@webstudio-is/template": "workspace:*","@webstudio-is/tsconfig": "workspace:*","fast-glob": "^3.3.2",diff --git a/packages/sdk-components-animation/src/animate-children.ws.ts b/packages/sdk-components-animation/src/animate-children.ws.tsindex 10a4cc204c..ba7ce47647 100644--- a/packages/sdk-components-animation/src/animate-children.ws.ts+++ b/packages/sdk-components-animation/src/animate-children.ws.ts@@ -1,6 +1,6 @@import { AnimationGroupIcon } from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";-import { animation } from "./shared/meta";+import { getAnimationComponentId } from "./shared/component-id";export const meta: WsComponentMeta = {category: "animations",@@ -12,9 +12,9 @@ export const meta: WsComponentMeta = {category: "instance",children: ["instance",- animation.AnimateText,- animation.StaggerAnimation,- animation.VideoAnimation,+ getAnimationComponentId("AnimateText"),+ getAnimationComponentId("StaggerAnimation"),+ getAnimationComponentId("VideoAnimation"),],},initialProps: ["action"],diff --git a/packages/sdk-components-animation/src/generate-stories.ts b/packages/sdk-components-animation/src/generate-stories.tsindex fe05a244fb..f0a8d10bc7 100644--- a/packages/sdk-components-animation/src/generate-stories.ts+++ b/packages/sdk-components-animation/src/generate-stories.ts@@ -1,12 +1,18 @@import { generateStories } from "@webstudio-is/sdk-cli/generate-stories";+import * as baseComponents from "@webstudio-is/sdk-components-react/components";import * as baseMetas from "@webstudio-is/sdk-components-react/metas";-import * as templates from "./story-templates";+import * as components from "./components";+import { templates } from "./story-templates";import * as metas from "./metas";await generateStories({packageName: "@webstudio-is/sdk-components-animation",+ components,templates,metas,+ namespaceComponents: new Map([+ ["@webstudio-is/sdk-components-react/components", baseComponents],+ ]),namespaceMetas: new Map([["@webstudio-is/sdk-components-react/components", baseMetas],]),diff --git a/packages/sdk-components-animation/src/shared/component-id.ts b/packages/sdk-components-animation/src/shared/component-id.tsnew file mode 100644index 0000000000..498f856fbe--- /dev/null+++ b/packages/sdk-components-animation/src/shared/component-id.ts@@ -0,0 +1,6 @@+/** Builds persisted IDs only for exported animation component names. */+type AnimationComponentName = keyof typeof import("../components");++export const getAnimationComponentId = <Name extends AnimationComponentName>(+ name: Name+) => `@webstudio-is/sdk-components-animation:${name}` as const;diff --git a/packages/sdk-components-animation/src/shared/meta.ts b/packages/sdk-components-animation/src/shared/meta.tsdeleted file mode 100644index 3e351858a4..0000000000--- a/packages/sdk-components-animation/src/shared/meta.ts+++ /dev/null@@ -1,14 +0,0 @@-const createMetaProxy = (prefix: string): Record<string, string> => {- return new Proxy(- {},- {- get(_target, prop) {- return `${prefix}${prop as string}`;- },- }- );-};--export const animation = createMetaProxy(- "@webstudio-is/sdk-components-animation:"-);diff --git a/packages/sdk-components-animation/src/shared/proxy.ts b/packages/sdk-components-animation/src/shared/proxy.tsdeleted file mode 100644index 8145a83a56..0000000000--- a/packages/sdk-components-animation/src/shared/proxy.ts+++ /dev/null@@ -1,3 +0,0 @@-import { createProxy } from "@webstudio-is/template";--export const animation = createProxy("@webstudio-is/sdk-components-animation:");diff --git a/packages/sdk-components-animation/src/story-templates.ts b/packages/sdk-components-animation/src/story-templates.tsindex 544a6c4c14..31b722ca8c 100644--- a/packages/sdk-components-animation/src/story-templates.ts+++ b/packages/sdk-components-animation/src/story-templates.ts@@ -1 +1,4 @@-export { meta as VideoAnimation } from "./video-animation.template";+/** Component templates consumed by story generation. */+import { meta as videoAnimation } from "./video-animation.template";++export const templates = [{ meta: videoAnimation }];diff --git a/packages/sdk-components-animation/src/video-animation.template.tsx b/packages/sdk-components-animation/src/video-animation.template.tsxindex 6a4253df32..0ce8667d98 100644--- a/packages/sdk-components-animation/src/video-animation.template.tsx+++ b/packages/sdk-components-animation/src/video-animation.template.tsx@@ -1,19 +1,21 @@-import { $, type TemplateMeta } from "@webstudio-is/template";-import { animation } from "./shared/proxy";+/** @jsxImportSource @webstudio-is/template */+import type { TemplateMeta } from "@webstudio-is/template";+import { Video } from "@webstudio-is/sdk-components-react/components";+import { VideoAnimation } from "./video-animation";export const meta: TemplateMeta = {category: "animations",description: "Video Animation",order: 2,template: (- <animation.VideoAnimation>- <$.Video+ <VideoAnimation>+ <Videopreload="auto"autoPlay={true}muted={true}playsInline={true}crossOrigin="anonymous"- ></$.Video>- </animation.VideoAnimation>+ />+ </VideoAnimation>),};diff --git a/packages/sdk-components-react-radix/package.json b/packages/sdk-components-react-radix/package.jsonindex 6533c97d28..052ec3f5a2 100644--- a/packages/sdk-components-react-radix/package.json+++ b/packages/sdk-components-react-radix/package.json@@ -63,6 +63,7 @@"@webstudio-is/icons": "workspace:*","@webstudio-is/react-sdk": "workspace:*","@webstudio-is/sdk": "workspace:*",+ "@webstudio-is/sdk-components-react": "workspace:*","await-interaction-response": "^0.0.2"},"devDependencies": {@@ -73,7 +74,6 @@"@webstudio-is/css-data": "workspace:*","@webstudio-is/generate-arg-types": "workspace:*","@webstudio-is/sdk-cli": "workspace:^",- "@webstudio-is/sdk-components-react": "workspace:*","@webstudio-is/template": "workspace:*","@webstudio-is/tsconfig": "workspace:*","playwright": "1.50.1",diff --git a/packages/sdk-components-react-radix/src/__generated__/checkbox.stories.tsx b/packages/sdk-components-react-radix/src/__generated__/checkbox.stories.tsxindex f1f418ed76..5ad4e95e29 100644--- a/packages/sdk-components-react-radix/src/__generated__/checkbox.stories.tsx+++ b/packages/sdk-components-react-radix/src/__generated__/checkbox.stories.tsx@@ -25,7 +25,7 @@ const Component = () => {/></CheckboxIndicator></Checkbox>- <Text data-ws-tag="span" className={`w-text`}>+ <Text tag={"span"} className={`w-text`}>{"Checkbox"}</Text></Label>diff --git a/packages/sdk-components-react-radix/src/__generated__/sheet.stories.tsx b/packages/sdk-components-react-radix/src/__generated__/sheet.stories.tsxindex ed7e4b06a3..0008999b39 100644--- a/packages/sdk-components-react-radix/src/__generated__/sheet.stories.tsx+++ b/packages/sdk-components-react-radix/src/__generated__/sheet.stories.tsx@@ -30,7 +30,7 @@ const Component = () => {</DialogTrigger><DialogOverlay className={`w-dialog-overlay w-sheet-overlay`}><DialogContent className={`w-dialog-content w-sheet-content`}>- <Box data-ws-tag="nav" className={`w-box`}>+ <Box tag={"nav"} className={`w-box`}><Box className={`w-box w-sheet-header`}><DialogTitle className={`w-dialog-title w-sheet-title`}>{"Sheet Title"}diff --git a/packages/sdk-components-react-radix/src/accordion.template.tsx b/packages/sdk-components-react-radix/src/accordion.template.tsxindex d8ac7fa52c..1227969c1b 100644--- a/packages/sdk-components-react-radix/src/accordion.template.tsx+++ b/packages/sdk-components-react-radix/src/accordion.template.tsx@@ -1,10 +1,22 @@+/** @jsxImportSource @webstudio-is/template */import {- $,css,PlaceholderValue,+ setInstanceMeta,type TemplateMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import {+ Box,+ HtmlEmbed,+ Text,+} from "@webstudio-is/sdk-components-react/components";+import {+ Accordion,+ AccordionContent,+ AccordionHeader,+ AccordionItem,+ AccordionTrigger,+} from "./components";import {borderWidth,colors,@@ -21,19 +33,19 @@ import { iconEmbedStyle } from "./shared/styles";const createAccordionItem = (triggerText: string, contentText: string) => {return (- <radix.AccordionItem+ <AccordionItem// border-bws:style={css`border-bottom: ${borderWidth.DEFAULT} solid ${colors.border};`}>- <radix.AccordionHeader+ <AccordionHeader// flexws:style={css`display: flex;`}>- <radix.AccordionTrigger+ <AccordionTrigger// flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180ws:style={css`display: flex;@@ -51,28 +63,29 @@ const createAccordionItem = (triggerText: string, contentText: string) => {}`}>- <$.Text>{new PlaceholderValue(triggerText)}</$.Text>- <$.Box- ws:label="Icon Container"- // h-4 w-4 shrink-0 transition-transform duration-200- ws:style={css`- rotate: var(--accordion-trigger-icon-transform);- height: ${height[4]};- width: ${width[4]};- flex-shrink: 0;- transition: ${transition.all};- transition-duration: 200ms;- `}- >- <$.HtmlEmbed- ws:label="Chevron Icon"- ws:style={iconEmbedStyle}- code={ChevronDownIcon}- />- </$.Box>- </radix.AccordionTrigger>- </radix.AccordionHeader>- <radix.AccordionContent+ <Text>{new PlaceholderValue(triggerText)}</Text>+ {setInstanceMeta(+ { label: "Icon Container" },+ <Box+ // h-4 w-4 shrink-0 transition-transform duration-200+ ws:style={css`+ rotate: var(--accordion-trigger-icon-transform);+ height: ${height[4]};+ width: ${width[4]};+ flex-shrink: 0;+ transition: ${transition.all};+ transition-duration: 200ms;+ `}+ >+ {setInstanceMeta(+ { label: "Chevron Icon" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={ChevronDownIcon} />+ )}+ </Box>+ )}+ </AccordionTrigger>+ </AccordionHeader>+ <AccordionContentforceMount={true}// overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down// pb-4 pt-0@@ -90,8 +103,8 @@ const createAccordionItem = (triggerText: string, contentText: string) => {`}>{new PlaceholderValue(contentText)}- </radix.AccordionContent>- </radix.AccordionItem>+ </AccordionContent>+ </AccordionItem>);};@@ -109,7 +122,7 @@ export const meta: TemplateMeta = {"A vertically stacked set of interactive headings that each reveal an associated section of content. Clicking on the heading will open the item and close other items.",order: 3,template: (- <radix.Accordion collapsible={true} value="0">+ <Accordion collapsible={true} value="0">{createAccordionItem("Is it accessible?","Yes. It adheres to the WAI-ARIA design pattern."@@ -122,6 +135,6 @@ export const meta: TemplateMeta = {"Is it animated?","Yes. It's animated by default, but you can disable it if you prefer.")}- </radix.Accordion>+ </Accordion>),};diff --git a/packages/sdk-components-react-radix/src/accordion.ws.ts b/packages/sdk-components-react-radix/src/accordion.ws.tsindex 279857b4fe..2191c3f390 100644--- a/packages/sdk-components-react-radix/src/accordion.ws.ts+++ b/packages/sdk-components-react-radix/src/accordion.ws.ts@@ -7,7 +7,7 @@ import {} from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { div, h3, button } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import { buttonReset } from "./shared/preset-styles";import {propsAccordion,@@ -22,7 +22,7 @@ export const metaAccordion: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.AccordionItem],+ descendants: [getRadixComponentId("AccordionItem")],},presetStyle: { div },initialProps: ["value", "collapsible"],@@ -32,11 +32,14 @@ export const metaAccordion: WsComponentMeta = {export const metaAccordionItem: WsComponentMeta = {label: "Item",icon: ItemIcon,- indexWithinAncestor: radix.Accordion,+ indexWithinAncestor: getRadixComponentId("Accordion"),contentModel: {category: "none",children: ["instance"],- descendants: [radix.AccordionHeader, radix.AccordionContent],+ descendants: [+ getRadixComponentId("AccordionHeader"),+ getRadixComponentId("AccordionContent"),+ ],},states: [{ label: "Open", selector: '[data-state="open"]' },@@ -53,7 +56,7 @@ export const metaAccordionHeader: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.AccordionTrigger],+ descendants: [getRadixComponentId("AccordionTrigger")],},states: [{ label: "Open", selector: '[data-state="open"]' },diff --git a/packages/sdk-components-react-radix/src/checkbox.template.tsx b/packages/sdk-components-react-radix/src/checkbox.template.tsxindex cfd3f70d99..fb70f50096 100644--- a/packages/sdk-components-react-radix/src/checkbox.template.tsx+++ b/packages/sdk-components-react-radix/src/checkbox.template.tsx@@ -1,11 +1,13 @@+/** @jsxImportSource @webstudio-is/template */import { CheckMarkIcon } from "@webstudio-is/icons/svg";import {type TemplateMeta,- $,css,PlaceholderValue,+ setInstanceMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import { HtmlEmbed, Text } from "@webstudio-is/sdk-components-react/components";+import { Checkbox, CheckboxIndicator, Label } from "./components";import {borderRadius,borderWidth,@@ -23,16 +25,16 @@ export const meta: TemplateMeta = {description:"Use within a form to allow your users to toggle between checked and not checked. Group checkboxes by matching their “Name” properties. Unlike radios, any number of checkboxes in a group can be checked.",order: 101,- template: (- <radix.Label- ws:label="Checkbox Field"+ template: setInstanceMeta(+ { label: "Checkbox Field" },+ <Labelws:style={css`display: flex;gap: ${spacing[2]};align-items: center;`}>- <radix.Checkbox+ <Checkbox// peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background// focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2// disabled:cursor-not-allowed disabled:opacity-50@@ -58,7 +60,7 @@ export const meta: TemplateMeta = {}`}>- <radix.CheckboxIndicator+ <CheckboxIndicator// flex items-center justify-center text-currentws:style={css`display: flex;@@ -67,16 +69,16 @@ export const meta: TemplateMeta = {color: currentColor;`}>- <$.HtmlEmbed- ws:label="Indicator Icon"- ws:style={iconEmbedStyle}- code={CheckMarkIcon}- />- </radix.CheckboxIndicator>- </radix.Checkbox>- <$.Text ws:label="Checkbox Label" ws:tag="span">- {new PlaceholderValue("Checkbox")}- </$.Text>- </radix.Label>+ {setInstanceMeta(+ { label: "Indicator Icon" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={CheckMarkIcon} />+ )}+ </CheckboxIndicator>+ </Checkbox>+ {setInstanceMeta(+ { label: "Checkbox Label" },+ <Text tag="span">{new PlaceholderValue("Checkbox")}</Text>+ )}+ </Label>),};diff --git a/packages/sdk-components-react-radix/src/checkbox.ws.ts b/packages/sdk-components-react-radix/src/checkbox.ws.tsindex 77f6752665..9953c38bb7 100644--- a/packages/sdk-components-react-radix/src/checkbox.ws.ts+++ b/packages/sdk-components-react-radix/src/checkbox.ws.ts@@ -1,7 +1,7 @@import { CheckboxCheckedIcon, TriggerIcon } from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { button, span } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import { buttonReset } from "./shared/preset-styles";import {propsCheckbox,@@ -13,7 +13,7 @@ export const metaCheckbox: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.CheckboxIndicator],+ descendants: [getRadixComponentId("CheckboxIndicator")],},states: [{ label: "Checked", selector: '[data-state="checked"]' },diff --git a/packages/sdk-components-react-radix/src/collapsible.template.tsx b/packages/sdk-components-react-radix/src/collapsible.template.tsxindex 9c4f75e165..f2234732a2 100644--- a/packages/sdk-components-react-radix/src/collapsible.template.tsx+++ b/packages/sdk-components-react-radix/src/collapsible.template.tsx@@ -1,10 +1,15 @@+/** @jsxImportSource @webstudio-is/template */import {- $,css,PlaceholderValue,type TemplateMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import { Button, Text } from "@webstudio-is/sdk-components-react/components";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "./components";import { getButtonStyle } from "./shared/styles";export const meta: TemplateMeta = {@@ -13,13 +18,13 @@ export const meta: TemplateMeta = {"An interactive component which expands and collapses some content, triggered by a button.",order: 5,template: (- <radix.Collapsible>- <radix.CollapsibleTrigger>- <$.Button ws:style={getButtonStyle("outline")}>+ <Collapsible>+ <CollapsibleTrigger>+ <Button ws:style={getButtonStyle("outline")}>{new PlaceholderValue("Click to toggle content")}- </$.Button>- </radix.CollapsibleTrigger>- <radix.CollapsibleContent+ </Button>+ </CollapsibleTrigger>+ <CollapsibleContentforceMount={true}ws:style={css`overflow: hidden;@@ -31,8 +36,8 @@ export const meta: TemplateMeta = {}`}>- <$.Text>{new PlaceholderValue("Collapsible Content")}</$.Text>- </radix.CollapsibleContent>- </radix.Collapsible>+ <Text>{new PlaceholderValue("Collapsible Content")}</Text>+ </CollapsibleContent>+ </Collapsible>),};diff --git a/packages/sdk-components-react-radix/src/collapsible.test.tsx b/packages/sdk-components-react-radix/src/collapsible.test.tsxindex 9ee8bc05ee..262a16b7b1 100644--- a/packages/sdk-components-react-radix/src/collapsible.test.tsx+++ b/packages/sdk-components-react-radix/src/collapsible.test.tsx@@ -1,10 +1,27 @@-import { renderTemplate } from "@webstudio-is/template";+import { Button, Text } from "@webstudio-is/sdk-components-react/components";+import { renderTemplate, type TemplateComponent } from "@webstudio-is/template";import { expect, test } from "vitest";import { propsCollapsibleContent } from "./__generated__/collapsible.props";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "./components";import { meta } from "./collapsible.template";+import { getRadixComponentId } from "./shared/component-id";++const componentIds = new Map<TemplateComponent, string>([+ [Button, "Button"],+ [Text, "Text"],+ [Collapsible, getRadixComponentId("Collapsible")],+ [CollapsibleTrigger, getRadixComponentId("CollapsibleTrigger")],+ [CollapsibleContent, getRadixComponentId("CollapsibleContent")],+]);test("enables Force Mount for new Collapsible Content instances", () => {- const fragment = renderTemplate(meta.template);+ const fragment = renderTemplate(meta.template, undefined, [], {+ componentIds,+ });const content = fragment.instances.find(({ component }) =>component ===diff --git a/packages/sdk-components-react-radix/src/collapsible.ws.ts b/packages/sdk-components-react-radix/src/collapsible.ws.tsindex c940db2a02..c70d7034fb 100644--- a/packages/sdk-components-react-radix/src/collapsible.ws.ts+++ b/packages/sdk-components-react-radix/src/collapsible.ws.ts@@ -5,7 +5,7 @@ import {} from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { div } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import {propsCollapsible,propsCollapsibleContent,@@ -17,7 +17,10 @@ export const metaCollapsible: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.CollapsibleTrigger, radix.CollapsibleContent],+ descendants: [+ getRadixComponentId("CollapsibleTrigger"),+ getRadixComponentId("CollapsibleContent"),+ ],},states: [{ label: "Open", selector: '[data-state="open"]' },diff --git a/packages/sdk-components-react-radix/src/dialog.template.tsx b/packages/sdk-components-react-radix/src/dialog.template.tsxindex 8c0c0bf2a1..286e65d7c9 100644--- a/packages/sdk-components-react-radix/src/dialog.template.tsx+++ b/packages/sdk-components-react-radix/src/dialog.template.tsx@@ -1,11 +1,26 @@+/** @jsxImportSource @webstudio-is/template */import { LargeXIcon } from "@webstudio-is/icons/svg";import {type TemplateMeta,- $,css,PlaceholderValue,+ setInstanceMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import {+ Box,+ Button,+ HtmlEmbed,+ Text,+} from "@webstudio-is/sdk-components-react/components";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogOverlay,+ DialogTitle,+ DialogTrigger,+} from "./components";import {blur,borderRadius,@@ -39,13 +54,13 @@ export const meta: TemplateMeta = {"Displays content with an overlay that covers the window, triggered by a button. Clicking the overlay will close the dialog.",order: 4,template: (- <radix.Dialog>- <radix.DialogTrigger>- <$.Button ws:style={getButtonStyle("outline")}>+ <Dialog>+ <DialogTrigger>+ <Button ws:style={getButtonStyle("outline")}>{new PlaceholderValue("Button")}- </$.Button>- </radix.DialogTrigger>- <radix.DialogOverlay+ </Button>+ </DialogTrigger>+ <DialogOverlay/*** fixed inset-0 z-50 bg-background/80 backdrop-blur-sm* flex@@ -61,7 +76,7 @@ export const meta: TemplateMeta = {overflow: auto;`}>- <radix.DialogContent+ <DialogContent/*** fixed w-full z-50* grid gap-4 max-w-lg@@ -83,81 +98,84 @@ export const meta: TemplateMeta = {position: relative;`}>- <$.Box- ws:label="Dialog Header"- ws:style={css`- display: flex;- flex-direction: column;- gap: ${spacing[2]};- `}- >- <radix.DialogTitle- /**- * text-lg leading-none tracking-tight- **/+ {setInstanceMeta(+ { label: "Dialog Header" },+ <Boxws:style={css`- font-size: ${fontSize.lg};- line-height: ${lineHeight.none};- letter-spacing: ${letterSpacing.tight};- margin: 0;+ display: flex;+ flex-direction: column;+ gap: ${spacing[2]};`}>- {new PlaceholderValue("Dialog Title you can edit")}- </radix.DialogTitle>- <radix.DialogDescription+ <DialogTitle+ /**+ * text-lg leading-none tracking-tight+ **/+ ws:style={css`+ font-size: ${fontSize.lg};+ line-height: ${lineHeight.none};+ letter-spacing: ${letterSpacing.tight};+ margin: 0;+ `}+ >+ {new PlaceholderValue("Dialog Title you can edit")}+ </DialogTitle>+ <DialogDescription+ /**+ * text-sm text-muted-foreground+ **/+ ws:style={css`+ font-size: ${fontSize.sm};+ line-height: ${fontSizeLineHeight.sm};+ color: ${colors.mutedForeground};+ margin: 0;+ `}+ >+ {new PlaceholderValue("Dialog description text you can edit")}+ </DialogDescription>+ </Box>+ )}+ <Text>{new PlaceholderValue("The text you can edit")}</Text>+ {setInstanceMeta(+ { label: "Close Button" },+ <DialogClose/**- * text-sm text-muted-foreground+ * absolute right-4 top-4+ * rounded-sm opacity-70+ * ring-offset-background+ * hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2+ * flex items-center justify-center h-4 w-4**/ws:style={css`- font-size: ${fontSize.sm};- line-height: ${fontSizeLineHeight.sm};- color: ${colors.mutedForeground};- margin: 0;+ position: absolute;+ right: ${spacing[4]};+ top: ${spacing[4]};+ border-radius: ${borderRadius.sm};+ opacity: ${opacity[70]};+ display: flex;+ align-items: center;+ justify-content: center;+ height: ${height[4]};+ width: ${height[4]};+ border: 0;+ background-color: transparent;+ outline: none;+ &:hover {+ opacity: ${opacity[100]};+ }+ &:focus-visible {+ box-shadow: ${boxShadow.ring};+ }`}>- {new PlaceholderValue("Dialog description text you can edit")}- </radix.DialogDescription>- </$.Box>- <$.Text>{new PlaceholderValue("The text you can edit")}</$.Text>- <radix.DialogClose- ws:label="Close Button"- /**- * absolute right-4 top-4- * rounded-sm opacity-70- * ring-offset-background- * hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2- * flex items-center justify-center h-4 w-4- **/- ws:style={css`- position: absolute;- right: ${spacing[4]};- top: ${spacing[4]};- border-radius: ${borderRadius.sm};- opacity: ${opacity[70]};- display: flex;- align-items: center;- justify-content: center;- height: ${height[4]};- width: ${height[4]};- border: 0;- background-color: transparent;- outline: none;- &:hover {- opacity: ${opacity[100]};- }- &:focus-visible {- box-shadow: ${boxShadow.ring};- }- `}- >- <$.HtmlEmbed- ws:label="Close Icon"- ws:style={iconEmbedStyle}- code={LargeXIcon}- />- </radix.DialogClose>- </radix.DialogContent>- </radix.DialogOverlay>- </radix.Dialog>+ {setInstanceMeta(+ { label: "Close Icon" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={LargeXIcon} />+ )}+ </DialogClose>+ )}+ </DialogContent>+ </DialogOverlay>+ </Dialog>),};diff --git a/packages/sdk-components-react-radix/src/dialog.ws.ts b/packages/sdk-components-react-radix/src/dialog.ws.tsindex def2afcdd1..3942dbc3cc 100644--- a/packages/sdk-components-react-radix/src/dialog.ws.ts+++ b/packages/sdk-components-react-radix/src/dialog.ws.ts@@ -9,7 +9,7 @@ import {} from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { div, button, h2, p } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import {propsDialog,propsDialogContent,@@ -39,7 +39,7 @@ export const metaDialogOverlay: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.DialogContent],+ descendants: [getRadixComponentId("DialogContent")],},states: [{ label: "Open", selector: '[data-state="open"]' },@@ -55,9 +55,9 @@ export const metaDialogContent: WsComponentMeta = {category: "none",children: ["instance"],descendants: [- radix.DialogTitle,- radix.DialogDescription,- radix.DialogClose,+ getRadixComponentId("DialogTitle"),+ getRadixComponentId("DialogDescription"),+ getRadixComponentId("DialogClose"),],},states: [@@ -106,7 +106,10 @@ export const metaDialog: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.DialogTrigger, radix.DialogOverlay],+ descendants: [+ getRadixComponentId("DialogTrigger"),+ getRadixComponentId("DialogOverlay"),+ ],},initialProps: ["open"],props: propsDialog,diff --git a/packages/sdk-components-react-radix/src/generate-stories.ts b/packages/sdk-components-react-radix/src/generate-stories.tsindex b361ba5244..1ad081a74c 100644--- a/packages/sdk-components-react-radix/src/generate-stories.ts+++ b/packages/sdk-components-react-radix/src/generate-stories.ts@@ -1,12 +1,18 @@import { generateStories } from "@webstudio-is/sdk-cli/generate-stories";+import * as baseComponents from "@webstudio-is/sdk-components-react/components";import * as baseMetas from "@webstudio-is/sdk-components-react/metas";-import * as templates from "./story-templates";+import * as components from "./components";+import { templates } from "./story-templates";import * as metas from "./metas";await generateStories({packageName: "@webstudio-is/sdk-components-react-radix",+ components,templates,metas,+ namespaceComponents: new Map([+ ["@webstudio-is/sdk-components-react/components", baseComponents],+ ]),namespaceMetas: new Map([["@webstudio-is/sdk-components-react/components", baseMetas],]),diff --git a/packages/sdk-components-react-radix/src/label.template.tsx b/packages/sdk-components-react-radix/src/label.template.tsxindex c78a7bee7c..7c6fbee7b4 100644--- a/packages/sdk-components-react-radix/src/label.template.tsx+++ b/packages/sdk-components-react-radix/src/label.template.tsx@@ -1,9 +1,10 @@+/** @jsxImportSource @webstudio-is/template */import {css,PlaceholderValue,type TemplateMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import { Label } from "./label";import { fontSize, lineHeight, weights } from "./shared/theme";/**@@ -20,7 +21,7 @@ export const meta: TemplateMeta = {"An accessible label to describe the purpose of an input. Match the “For” property on the label with the “ID” of the input to connect them.",order: 102,template: (- <radix.Label+ <Label// text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70// We are not supporting peer like styles yetws:style={css`@@ -30,6 +31,6 @@ export const meta: TemplateMeta = {`}>{new PlaceholderValue("Form Label")}- </radix.Label>+ </Label>),};diff --git a/packages/sdk-components-react-radix/src/navigation-menu.template.tsx b/packages/sdk-components-react-radix/src/navigation-menu.template.tsxindex 1b6fc6306f..a59a39553d 100644--- a/packages/sdk-components-react-radix/src/navigation-menu.template.tsx+++ b/packages/sdk-components-react-radix/src/navigation-menu.template.tsx@@ -1,12 +1,29 @@+/** @jsxImportSource @webstudio-is/template */import type { ReactNode } from "react";import { ChevronDownIcon } from "@webstudio-is/icons/svg";import {- $,css,PlaceholderValue,+ setInstanceMeta,type TemplateMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import {+ Box,+ Button,+ HtmlEmbed,+ Link,+ Paragraph,+ Text,+} from "@webstudio-is/sdk-components-react/components";+import {+ NavigationMenu,+ NavigationMenuContent,+ NavigationMenuItem,+ NavigationMenuLink,+ NavigationMenuList,+ NavigationMenuTrigger,+ NavigationMenuViewport,+} from "./components";import { getButtonStyle, iconEmbedStyle } from "./shared/styles";import {borderRadius,@@ -76,8 +93,8 @@ const components = [];const createMenuContentItem = (props: (typeof components)[number]) => (- <radix.NavigationMenuLink key={props.title}>- <$.Link+ <NavigationMenuLink key={props.title}>+ <Linkhref={`https://ui.shadcn.com${props.href}`}// block select-none space-y-1 rounded-md p-3 leading-none// no-underline outline-none transition-colors@@ -101,7 +118,7 @@ const createMenuContentItem = (props: (typeof components)[number]) => (}`}>- <$.Text+ <Text// text-sm font-medium leading-nonews:style={css`font-size: ${fontSize.sm};@@ -110,8 +127,8 @@ const createMenuContentItem = (props: (typeof components)[number]) => (`}>{new PlaceholderValue(props.title)}- </$.Text>- <$.Paragraph+ </Text>+ <Paragraph// line-clamp-2 text-sm leading-snug text-muted-foregroundws:style={css`margin: 0;@@ -125,37 +142,38 @@ const createMenuContentItem = (props: (typeof components)[number]) => (`}>{new PlaceholderValue(props.description)}- </$.Paragraph>- </$.Link>- </radix.NavigationMenuLink>+ </Paragraph>+ </Link>+ </NavigationMenuLink>);-const createMenuContentList = (props: { count: number; offset: number }) => (- <$.Box- ws:label="Flex Column"- ws:style={css`- width: ${width[64]};- display: flex;- gap: ${spacing[4]};- flex-direction: column;- `}- >- {components- .slice(props.offset, props.offset + props.count)- .map(createMenuContentItem)}- </$.Box>-);+const createMenuContentList = (props: { count: number; offset: number }) =>+ setInstanceMeta(+ { label: "Flex Column" },+ <Box+ ws:style={css`+ width: ${width[64]};+ display: flex;+ gap: ${spacing[4]};+ flex-direction: column;+ `}+ >+ {components+ .slice(props.offset, props.offset + props.count)+ .map(createMenuContentItem)}+ </Box>+ );-const aboutMenuContent = (- <$.Box- ws:label="Content"+const aboutMenuContent = setInstanceMeta(+ { label: "Content" },+ <Boxws:style={css`display: flex;gap: ${spacing[4]};padding: ${spacing[2]};`}>- <$.Box+ <Boxws:style={css`background-color: ${colors.border};padding: ${spacing[4]};@@ -164,14 +182,14 @@ const aboutMenuContent = (`}>{new PlaceholderValue("")}- </$.Box>+ </Box>{createMenuContentList({ count: 3, offset: 0 })}- </$.Box>+ </Box>);-const componentsMenuContent = (- <$.Box- ws:label="Content"+const componentsMenuContent = setInstanceMeta(+ { label: "Content" },+ <Boxws:style={css`display: flex;gap: ${spacing[4]};@@ -179,14 +197,14 @@ const componentsMenuContent = (>{createMenuContentList({ count: 3, offset: 3 })}{createMenuContentList({ count: 3, offset: 6 })}- </$.Box>+ </Box>);const createMenuItem = (title: string, content: ReactNode) => {return (- <radix.NavigationMenuItem>- <radix.NavigationMenuTrigger>- <$.Button+ <NavigationMenuItem>+ <NavigationMenuTrigger>+ <Buttonws:style={[...getButtonStyle("ghost", "sm"),...css`@@ -197,29 +215,30 @@ const createMenuItem = (title: string, content: ReactNode) => {`,]}>- <$.Text>{new PlaceholderValue(title)}</$.Text>- <$.Box- ws:label="Icon Container"- // h-4 w-4 shrink-0 transition-transform duration-200- ws:style={css`- margin-left: ${spacing[1]};- rotate: var(--navigation-menu-trigger-icon-transform);- height: ${height[4]};- width: ${width[4]};- flex-shrink: 0;- transition: ${transition.all};- transition-duration: 200ms;- `}- >- <$.HtmlEmbed- ws:label="Chevron Icon"- ws:style={iconEmbedStyle}- code={ChevronDownIcon}- />- </$.Box>- </$.Button>- </radix.NavigationMenuTrigger>- <radix.NavigationMenuContent+ <Text>{new PlaceholderValue(title)}</Text>+ {setInstanceMeta(+ { label: "Icon Container" },+ <Box+ // h-4 w-4 shrink-0 transition-transform duration-200+ ws:style={css`+ margin-left: ${spacing[1]};+ rotate: var(--navigation-menu-trigger-icon-transform);+ height: ${height[4]};+ width: ${width[4]};+ flex-shrink: 0;+ transition: ${transition.all};+ transition-duration: 200ms;+ `}+ >+ {setInstanceMeta(+ { label: "Chevron Icon" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={ChevronDownIcon} />+ )}+ </Box>+ )}+ </Button>+ </NavigationMenuTrigger>+ <NavigationMenuContent// left-0 top-0 absolute w-maxws:style={css`left: 0;@@ -230,16 +249,16 @@ const createMenuItem = (title: string, content: ReactNode) => {`}>{content}- </radix.NavigationMenuContent>- </radix.NavigationMenuItem>+ </NavigationMenuContent>+ </NavigationMenuItem>);};const createMenuLink = (title: string) => {return (- <radix.NavigationMenuItem>- <radix.NavigationMenuLink>- <$.Link+ <NavigationMenuItem>+ <NavigationMenuLink>+ <Linkws:style={[...getButtonStyle("ghost", "sm"),...css`@@ -249,9 +268,9 @@ const createMenuLink = (title: string) => {]}>{new PlaceholderValue(title)}- </$.Link>- </radix.NavigationMenuLink>- </radix.NavigationMenuItem>+ </Link>+ </NavigationMenuLink>+ </NavigationMenuItem>);};@@ -260,7 +279,7 @@ export const meta: TemplateMeta = {description: "A collection of links for navigating websites.",order: 2,template: (- <radix.NavigationMenu+ <NavigationMenu// relative// Omiting this: z-10 flex max-w-max flex-1 items-center justify-centerws:style={css`@@ -268,7 +287,7 @@ export const meta: TemplateMeta = {max-width: max-content;`}>- <radix.NavigationMenuList+ <NavigationMenuListws:style={css`/* ul defaults in tailwind */padding: 0;@@ -285,20 +304,21 @@ export const meta: TemplateMeta = {{createMenuItem("About", aboutMenuContent)}{createMenuItem("Components", componentsMenuContent)}{createMenuLink("Standalone")}- </radix.NavigationMenuList>- <$.Box- ws:label="Viewport Container"- // absolute left-0 top-full flex justify-center- ws:style={css`- position: absolute;- left: 0;- top: 100%;- display: flex;- justify-content: center;- `}- >- <radix.NavigationMenuViewport- /*+ </NavigationMenuList>+ {setInstanceMeta(+ { label: "Viewport Container" },+ <Box+ // absolute left-0 top-full flex justify-center+ ws:style={css`+ position: absolute;+ left: 0;+ top: 100%;+ display: flex;+ justify-content: center;+ `}+ >+ <NavigationMenuViewport+ /*origin-top-center relative mt-1.5 w-fulloverflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lgh-[var(--radix-navigation-menu-viewport-height)]@@ -308,20 +328,21 @@ export const meta: TemplateMeta = {data-[state=open]:animate-in data-[state=closed]:animate-outdata-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90*/- ws:style={css`- position: relative;- margin-top: ${spacing[1.5]};- overflow: hidden;- border-radius: ${borderRadius.md};- border: ${borderWidth.DEFAULT} solid ${colors.border};- background-color: ${colors.popover};- color: ${colors.popoverForeground};- box-shadow: ${boxShadow.lg};- height: var(--radix-navigation-menu-viewport-height);- width: var(--radix-navigation-menu-viewport-width);- `}- />- </$.Box>- </radix.NavigationMenu>+ ws:style={css`+ position: relative;+ margin-top: ${spacing[1.5]};+ overflow: hidden;+ border-radius: ${borderRadius.md};+ border: ${borderWidth.DEFAULT} solid ${colors.border};+ background-color: ${colors.popover};+ color: ${colors.popoverForeground};+ box-shadow: ${boxShadow.lg};+ height: var(--radix-navigation-menu-viewport-height);+ width: var(--radix-navigation-menu-viewport-width);+ `}+ />+ </Box>+ )}+ </NavigationMenu>),};diff --git a/packages/sdk-components-react-radix/src/navigation-menu.ws.ts b/packages/sdk-components-react-radix/src/navigation-menu.ws.tsindex 25442dd4ed..7bf14e3b32 100644--- a/packages/sdk-components-react-radix/src/navigation-menu.ws.ts+++ b/packages/sdk-components-react-radix/src/navigation-menu.ws.ts@@ -9,7 +9,7 @@ import {} from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { div } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import {propsNavigationMenu,propsNavigationMenuItem,@@ -25,7 +25,10 @@ export const metaNavigationMenu: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.NavigationMenuList, radix.NavigationMenuViewport],+ descendants: [+ getRadixComponentId("NavigationMenuList"),+ getRadixComponentId("NavigationMenuViewport"),+ ],},presetStyle: {div,@@ -39,7 +42,7 @@ export const metaNavigationMenuList: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.NavigationMenuItem],+ descendants: [getRadixComponentId("NavigationMenuItem")],},presetStyle: {div,@@ -50,14 +53,14 @@ export const metaNavigationMenuList: WsComponentMeta = {export const metaNavigationMenuItem: WsComponentMeta = {icon: ListItemIcon,label: "Menu Item",- indexWithinAncestor: radix.NavigationMenu,+ indexWithinAncestor: getRadixComponentId("NavigationMenu"),contentModel: {category: "none",children: ["instance"],descendants: [- radix.NavigationMenuTrigger,- radix.NavigationMenuContent,- radix.NavigationMenuLink,+ getRadixComponentId("NavigationMenuTrigger"),+ getRadixComponentId("NavigationMenuContent"),+ getRadixComponentId("NavigationMenuLink"),],},presetStyle: {@@ -86,7 +89,7 @@ export const metaNavigationMenuContent: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.NavigationMenuLink],+ descendants: [getRadixComponentId("NavigationMenuLink")],},states: [{ label: "Open", selector: '[data-state="open"]' },diff --git a/packages/sdk-components-react-radix/src/popover.template.tsx b/packages/sdk-components-react-radix/src/popover.template.tsxindex 61363d7b93..1b792282dd 100644--- a/packages/sdk-components-react-radix/src/popover.template.tsx+++ b/packages/sdk-components-react-radix/src/popover.template.tsx@@ -1,11 +1,22 @@+/** @jsxImportSource @webstudio-is/template */import { LargeXIcon } from "@webstudio-is/icons/svg";import {- $,css,PlaceholderValue,+ setInstanceMeta,type TemplateMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import {+ Button,+ HtmlEmbed,+ Text,+} from "@webstudio-is/sdk-components-react/components";+import {+ Popover,+ PopoverClose,+ PopoverContent,+ PopoverTrigger,+} from "./components";import { getButtonStyle, iconEmbedStyle } from "./shared/styles";import {borderRadius,@@ -32,13 +43,13 @@ export const meta: TemplateMeta = {description: "Displays rich content in a portal, triggered by a button.",order: 6,template: (- <radix.Popover>- <radix.PopoverTrigger>- <$.Button ws:style={getButtonStyle("outline")}>+ <Popover>+ <PopoverTrigger>+ <Button ws:style={getButtonStyle("outline")}>{new PlaceholderValue("Button")}- </$.Button>- </radix.PopoverTrigger>- <radix.PopoverContent+ </Button>+ </PopoverTrigger>+ <PopoverContent/*** z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none**/@@ -54,44 +65,45 @@ export const meta: TemplateMeta = {outline: none;`}>- <$.Text>{new PlaceholderValue("The text you can edit")}</$.Text>- <radix.PopoverClose- ws:label="Close Button"- /**- * absolute right-4 top-4- * rounded-sm opacity-70- * ring-offset-background- * hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2- * flex items-center justify-center h-4 w-4- **/- ws:style={css`- position: absolute;- right: ${spacing[4]};- top: ${spacing[4]};- border-radius: ${borderRadius.sm};- display: flex;- align-items: center;- justify-content: center;- height: ${height[4]};- width: ${height[4]};- border: 0;- background-color: transparent;- outline: none;- &:hover {- opacity: ${opacity[100]};- }- &:focus-visible {- box-shadow: ${boxShadow.ring};- }- `}- >- <$.HtmlEmbed- ws:label="Close Icon"- ws:style={iconEmbedStyle}- code={LargeXIcon}- />- </radix.PopoverClose>- </radix.PopoverContent>- </radix.Popover>+ <Text>{new PlaceholderValue("The text you can edit")}</Text>+ {setInstanceMeta(+ { label: "Close Button" },+ <PopoverClose+ /**+ * absolute right-4 top-4+ * rounded-sm opacity-70+ * ring-offset-background+ * hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2+ * flex items-center justify-center h-4 w-4+ **/+ ws:style={css`+ position: absolute;+ right: ${spacing[4]};+ top: ${spacing[4]};+ border-radius: ${borderRadius.sm};+ display: flex;+ align-items: center;+ justify-content: center;+ height: ${height[4]};+ width: ${height[4]};+ border: 0;+ background-color: transparent;+ outline: none;+ &:hover {+ opacity: ${opacity[100]};+ }+ &:focus-visible {+ box-shadow: ${boxShadow.ring};+ }+ `}+ >+ {setInstanceMeta(+ { label: "Close Icon" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={LargeXIcon} />+ )}+ </PopoverClose>+ )}+ </PopoverContent>+ </Popover>),};diff --git a/packages/sdk-components-react-radix/src/popover.ws.ts b/packages/sdk-components-react-radix/src/popover.ws.tsindex 030ddc22a8..65c441ea2a 100644--- a/packages/sdk-components-react-radix/src/popover.ws.ts+++ b/packages/sdk-components-react-radix/src/popover.ws.ts@@ -6,7 +6,7 @@ import {} from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { button, div } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import {propsPopover,propsPopoverContent,@@ -33,7 +33,7 @@ export const metaPopoverContent: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.PopoverClose],+ descendants: [getRadixComponentId("PopoverClose")],},states: [{ label: "Open", selector: '[data-state="open"]' },@@ -51,7 +51,10 @@ export const metaPopover: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.PopoverTrigger, radix.PopoverContent],+ descendants: [+ getRadixComponentId("PopoverTrigger"),+ getRadixComponentId("PopoverContent"),+ ],},initialProps: ["open"],props: propsPopover,diff --git a/packages/sdk-components-react-radix/src/radio-group.template.tsx b/packages/sdk-components-react-radix/src/radio-group.template.tsxindex 7733c53b61..27917bd8b1 100644--- a/packages/sdk-components-react-radix/src/radio-group.template.tsx+++ b/packages/sdk-components-react-radix/src/radio-group.template.tsx@@ -1,11 +1,18 @@+/** @jsxImportSource @webstudio-is/template */import {- $,css,PlaceholderValue,+ setInstanceMeta,type TemplateMeta,} from "@webstudio-is/template";import { DotIcon } from "@webstudio-is/icons/svg";-import { radix } from "./shared/proxy";+import { HtmlEmbed, Text } from "@webstudio-is/sdk-components-react/components";+import {+ Label,+ RadioGroup,+ RadioGroupIndicator,+ RadioGroupItem,+} from "./components";import {borderRadius,borderWidth,@@ -25,7 +32,7 @@ const createRadioGroupItem = ({value: string;label: string;}) => (- <radix.Label+ <Label// flex items-center space-x-2ws:style={css`display: flex;@@ -33,7 +40,7 @@ const createRadioGroupItem = ({gap: ${spacing[2]};`}>- <radix.RadioGroupItem+ <RadioGroupItemvalue={value}// aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background// focus:outline-none@@ -56,16 +63,15 @@ const createRadioGroupItem = ({}`}>- <radix.RadioGroupIndicator>- <$.HtmlEmbed- ws:label="Indicator Icon"- ws:style={iconEmbedStyle}- code={DotIcon}- />- </radix.RadioGroupIndicator>- </radix.RadioGroupItem>- <$.Text>{new PlaceholderValue(label)}</$.Text>- </radix.Label>+ <RadioGroupIndicator>+ {setInstanceMeta(+ { label: "Indicator Icon" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={DotIcon} />+ )}+ </RadioGroupIndicator>+ </RadioGroupItem>+ <Text>{new PlaceholderValue(label)}</Text>+ </Label>);export const meta: TemplateMeta = {@@ -74,7 +80,7 @@ export const meta: TemplateMeta = {description:"A set of checkable buttons—known as radio buttons—where no more than one of the buttons can be checked at a time.",template: (- <radix.RadioGroup+ <RadioGroup// grid gap-2ws:style={css`display: flex;@@ -85,6 +91,6 @@ export const meta: TemplateMeta = {{createRadioGroupItem({ value: "default", label: "Default" })}{createRadioGroupItem({ value: "comfortable", label: "Comfortable" })}{createRadioGroupItem({ value: "compact", label: "Compact" })}- </radix.RadioGroup>+ </RadioGroup>),};diff --git a/packages/sdk-components-react-radix/src/radio-group.ws.ts b/packages/sdk-components-react-radix/src/radio-group.ws.tsindex 6edd34b00b..f352c074bb 100644--- a/packages/sdk-components-react-radix/src/radio-group.ws.ts+++ b/packages/sdk-components-react-radix/src/radio-group.ws.ts@@ -1,7 +1,7 @@import { ItemIcon, RadioGroupIcon, TriggerIcon } from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { button, div, span } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import { buttonReset } from "./shared/preset-styles";import {propsRadioGroup,@@ -14,7 +14,7 @@ export const metaRadioGroup: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.RadioGroupItem],+ descendants: [getRadixComponentId("RadioGroupItem")],},presetStyle: {div,@@ -28,7 +28,7 @@ export const metaRadioGroupItem: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.RadioGroupIndicator],+ descendants: [getRadixComponentId("RadioGroupIndicator")],},states: [{ label: "Checked", selector: '[data-state="checked"]' },diff --git a/packages/sdk-components-react-radix/src/select.template.tsx b/packages/sdk-components-react-radix/src/select.template.tsxindex ca2c059a75..3a2161d313 100644--- a/packages/sdk-components-react-radix/src/select.template.tsx+++ b/packages/sdk-components-react-radix/src/select.template.tsx@@ -1,10 +1,21 @@+/** @jsxImportSource @webstudio-is/template */import {- $,css,PlaceholderValue,+ setInstanceMeta,type TemplateMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import { HtmlEmbed } from "@webstudio-is/sdk-components-react/components";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectItemIndicator,+ SelectItemText,+ SelectTrigger,+ SelectValue,+ SelectViewport,+} from "./components";import {borderRadius,borderWidth,@@ -23,7 +34,7 @@ import { iconEmbedStyle } from "./shared/styles";const createSelectItem = (value: string, label: string) => {return (- <radix.SelectItem+ <SelectItemvalue={value}// relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none// focus:bg-accent focus:text-accent-foreground@@ -50,7 +61,7 @@ const createSelectItem = (value: string, label: string) => {}`}>- <radix.SelectItemIndicator+ <SelectItemIndicator// absolute left-2 flex h-3.5 w-3.5 items-center justify-centerws:style={css`position: absolute;@@ -62,14 +73,13 @@ const createSelectItem = (value: string, label: string) => {justify-content: center;`}>- <$.HtmlEmbed- ws:label="Indicator Icon"- ws:style={iconEmbedStyle}- code={CheckMarkIcon}- />- </radix.SelectItemIndicator>- <radix.SelectItemText>{new PlaceholderValue(label)}</radix.SelectItemText>- </radix.SelectItem>+ {setInstanceMeta(+ { label: "Indicator Icon" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={CheckMarkIcon} />+ )}+ </SelectItemIndicator>+ <SelectItemText>{new PlaceholderValue(label)}</SelectItemText>+ </SelectItem>);};@@ -79,8 +89,8 @@ export const meta: TemplateMeta = {"Use within a form to give your users a list of options to choose from.",order: 10,template: (- <radix.Select>- <radix.SelectTrigger+ <Select>+ <SelectTrigger// flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background// placeholder:text-muted-foreground// focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2@@ -110,9 +120,9 @@ export const meta: TemplateMeta = {}`}>- <radix.SelectValue placeholder="Theme" />- </radix.SelectTrigger>- <radix.SelectContent+ <SelectValue placeholder="Theme" />+ </SelectTrigger>+ <SelectContent// relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md// data-[state=open]:animate-in// data-[state=closed]:animate-out data-[state=closed]:fade-out-0@@ -140,7 +150,7 @@ export const meta: TemplateMeta = {box-shadow: ${boxShadow.md};`}>- <radix.SelectViewport+ <SelectViewport// p-1// position=popper// h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]@@ -154,8 +164,8 @@ export const meta: TemplateMeta = {{createSelectItem("light", "Light")}{createSelectItem("dark", "Dark")}{createSelectItem("system", "System")}- </radix.SelectViewport>- </radix.SelectContent>- </radix.Select>+ </SelectViewport>+ </SelectContent>+ </Select>),};diff --git a/packages/sdk-components-react-radix/src/select.ws.ts b/packages/sdk-components-react-radix/src/select.ws.tsindex 43ac5272a4..a3b03715a6 100644--- a/packages/sdk-components-react-radix/src/select.ws.ts+++ b/packages/sdk-components-react-radix/src/select.ws.ts@@ -10,7 +10,7 @@ import {} from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { button, div, span } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import {propsSelect,propsSelectContent,@@ -27,7 +27,10 @@ export const metaSelect: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.SelectTrigger, radix.SelectContent],+ descendants: [+ getRadixComponentId("SelectTrigger"),+ getRadixComponentId("SelectContent"),+ ],},initialProps: ["name", "value", "open", "required"],props: propsSelect,@@ -38,7 +41,7 @@ export const metaSelectTrigger: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.SelectValue],+ descendants: [getRadixComponentId("SelectValue")],},states: [{ label: "Open", selector: '[data-state="open"]' },@@ -65,7 +68,7 @@ export const metaSelectContent: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.SelectViewport],+ descendants: [getRadixComponentId("SelectViewport")],},states: [{ label: "Open", selector: '[data-state="open"]' },@@ -80,7 +83,7 @@ export const metaSelectViewport: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.SelectItem],+ descendants: [getRadixComponentId("SelectItem")],},presetStyle: { div },props: propsSelectViewport,@@ -91,7 +94,10 @@ export const metaSelectItem: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.SelectItemIndicator, radix.SelectItemText],+ descendants: [+ getRadixComponentId("SelectItemIndicator"),+ getRadixComponentId("SelectItemText"),+ ],},states: [{ label: "Checked", selector: '[data-state="checked"]' },diff --git a/packages/sdk-components-react-radix/src/shared/component-id.ts b/packages/sdk-components-react-radix/src/shared/component-id.tsnew file mode 100644index 0000000000..c187454225--- /dev/null+++ b/packages/sdk-components-react-radix/src/shared/component-id.ts@@ -0,0 +1,6 @@+/** Builds persisted IDs only for exported Radix component names. */+type RadixComponentName = keyof typeof import("../components");++export const getRadixComponentId = <Name extends RadixComponentName>(+ name: Name+) => `@webstudio-is/sdk-components-react-radix:${name}` as const;diff --git a/packages/sdk-components-react-radix/src/shared/meta.ts b/packages/sdk-components-react-radix/src/shared/meta.tsdeleted file mode 100644index 8c756ab27d..0000000000--- a/packages/sdk-components-react-radix/src/shared/meta.ts+++ /dev/null@@ -1,14 +0,0 @@-const createMetaProxy = (prefix: string): Record<string, string> => {- return new Proxy(- {},- {- get(_target, prop) {- return `${prefix}${prop as string}`;- },- }- );-};--export const radix = createMetaProxy(- "@webstudio-is/sdk-components-react-radix:"-);diff --git a/packages/sdk-components-react-radix/src/shared/proxy.ts b/packages/sdk-components-react-radix/src/shared/proxy.tsdeleted file mode 100644index b07d0ef5f5..0000000000--- a/packages/sdk-components-react-radix/src/shared/proxy.ts+++ /dev/null@@ -1,3 +0,0 @@-import { createProxy } from "@webstudio-is/template";--export const radix = createProxy("@webstudio-is/sdk-components-react-radix:");diff --git a/packages/sdk-components-react-radix/src/sheet.template.tsx b/packages/sdk-components-react-radix/src/sheet.template.tsxindex f66ca88a98..0adc96861c 100644--- a/packages/sdk-components-react-radix/src/sheet.template.tsx+++ b/packages/sdk-components-react-radix/src/sheet.template.tsx@@ -1,11 +1,26 @@+/** @jsxImportSource @webstudio-is/template */import { LargeXIcon, MenuIcon } from "@webstudio-is/icons/svg";import {type TemplateMeta,- $,css,PlaceholderValue,+ setInstanceMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import {+ Box,+ Button,+ HtmlEmbed,+ Text,+} from "@webstudio-is/sdk-components-react/components";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogOverlay,+ DialogTitle,+ DialogTrigger,+} from "./components";import {blur,borderRadius,@@ -39,139 +54,160 @@ export const meta: TemplateMeta = {description:"Displays content in a menu that slides out from the side of the screen, triggered by a button. Use this component for a typical mobile hamburger menu.",order: 1,- template: (- <radix.Dialog ws:label="Sheet">- <radix.DialogTrigger ws:label="Sheet Trigger">- <$.Button ws:style={getButtonStyle("ghost", "icon")}>- <$.HtmlEmbed- ws:label="Hamburger Menu Svg"- ws:style={iconEmbedStyle}- code={MenuIcon}- />- </$.Button>- </radix.DialogTrigger>- <radix.DialogOverlay- ws:label="Sheet Overlay"- /**- * fixed inset-0 z-50 bg-background/80 backdrop-blur-sm- * flex- **/- ws:style={css`- position: fixed;- inset: 0;- z-index: ${zIndex[50]};- background-color: rgb(255 255 255 / 0.8);- backdrop-filter: ${blur.sm};- /* To allow positioning Content */- display: flex;- flex-direction: column;- overflow: auto;- `}- >- <radix.DialogContent- ws:label="Sheet Content"+ template: setInstanceMeta(+ { label: "Sheet" },+ <Dialog>+ {setInstanceMeta(+ { label: "Sheet Trigger" },+ <DialogTrigger>+ <Button ws:style={getButtonStyle("ghost", "icon")}>+ {setInstanceMeta(+ { label: "Hamburger Menu Svg" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={MenuIcon} />+ )}+ </Button>+ </DialogTrigger>+ )}+ {setInstanceMeta(+ { label: "Sheet Overlay" },+ <DialogOverlay/**- * fixed w-full z-50- * grid gap-4 max-w-lg- * m-auto- * border bg-background p-6 shadow-lg+ * fixed inset-0 z-50 bg-background/80 backdrop-blur-sm+ * flex**/ws:style={css`- width: ${width.full};+ position: fixed;+ inset: 0;z-index: ${zIndex[50]};+ background-color: rgb(255 255 255 / 0.8);+ backdrop-filter: ${blur.sm};+ /* To allow positioning Content */display: flex;flex-direction: column;- gap: ${spacing[4]};- border: ${borderWidth.DEFAULT} solid ${colors.border};- background-color: ${colors.background};- padding: ${spacing[6]};- box-shadow: ${boxShadow.lg};- position: relative;- /* side=left */- margin-right: auto;- max-width: ${maxWidth.sm};- flex-grow: 1;+ overflow: auto;`}>- <$.Box ws:label="Navigation" ws:tag="nav">- <$.Box- ws:label="Sheet Header"+ {setInstanceMeta(+ { label: "Sheet Content" },+ <DialogContent+ /**+ * fixed w-full z-50+ * grid gap-4 max-w-lg+ * m-auto+ * border bg-background p-6 shadow-lg+ **/ws:style={css`+ width: ${width.full};+ z-index: ${zIndex[50]};display: flex;flex-direction: column;- gap: ${spacing[2]};+ gap: ${spacing[4]};+ border: ${borderWidth.DEFAULT} solid ${colors.border};+ background-color: ${colors.background};+ padding: ${spacing[6]};+ box-shadow: ${boxShadow.lg};+ position: relative;+ /* side=left */+ margin-right: auto;+ max-width: ${maxWidth.sm};+ flex-grow: 1;`}>- <radix.DialogTitle- ws:label="Sheet Title"- /**- * text-lg leading-none tracking-tight- **/- ws:style={css`- font-size: ${fontSize.lg};- line-height: ${lineHeight.none};- letter-spacing: ${letterSpacing.tight};- margin: 0;- `}- >- {new PlaceholderValue("Sheet Title")}- </radix.DialogTitle>- <radix.DialogDescription- ws:label="Sheet Description"- /**- * text-sm text-muted-foreground- **/- ws:style={css`- font-size: ${fontSize.sm};- line-height: ${fontSizeLineHeight.sm};- color: ${colors.mutedForeground};- margin: 0;- `}- >- {new PlaceholderValue("Sheet description text you can edit")}- </radix.DialogDescription>- </$.Box>- <$.Text>{new PlaceholderValue("The text you can edit")}</$.Text>- </$.Box>- <radix.DialogClose- ws:label="Close Button"- /**- * absolute right-4 top-4- * rounded-sm opacity-70- * ring-offset-background- * hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2- * flex items-center justify-center h-4 w-4- **/- ws:style={css`- position: absolute;- right: ${spacing[4]};- top: ${spacing[4]};- border-radius: ${borderRadius.sm};- opacity: ${opacity[70]};- display: flex;- align-items: center;- justify-content: center;- height: ${height[4]};- width: ${height[4]};- border: 0;- background-color: transparent;- outline: none;- &:hover {- opacity: ${opacity[100]};- }- &:focus-visible {- box-shadow: ${boxShadow.ring};- }- `}- >- <$.HtmlEmbed- ws:label="Close Icon"- ws:style={iconEmbedStyle}- code={LargeXIcon}- />- </radix.DialogClose>- </radix.DialogContent>- </radix.DialogOverlay>- </radix.Dialog>+ {setInstanceMeta(+ { label: "Navigation" },+ <Box tag="nav">+ {setInstanceMeta(+ { label: "Sheet Header" },+ <Box+ ws:style={css`+ display: flex;+ flex-direction: column;+ gap: ${spacing[2]};+ `}+ >+ {setInstanceMeta(+ { label: "Sheet Title" },+ <DialogTitle+ /**+ * text-lg leading-none tracking-tight+ **/+ ws:style={css`+ font-size: ${fontSize.lg};+ line-height: ${lineHeight.none};+ letter-spacing: ${letterSpacing.tight};+ margin: 0;+ `}+ >+ {new PlaceholderValue("Sheet Title")}+ </DialogTitle>+ )}+ {setInstanceMeta(+ { label: "Sheet Description" },+ <DialogDescription+ /**+ * text-sm text-muted-foreground+ **/+ ws:style={css`+ font-size: ${fontSize.sm};+ line-height: ${fontSizeLineHeight.sm};+ color: ${colors.mutedForeground};+ margin: 0;+ `}+ >+ {+ new PlaceholderValue(+ "Sheet description text you can edit"+ )+ }+ </DialogDescription>+ )}+ </Box>+ )}+ <Text>{new PlaceholderValue("The text you can edit")}</Text>+ </Box>+ )}+ {setInstanceMeta(+ { label: "Close Button" },+ <DialogClose+ /**+ * absolute right-4 top-4+ * rounded-sm opacity-70+ * ring-offset-background+ * hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2+ * flex items-center justify-center h-4 w-4+ **/+ ws:style={css`+ position: absolute;+ right: ${spacing[4]};+ top: ${spacing[4]};+ border-radius: ${borderRadius.sm};+ opacity: ${opacity[70]};+ display: flex;+ align-items: center;+ justify-content: center;+ height: ${height[4]};+ width: ${height[4]};+ border: 0;+ background-color: transparent;+ outline: none;+ &:hover {+ opacity: ${opacity[100]};+ }+ &:focus-visible {+ box-shadow: ${boxShadow.ring};+ }+ `}+ >+ {setInstanceMeta(+ { label: "Close Icon" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={LargeXIcon} />+ )}+ </DialogClose>+ )}+ </DialogContent>+ )}+ </DialogOverlay>+ )}+ </Dialog>),};diff --git a/packages/sdk-components-react-radix/src/story-templates.ts b/packages/sdk-components-react-radix/src/story-templates.tsindex 1be856bca1..2d5fa78508 100644--- a/packages/sdk-components-react-radix/src/story-templates.ts+++ b/packages/sdk-components-react-radix/src/story-templates.ts@@ -1,13 +1,30 @@-export { meta as Label } from "./label.template";-export { meta as Tabs } from "./tabs.template";-export { meta as Sheet } from "./sheet.template";-export { meta as Dialog } from "./dialog.template";-export { meta as Switch } from "./switch.template";-export { meta as Checkbox } from "./checkbox.template";-export { meta as Collapsible } from "./collapsible.template";-export { meta as Accordion } from "./accordion.template";-export { meta as Tooltip } from "./tooltip.template";-export { meta as Popover } from "./popover.template";-export { meta as RadioGroup } from "./radio-group.template";-export { meta as Select } from "./select.template";-export { meta as NavigationMenu } from "./navigation-menu.template";+/** Component templates consumed by story generation. */+import { meta as label } from "./label.template";+import { meta as tabs } from "./tabs.template";+import { meta as sheet } from "./sheet.template";+import { meta as dialog } from "./dialog.template";+import { meta as switchTemplate } from "./switch.template";+import { meta as checkbox } from "./checkbox.template";+import { meta as collapsible } from "./collapsible.template";+import { meta as accordion } from "./accordion.template";+import { meta as tooltip } from "./tooltip.template";+import { meta as popover } from "./popover.template";+import { meta as radioGroup } from "./radio-group.template";+import { meta as select } from "./select.template";+import { meta as navigationMenu } from "./navigation-menu.template";++export const templates = [+ { meta: label },+ { meta: tabs },+ { storyName: "Sheet", meta: sheet },+ { meta: dialog },+ { meta: switchTemplate },+ { storyName: "Checkbox", meta: checkbox },+ { meta: collapsible },+ { meta: accordion },+ { meta: tooltip },+ { meta: popover },+ { meta: radioGroup },+ { meta: select },+ { meta: navigationMenu },+];diff --git a/packages/sdk-components-react-radix/src/switch.template.tsx b/packages/sdk-components-react-radix/src/switch.template.tsxindex 756b226a23..acd04442f0 100644--- a/packages/sdk-components-react-radix/src/switch.template.tsx+++ b/packages/sdk-components-react-radix/src/switch.template.tsx@@ -1,5 +1,6 @@+/** @jsxImportSource @webstudio-is/template */import { css, type TemplateMeta } from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import { Switch, SwitchThumb } from "./components";import {borderRadius,borderWidth,@@ -17,7 +18,7 @@ export const meta: TemplateMeta = {"A control that allows the user to toggle between checked and not checked.",order: 11,template: (- <radix.Switch+ <Switch// peer inline-flex h-[24px] w-[44px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors// focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background// disabled:cursor-not-allowed disabled:opacity-50@@ -49,7 +50,7 @@ export const meta: TemplateMeta = {}`}>- <radix.SwitchThumb+ <SwitchThumb// pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform// data-[state=checked]:translate-x-5// data-[state=unchecked]:translate-x-0@@ -70,6 +71,6 @@ export const meta: TemplateMeta = {}`}/>- </radix.Switch>+ </Switch>),};diff --git a/packages/sdk-components-react-radix/src/switch.ws.ts b/packages/sdk-components-react-radix/src/switch.ws.tsindex 1bc6eb3fd8..db715cc742 100644--- a/packages/sdk-components-react-radix/src/switch.ws.ts+++ b/packages/sdk-components-react-radix/src/switch.ws.ts@@ -1,7 +1,7 @@import { SwitchIcon, TriggerIcon } from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { button, span } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import { buttonReset } from "./shared/preset-styles";import { propsSwitch, propsSwitchThumb } from "./__generated__/switch.props";@@ -10,7 +10,7 @@ export const metaSwitch: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.SwitchThumb],+ descendants: [getRadixComponentId("SwitchThumb")],},states: [{ label: "Checked", selector: '[data-state="checked"]' },diff --git a/packages/sdk-components-react-radix/src/tabs.template.tsx b/packages/sdk-components-react-radix/src/tabs.template.tsxindex 81ca57ecf5..3875762526 100644--- a/packages/sdk-components-react-radix/src/tabs.template.tsx+++ b/packages/sdk-components-react-radix/src/tabs.template.tsx@@ -1,9 +1,10 @@+/** @jsxImportSource @webstudio-is/template */import {css,PlaceholderValue,type TemplateMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "./components";import {borderRadius,colors,@@ -73,8 +74,8 @@ export const meta: TemplateMeta = {"A set of panels with content that are displayed one at a time. Duplicate both a tab trigger and tab content to add more tabs. Triggers and content are connected according to their order in the Navigator.",order: 2,template: (- <radix.Tabs value="0">- <radix.TabsList+ <Tabs value="0">+ <TabsList// inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foregroundws:style={css`display: inline-flex;@@ -87,19 +88,19 @@ export const meta: TemplateMeta = {color: ${colors.mutedForeground};`}>- <radix.TabsTrigger ws:style={tabsTriggerStyle}>+ <TabsTrigger ws:style={tabsTriggerStyle}>{new PlaceholderValue("Account")}- </radix.TabsTrigger>- <radix.TabsTrigger ws:style={tabsTriggerStyle}>+ </TabsTrigger>+ <TabsTrigger ws:style={tabsTriggerStyle}>{new PlaceholderValue("Password")}- </radix.TabsTrigger>- </radix.TabsList>- <radix.TabsContent ws:style={tabsContentStyle}>+ </TabsTrigger>+ </TabsList>+ <TabsContent ws:style={tabsContentStyle}>{new PlaceholderValue("Make changes to your account here.")}- </radix.TabsContent>- <radix.TabsContent ws:style={tabsContentStyle}>+ </TabsContent>+ <TabsContent ws:style={tabsContentStyle}>{new PlaceholderValue("Change your password here.")}- </radix.TabsContent>- </radix.Tabs>+ </TabsContent>+ </Tabs>),};diff --git a/packages/sdk-components-react-radix/src/tabs.ws.ts b/packages/sdk-components-react-radix/src/tabs.ws.tsindex c06401182c..b32ff9236c 100644--- a/packages/sdk-components-react-radix/src/tabs.ws.ts+++ b/packages/sdk-components-react-radix/src/tabs.ws.ts@@ -6,7 +6,7 @@ import {} from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { button, div } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import { buttonReset } from "./shared/preset-styles";import {propsTabs,@@ -20,7 +20,10 @@ export const metaTabs: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.TabsList, radix.TabsContent],+ descendants: [+ getRadixComponentId("TabsList"),+ getRadixComponentId("TabsContent"),+ ],},presetStyle: { div },props: propsTabs,@@ -31,7 +34,7 @@ export const metaTabsList: WsComponentMeta = {contentModel: {category: "none",children: ["instance"],- descendants: [radix.TabsTrigger],+ descendants: [getRadixComponentId("TabsTrigger")],},presetStyle: { div },props: propsTabsList,@@ -40,7 +43,7 @@ export const metaTabsList: WsComponentMeta = {export const metaTabsTrigger: WsComponentMeta = {icon: TriggerIcon,label: "Tab Trigger",- indexWithinAncestor: radix.Tabs,+ indexWithinAncestor: getRadixComponentId("Tabs"),contentModel: {category: "none",children: ["instance", "rich-text"],@@ -58,7 +61,7 @@ export const metaTabsTrigger: WsComponentMeta = {export const metaTabsContent: WsComponentMeta = {label: "Tab Content",icon: ContentIcon,- indexWithinAncestor: radix.Tabs,+ indexWithinAncestor: getRadixComponentId("Tabs"),contentModel: {category: "none",children: ["instance", "rich-text"],diff --git a/packages/sdk-components-react-radix/src/tooltip.template.tsx b/packages/sdk-components-react-radix/src/tooltip.template.tsxindex bd9fcadae2..96bd3d3e8a 100644--- a/packages/sdk-components-react-radix/src/tooltip.template.tsx+++ b/packages/sdk-components-react-radix/src/tooltip.template.tsx@@ -1,10 +1,11 @@+/** @jsxImportSource @webstudio-is/template */import {- $,css,PlaceholderValue,type TemplateMeta,} from "@webstudio-is/template";-import { radix } from "./shared/proxy";+import { Button, Text } from "@webstudio-is/sdk-components-react/components";+import { Tooltip, TooltipContent, TooltipTrigger } from "./components";import { getButtonStyle } from "./shared/styles";import {borderRadius,@@ -30,13 +31,13 @@ export const meta: TemplateMeta = {"Displays content that is related to the trigger, when the trigger is hovered with the mouse or focused with the keyboard. You are reading an example of a tooltip right now.",order: 7,template: (- <radix.Tooltip>- <radix.TooltipTrigger>- <$.Button ws:style={getButtonStyle("outline")}>+ <Tooltip>+ <TooltipTrigger>+ <Button ws:style={getButtonStyle("outline")}>{new PlaceholderValue("Button")}- </$.Button>- </radix.TooltipTrigger>- <radix.TooltipContent+ </Button>+ </TooltipTrigger>+ <TooltipContent/*** z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md**/@@ -52,8 +53,8 @@ export const meta: TemplateMeta = {box-shadow: ${boxShadow.md};`}>- <$.Text>{new PlaceholderValue("The text you can edit")}</$.Text>- </radix.TooltipContent>- </radix.Tooltip>+ <Text>{new PlaceholderValue("The text you can edit")}</Text>+ </TooltipContent>+ </Tooltip>),};diff --git a/packages/sdk-components-react-radix/src/tooltip.ws.ts b/packages/sdk-components-react-radix/src/tooltip.ws.tsindex 551227d8f5..c4ab91c99c 100644--- a/packages/sdk-components-react-radix/src/tooltip.ws.ts+++ b/packages/sdk-components-react-radix/src/tooltip.ws.ts@@ -1,7 +1,7 @@import { TooltipIcon, TriggerIcon, ContentIcon } from "@webstudio-is/icons/svg";import type { WsComponentMeta } from "@webstudio-is/sdk";import { div } from "@webstudio-is/sdk/normalize.css";-import { radix } from "./shared/meta";+import { getRadixComponentId } from "./shared/component-id";import {propsTooltip,propsTooltipContent,@@ -43,7 +43,10 @@ export const metaTooltip: WsComponentMeta = {contentModel: {category: "instance",children: ["instance"],- descendants: [radix.TooltipTrigger, radix.TooltipContent],+ descendants: [+ getRadixComponentId("TooltipTrigger"),+ getRadixComponentId("TooltipContent"),+ ],},initialProps: ["open", "delayDuration", "disableHoverableContent"],props: propsTooltip,diff --git a/packages/sdk-components-react/src/__generated__/list.stories.tsx b/packages/sdk-components-react/src/__generated__/list.stories.tsxindex 1a93698e34..481a450e64 100644--- a/packages/sdk-components-react/src/__generated__/list.stories.tsx+++ b/packages/sdk-components-react/src/__generated__/list.stories.tsx@@ -28,7 +28,7 @@ const Story = {div.w-box {box-sizing: border-box}- ol.w-list {+ ul.w-list {box-sizing: border-box;margin-top: 0;margin-bottom: 10px;diff --git a/packages/sdk-components-react/src/basic.template.tsx b/packages/sdk-components-react/src/basic.template.tsxindex 650b54fae2..987506b60e 100644--- a/packages/sdk-components-react/src/basic.template.tsx+++ b/packages/sdk-components-react/src/basic.template.tsx@@ -1,90 +1,119 @@+/** @jsxImportSource @webstudio-is/template */import {- $,css,PlaceholderValue,+ setInstanceMeta,type TemplateMeta,} from "@webstudio-is/template";+import {+ Blockquote,+ Bold,+ Box,+ Button,+ Checkbox,+ Fragment,+ Heading,+ HtmlEmbed,+ Image,+ Input,+ Italic,+ JsonLd,+ Label,+ Link,+ List,+ ListItem,+ Paragraph,+ RadioButton,+ RemixForm,+ RichTextLink,+ Separator,+ Span,+ Subscript,+ Superscript,+ Text,+ Textarea,+ Time,+ Video,+} from "./components";const sampleImage ="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 360'%3E%3Crect width='640' height='360' fill='%23eef2ff'/%3E%3Cpath d='M96 264l120-120 88 88 56-56 184 184H96z' fill='%2394a3b8'/%3E%3Ccircle cx='456' cy='112' r='44' fill='%23f59e0b'/%3E%3C/svg%3E";-export const Blockquote: TemplateMeta = {+const BlockquoteTemplate: TemplateMeta = {category: "typography",description: "A quoted customer insight or design principle.",template: (- <$.Blockquote>- <$.Text>+ <Blockquote>+ <Text>{new PlaceholderValue("Operations teams need interfaces that make the next action obvious.")}- </$.Text>- </$.Blockquote>+ </Text>+ </Blockquote>),};-export const Bold: TemplateMeta = {+const BoldTemplate: TemplateMeta = {category: "typography",- template: <$.Bold>{new PlaceholderValue("Critical update")}</$.Bold>,+ template: <Bold>{new PlaceholderValue("Critical update")}</Bold>,};-export const Box: TemplateMeta = {+const BoxTemplate: TemplateMeta = {category: "general",- template: (- <$.Box- ws:label="Example Card"+ template: setInstanceMeta(+ { label: "Example Card" },+ <Boxws:style={css`padding: 16px;border: 1px solid #d4d4d8;border-radius: 8px;`}>- <$.Text>{new PlaceholderValue("Component example container")}</$.Text>- </$.Box>+ <Text>{new PlaceholderValue("Component example container")}</Text>+ </Box>),};-export const Button: TemplateMeta = {+const ButtonTemplate: TemplateMeta = {category: "forms",- template: <$.Button>{new PlaceholderValue("Save changes")}</$.Button>,+ template: <Button>{new PlaceholderValue("Save changes")}</Button>,};-export const Checkbox: TemplateMeta = {+const CheckboxTemplate: TemplateMeta = {category: "forms",- template: <$.Checkbox aria-label="Enable weekly summary" />,+ template: <Checkbox aria-label="Enable weekly summary" />,};-export const Fragment: TemplateMeta = {+const FragmentTemplate: TemplateMeta = {category: "general",template: (- <$.Fragment>- <$.Text>{new PlaceholderValue("Reusable fragment content")}</$.Text>- </$.Fragment>+ <Fragment>+ <Text>{new PlaceholderValue("Reusable fragment content")}</Text>+ </Fragment>),};-export const Heading: TemplateMeta = {+const HeadingTemplate: TemplateMeta = {category: "typography",template: (- <$.Heading tag="h2">- {new PlaceholderValue("Operational UI pattern")}- </$.Heading>+ <Heading tag="h2">{new PlaceholderValue("Operational UI pattern")}</Heading>),};-export const HtmlEmbed: TemplateMeta = {+const HtmlEmbedTemplate: TemplateMeta = {category: "media",template: (- <$.HtmlEmbed code="<div style='padding:12px;border:1px dashed #94a3b8;border-radius:8px'>Embedded status widget</div>" />+ <HtmlEmbed code="<div style='padding:12px;border:1px dashed #94a3b8;border-radius:8px'>Embedded status widget</div>" />),};-export const JsonLd: TemplateMeta = {+const JsonLdTemplate: TemplateMeta = {category: "general",order: 6,template: (- <$.JsonLd+ <JsonLdcode={JSON.stringify({"@context": "https://schema.org","@type": "Organization",@@ -94,10 +123,10 @@ export const JsonLd: TemplateMeta = {),};-export const Image: TemplateMeta = {+const ImageTemplate: TemplateMeta = {category: "media",template: (- <$.Image+ <Imagesrc={sampleImage}alt="Abstract dashboard illustration"width={640}@@ -106,67 +135,61 @@ export const Image: TemplateMeta = {),};-export const Input: TemplateMeta = {+const InputTemplate: TemplateMeta = {category: "forms",- template: <$.Input name="workspace" placeholder="Workspace name" />,+ template: <Input name="workspace" placeholder="Workspace name" />,};-export const Italic: TemplateMeta = {+const ItalicTemplate: TemplateMeta = {category: "typography",- template: <$.Italic>{new PlaceholderValue("Draft state")}</$.Italic>,+ template: <Italic>{new PlaceholderValue("Draft state")}</Italic>,};-export const Label: TemplateMeta = {+const LabelTemplate: TemplateMeta = {category: "forms",- template: <$.Label>{new PlaceholderValue("Workspace")}</$.Label>,+ template: <Label>{new PlaceholderValue("Workspace")}</Label>,};-export const Link: TemplateMeta = {+const LinkTemplate: TemplateMeta = {category: "general",template: (- <$.Link href="#components">- {new PlaceholderValue("View components")}- </$.Link>+ <Link href="#components">{new PlaceholderValue("View components")}</Link>),};-export const List: TemplateMeta = {+const ListTemplate: TemplateMeta = {category: "typography",template: (- <$.List>- <$.ListItem>- {new PlaceholderValue("Triage incoming requests")}- </$.ListItem>- <$.ListItem>{new PlaceholderValue("Assign an owner")}</$.ListItem>- <$.ListItem>{new PlaceholderValue("Resolve before SLA")}</$.ListItem>- </$.List>+ <List>+ <ListItem>{new PlaceholderValue("Triage incoming requests")}</ListItem>+ <ListItem>{new PlaceholderValue("Assign an owner")}</ListItem>+ <ListItem>{new PlaceholderValue("Resolve before SLA")}</ListItem>+ </List>),};-export const ListItem: TemplateMeta = {+const ListItemTemplate: TemplateMeta = {category: "typography",- template: (- <$.ListItem>{new PlaceholderValue("Review queue health")}</$.ListItem>- ),+ template: <ListItem>{new PlaceholderValue("Review queue health")}</ListItem>,};-export const Paragraph: TemplateMeta = {+const ParagraphTemplate: TemplateMeta = {category: "typography",template: (- <$.Paragraph>+ <Paragraph>{new PlaceholderValue("Use these patterns to compose dense operational screens that stay readable under pressure.")}- </$.Paragraph>+ </Paragraph>),};-export const RadioButton: TemplateMeta = {+const RadioButtonTemplate: TemplateMeta = {category: "forms",template: (- <$.RadioButton+ <RadioButtonname="priority"value="standard"aria-label="Standard priority"@@ -174,66 +197,97 @@ export const RadioButton: TemplateMeta = {),};-export const RemixForm: TemplateMeta = {+const RemixFormTemplate: TemplateMeta = {category: "forms",template: (- <$.RemixForm>- <$.Label>{new PlaceholderValue("Search")}</$.Label>- <$.Input name="query" placeholder="Find a ticket" />- <$.Button>{new PlaceholderValue("Search")}</$.Button>- </$.RemixForm>+ <RemixForm>+ <Label>{new PlaceholderValue("Search")}</Label>+ <Input name="query" placeholder="Find a ticket" />+ <Button>{new PlaceholderValue("Search")}</Button>+ </RemixForm>),};-export const RichTextLink: TemplateMeta = {+const RichTextLinkTemplate: TemplateMeta = {category: "typography",template: (- <$.RichTextLink href="#guidelines">+ <RichTextLink href="#guidelines">{new PlaceholderValue("Read the usage guidelines")}- </$.RichTextLink>+ </RichTextLink>),};-export const Separator: TemplateMeta = {+const SeparatorTemplate: TemplateMeta = {category: "general",- template: <$.Separator />,+ template: <Separator />,};-export const Span: TemplateMeta = {+const SpanTemplate: TemplateMeta = {category: "typography",- template: <$.Span>{new PlaceholderValue("Inline status")}</$.Span>,+ template: <Span>{new PlaceholderValue("Inline status")}</Span>,};-export const Subscript: TemplateMeta = {+const SubscriptTemplate: TemplateMeta = {category: "typography",- template: <$.Subscript>{new PlaceholderValue("beta")}</$.Subscript>,+ template: <Subscript>{new PlaceholderValue("beta")}</Subscript>,};-export const Superscript: TemplateMeta = {+const SuperscriptTemplate: TemplateMeta = {category: "typography",- template: <$.Superscript>{new PlaceholderValue("new")}</$.Superscript>,+ template: <Superscript>{new PlaceholderValue("new")}</Superscript>,};-export const Text: TemplateMeta = {+const TextTemplate: TemplateMeta = {category: "typography",- template: <$.Text>{new PlaceholderValue("System message")}</$.Text>,+ template: <Text>{new PlaceholderValue("System message")}</Text>,};-export const Textarea: TemplateMeta = {+const TextareaTemplate: TemplateMeta = {category: "forms",- template: <$.Textarea name="notes" placeholder="Add handoff notes" />,+ template: <Textarea name="notes" placeholder="Add handoff notes" />,};-export const Time: TemplateMeta = {+const TimeTemplate: TemplateMeta = {category: "typography",template: (- <$.Time datetime="2026-07-06T09:00:00Z">+ <Time datetime="2026-07-06T09:00:00Z">{new PlaceholderValue("Jul 6, 2026, 09:00")}- </$.Time>+ </Time>),};-export const Video: TemplateMeta = {+const VideoTemplate: TemplateMeta = {category: "media",- template: <$.Video controls aria-label="Workflow walkthrough video" />,+ template: <Video controls aria-label="Workflow walkthrough video" />,};++export const templates = [+ BlockquoteTemplate,+ BoldTemplate,+ BoxTemplate,+ ButtonTemplate,+ CheckboxTemplate,+ FragmentTemplate,+ HeadingTemplate,+ HtmlEmbedTemplate,+ ImageTemplate,+ InputTemplate,+ ItalicTemplate,+ JsonLdTemplate,+ LabelTemplate,+ LinkTemplate,+ ListTemplate,+ ListItemTemplate,+ ParagraphTemplate,+ RadioButtonTemplate,+ RemixFormTemplate,+ RichTextLinkTemplate,+ SeparatorTemplate,+ SpanTemplate,+ SubscriptTemplate,+ SuperscriptTemplate,+ TextTemplate,+ TextareaTemplate,+ TimeTemplate,+ VideoTemplate,+].map((meta) => ({ meta }));diff --git a/packages/sdk-components-react/src/code-text/template.tsx b/packages/sdk-components-react/src/code-text/template.tsxindex cf046b667f..657f976ff8 100644--- a/packages/sdk-components-react/src/code-text/template.tsx+++ b/packages/sdk-components-react/src/code-text/template.tsx@@ -1,6 +1,8 @@-import { $, type TemplateMeta } from "@webstudio-is/template";+/** @jsxImportSource @webstudio-is/template */+import type { TemplateMeta } from "@webstudio-is/template";+import { CodeText } from "./base";-export const CodeText: TemplateMeta = {+export const meta: TemplateMeta = {category: "typography",- template: <$.CodeText>{'const status = "ready";'}</$.CodeText>,+ template: <CodeText>{'const status = "ready";'}</CodeText>,};diff --git a/packages/sdk-components-react/src/content-embed.template.tsx b/packages/sdk-components-react/src/content-embed.template.tsxindex 109e0951cc..4c60029f30 100644--- a/packages/sdk-components-react/src/content-embed.template.tsx+++ b/packages/sdk-components-react/src/content-embed.template.tsx@@ -1,6 +1,8 @@-import { type TemplateMeta, $, ws } from "@webstudio-is/template";+/** @jsxImportSource @webstudio-is/template */+import { type TemplateMeta, setInstanceMeta, ws } from "@webstudio-is/template";import { imagePlaceholderDataUrl } from "@webstudio-is/image";import { ContentEmbedIcon } from "@webstudio-is/icons/svg";+import { HtmlEmbed } from "./html-embed";const htmlSample = `<h1>Styling HTML with Content Embed</h1>@@ -58,8 +60,9 @@ export const meta: TemplateMeta = {description:"Content Embed allows styling of HTML, which can be provided via the Code property statically or loaded dynamically from any Resource, for example, from a CMS.",order: 3,- template: (- <$.HtmlEmbed ws:label="Content Embed" code={htmlSample}>+ template: setInstanceMeta(+ { label: "Content Embed" },+ <HtmlEmbed code={htmlSample}><ws.descendant ws:label="Paragraph" selector=" p" /><ws.descendant ws:label="Heading 1" selector=" h1" /><ws.descendant ws:label="Heading 2" selector=" h2" />@@ -80,6 +83,6 @@ export const meta: TemplateMeta = {<ws.descendant ws:label="Table Row" selector=" tr" /><ws.descendant ws:label="Table Header Cell" selector=" th" /><ws.descendant ws:label="Table Cell" selector=" td" />- </$.HtmlEmbed>+ </HtmlEmbed>),};diff --git a/packages/sdk-components-react/src/generate-stories.ts b/packages/sdk-components-react/src/generate-stories.tsindex f196d17ec4..cedb69dfde 100644--- a/packages/sdk-components-react/src/generate-stories.ts+++ b/packages/sdk-components-react/src/generate-stories.ts@@ -1,9 +1,11 @@import { generateStories } from "@webstudio-is/sdk-cli/generate-stories";-import * as templates from "./story-templates";+import * as components from "./components";+import { templates } from "./story-templates";import * as metas from "./metas";await generateStories({packageName: "@webstudio-is/sdk-components-react",+ components,templates,metas,});diff --git a/packages/sdk-components-react/src/head-slot.template.tsx b/packages/sdk-components-react/src/head-slot.template.tsxindex 41e577fbab..6f704284a7 100644--- a/packages/sdk-components-react/src/head-slot.template.tsx+++ b/packages/sdk-components-react/src/head-slot.template.tsx@@ -1,4 +1,6 @@-import { type TemplateMeta, $ } from "@webstudio-is/template";+/** @jsxImportSource @webstudio-is/template */+import { type TemplateMeta, setInstanceMeta } from "@webstudio-is/template";+import { HeadLink, HeadMeta, HeadSlot, HeadTitle } from "./components";export const meta: TemplateMeta = {category: "general",@@ -6,10 +8,13 @@ export const meta: TemplateMeta = {"The Head Slot component lets you customize page-specific head elements (like canonical URLs), which merge with your site's global head settings, with Head Slot definitions taking priority over Page Settings. For site-wide head changes, use project settings instead.",order: 5,template: (- <$.HeadSlot>- <$.HeadTitle ws:label="Title">Title</$.HeadTitle>- <$.HeadLink ws:label="Link" rel="help" href="/help"></$.HeadLink>- <$.HeadMeta ws:label="Meta" name="keywords" content="SEO"></$.HeadMeta>- </$.HeadSlot>+ <HeadSlot>+ {setInstanceMeta({ label: "Title" }, <HeadTitle>Title</HeadTitle>)}+ {setInstanceMeta({ label: "Link" }, <HeadLink rel="help" href="/help" />)}+ {setInstanceMeta(+ { label: "Meta" },+ <HeadMeta name="keywords" content="SEO" />+ )}+ </HeadSlot>),};diff --git a/packages/sdk-components-react/src/list.ws.ts b/packages/sdk-components-react/src/list.ws.tsindex 547f217eac..d0ca433f75 100644--- a/packages/sdk-components-react/src/list.ws.ts+++ b/packages/sdk-components-react/src/list.ws.ts@@ -39,6 +39,11 @@ const presetStyle = {export const meta: WsComponentMeta = {deprecated: true,presetStyle,+ renderedTag: {+ prop: "ordered",+ values: { true: "ol", false: "ul" },+ default: "ul",+ },initialProps: ["id", "class", "ordered", "start", "reversed"],props,};diff --git a/packages/sdk-components-react/src/markdown-embed.template.tsx b/packages/sdk-components-react/src/markdown-embed.template.tsxindex c9f78e5a59..2a53ef1d1b 100644--- a/packages/sdk-components-react/src/markdown-embed.template.tsx+++ b/packages/sdk-components-react/src/markdown-embed.template.tsx@@ -1,5 +1,7 @@-import { type TemplateMeta, $, ws } from "@webstudio-is/template";+/** @jsxImportSource @webstudio-is/template */+import { type TemplateMeta, ws } from "@webstudio-is/template";import { imagePlaceholderDataUrl } from "@webstudio-is/image";+import { MarkdownEmbed } from "./markdown-embed";const markdownSample = `# Styling Markdown with Markdown Embed@@ -50,7 +52,7 @@ export const meta: TemplateMeta = {description: "Used to add markdown code to the page",order: 4,template: (- <$.MarkdownEmbed code={markdownSample}>+ <MarkdownEmbed code={markdownSample}><ws.descendant ws:label="Paragraph" selector=" p" /><ws.descendant ws:label="Heading 1" selector=" h1" /><ws.descendant ws:label="Heading 2" selector=" h2" />@@ -71,6 +73,6 @@ export const meta: TemplateMeta = {<ws.descendant ws:label="Table Row" selector=" tr" /><ws.descendant ws:label="Table Header Cell" selector=" th" /><ws.descendant ws:label="Table Cell" selector=" td" />- </$.MarkdownEmbed>+ </MarkdownEmbed>),};diff --git a/packages/sdk-components-react/src/rich-text-link.tsx b/packages/sdk-components-react/src/rich-text-link.tsxindex dd18b64a91..001dd0ba45 100644--- a/packages/sdk-components-react/src/rich-text-link.tsx+++ b/packages/sdk-components-react/src/rich-text-link.tsx@@ -1 +1,14 @@-export { Link as RichTextLink } from "./link";+/** Gives rich-text links a distinct component identity while reusing Link. */+import {+ forwardRef,+ type ComponentPropsWithoutRef,+ type ElementRef,+} from "react";+import { Link } from "./link";++export const RichTextLink = forwardRef<+ ElementRef<typeof Link>,+ ComponentPropsWithoutRef<typeof Link>+>((props, ref) => <Link {...props} ref={ref} />);++RichTextLink.displayName = "RichTextLink";diff --git a/packages/sdk-components-react/src/select.template.tsx b/packages/sdk-components-react/src/select.template.tsxindex 4b338904db..421003739c 100644--- a/packages/sdk-components-react/src/select.template.tsx+++ b/packages/sdk-components-react/src/select.template.tsx@@ -1,19 +1,21 @@-import { $, css, type TemplateMeta } from "@webstudio-is/template";+/** @jsxImportSource @webstudio-is/template */+import { css, type TemplateMeta } from "@webstudio-is/template";+import { Option, Select } from "./components";export const meta: TemplateMeta = {category: "forms",description:"A drop-down menu for users to select a single option from a predefined list.",template: (- <$.Select+ <Selectws:style={css`display: block;`}>- <$.Option label="Please choose an option" value="" />- <$.Option label="Option A" value="a" />- <$.Option label="Option B" value="b" />- <$.Option label="Option C" value="c" />- </$.Select>+ <Option label="Please choose an option" value="" />+ <Option label="Option A" value="a" />+ <Option label="Option B" value="b" />+ <Option label="Option C" value="c" />+ </Select>),};diff --git a/packages/sdk-components-react/src/story-templates.ts b/packages/sdk-components-react/src/story-templates.tsindex 157f13cebe..61c9154c93 100644--- a/packages/sdk-components-react/src/story-templates.ts+++ b/packages/sdk-components-react/src/story-templates.ts@@ -1,9 +1,25 @@-export { meta as ContentEmbed } from "./content-embed.template";-export { meta as MarkdownEmbed } from "./markdown-embed.template";-export { meta as Form } from "./webhook-form.template";-export { meta as Vimeo } from "./vimeo.template";-export { meta as YouTube } from "./youtube.template";-export { meta as HeadSlot } from "./head-slot.template";-export { meta as Select } from "./select.template";-export * from "./basic.template";-export * from "./code-text/template";+/**+ * Collects component templates for story generation without assigning component+ * identity through export names. The generator derives identity from each root.+ */+import { templates as basicTemplates } from "./basic.template";+import { meta as contentEmbed } from "./content-embed.template";+import { meta as markdownEmbed } from "./markdown-embed.template";+import { meta as form } from "./webhook-form.template";+import { meta as vimeo } from "./vimeo.template";+import { meta as youtube } from "./youtube.template";+import { meta as headSlot } from "./head-slot.template";+import { meta as select } from "./select.template";+import { meta as codeText } from "./code-text/template";++export const templates = [+ ...basicTemplates,+ { storyName: "ContentEmbed", meta: contentEmbed },+ { meta: markdownEmbed },+ { meta: form },+ { meta: vimeo },+ { meta: youtube },+ { meta: headSlot },+ { meta: select },+ { meta: codeText },+];diff --git a/packages/sdk-components-react/src/vimeo.template.tsx b/packages/sdk-components-react/src/vimeo.template.tsxindex 0fbc7f0455..2ac47d9175 100644--- a/packages/sdk-components-react/src/vimeo.template.tsx+++ b/packages/sdk-components-react/src/vimeo.template.tsx@@ -1,6 +1,18 @@+/** @jsxImportSource @webstudio-is/template */import { PlayIcon, SpinnerIcon } from "@webstudio-is/icons/svg";-import { type TemplateMeta, $, css, ws } from "@webstudio-is/template";+import {+ type TemplateMeta,+ css,+ setInstanceMeta,+} from "@webstudio-is/template";import { iconEmbedStyle } from "./shared/icon-embed-style";+import {+ HtmlEmbed,+ Vimeo,+ VimeoPlayButton,+ VimeoPreviewImage,+ VimeoSpinner,+} from "./components";export const meta: TemplateMeta = {category: "media",@@ -8,14 +20,14 @@ export const meta: TemplateMeta = {description:"Add a video to your page that is hosted on Vimeo. Paste a Vimeo URL and configure the video in the Settings tab.",template: (- <$.Vimeo+ <Vimeows:style={css`position: relative;aspect-ratio: 640/360;width: 100%;`}>- <$.VimeoPreviewImage+ <VimeoPreviewImagews:style={css`position: absolute;object-fit: cover;@@ -28,25 +40,26 @@ export const meta: TemplateMeta = {sizes="100vw"optimize={true}/>- <$.VimeoSpinner- ws:label="Spinner"- ws:style={css`- position: absolute;- top: 50%;- left: 50%;- width: 70px;- height: 70px;- margin-top: -35px;- margin-left: -35px;- `}- >- <$.HtmlEmbed- ws:label="Spinner SVG"- ws:style={iconEmbedStyle}- code={SpinnerIcon}- />- </$.VimeoSpinner>- <$.VimeoPlayButton+ {setInstanceMeta(+ { label: "Spinner" },+ <VimeoSpinner+ ws:style={css`+ position: absolute;+ top: 50%;+ left: 50%;+ width: 70px;+ height: 70px;+ margin-top: -35px;+ margin-left: -35px;+ `}+ >+ {setInstanceMeta(+ { label: "Spinner SVG" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={SpinnerIcon} />+ )}+ </VimeoSpinner>+ )}+ <VimeoPlayButtonws:style={css`position: absolute;width: 140px;@@ -69,22 +82,22 @@ export const meta: TemplateMeta = {`}aria-label="Play button">- <ws.element- ws:tag="div"- ws:label="Play Icon"- ws:style={css`- width: 60px;- height: 60px;- `}- aria-hidden={true}- >- <$.HtmlEmbed- ws:label="Play SVG"- ws:style={iconEmbedStyle}- code={PlayIcon}- />- </ws.element>- </$.VimeoPlayButton>- </$.Vimeo>+ {setInstanceMeta(+ { label: "Play Icon" },+ <div+ ws:style={css`+ width: 60px;+ height: 60px;+ `}+ aria-hidden={true}+ >+ {setInstanceMeta(+ { label: "Play SVG" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={PlayIcon} />+ )}+ </div>+ )}+ </VimeoPlayButton>+ </Vimeo>),};diff --git a/packages/sdk-components-react/src/webhook-form.template.tsx b/packages/sdk-components-react/src/webhook-form.template.tsxindex 97587a53b9..7f3947f59b 100644--- a/packages/sdk-components-react/src/webhook-form.template.tsx+++ b/packages/sdk-components-react/src/webhook-form.template.tsx@@ -1,13 +1,15 @@+/** @jsxImportSource @webstudio-is/template */import {- $,- ws,ActionValue,css,expression,PlaceholderValue,+ setInstanceMeta,Variable,type TemplateMeta,} from "@webstudio-is/template";+import type { ReactNode } from "react";+import { Form } from "./components";const formState = new Variable("formState", "initial");@@ -16,65 +18,68 @@ export const meta: TemplateMeta = {order: 1,description: "Collect user data and send it to any webhook.",template: (- <$.Form+ <Formstate={expression`${formState}`}onStateChange={new ActionValue(["state"], expression`${formState} = state`)}>- <ws.element- ws:tag="div"- ws:label="Form Content"- ws:show={expression`${formState} === 'initial' || ${formState} === 'error'`}- >- <ws.element- ws:tag="label"- ws:style={css`- display: block;- `}+ {setInstanceMeta(+ { label: "Form Content" },+ <div+ ws:show={expression`${formState} === 'initial' || ${formState} === 'error'`}>- {new PlaceholderValue("Name")}- </ws.element>- <ws.element- ws:tag="input"- ws:style={css`- display: block;- `}- name="name"- />- <ws.element- ws:tag="label"- ws:style={css`- display: block;- `}- >- {new PlaceholderValue("Email")}- </ws.element>- <ws.element- ws:tag="input"- ws:style={css`- display: block;- `}- name="email"- />- <ws.element ws:tag="button">- {new PlaceholderValue("Submit")}- </ws.element>- </ws.element>- <ws.element- ws:tag="div"- ws:label="Success Message"- ws:show={expression`${formState} === 'success'`}- >- {new PlaceholderValue("Thank you for getting in touch!")}- </ws.element>- <ws.element- ws:tag="div"- ws:label="Error Message"- ws:show={expression`${formState} === 'error'`}- >- {new PlaceholderValue("Sorry, something went wrong.")}- </ws.element>- </$.Form>+ <label+ ws:style={css`+ display: block;+ `}+ >+ {new PlaceholderValue("Name") as unknown as ReactNode}+ </label>+ <input+ ws:style={css`+ display: block;+ `}+ name="name"+ />+ <label+ ws:style={css`+ display: block;+ `}+ >+ {new PlaceholderValue("Email") as unknown as ReactNode}+ </label>+ <input+ ws:style={css`+ display: block;+ `}+ name="email"+ />+ <button>+ {new PlaceholderValue("Submit") as unknown as ReactNode}+ </button>+ </div>+ )}+ {setInstanceMeta(+ { label: "Success Message" },+ <div ws:show={expression`${formState} === 'success'`}>+ {+ new PlaceholderValue(+ "Thank you for getting in touch!"+ ) as unknown as ReactNode+ }+ </div>+ )}+ {setInstanceMeta(+ { label: "Error Message" },+ <div ws:show={expression`${formState} === 'error'`}>+ {+ new PlaceholderValue(+ "Sorry, something went wrong."+ ) as unknown as ReactNode+ }+ </div>+ )}+ </Form>),};diff --git a/packages/sdk-components-react/src/youtube.template.tsx b/packages/sdk-components-react/src/youtube.template.tsxindex 09550e4887..c5a79088b3 100644--- a/packages/sdk-components-react/src/youtube.template.tsx+++ b/packages/sdk-components-react/src/youtube.template.tsx@@ -1,6 +1,18 @@+/** @jsxImportSource @webstudio-is/template */import { PlayIcon, SpinnerIcon } from "@webstudio-is/icons/svg";-import { type TemplateMeta, $, css, ws } from "@webstudio-is/template";+import {+ type TemplateMeta,+ css,+ setInstanceMeta,+} from "@webstudio-is/template";import { iconEmbedStyle } from "./shared/icon-embed-style";+import {+ HtmlEmbed,+ VimeoPlayButton,+ VimeoPreviewImage,+ VimeoSpinner,+ YouTube,+} from "./components";export const meta: TemplateMeta = {label: "YouTube",@@ -8,87 +20,92 @@ export const meta: TemplateMeta = {order: 1,description:"Add a video to your page that is hosted on YouTube. Paste a YouTube URL and configure the video in the Settings tab.",- template: (- <$.YouTube- ws:label="YouTube"+ template: setInstanceMeta(+ { label: "YouTube" },+ <YouTubews:style={css`position: relative;aspect-ratio: 640/360;width: 100%;`}>- <$.VimeoPreviewImage- ws:label="Preview Image"- ws:style={css`- position: absolute;- object-fit: cover;- object-position: center;- width: 100%;- height: 100%;- border-radius: 20px;- `}- alt="YouTube video preview image"- sizes="100vw"- optimize={true}- />- <$.VimeoSpinner- ws:label="Spinner"- ws:style={css`- position: absolute;- top: 50%;- left: 50%;- width: 70px;- height: 70px;- margin-top: -35px;- margin-left: -35px;- `}- >- <$.HtmlEmbed- ws:label="Spinner SVG"- ws:style={iconEmbedStyle}- code={SpinnerIcon}+ {setInstanceMeta(+ { label: "Preview Image" },+ <VimeoPreviewImage+ ws:style={css`+ position: absolute;+ object-fit: cover;+ object-position: center;+ width: 100%;+ height: 100%;+ border-radius: 20px;+ `}+ alt="YouTube video preview image"+ sizes="100vw"+ optimize={true}/>- </$.VimeoSpinner>- <$.VimeoPlayButton- ws:label="Play Button"- ws:style={css`- position: absolute;- width: 140px;- height: 80px;- top: 50%;- left: 50%;- margin-top: -40px;- margin-left: -70px;- display: flex;- align-items: center;- justify-content: center;- border-style: none;- border-radius: 5px;- cursor: pointer;- background-color: rgb(18, 18, 18);- color: rgb(255, 255, 255);- &:hover {- background-color: rgb(0, 173, 239);- }- `}- aria-label="Play button"- >- <ws.element- ws:tag="div"- ws:label="Play Icon"+ )}+ {setInstanceMeta(+ { label: "Spinner" },+ <VimeoSpinner+ ws:style={css`+ position: absolute;+ top: 50%;+ left: 50%;+ width: 70px;+ height: 70px;+ margin-top: -35px;+ margin-left: -35px;+ `}+ >+ {setInstanceMeta(+ { label: "Spinner SVG" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={SpinnerIcon} />+ )}+ </VimeoSpinner>+ )}+ {setInstanceMeta(+ { label: "Play Button" },+ <VimeoPlayButtonws:style={css`- width: 60px;- height: 60px;+ position: absolute;+ width: 140px;+ height: 80px;+ top: 50%;+ left: 50%;+ margin-top: -40px;+ margin-left: -70px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-style: none;+ border-radius: 5px;+ cursor: pointer;+ background-color: rgb(18, 18, 18);+ color: rgb(255, 255, 255);+ &:hover {+ background-color: rgb(0, 173, 239);+ }`}- aria-hidden={true}+ aria-label="Play button">- <$.HtmlEmbed- ws:label="Play SVG"- ws:style={iconEmbedStyle}- code={PlayIcon}- />- </ws.element>- </$.VimeoPlayButton>- </$.YouTube>+ {setInstanceMeta(+ { label: "Play Icon" },+ <div+ ws:style={css`+ width: 60px;+ height: 60px;+ `}+ aria-hidden={true}+ >+ {setInstanceMeta(+ { label: "Play SVG" },+ <HtmlEmbed ws:style={iconEmbedStyle} code={PlayIcon} />+ )}+ </div>+ )}+ </VimeoPlayButton>+ )}+ </YouTube>),};diff --git a/packages/sdk-components-registry/package.json b/packages/sdk-components-registry/package.jsonindex 703a1ffb67..8d0ec41058 100644--- a/packages/sdk-components-registry/package.json+++ b/packages/sdk-components-registry/package.json@@ -27,10 +27,18 @@"webstudio": "./src/canvas.ts","types": "./lib/types/canvas.d.ts","import": "./lib/canvas.js"+ },+ "./components": {+ "webstudio": "./src/components.ts",+ "types": "./lib/types/components.d.ts",+ "import": "./lib/components.js"+ },+ "./core-templates": {+ "webstudio": "./src/core-templates.tsx"}},"scripts": {- "build": "rm -rf lib && esbuild src/metas.ts src/framework.ts src/canvas.ts --outdir=lib --bundle --format=esm --packages=external",+ "build": "rm -rf lib && esbuild src/metas.ts src/framework.ts src/components.ts src/canvas.ts --outdir=lib --bundle --format=esm --packages=external","dts": "tsc --project tsconfig.dts.json","test": "vitest run","typecheck": "tsc --noEmit"@@ -40,6 +48,7 @@"react-dom": "18.3.0-canary-14898b6a9-20240318"},"dependencies": {+ "@webstudio-is/icons": "workspace:*","@webstudio-is/sdk": "workspace:*","@webstudio-is/sdk-components-animation": "workspace:*","@webstudio-is/sdk-components-react": "workspace:*",@@ -49,6 +58,7 @@"@testing-library/react": "^16.2.0","@types/react": "^18.2.70","@types/react-dom": "^18.2.25",+ "@webstudio-is/template": "workspace:*","@webstudio-is/tsconfig": "workspace:*","react": "18.3.0-canary-14898b6a9-20240318","react-dom": "18.3.0-canary-14898b6a9-20240318",diff --git a/packages/sdk-components-registry/src/canvas.ts b/packages/sdk-components-registry/src/canvas.tsindex 535cc83402..388c23b6f1 100644--- a/packages/sdk-components-registry/src/canvas.ts+++ b/packages/sdk-components-registry/src/canvas.ts@@ -1,13 +1,10 @@+/** Composes registered components with their canvas metadata and templates. */import { coreMetas } from "@webstudio-is/sdk";-import { coreTemplates } from "@webstudio-is/sdk/core-templates";-import * as baseComponents from "@webstudio-is/sdk-components-react/components";-import { canvasComponents as baseCanvasComponents } from "@webstudio-is/sdk-components-react/canvas-components";+import { coreTemplates } from "./core-templates";import { hooks as baseHooks } from "@webstudio-is/sdk-components-react/hooks";import * as baseTemplates from "@webstudio-is/sdk-components-react/templates";-import * as animationComponents from "@webstudio-is/sdk-components-animation";import { hooks as animationHooks } from "@webstudio-is/sdk-components-animation/hooks";import * as animationTemplates from "@webstudio-is/sdk-components-animation/templates";-import * as radixComponents from "@webstudio-is/sdk-components-react-radix";import { hooks as radixHooks } from "@webstudio-is/sdk-components-react-radix/hooks";import * as radixTemplates from "@webstudio-is/sdk-components-react-radix/templates";import {@@ -15,6 +12,12 @@ import {componentMetaLibraries,radixComponentNamespace,} from "./shared";+import {+ animationComponentLibrary,+ baseComponentLibrary,+ componentIds,+ radixComponentLibrary,+} from "./components";const getLibraryMetas = (namespace?: string) => {const library = componentMetaLibraries.find(@@ -31,25 +34,29 @@ const getLibraryMetas = (namespace?: string) => {export const canvasComponentLibraries = [{components: {},+ componentIds,metas: coreMetas,templates: coreTemplates,},{- components: { ...baseComponents, ...baseCanvasComponents },+ components: baseComponentLibrary.components,+ componentIds,metas: getLibraryMetas(),hooks: baseHooks,templates: baseTemplates,},{namespace: radixComponentNamespace,- components: radixComponents,+ components: radixComponentLibrary.components,+ componentIds,metas: getLibraryMetas(radixComponentNamespace),hooks: radixHooks,templates: radixTemplates,},{namespace: animationComponentNamespace,- components: animationComponents,+ components: animationComponentLibrary.components,+ componentIds,metas: getLibraryMetas(animationComponentNamespace),hooks: animationHooks,templates: animationTemplates,diff --git a/packages/sdk-components-registry/src/components.test.ts b/packages/sdk-components-registry/src/components.test.tsnew file mode 100644index 0000000000..25dc421733--- /dev/null+++ b/packages/sdk-components-registry/src/components.test.ts@@ -0,0 +1,27 @@+/** Verifies that registered component objects keep their persisted identities. */+import { expect, test } from "vitest";+import {+ CodeText,+ Label as BaseLabel,+} from "@webstudio-is/sdk-components-react/components";+import { canvasComponents } from "@webstudio-is/sdk-components-react/canvas-components";+import { Label as RadixLabel } from "@webstudio-is/sdk-components-react-radix";+import { VideoAnimation as PublicVideoAnimation } from "@webstudio-is/sdk-components-animation/components";+import { componentIds, componentsById } from "./components";++test("distinguishes component exports with the same display name", () => {+ expect(componentIds.get(BaseLabel)).toBe("Label");+ expect(componentIds.get(CodeText)).toBe("CodeText");+ expect(componentIds.get(canvasComponents.CodeText)).toBe("CodeText");+ expect(componentsById.get("CodeText")).toBe(canvasComponents.CodeText);+ expect(componentIds.get(RadixLabel)).toBe(+ "@webstudio-is/sdk-components-react-radix:Label"+ );+ expect(componentsById.get("Label")).toBe(BaseLabel);+ expect(componentIds.get(PublicVideoAnimation)).toBe(+ "@webstudio-is/sdk-components-animation:VideoAnimation"+ );+ expect(+ componentsById.get("@webstudio-is/sdk-components-react-radix:Label")+ ).toBe(RadixLabel);+});diff --git a/packages/sdk-components-registry/src/components.ts b/packages/sdk-components-registry/src/components.tsnew file mode 100644index 0000000000..d0fe0429d3--- /dev/null+++ b/packages/sdk-components-registry/src/components.ts@@ -0,0 +1,88 @@+/** Owns registered React component objects and their persisted identities. */+import type { Instance } from "@webstudio-is/sdk";+import * as baseComponents from "@webstudio-is/sdk-components-react/components";+import { canvasComponents as baseCanvasComponents } from "@webstudio-is/sdk-components-react/canvas-components";+import * as animationComponents from "@webstudio-is/sdk-components-animation";+import * as publicAnimationComponents from "@webstudio-is/sdk-components-animation/components";+import * as radixComponents from "@webstudio-is/sdk-components-react-radix";+import {+ animationComponentNamespace,+ getComponentName,+ radixComponentNamespace,+} from "./shared";++export const baseComponentLibrary = {+ components: { ...baseComponents, ...baseCanvasComponents },+};++export const radixComponentLibrary = {+ namespace: radixComponentNamespace,+ components: radixComponents,+};++export const animationComponentLibrary = {+ namespace: animationComponentNamespace,+ components: animationComponents,+};++export const componentLibraries = [+ baseComponentLibrary,+ radixComponentLibrary,+ animationComponentLibrary,+] as const;++const mutableComponentIds = new Map<object, Instance["component"]>();+const mutableComponentsById = new Map<Instance["component"], object>();++for (const library of componentLibraries) {+ for (const [exportName, component] of Object.entries(library.components)) {+ const namespace = "namespace" in library ? library.namespace : undefined;+ const componentId = getComponentName({ namespace }, exportName);+ if (mutableComponentsById.has(componentId)) {+ throw new Error(+ `Component ID "${componentId}" is registered more than once`+ );+ }+ mutableComponentsById.set(componentId, component);+ }+}++// A persisted ID can have a runtime and a canvas implementation. Both objects+// must render to the same ID, while componentsById exposes the canvas version.+const componentImplementationLibraries = [+ { components: baseComponents },+ { components: baseCanvasComponents },+ radixComponentLibrary,+ animationComponentLibrary,+ {+ namespace: animationComponentNamespace,+ components: publicAnimationComponents,+ },+] as const;++for (const library of componentImplementationLibraries) {+ for (const [exportName, component] of Object.entries(library.components)) {+ const namespace = "namespace" in library ? library.namespace : undefined;+ const componentId = getComponentName({ namespace }, exportName);+ if (mutableComponentsById.has(componentId) === false) {+ throw new Error(+ `Component implementation "${componentId}" has no registered component`+ );+ }+ const existingComponentId = mutableComponentIds.get(component);+ if (+ existingComponentId !== undefined &&+ existingComponentId !== componentId+ ) {+ throw new Error(+ `Component object is registered as both "${existingComponentId}" and "${componentId}"`+ );+ }+ mutableComponentIds.set(component, componentId);+ }+}++export const componentIds: ReadonlyMap<object, Instance["component"]> =+ mutableComponentIds;+export const componentsById: ReadonlyMap<Instance["component"], object> =+ mutableComponentsById;diff --git a/packages/sdk-components-registry/src/core-templates.test.tsx b/packages/sdk-components-registry/src/core-templates.test.tsxnew file mode 100644index 0000000000..6b31cd2456--- /dev/null+++ b/packages/sdk-components-registry/src/core-templates.test.tsx@@ -0,0 +1,118 @@+/** Verifies the registry-owned templates that require real components. */+import { expect, test } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ contentBlockMdxTemplateDescriptors,+ getContentBlockMdxTemplateDescriptor,+ getDefaultContentBlockTemplateName,+} from "@webstudio-is/sdk";+import { renderTemplate, type TemplateMeta } from "@webstudio-is/template";+import { componentIds } from "./components";+import { coreTemplates } from "./core-templates";++const renderCoreTemplate = (template: TemplateMeta | undefined) => {+ if (template === undefined) {+ throw new Error("Expected core template");+ }+ return renderTemplate(template.template, undefined, [], { componentIds });+};++const expectCodeTextDefaultsToStayImplicit = (+ template: TemplateMeta | undefined+) => {+ const fragment = renderCoreTemplate(template);+ const codeText = fragment.instances.find(+ ({ component }) => component === "CodeText"+ );+ expect(codeText?.children).toEqual([+ { type: "text", value: 'const status = "ready";' },+ ]);+ expect(+ fragment.props.filter(({ instanceId }) => instanceId === codeText?.id)+ ).toEqual([]);+};++test("keeps Code Text defaults out of standalone and Content Block props", () => {+ expectCodeTextDefaultsToStayImplicit(coreTemplates.code_text);+ expectCodeTextDefaultsToStayImplicit(coreTemplates[blockComponent]);+});++test("keeps the Content Block Image template free of local styles", () => {+ const fragment = renderCoreTemplate(coreTemplates[blockComponent]);+ const image = fragment.instances.find(+ ({ component }) => component === "Image"+ );+ if (image === undefined) {+ throw new Error("Expected Image template");+ }+ expect(+ fragment.styleSourceSelections.filter(+ ({ instanceId }) => instanceId === image.id+ )+ ).toEqual([]);+});++test("generates ordered semantic defaults from their descriptors", () => {+ const fragment = renderCoreTemplate(coreTemplates[blockComponent]);+ const instances = new Map(+ fragment.instances.map((instance) => [instance.id, instance])+ );+ const templates = fragment.instances.find(+ ({ component }) => component === blockTemplateComponent+ );+ if (templates === undefined) {+ throw new Error("Expected Templates container");+ }+ const defaults = templates.children.map((child, index) => {+ if (child.type !== "id") {+ throw new Error("Expected template instance child");+ }+ const instance = instances.get(child.value);+ if (instance === undefined) {+ throw new Error("Expected template instance");+ }+ const descriptor = getContentBlockMdxTemplateDescriptor(instance);+ return descriptor === undefined+ ? {+ type: "custom" as const,+ index,+ component: instance.component,+ label: instance.label,+ name: instance.name,+ }+ : {+ type: "semantic" as const,+ resolutionKey: descriptor.resolutionKey,+ label: instance.label,+ name: instance.name,+ };+ });+ const expectedSemanticDefaults = contentBlockMdxTemplateDescriptors.map(+ (descriptor) => ({+ type: "semantic" as const,+ resolutionKey: descriptor.resolutionKey,+ label: descriptor.label,+ name: getDefaultContentBlockTemplateName(+ descriptor.kind === "element"+ ? { component: "ws:element", tag: descriptor.tag }+ : { component: descriptor.component }+ ),+ })+ );++ expect(defaults.filter(({ type }) => type === "semantic")).toEqual(+ expectedSemanticDefaults+ );+ expect(defaults.filter(({ type }) => type === "custom")).toEqual([+ {+ type: "custom",+ index: contentBlockMdxTemplateDescriptors.findIndex(+ ({ resolutionKey }) => resolutionKey === "component:CodeText"+ ),+ component: "HtmlEmbed",+ label: undefined,+ name: "HtmlEmbed",+ },+ ]);+});diff --git a/packages/sdk-components-registry/src/core-templates.tsx b/packages/sdk-components-registry/src/core-templates.tsxnew file mode 100644index 0000000000..60350b29ff--- /dev/null+++ b/packages/sdk-components-registry/src/core-templates.tsx@@ -0,0 +1,202 @@+/** @jsxImportSource @webstudio-is/template */+/** Assembles core templates that depend on registered React components. */+import { createElement, type ElementType } from "react";+import { Webstudio1cIcon } from "@webstudio-is/icons/svg";+import {+ blockComponent,+ contentBlockDocumentProp,+ contentBlockMdxTemplateDescriptors,+ elementComponent,+ getDefaultContentBlockTemplateName,+ type ContentBlockMdxTemplateDescriptor,+} from "@webstudio-is/sdk";+import { intrinsicCoreTemplates } from "@webstudio-is/sdk/core-templates";+import {+ css,+ Parameter,+ setInstanceMeta,+ setTemplateMeta,+ type TemplateMeta,+ ws,+} from "@webstudio-is/template";+import {+ CodeText,+ HtmlEmbed,+} from "@webstudio-is/sdk-components-react/components";+import { componentsById } from "./components";++const BlockTemplate = ws.blockTemplate;+const BlockBody = ws.contentBlockBody;+const blockDocument = new Parameter(contentBlockDocumentProp);++const listItemMdxTemplateDescriptor = contentBlockMdxTemplateDescriptors.find(+ ({ resolutionKey }) => resolutionKey === "element:li"+);+if (listItemMdxTemplateDescriptor?.kind !== "element") {+ throw new Error("Expected the Content Block list item template descriptor");+}++const createContentBlockMdxTemplate = (+ descriptor: ContentBlockMdxTemplateDescriptor+) => {+ if (descriptor.kind === "element") {+ const name = getDefaultContentBlockTemplateName({+ component: elementComponent,+ tag: descriptor.tag,+ });+ if (descriptor.tag === "ul" || descriptor.tag === "ol") {+ return setTemplateMeta(+ { name, label: descriptor.label },+ createElement(+ descriptor.tag,+ { key: descriptor.resolutionKey },+ createElement(listItemMdxTemplateDescriptor.tag)+ )+ );+ }+ return setTemplateMeta(+ { name, label: descriptor.label },+ createElement(descriptor.tag, { key: descriptor.resolutionKey })+ );+ }++ const component = componentsById.get(descriptor.component);+ if (component === undefined) {+ throw new Error(+ `Content Block component template "${descriptor.component}" is not registered`+ );+ }+ return setTemplateMeta(+ {+ name: getDefaultContentBlockTemplateName({+ component: descriptor.component,+ }),+ label: descriptor.label,+ },+ createElement(+ component as ElementType,+ { key: descriptor.resolutionKey },+ descriptor.component === "CodeText"+ ? 'const status = "ready";'+ : undefined+ )+ );+};++const contentBlockDefaultTemplates = contentBlockMdxTemplateDescriptors.flatMap(+ (descriptor) => [+ ...(descriptor.resolutionKey === "component:CodeText"+ ? [+ setTemplateMeta(+ { name: "HtmlEmbed" },+ <HtmlEmbed key="custom:HtmlEmbed" />+ ),+ ]+ : []),+ createContentBlockMdxTemplate(descriptor),+ ]+);++const blockMeta: TemplateMeta = {+ category: "general",+ template: (+ <ws.block document={blockDocument}>+ {setInstanceMeta(+ { 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>+ </ws.block>+ ),+};++const builtWithWebstudioMeta: TemplateMeta = {+ category: "other",+ description:+ "A “Built with Webstudio” badge should be added to every project page on the free plan. This helps Webstudio spread awareness as a platform.",+ icon: Webstudio1cIcon,+ template: setInstanceMeta(+ { label: "Built with Webstudio" },+ <a+ href="https://webstudio.is/?via=badge"+ target="_blank"+ ws:style={css`+ display: inline-flex;+ gap: 6px;+ align-items: center;+ justify-content: center;+ position: fixed;+ z-index: 1000;+ padding: 6px 10px;+ right: 16px;+ bottom: 16px;+ color: rgba(251, 252, 253, 1);+ font-family: system-ui, sans-serif;+ font-size: 12px;+ font-weight: 500;+ line-height: 1;+ border: 1px solid transparent;+ border-radius: 9px;+ text-decoration-line: none;+ text-wrap-mode: nowrap;+ background-clip: padding-box, border-box;+ background-origin: padding-box, border-box;+ background-image:+ linear-gradient(135deg, #4a4efa 0%, #bd2fdb 66%, #ec59ce 100%),+ linear-gradient(+ 135deg,+ #92fddc 0%,+ #7d7ffb 31.94%,+ #ed72fe 64.24%,+ #fdd791 100%+ );+ `}+ >+ {setInstanceMeta(+ { label: "Logo" },+ <HtmlEmbed+ code={Webstudio1cIcon}+ ws:style={css`+ display: block;+ width: 16px;+ height: 16px;+ flex-shrink: 0;+ `}+ />+ )}+ {setInstanceMeta({ label: "Text" }, <div>Built with Webstudio</div>)}+ </a>+ ),+};++export const coreTemplates = {+ ...intrinsicCoreTemplates,+ [blockComponent]: blockMeta,+ code_text: {+ category: "typography",+ template: <CodeText>{'const status = "ready";'}</CodeText>,+ },+ builtWithWebstudio: builtWithWebstudioMeta,+} satisfies Record<string, TemplateMeta>;diff --git a/packages/sdk-components-registry/src/shared.ts b/packages/sdk-components-registry/src/shared.tsindex 389e29fe30..fb4cb5d1c5 100644--- a/packages/sdk-components-registry/src/shared.ts+++ b/packages/sdk-components-registry/src/shared.ts@@ -34,7 +34,7 @@ export const componentMetaLibraries: readonly ComponentMetaLibrary[] = [];export const getComponentName = (- library: ComponentMetaLibrary,+ library: Pick<ComponentMetaLibrary, "namespace">,exportName: string) =>library.namespace === undefineddiff --git a/packages/sdk-components-registry/vitest.config.ts b/packages/sdk-components-registry/vitest.config.tsnew file mode 100644index 0000000000..b92393c119--- /dev/null+++ b/packages/sdk-components-registry/vitest.config.ts@@ -0,0 +1,24 @@+/** Matches Builder component resolution when private implementations exist. */+import { existsSync } from "node:fs";+import path from "node:path";+import { defineConfig } from "vitest/config";++const rootDir = ["..", "../..", "../../.."]+ .map((directory) => path.join(import.meta.dirname, directory))+ .find((directory) => existsSync(path.join(directory, ".git")));++const hasPrivateComponents = existsSync(+ path.join(+ rootDir ?? "",+ "packages/sdk-components-animation/private-src/components.ts"+ )+);++const conditions = hasPrivateComponents+ ? ["webstudio-private", "webstudio"]+ : ["webstudio"];++export default defineConfig({+ resolve: { conditions },+ ssr: { resolve: { conditions } },+});diff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex faab48ca9d..97ce841611 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -44,9 +44,7 @@"import": "./lib/__generated__/normalize.css.js"},"./core-templates": {- "webstudio": "./src/core-templates.tsx",- "types": "./lib/types/core-templates.d.ts",- "import": "./lib/core-templates.js"+ "webstudio": "./src/core-templates.tsx"},"./router-path-test-data": {"webstudio": "./src/router-path-test-data.ts"@@ -65,7 +63,7 @@"test": "vitest run","build:schema-org-data": "tsx scripts/schema-org-data.ts && oxfmt src/__generated__/schema-org-data.ts","build:normalize.css": "tsx --conditions=webstudio ./scripts/normalize.css.ts && oxfmt src/__generated__/normalize.css.ts",- "build": "rm -rf lib && esbuild src/index.ts src/runtime.ts src/asset-resource-limits.ts src/schema-org.ts src/link-utils.ts src/schema.ts src/__generated__/normalize.css.ts src/core-templates.tsx --outdir=lib --bundle --format=esm --packages=external",+ "build": "rm -rf lib && esbuild src/index.ts src/runtime.ts src/asset-resource-limits.ts src/schema-org.ts src/link-utils.ts src/schema.ts src/__generated__/normalize.css.ts --outdir=lib --bundle --format=esm --packages=external","dts": "tsc --project tsconfig.dts.json"},"dependencies": {diff --git a/packages/sdk/src/content-block.test.ts b/packages/sdk/src/content-block.test.tsindex f4733fa62a..893e66c750 100644--- a/packages/sdk/src/content-block.test.ts+++ b/packages/sdk/src/content-block.test.ts@@ -15,7 +15,10 @@ import {getWritableContentBlockDocumentBinding,findWritableContentBlockDocumentBindings,getContentBlockSourceIntegrityIssues,+ getDefaultContentBlockTemplateName,+ getContentBlockMdxTemplateDescriptor,isEqualContentBlockSource,+ isContentBlockMdxTemplateInsertable,parseContentBlockSourceProp,} from "./content-block";import { encodeDataSourceVariable } from "./expression";@@ -67,6 +70,53 @@ const mdxAsset: FileAsset = {createdAt: "2026-08-14T00:00:00.000Z",};+describe("Content Block MDX template semantics", () => {+ test("derives identity from the component or intrinsic tag, never its label", () => {+ expect(+ getDefaultContentBlockTemplateName({ component: "Heading", tag: "h1" })+ ).toBe("Heading");+ expect(+ getDefaultContentBlockTemplateName({+ component: "ws:element",+ tag: "h1",+ })+ ).toBe("H1");+ expect(+ getDefaultContentBlockTemplateName({ component: "radix:Checkbox" }, [+ "Checkbox",+ "radix:Checkbox",+ ])+ ).toBe("RadixCheckbox");+ });++ test("matches element semantics by rendered tag across component types", () => {+ expect(+ getContentBlockMdxTemplateDescriptor({+ component: "Heading",+ tag: "h2",+ })+ ).toEqual({+ kind: "element",+ resolutionKey: "element:h2",+ label: "Heading 2",+ tag: "h2",+ insertable: true,+ });+ });++ test("keeps custom templates insertable while hiding structural semantics", () => {+ expect(+ isContentBlockMdxTemplateInsertable({+ component: "Element",+ tag: "td",+ })+ ).toBe(false);+ expect(+ isContentBlockMdxTemplateInsertable({ component: "CustomCard" })+ ).toBe(true);+ });+});+describe("Content Block source", () => {test("finds every Templates container without hiding invalid duplicates", () => {const first: Instance = {@@ -356,123 +406,26 @@ describe("Content Block source", () => {describe("allocateUniqueContentBlockTemplateName", () => {test.each([- {- name: "Card",- existingNames: [],- expected: "Card",- reason: "keeps an unused name",- },- {- name: " Card ",- existingNames: [],- expected: "Card",- reason: "trims an unused name",- },- {- name: "Card",- existingNames: ["Card"],- expected: "Card 2",- reason: "adds the first suffix",- },- {- name: "Card",- existingNames: ["Card", "Card 2"],- expected: "Card 3",- reason: "skips a consecutive collision",- },- {- name: "Card",- existingNames: ["Card", "Card 3"],- expected: "Card 2",- reason: "fills the first available suffix",- },- {- name: "Card 2",- existingNames: ["Card 2"],- expected: "Card 3",- reason: "increments an existing suffix",- },- {- name: "Card 2",- existingNames: ["Card 2", "Card 3", "Card 5"],- expected: "Card 4",- reason: "fills a gap after an existing suffix",- },- {- name: "Card 20",- existingNames: ["Card 20"],- expected: "Card 21",- reason: "increments a multi-digit suffix",- },- {- name: "Card 1",- existingNames: ["Card 1"],- expected: "Card 1 2",- reason: "treats one as part of the base name",- },- {- name: "Card 0",- existingNames: ["Card 0"],- expected: "Card 0 2",- reason: "treats zero as part of the base name",- },- {- name: "Card -2",- existingNames: ["Card -2"],- expected: "Card -2 2",- reason: "does not interpret a negative suffix",- },- {- name: "Card 2.5",- existingNames: ["Card 2.5"],- expected: "Card 2.5 2",- reason: "does not interpret a decimal suffix",- },- {- name: "Card 9007199254740992",- existingNames: ["Card 9007199254740992"],- expected: "Card 9007199254740992 2",- reason: "does not increment an unsafe integer suffix",- },- {- name: "Card 9007199254740991",- existingNames: ["Card 9007199254740991"],- expected: "Card 9007199254740991 2",- reason: "does not increment past the safe integer range",- },- {- name: "Card 9007199254740990",- existingNames: ["Card 9007199254740990", "Card 9007199254740991"],- expected: "Card 9007199254740991 2",- reason: "falls back after colliding at the safe integer boundary",- },- {- name: "Card 02",- existingNames: ["Card 02"],- expected: "Card 3",- reason: "normalizes an incremented numeric suffix",- },- {- name: "card",- existingNames: ["Card"],- expected: "card",- reason: "matches names case-sensitively",- },- {- name: "Héro 🦸",- existingNames: ["Héro 🦸"],- expected: "Héro 🦸 2",- reason: "preserves Unicode names",- },- ])("$reason", ({ name, existingNames, expected }) => {- const names = new Set(existingNames);+ ["Card", [], "Card"],+ ["promotion card", [], "PromotionCard"],+ ["Card", ["Card"], "Card2"],+ ["Card", ["Card", "Card2"], "Card3"],+ ["Card", ["Card", "Card3"], "Card2"],+ ["Card2", ["Card2", "Card3"], "Card4"],+ ["Héro 🦸", [], "Hero"],+ ["", [], "Template"],+ ])(+ "allocates the canonical identifier %s",+ (name, existingNames, expected) => {+ const names = new Set(existingNames);- expect(- allocateUniqueContentBlockTemplateName({- name,- existingNames: names,- })- ).toBe(expected);- expect(names).toEqual(new Set(existingNames));- });+ expect(+ allocateUniqueContentBlockTemplateName({+ name,+ existingNames: names,+ })+ ).toBe(expected);+ expect(names).toEqual(new Set(existingNames));+ }+ );});diff --git a/packages/sdk/src/content-block.ts b/packages/sdk/src/content-block.tsindex de3f361081..1c055b061f 100644--- a/packages/sdk/src/content-block.ts+++ b/packages/sdk/src/content-block.ts@@ -21,6 +21,184 @@ import type { ExpressionChild, Instance, Instances } from "./schema/instances";import type { ExpressionBinding } from "./schema/expression";import type { Prop, Props } from "./schema/props";import { decodeDataSourceVariable } from "./expression";+import { pascalCase } from "change-case";+import { getComponentJsxName } from "./instances-utils";++const toContentBlockTemplateIdentifier = (value: string) =>+ pascalCase(value.normalize("NFKD").replaceAll(/\p{M}/gu, "")).replaceAll(+ "_",+ ""+ ) || "Template";++export type ContentBlockMdxTemplateDescriptor =+ | Readonly<{+ kind: "element";+ resolutionKey: `element:${string}`;+ label: string;+ tag: string;+ insertable: boolean;+ }>+ | Readonly<{+ kind: "component";+ resolutionKey: `component:${string}`;+ label: string;+ component: string;+ insertable: boolean;+ }>;++const defineMdxElementTemplate = <const Tag extends string>(+ tag: Tag,+ label: string,+ insertable: boolean+) =>+ ({+ kind: "element",+ resolutionKey: `element:${tag}`,+ label,+ tag,+ insertable,+ }) as const;++const defineMdxComponentTemplate = <const Component extends string>(+ component: Component,+ label: string,+ insertable: boolean+) =>+ ({+ kind: "component",+ resolutionKey: `component:${component}`,+ label,+ component,+ insertable,+ }) as const;++/**+ * Defines every MDX semantic that can resolve through a default Content Block+ * template, in its default display order. Structural and inline-only semantics+ * remain available for styling without being offered as standalone slash-menu+ * insertions.+ */+export const contentBlockMdxTemplateDescriptors = [+ defineMdxElementTemplate("p", "Paragraph", true),+ defineMdxElementTemplate("h1", "Heading 1", true),+ defineMdxElementTemplate("h2", "Heading 2", true),+ defineMdxElementTemplate("h3", "Heading 3", true),+ defineMdxElementTemplate("h4", "Heading 4", true),+ defineMdxElementTemplate("h5", "Heading 5", true),+ defineMdxElementTemplate("h6", "Heading 6", true),+ defineMdxElementTemplate("ul", "Unordered List", true),+ defineMdxElementTemplate("ol", "Ordered List", true),+ defineMdxElementTemplate("li", "List Item", false),+ defineMdxElementTemplate("a", "Link", true),+ defineMdxComponentTemplate("Image", "Image", true),+ defineMdxElementTemplate("hr", "Separator", true),+ defineMdxElementTemplate("br", "Line Break", false),+ defineMdxElementTemplate("blockquote", "Blockquote", true),+ defineMdxElementTemplate("em", "Emphasis", false),+ defineMdxElementTemplate("strong", "Strong", false),+ defineMdxElementTemplate("del", "Strikethrough", false),+ defineMdxElementTemplate("code", "Inline Code", false),+ defineMdxElementTemplate("input", "Task Checkbox", false),+ defineMdxElementTemplate("table", "Table", true),+ defineMdxElementTemplate("thead", "Table Head", false),+ defineMdxElementTemplate("tbody", "Table Body", false),+ defineMdxElementTemplate("tr", "Table Row", false),+ defineMdxElementTemplate("th", "Table Header", false),+ defineMdxElementTemplate("td", "Table Cell", false),+ defineMdxComponentTemplate("CodeText", "Code Block", true),+] as const satisfies readonly ContentBlockMdxTemplateDescriptor[];++export type ContentBlockMdxTemplateResolutionKey =+ (typeof contentBlockMdxTemplateDescriptors)[number]["resolutionKey"];++export const getContentBlockMdxTemplateDescriptor = (instance: {+ component: string;+ tag?: string;+}): ContentBlockMdxTemplateDescriptor | undefined =>+ contentBlockMdxTemplateDescriptors.find((descriptor) => {+ if (descriptor.kind === "component") {+ return descriptor.component === instance.component;+ }+ return descriptor.tag === instance.tag;+ });++/** Unknown, author-defined templates stay insertable. */+export const isContentBlockMdxTemplateInsertable = (instance: {+ component: string;+ tag?: string;+}) => getContentBlockMdxTemplateDescriptor(instance)?.insertable ?? true;++/**+ * Derives the canonical MDX identifier for a template that does not have a+ * persisted name yet. Display labels never participate in this identity.+ */+export const getDefaultContentBlockTemplateName = (+ instance: Pick<Instance, "component" | "tag">,+ components?: Iterable<Instance["component"]>+) => {+ if (instance.component === "ws:element") {+ return toContentBlockTemplateIdentifier(instance.tag ?? "Element");+ }+ const componentName =+ components === undefined+ ? (instance.component.split(":").at(-1) ?? "Component")+ : getComponentJsxName({ component: instance.component, components });+ return toContentBlockTemplateIdentifier(componentName);+};++/**+ * Returns the stable MDX identifier for a direct Content Block template.+ * The label fallback reads projects created before template names existed and+ * can be removed after their authored MDX has been migrated.+ */+export const getContentBlockTemplateName = (+ instance: Pick<Instance, "component" | "label" | "name" | "tag">+) =>+ instance.name ??+ instance.label ??+ getDefaultContentBlockTemplateName(instance);++/** Assigns stable, unique MDX names to templates newly placed in a container. */+export const assignUniqueBlockTemplateNamesMutable = ({+ instanceIds,+ parent,+ replacedInstanceIds = [],+ instances,+ components,+}: {+ instanceIds: readonly Instance["id"][];+ parent: Instance;+ replacedInstanceIds?: readonly Instance["id"][];+ instances: Instances;+ components?: Iterable<Instance["component"]>;+}) => {+ if (parent.component !== blockTemplateComponent) {+ return;+ }+ const ignoredIds = new Set([...instanceIds, ...replacedInstanceIds]);+ const existingNames = new Set<string>();+ for (const child of parent.children) {+ const instance =+ child.type === "id" ? instances.get(child.value) : undefined;+ if (instance !== undefined && ignoredIds.has(instance.id) === false) {+ existingNames.add(getContentBlockTemplateName(instance));+ }+ }+ for (const instanceId of instanceIds) {+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ continue;+ }+ const uniqueName = allocateUniqueContentBlockTemplateName({+ name:+ instance.name ??+ getDefaultContentBlockTemplateName(instance, components),+ existingNames,+ });+ instance.name = uniqueName;+ existingNames.add(uniqueName);+ }+};export const createContentBlockExternalContentIdentity = ({blockInstanceId,@@ -529,12 +707,12 @@ export const allocateUniqueContentBlockTemplateName = ({name: string;existingNames: ReadonlySet<string>;}) => {- const normalizedName = name.trim();+ const normalizedName = toContentBlockTemplateIdentifier(name);if (existingNames.has(normalizedName) === false) {return normalizedName;}- const suffixMatch = /^(.*) (\d+)$/.exec(normalizedName);+ const suffixMatch = /^(.*?)(\d+)$/.exec(normalizedName);let baseName = normalizedName;let index = 2;if (suffixMatch !== null) {@@ -544,7 +722,7 @@ export const allocateUniqueContentBlockTemplateName = ({index = suffix + 1;}}- let candidate = `${baseName} ${index}`;+ let candidate = `${baseName}${index}`;while (existingNames.has(candidate)) {if (Number.isSafeInteger(index + 1) === false) {baseName = candidate;@@ -552,7 +730,7 @@ export const allocateUniqueContentBlockTemplateName = ({} else {index += 1;}- candidate = `${baseName} ${index}`;+ candidate = `${baseName}${index}`;}return candidate;};diff --git a/packages/sdk/src/core-templates.test.tsx b/packages/sdk/src/core-templates.test.tsxindex d754cabd2a..cbd13e39ef 100644--- a/packages/sdk/src/core-templates.test.tsx+++ b/packages/sdk/src/core-templates.test.tsx@@ -1,52 +1,42 @@import { expect, test } from "vitest";import { renderTemplate, type TemplateMeta } from "@webstudio-is/template";-import { blockComponent } from "./core-metas";-import { coreTemplates } from "./core-templates";+import { contentBlockMdxTemplateDescriptors } from "./content-block";+import { intrinsicCoreTemplates } from "./core-templates";-const expectCodeTextDefaultsToStayImplicit = (- template: TemplateMeta | undefined-) => {- if (template === undefined) {- throw new Error("Expected Code Text template");- }- const fragment = renderTemplate(template.template);- const codeText = fragment.instances.find(- ({ component }) => component === "CodeText"- );- expect(codeText?.children).toEqual([- { type: "text", value: 'const status = "ready";' },- ]);+test("marks structural-only MDX semantics as unavailable in insertion menus", () => {expect(- fragment.props.filter(({ instanceId }) => instanceId === codeText?.id)- ).toEqual([]);-};--test("keeps standalone Code Text defaults out of instance props", () => {- expectCodeTextDefaultsToStayImplicit(- (coreTemplates as Record<string, TemplateMeta>).code_text- );-});--test("keeps Content Block Code Text defaults out of template props", () => {- expectCodeTextDefaultsToStayImplicit(coreTemplates[blockComponent]);+ contentBlockMdxTemplateDescriptors+ .filter(({ insertable }) => insertable === false)+ .map(({ resolutionKey }) => resolutionKey)+ ).toEqual([+ "element:li",+ "element:br",+ "element:em",+ "element:strong",+ "element:del",+ "element:code",+ "element:input",+ "element:thead",+ "element:tbody",+ "element:tr",+ "element:th",+ "element:td",+ ]);});-test("keeps the Content Block Image template representable as Markdown", () => {- const template = coreTemplates[blockComponent];+test.each([+ ["input_label", undefined],+ ["radio", "Radio Field"],+ ["checkbox", "Checkbox Field"],+] as const)("keeps the %s root label", (templateName, expectedLabel) => {+ const template = (intrinsicCoreTemplates as Record<string, TemplateMeta>)[+ templateName+ ];if (template === undefined) {- throw new Error("Expected Content Block template");+ throw new Error(`Expected ${templateName} template`);}+const fragment = renderTemplate(template.template);- const image = fragment.instances.find(- ({ component }) => component === "Image"- );- if (image === undefined) {- throw new Error("Expected Image template");- }- expect(- fragment.styleSourceSelections.filter(- ({ instanceId }) => instanceId === image.id- )- ).toEqual([]);+ expect(fragment.instances[0]?.label).toBe(expectedLabel);});diff --git a/packages/sdk/src/core-templates.tsx b/packages/sdk/src/core-templates.tsxindex 0c113151ef..d26eae68d7 100644--- a/packages/sdk/src/core-templates.tsx+++ b/packages/sdk/src/core-templates.tsx@@ -1,32 +1,28 @@+/** Defines templates made only from intrinsic HTML and compiler primitives. */import {- $,css,expression,+ setInstanceMeta,Parameter,PlaceholderValue,ws,type TemplateMeta,} from "@webstudio-is/template";+import { CheckboxCheckedIcon, RadioCheckedIcon } from "@webstudio-is/icons/svg";+import type { ReactNode } from "react";import {- CheckboxCheckedIcon,- RadioCheckedIcon,- Webstudio1cIcon,-} from "@webstudio-is/icons/svg";-import {- blockComponent,collectionComponent,collectionDescription,descendantComponent,elementComponent,} from "./core-metas";-import { contentBlockDocumentProp } from "./schema/content-block";const elementMeta: TemplateMeta = {category: "general",order: 1,description:"An HTML element is a core building block for web pages, structuring and displaying content like text, images, and links.",- template: <ws.element></ws.element>,+ template: <div />,};const linkMeta: TemplateMeta = {@@ -35,12 +31,11 @@ const linkMeta: TemplateMeta = {"Use a link to send your users to another page, section, or resource. Configure links in the Settings panel.",order: 2,template: (- <ws.element- ws:tag="a"+ <aws:style={css`display: inline-block;`}- ></ws.element>+ />),};@@ -57,9 +52,9 @@ const collectionMeta: TemplateMeta = {item={collectionItem}itemKey={collectionItemKey}>- <ws.element ws:tag="div">- <ws.element ws:tag="div">{expression`${collectionItem}`}</ws.element>- </ws.element>+ <div>+ <div>{expression`${collectionItem}` as unknown as ReactNode}</div>+ </div></ws.collection>),};@@ -69,81 +64,18 @@ const descendantMeta: TemplateMeta = {template: <ws.descendant selector=" p" />,};-const BlockTemplate = ws["block-template"];-const BlockBody = ws["content-block-body"];-const blockDocument = new Parameter(contentBlockDocumentProp);--const blockMeta: TemplateMeta = {- category: "general",- template: (- <ws.block document={blockDocument}>- <BlockTemplate ws:label="Templates">- <ws.element ws:label="Paragraph" ws:tag="p"></ws.element>- <ws.element ws:label="Heading 1" ws:tag="h1"></ws.element>- <ws.element ws:label="Heading 2" ws:tag="h2"></ws.element>- <ws.element ws:label="Heading 3" ws:tag="h3"></ws.element>- <ws.element ws:label="Heading 4" ws:tag="h4"></ws.element>- <ws.element ws:label="Heading 5" ws:tag="h5"></ws.element>- <ws.element ws:label="Heading 6" ws:tag="h6"></ws.element>- <ws.element ws:label="Unordered List" ws:tag="ul">- <ws.element ws:label="List Item" ws:tag="li"></ws.element>- </ws.element>- <ws.element ws:label="Ordered List" ws:tag="ol">- <ws.element ws:label="List Item" ws:tag="li"></ws.element>- </ws.element>- <ws.element ws:label="Link" ws:tag="a"></ws.element>- <$.Image />- <ws.element ws:label="Separator" ws:tag="hr" />- <ws.element ws:label="Blockquote" ws:tag="blockquote"></ws.element>- <$.HtmlEmbed />- <$.CodeText>{'const status = "ready";'}</$.CodeText>- </BlockTemplate>- <BlockBody>- <ws.element ws:label="Paragraph" ws:tag="p">- The Content Block component designates regions on the page where- pre-styled instances can be inserted in{" "}- <ws.element- ws:label="Link"- ws:tag="a"- href="https://wstd.us/content-block"- >- Content mode- </ws.element>- .- </ws.element>- <ws.element ws:label="Unordered List" ws:tag="ul">- <ws.element ws:label="List Item" ws:tag="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.- </ws.element>- <ws.element ws:label="List Item" ws:tag="li">- To predefine instances for insertion in Content mode, switch to- Design mode and add them to the Templates container.- </ws.element>- <ws.element ws:label="List Item" ws:tag="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.- </ws.element>- </ws.element>- </BlockBody>- </ws.block>- ),-};-const typography: Record<string, TemplateMeta> = {heading: {category: "typography",description:"Use HTML headings to structure and organize content. Use the Tag property in settings to change the heading level (h1-h6).",- template: <ws.element ws:tag="h1"></ws.element>,+ template: <h1 />,},paragraph: {category: "typography",description: "A container for multi-line text.",- template: <ws.element ws:tag="p"></ws.element>,+ template: <p />,},blockquote: {@@ -151,15 +83,14 @@ const typography: Record<string, TemplateMeta> = {description:"Use to style a quote from an external source like an article or book.",template: (- <ws.element- ws:tag="blockquote"+ <blockquotews:style={css`margin-left: 0;margin-right: 0;padding: 10px 20px;border-left: 5px solid rgb(226 226 226 / 1);`}- ></ws.element>+ />),},@@ -167,23 +98,18 @@ const typography: Record<string, TemplateMeta> = {category: "typography",description: "Groups content, like links in a menu or steps in a recipe.",template: (- <ws.element ws:tag="ul">- <ws.element ws:tag="li"></ws.element>- <ws.element ws:tag="li"></ws.element>- <ws.element ws:tag="li"></ws.element>- </ws.element>+ <ul>+ <li />+ <li />+ <li />+ </ul>),},list_item: {category: "typography",description: "Adds a new item to an existing list.",- template: <ws.element ws:tag="li"></ws.element>,- },-- code_text: {- category: "typography",- template: <$.CodeText>{'const status = "ready";'}</$.CodeText>,+ template: <li />,},thematic_break: {@@ -191,13 +117,12 @@ const typography: Record<string, TemplateMeta> = {description:"Used to visually divide sections of content, helping to improve readability and organization within a webpage.",template: (- <ws.element- ws:tag="hr"+ <hrws:style={css`color: gray;border-style: none none solid;`}- ></ws.element>+ />),},};@@ -207,17 +132,16 @@ const forms: Record<string, TemplateMeta> = {category: "forms",description: "Create filters, surveys, searches and more.",template: (- <ws.element ws:tag="form">- <ws.element- ws:tag="input"+ <form>+ <inputws:style={css`display: block;`}/>- <ws.element ws:tag="button">- {new PlaceholderValue("Submit")}- </ws.element>- </ws.element>+ <button>+ {new PlaceholderValue("Submit") as unknown as ReactNode}+ </button>+ </form>),},@@ -226,21 +150,20 @@ const forms: Record<string, TemplateMeta> = {description:"Use a button to submit forms or trigger actions within a page. Do not use a button to navigate users to another resource or another page - that’s what a link is used for.",template: (- <ws.element ws:tag="button">{new PlaceholderValue("Button")}</ws.element>+ <button>{new PlaceholderValue("Button") as unknown as ReactNode}</button>),},input_label: {category: "forms",template: (- <ws.element- ws:tag="label"+ <labelws:style={css`display: block;`}>- {new PlaceholderValue("Label")}- </ws.element>+ {new PlaceholderValue("Label") as unknown as ReactNode}+ </label>),},@@ -249,8 +172,7 @@ const forms: Record<string, TemplateMeta> = {description:"A single-line text input for collecting string data from your users.",template: (- <ws.element- ws:tag="input"+ <inputws:style={css`display: block;`}@@ -263,8 +185,7 @@ const forms: Record<string, TemplateMeta> = {description:"A multi-line text input for collecting longer string data from your users.",template: (- <ws.element- ws:tag="textarea"+ <textareaws:style={css`display: block;`}@@ -277,17 +198,16 @@ const forms: Record<string, TemplateMeta> = {description:"A drop-down menu for users to select a single option from a predefined list.",template: (- <ws.element- ws:tag="select"+ <selectws:style={css`display: block;`}>- <ws.element ws:tag="option" label="Please choose an option" value="" />- <ws.element ws:tag="option" label="Option A" value="a" />- <ws.element ws:tag="option" label="Option B" value="b" />- <ws.element ws:tag="option" label="Option C" value="c" />- </ws.element>+ <option label="Please choose an option" value="" />+ <option label="Option A" value="a" />+ <option label="Option B" value="b" />+ <option label="Option C" value="c" />+ </select>),},@@ -296,26 +216,25 @@ const forms: Record<string, TemplateMeta> = {description:"Use within a form to allow your users to select a single option from a set of mutually exclusive choices. Group multiple radios by matching their “Name” properties.",icon: RadioCheckedIcon,- template: (- <ws.element- ws:tag="label"- ws:label="Radio Field"+ template: setInstanceMeta(+ { label: "Radio Field" },+ <labelws:style={css`display: block;`}>- <ws.element- ws:tag="input"+ <inputws:style={css`border-style: none;margin-right: 0.5em;`}type="radio"/>- <ws.element ws:tag="span" ws:label="Radio Label">- {new PlaceholderValue("Radio")}- </ws.element>- </ws.element>+ {setInstanceMeta(+ { label: "Radio Label" },+ <span>{new PlaceholderValue("Radio") as unknown as ReactNode}</span>+ )}+ </label>),},@@ -324,98 +243,36 @@ const forms: Record<string, TemplateMeta> = {description:"Use within a form to allow your users to toggle between checked and not checked. Group checkboxes by matching their “Name” properties. Unlike radios, any number of checkboxes in a group can be checked.",icon: CheckboxCheckedIcon,- template: (- <ws.element- ws:tag="label"- ws:label="Checkbox Field"+ template: setInstanceMeta(+ { label: "Checkbox Field" },+ <labelws:style={css`display: block;`}>- <ws.element- ws:tag="input"+ <inputws:style={css`border-style: none;margin-right: 0.5em;`}type="checkbox"/>- <ws.element ws:tag="span" ws:label="Checkbox Label">- {new PlaceholderValue("Checkbox")}- </ws.element>- </ws.element>+ {setInstanceMeta(+ { label: "Checkbox Label" },+ <span>+ {new PlaceholderValue("Checkbox") as unknown as ReactNode}+ </span>+ )}+ </label>),},};-const builtWithWebstudioMeta: TemplateMeta = {- category: "other",- description:- "A “Built with Webstudio” badge should be added to every project page on the free plan. This helps Webstudio spread awareness as a platform.",- icon: Webstudio1cIcon,- template: (- <ws.element- ws:tag="a"- ws:label="Built with Webstudio"- // If you change this, you need to also update this link in publish checks- href="https://webstudio.is/?via=badge"- target="_blank"- ws:style={css`- display: inline-flex;- gap: 6px;- align-items: center;- justify-content: center;- position: fixed;- z-index: 1000;- padding: 6px 10px;- right: 16px;- bottom: 16px;- color: rgba(251, 252, 253, 1);- font-family: system-ui, sans-serif;- font-size: 12px;- font-weight: 500;- line-height: 1;- border: 1px solid transparent;- border-radius: 9px;- text-decoration-line: none;- text-wrap-mode: nowrap;- background-clip: padding-box, border-box;- background-origin: padding-box, border-box;- background-image:- linear-gradient(135deg, #4a4efa 0%, #bd2fdb 66%, #ec59ce 100%),- linear-gradient(- 135deg,- #92fddc 0%,- #7d7ffb 31.94%,- #ed72fe 64.24%,- #fdd791 100%- );- `}- >- <$.HtmlEmbed- ws:label="Logo"- code={Webstudio1cIcon}- ws:style={css`- display: block;- width: 16px;- height: 16px;- flex-shrink: 0;- `}- ></$.HtmlEmbed>- <ws.element ws:tag="div" ws:label="Text">- Built with Webstudio- </ws.element>- </ws.element>- ),-};--export const coreTemplates = {+export const intrinsicCoreTemplates = {[elementComponent]: elementMeta,link: linkMeta,[collectionComponent]: collectionMeta,[descendantComponent]: descendantMeta,- [blockComponent]: blockMeta,...typography,...forms,- builtWithWebstudio: builtWithWebstudioMeta,};diff --git a/packages/sdk/src/css.test.tsx b/packages/sdk/src/css.test.tsxindex 6e228846c5..ad64707055 100644--- a/packages/sdk/src/css.test.tsx+++ b/packages/sdk/src/css.test.tsx@@ -1,10 +1,19 @@import { expect, test } from "vitest";-import { $, ws, css, renderData, createProxy } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ ws,+ css,+ renderData,+} from "@webstudio-is/template";import { generateCss, type CssConfig } from "./css";import type { Breakpoint } from "./schema/breakpoints";import type { Asset } from "./schema/assets";import { rootComponent } from "./core-metas";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const ListItem = createTemplateComponentFixture("ListItem");+const toMap = <T extends { id: string }>(list: T[]) =>new Map(list.map((item) => [item.id, item] as const));@@ -43,7 +52,7 @@ test("generates distinct upright and italic variable font faces", () => {variableFontAsset("italic"),]);const { cssText } = generateCss({- ...renderData(<$.Body />),+ ...renderData(<Body />),assets,atomic: false,componentMetas: new Map(),@@ -61,7 +70,7 @@ test("generates distinct upright and italic variable font faces", () => {test("generate css for one instance with two tokens", () => {const { cssText, atomicCssText, atomicClasses } = generateAllCss({- ...renderData(<$.Box ws:id="box"></$.Box>),+ ...renderData(<Box ws:id="box"></Box>),breakpoints: toMap<Breakpoint>([{ id: "base", label: "" }]),styleSourceSelections: new Map([["box", { instanceId: "box", values: ["token", "local"] }],@@ -118,7 +127,7 @@ Map {test("generate descendant selector", () => {const { cssText, atomicCssText, atomicClasses } = generateAllCss({...renderData(- <$.Body+ <Bodyws:id="body"ws:style={css`color: blue;@@ -137,7 +146,7 @@ test("generate descendant selector", () => {}`}/>- </$.Body>+ </Body>),componentMetas: new Map(),assetBaseUrl: "",@@ -191,9 +200,9 @@ Map {test("generate component presets with multiple tags", () => {const { cssText, atomicCssText, classes, atomicClasses } = generateAllCss({...renderData(- <$.ListItem tag="div">- <$.ListItem tag="a"></$.ListItem>- </$.ListItem>+ <ListItem tag="div">+ <ListItem tag="a"></ListItem>+ </ListItem>),assets: new Map(),breakpoints: new Map(),@@ -239,15 +248,19 @@ test("generate component presets with multiple tags", () => {});test("deduplicate component presets for similarly named components", () => {- const radix = createProxy("@webstudio/radix:");- const aria = createProxy("@webstudio/aria:");+ const RadixListItem = createTemplateComponentFixture(+ "@webstudio/radix:ListItem"+ );+ const AriaListItem = createTemplateComponentFixture(+ "@webstudio/aria:ListItem"+ );const { cssText, atomicCssText, classes, atomicClasses } = generateAllCss({...renderData(- <$.ListItem>- <radix.ListItem>- <aria.ListItem></aria.ListItem>- </radix.ListItem>- </$.ListItem>+ <ListItem>+ <RadixListItem>+ <AriaListItem></AriaListItem>+ </RadixListItem>+ </ListItem>),assets: new Map(),breakpoints: new Map(),@@ -315,19 +328,19 @@ test("deduplicate component presets for similarly named components", () => {test("expose preset classes to instances", () => {const { atomicCssText, classes, atomicClasses } = generateAllCss({...renderData(- <$.Body+ <Bodyws:id="body"ws:style={css`color: blue;`}>- <$.Box+ <Boxws:id="box"ws:style={css`color: red;`}- ></$.Box>- </$.Body>+ ></Box>+ </Body>),componentMetas: new Map([[@@ -400,20 +413,20 @@ Map {test("generate classes with instance and meta label", () => {const { cssText, classes } = generateAllCss({...renderData(- <$.Body+ <Bodyws:id="body"ws:style={css`color: blue;`}>- <$.Box+ <Boxws:id="box"ws:label="box%instance#label"ws:style={css`color: red;`}- ></$.Box>- </$.Body>+ ></Box>+ </Body>),componentMetas: new Map([[@@ -476,9 +489,9 @@ Map {test("generate :root preset and user styles", () => {const { cssText, atomicCssText, classes, atomicClasses } = generateAllCss({...renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>),breakpoints: toMap([{ id: "base", label: "" }]),styleSourceSelections: new Map([@@ -552,14 +565,14 @@ test("generate :root preset and user styles", () => {test("generate presets only for used tags", () => {const { cssText, classes } = generateCss({...renderData(- <$.Body ws:id="body">+ <Body ws:id="body">{/* first tag in preset */}- <$.Box></$.Box>+ <Box></Box>{/* legacy tag property */}- <$.Box tag="span"></$.Box>+ <Box tag="span"></Box>{/* modern ws:tag property */}- <$.Box ws:tag="article"></$.Box>- </$.Body>+ <Box ws:tag="article"></Box>+ </Body>),atomic: false,breakpoints: toMap([{ id: "base", label: "" }]),diff --git a/packages/sdk/src/instances-utils.test.tsx b/packages/sdk/src/instances-utils.test.tsxindex 0038598ee9..d0d66bedb6 100644--- a/packages/sdk/src/instances-utils.test.tsx+++ b/packages/sdk/src/instances-utils.test.tsx@@ -1,5 +1,9 @@import { expect, test } from "vitest";-import { $, renderData, ws } from "@webstudio-is/template";+import {+ createTemplateComponentFixture,+ renderData,+ ws,+} from "@webstudio-is/template";import {findChildReferenceIndex,findTreeInstanceIds,@@ -7,6 +11,8 @@ import {findTreeInstanceIdsExcludingSubtrees,findTreeInstanceIdsExcludingSlotDescendants,findParentInstanceReference,+ getComponentByJsxName,+ getComponentJsxName,getHtmlTagsFromProps,getHtmlTagFromInstance,getIndexesWithinAncestors,@@ -17,27 +23,79 @@ import type { WsComponentMeta } from "./schema/component-meta";import type { Instance } from "./schema/instances";import type { Prop, Props } from "./schema/props";+const Body = createTemplateComponentFixture("Body");+const Box = createTemplateComponentFixture("Box");+const Slot = createTemplateComponentFixture("Slot");+const Tabs = createTemplateComponentFixture("Tabs");+const TabsContent = createTemplateComponentFixture("TabsContent");+const TabsList = createTemplateComponentFixture("TabsList");+const TabsTrigger = createTemplateComponentFixture("TabsTrigger");+const XmlNode = createTemplateComponentFixture("XmlNode");++test("resolves component JSX names and prefixes namespaced collisions", () => {+ const components = [+ "Heading",+ "@webstudio-is/radix:Button",+ "@webstudio-is/base:Button",+ ];++ expect(getComponentByJsxName({ name: "Heading", components })).toBe(+ "Heading"+ );+ expect(getComponentByJsxName({ name: "Button", components })).toBe(undefined);+ expect(getComponentByJsxName({ name: "RadixButton", components })).toBe(+ "@webstudio-is/radix:Button"+ );+ expect(+ getComponentJsxName({+ component: "@webstudio-is/radix:Button",+ components,+ })+ ).toBe("RadixButton");+});++test("keeps the base component unprefixed when it collides", () => {+ const components = ["Button", "@webstudio-is/radix:Button"];+ expect(getComponentByJsxName({ name: "Button", components })).toBe("Button");+ expect(getComponentByJsxName({ name: "RadixButton", components })).toBe(+ "@webstudio-is/radix:Button"+ );+});++test("keeps direct JSX names unique across arbitrary component libraries", () => {+ const components = ["@acme/one:Button", "@acme/two:Button"];+ expect(+ getComponentJsxName({ component: "@acme/one:Button", components })+ ).toBe("AcmeOneButton");+ expect(+ getComponentJsxName({ component: "@acme/two:Button", components })+ ).toBe("AcmeTwoButton");+ expect(getComponentByJsxName({ name: "AcmeTwoButton", components })).toBe(+ "@acme/two:Button"+ );+});+test("find all tree instances", () => {const { instances } = renderData(- <$.Body ws:id="1">- <$.Box ws:id="2"></$.Box>- <$.Box ws:id="3">- <$.Box ws:id="4"></$.Box>- <$.Box ws:id="5"></$.Box>- </$.Box>- </$.Body>+ <Body ws:id="1">+ <Box ws:id="2"></Box>+ <Box ws:id="3">+ <Box ws:id="4"></Box>+ <Box ws:id="5"></Box>+ </Box>+ </Body>);expect(findTreeInstanceIds(instances, "3")).toEqual(new Set(["3", "4", "5"]));});test("find tree instances excluding complete subtrees", () => {const { instances } = renderData(- <$.Body ws:id="root">- <$.Box ws:id="hidden">- <$.Box ws:id="hidden-child"></$.Box>- </$.Box>- <$.Box ws:id="visible"></$.Box>- </$.Body>+ <Body ws:id="root">+ <Box ws:id="hidden">+ <Box ws:id="hidden-child"></Box>+ </Box>+ <Box ws:id="visible"></Box>+ </Body>);expect(@@ -47,16 +105,16 @@ test("find tree instances excluding complete subtrees", () => {test("find all tree instances excluding slot descendants", () => {const { instances } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box1">- <$.Slot ws:id="slot">- <$.Box ws:id="slotbox1"></$.Box>- <$.Box ws:id="slotbox2"></$.Box>- </$.Slot>- <$.Box ws:id="box2"></$.Box>- </$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box1">+ <Slot ws:id="slot">+ <Box ws:id="slotbox1"></Box>+ <Box ws:id="slotbox2"></Box>+ </Slot>+ <Box ws:id="box2"></Box>+ </Box>+ <Box ws:id="box3"></Box>+ </Body>);expect(findTreeInstanceIdsExcludingSlotDescendants(instances, "box1")@@ -112,7 +170,7 @@ test("finds rendered tree instances without traversing block templates", () => {});test("include not existing/virtual instance", () => {- const { instances } = renderData(<$.Body ws:id="1"></$.Body>);+ const { instances } = renderData(<Body ws:id="1"></Body>);expect(findTreeInstanceIds(instances, ":root")).toEqual(new Set([":root"]));expect(findTreeInstanceIdsExcludingSlotDescendants(instances, ":root")@@ -198,12 +256,12 @@ test("get html tag from instance", () => {["XmlNode", { presetStyle: { div: [] } }],]);const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="meta"></$.Box>- <$.Box ws:id="prop" ws:tag="article"></$.Box>- <$.Box ws:id="instance" ws:tag="nav"></$.Box>- <$.XmlNode ws:id="xml" tag="svg"></$.XmlNode>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="meta"></Box>+ <Box ws:id="prop" ws:tag="article"></Box>+ <Box ws:id="instance" ws:tag="nav"></Box>+ <XmlNode ws:id="xml" tag="svg"></XmlNode>+ </Body>);expect(@@ -213,6 +271,29 @@ test("get html tag from instance", () => {props,})).toEqual("section");+ props.set("dynamic-tag", {+ id: "dynamic-tag",+ instanceId: "meta",+ name: "tag",+ type: "expression",+ value: '"aside"',+ mode: "read",+ });+ expect(+ getHtmlTagFromInstance({+ instance: instances.get("meta") as Instance,+ metas,+ props,+ })+ ).toBeUndefined();+ expect(+ getHtmlTagFromInstance({+ instance: instances.get("meta") as Instance,+ metas,+ props,+ htmlTagsByInstanceId: getHtmlTagsFromProps(props),+ })+ ).toBeUndefined();expect(getHtmlTagFromInstance({instance: instances.get("prop") as Instance,@@ -240,11 +321,141 @@ test("get html tag from instance", () => {).toBeUndefined();});+test("gets the rendered tag of the deprecated List component", () => {+ const instance: Instance = {+ type: "instance",+ id: "list",+ component: "List",+ children: [],+ };+ const metas = new Map<Instance["component"], WsComponentMeta>([+ [+ "List",+ {+ presetStyle: { ol: [], ul: [] },+ props: {+ ordered: {+ type: "boolean",+ control: "boolean",+ required: false,+ },+ },+ renderedTag: {+ prop: "ordered",+ values: { true: "ol", false: "ul" },+ default: "ul",+ },+ },+ ],+ ]);+ const props = new Map<string, Prop>();++ expect(getHtmlTagFromInstance({ instance, metas, props })).toBe("ul");++ props.set("ordered", {+ id: "ordered",+ instanceId: instance.id,+ name: "ordered",+ type: "boolean",+ value: false,+ });+ expect(getHtmlTagFromInstance({ instance, metas, props })).toBe("ul");++ props.set("ordered", {+ id: "ordered",+ instanceId: instance.id,+ name: "ordered",+ type: "boolean",+ value: true,+ });+ expect(getHtmlTagFromInstance({ instance, metas, props })).toBe("ol");++ props.set("ordered", {+ id: "ordered",+ instanceId: instance.id,+ name: "ordered",+ type: "expression",+ value: "true",+ });+ expect(getHtmlTagFromInstance({ instance, metas, props })).toBeUndefined();++ props.set("ordered", {+ id: "ordered",+ instanceId: instance.id,+ name: "ordered",+ type: "string",+ value: "false",+ });+ expect(getHtmlTagFromInstance({ instance, metas, props })).toBeUndefined();++ props.set("ordered", {+ id: "ordered",+ instanceId: instance.id,+ name: "ordered",+ type: "boolean",+ value: true,+ });+ props.set("ordered-duplicate", {+ id: "ordered-duplicate",+ instanceId: instance.id,+ name: "ordered",+ type: "boolean",+ value: false,+ });+ expect(getHtmlTagFromInstance({ instance, metas, props })).toBeUndefined();+});++test("does not choose between duplicate tag props", () => {+ const instance: Instance = {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ };+ const metas = new Map<Instance["component"], WsComponentMeta>([+ ["Box", { presetStyle: { section: [] } }],+ ]);+ const props = new Map<string, Prop>([+ [+ "first-tag",+ {+ id: "first-tag",+ instanceId: instance.id,+ name: "tag",+ type: "string",+ value: "article",+ },+ ],+ [+ "second-tag",+ {+ id: "second-tag",+ instanceId: instance.id,+ name: "tag",+ type: "string",+ value: "aside",+ },+ ],+ ]);++ expect(getHtmlTagFromInstance({ instance, metas, props })).toBeUndefined();+ const htmlTagsByInstanceId = getHtmlTagsFromProps(props);+ expect(htmlTagsByInstanceId).toEqual(new Map([[instance.id, "aside"]]));+ expect(+ getHtmlTagFromInstance({+ instance,+ metas,+ props,+ htmlTagsByInstanceId,+ })+ ).toBeUndefined();+});+test("gets html tags from props", () => {const { props } = renderData(- <$.Body ws:id="body">- <$.XmlNode ws:id="xml" tag="svg"></$.XmlNode>- </$.Body>+ <Body ws:id="body">+ <XmlNode ws:id="xml" tag="svg"></XmlNode>+ </Body>);props.set("tag-prop", {id: "tag-prop",@@ -253,6 +464,14 @@ test("gets html tags from props", () => {type: "string",value: "article",});+ props.set("dynamic-tag-prop", {+ id: "dynamic-tag-prop",+ instanceId: "dynamic-box",+ name: "tag",+ type: "expression",+ value: '"aside"',+ mode: "read",+ });expect(getHtmlTagsFromProps(props)).toEqual(new Map([@@ -267,9 +486,9 @@ test("get html tag from instance reads mutable props maps", () => {["Box", { presetStyle: { section: [] } }],]);const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:id="box"></Box>+ </Body>);const instance = instances.get("box") as Instance;props.set("tag-prop", {@@ -345,25 +564,25 @@ test("get html tag from instance skips props when provided tag map has no tag",test("get indexes within ancestors", () => {const { instances } = renderData(- <$.Body ws:id="body0">- <$.Tabs ws:id="tabs1">- <$.TabsList ws:id="tabs1list">- <$.Box>- <$.TabsTrigger ws:id="tabs1trigger1"></$.TabsTrigger>- <$.TabsTrigger ws:id="tabs1trigger2"></$.TabsTrigger>- </$.Box>- </$.TabsList>- <$.TabsContent ws:id="tabs1content1"></$.TabsContent>- <$.TabsContent ws:id="tabs1content2">- <$.Tabs ws:id="tabs2">- <$.TabsList ws:id="tabs2list">- <$.TabsTrigger ws:id="tabs2trigger1"></$.TabsTrigger>- </$.TabsList>- <$.TabsContent ws:id="tabs2content1"></$.TabsContent>- </$.Tabs>- </$.TabsContent>- </$.Tabs>- </$.Body>+ <Body ws:id="body0">+ <Tabs ws:id="tabs1">+ <TabsList ws:id="tabs1list">+ <Box>+ <TabsTrigger ws:id="tabs1trigger1"></TabsTrigger>+ <TabsTrigger ws:id="tabs1trigger2"></TabsTrigger>+ </Box>+ </TabsList>+ <TabsContent ws:id="tabs1content1"></TabsContent>+ <TabsContent ws:id="tabs1content2">+ <Tabs ws:id="tabs2">+ <TabsList ws:id="tabs2list">+ <TabsTrigger ws:id="tabs2trigger1"></TabsTrigger>+ </TabsList>+ <TabsContent ws:id="tabs2content1"></TabsContent>+ </Tabs>+ </TabsContent>+ </Tabs>+ </Body>);const metas = new Map<Instance["component"], WsComponentMeta>([["TabsList", { indexWithinAncestor: "Tabs" }],@@ -386,17 +605,17 @@ test("get indexes within ancestors", () => {});test("ignore ws:block-template when compute indexes within ancestors", () => {- const BlockTemplate = ws["block-template"];+ const BlockTemplate = ws.blockTemplate;const { instances } = renderData(- <$.Body ws:id="body0">- <$.Tabs>+ <Body ws:id="body0">+ <Tabs><BlockTemplate>- <$.TabsTrigger ws:id="trigger1"></$.TabsTrigger>+ <TabsTrigger ws:id="trigger1"></TabsTrigger></BlockTemplate>- <$.TabsTrigger ws:id="trigger2"></$.TabsTrigger>- <$.TabsTrigger ws:id="trigger3"></$.TabsTrigger>- </$.Tabs>- </$.Body>+ <TabsTrigger ws:id="trigger2"></TabsTrigger>+ <TabsTrigger ws:id="trigger3"></TabsTrigger>+ </Tabs>+ </Body>);const metas = new Map<Instance["component"], WsComponentMeta>([["TabsTrigger", { indexWithinAncestor: "Tabs" }],diff --git a/packages/sdk/src/instances-utils.ts b/packages/sdk/src/instances-utils.tsindex 653de8b2ad..cc86194c2c 100644--- a/packages/sdk/src/instances-utils.ts+++ b/packages/sdk/src/instances-utils.ts@@ -1,7 +1,8 @@import type { WsComponentMeta } from "./schema/component-meta";import type { Instance, Instances } from "./schema/instances";-import type { Props } from "./schema/props";+import type { Prop } from "./schema/props";import { blockTemplateComponent, elementComponent } from "./core-metas";+import { pascalCase } from "change-case";export const ROOT_INSTANCE_ID = ":root";@@ -117,6 +118,78 @@ export const parseComponentName = (componentName: string) => {return [namespace, name] as const;};+const getPreferredComponentNamespaceJsxPrefix = (namespace: string) => {+ if (namespace.includes("radix")) {+ return "Radix";+ }+ if (namespace.includes("animation")) {+ return "Animation";+ }+ return "Library";+};++const getQualifiedComponentNamespaceJsxPrefix = (namespace: string) =>+ pascalCase(namespace.replaceAll("/", "-"));++/** Returns the stable public JSX identifier for a registered component. */+export const getComponentJsxName = ({+ component,+ components,+}: {+ component: Instance["component"];+ components: Iterable<Instance["component"]>;+}) => {+ const [namespace, exportName] = parseComponentName(component);+ const matches = Array.from(components).filter(+ (candidate) => parseComponentName(candidate)[1] === exportName+ );+ if (matches.length === 1 || namespace === undefined) {+ return exportName;+ }+ const preferredPrefix = getPreferredComponentNamespaceJsxPrefix(namespace);+ const preferredPrefixMatches = matches.filter((candidate) => {+ const [candidateNamespace] = parseComponentName(candidate);+ return (+ candidateNamespace !== undefined &&+ getPreferredComponentNamespaceJsxPrefix(candidateNamespace) ===+ preferredPrefix+ );+ });+ const prefix =+ preferredPrefixMatches.length === 1+ ? preferredPrefix+ : getQualifiedComponentNamespaceJsxPrefix(namespace);+ return `${prefix}${exportName}`;+};++/** Resolves direct and collision-prefixed public JSX component identifiers. */+export const getComponentByJsxName = ({+ name,+ components,+}: {+ name: string;+ components: Iterable<Instance["component"]>;+}) => {+ const candidates = Array.from(components);+ const exact = candidates.filter(+ (component) => parseComponentName(component)[1] === name+ );+ if (exact.length === 1) {+ return exact[0];+ }+ const core = exact.filter(+ (component) => parseComponentName(component)[0] === undefined+ );+ if (core.length === 1) {+ return core[0];+ }+ const aliases = candidates.filter(+ (component) =>+ getComponentJsxName({ component, components: candidates }) === name+ );+ return aliases.length === 1 ? aliases[0] : undefined;+};+/*** Returns the instance name shown to users. The component or tag supplies the* default name; instance.label is the user-defined name created by renaming.@@ -143,16 +216,55 @@ export const getInstanceName = ({);};-export const getHtmlTagsFromProps = (props: Props) => {+const unresolvedHtmlTagIdsByIndex = new WeakMap<+ ReadonlyMap<Instance["id"], string>,+ ReadonlySet<Instance["id"]>+>();++export const getHtmlTagsFromProps = (props: ReadonlyMap<Prop["id"], Prop>) => {const tags = new Map<Instance["id"], string>();+ const unresolvedIds = new Set<Instance["id"]>();for (const prop of props.values()) {- if (prop.type === "string" && prop.name === "tag") {+ if (prop.name !== "tag") {+ continue;+ }+ if (tags.has(prop.instanceId) || prop.type !== "string") {+ unresolvedIds.add(prop.instanceId);+ }+ // Preserve the public index's existing behavior: it contains only static+ // string values and, for invalid duplicates, the last static value.+ if (prop.type === "string") {tags.set(prop.instanceId, prop.value);}}+ unresolvedHtmlTagIdsByIndex.set(tags, unresolvedIds);return tags;};+const ambiguousProp = Symbol("ambiguous prop");++const findUniqueInstanceProp = ({+ props,+ instanceId,+ name,+}: {+ props: ReadonlyMap<Prop["id"], Prop> | undefined;+ instanceId: Instance["id"];+ name: string;+}): Prop | typeof ambiguousProp | undefined => {+ let result: Prop | undefined;+ for (const prop of props?.values() ?? []) {+ if (prop.instanceId !== instanceId || prop.name !== name) {+ continue;+ }+ if (result !== undefined) {+ return ambiguousProp;+ }+ result = prop;+ }+ return result;+};+export const getHtmlTagFromInstance = ({instance,metas,@@ -160,9 +272,9 @@ export const getHtmlTagFromInstance = ({htmlTagsByInstanceId,}: {instance: Instance;- metas: Map<Instance["component"], WsComponentMeta>;- props?: Props;- htmlTagsByInstanceId?: Map<Instance["id"], string>;+ metas: ReadonlyMap<Instance["component"], WsComponentMeta>;+ props?: ReadonlyMap<Prop["id"], Prop>;+ htmlTagsByInstanceId?: ReadonlyMap<Instance["id"], string>;}) => {// XmlNode's "tag" prop is an XML element name, not an HTML rendering tag.if (instance.component === "XmlNode") {@@ -171,16 +283,46 @@ export const getHtmlTagFromInstance = ({if (instance.tag !== undefined) {return instance.tag;}- const propTag =- htmlTagsByInstanceId === undefined- ? props === undefined- ? undefined- : getHtmlTagsFromProps(props).get(instance.id)- : htmlTagsByInstanceId.get(instance.id);- if (propTag !== undefined) {- return propTag;+ if (htmlTagsByInstanceId !== undefined) {+ const unresolvedIds = unresolvedHtmlTagIdsByIndex.get(htmlTagsByInstanceId);+ if (unresolvedIds?.has(instance.id)) {+ return;+ }+ if (htmlTagsByInstanceId.has(instance.id)) {+ return htmlTagsByInstanceId.get(instance.id);+ }+ } else {+ const tagProp = findUniqueInstanceProp({+ props,+ instanceId: instance.id,+ name: "tag",+ });+ if (tagProp === ambiguousProp || (tagProp && tagProp.type !== "string")) {+ return;+ }+ if (tagProp?.type === "string") {+ return tagProp.value;+ }}const meta = metas.get(instance.component);+ if (meta?.renderedTag !== undefined) {+ const tagProp = findUniqueInstanceProp({+ props,+ instanceId: instance.id,+ name: meta.renderedTag.prop,+ });+ if (tagProp === undefined) {+ return meta.renderedTag.default;+ }+ if (tagProp === ambiguousProp) {+ return;+ }+ const propMeta = meta.props?.[meta.renderedTag.prop];+ if (propMeta === undefined || tagProp.type !== propMeta.type) {+ return;+ }+ return meta.renderedTag.values[String(tagProp.value)];+ }const metaTag = Object.keys(meta?.presetStyle ?? {}).at(0);return metaTag;};diff --git a/packages/sdk/src/resources-generator.test.tsx b/packages/sdk/src/resources-generator.test.tsxindex b196cf6dde..50059e1151 100644--- a/packages/sdk/src/resources-generator.test.tsx+++ b/packages/sdk/src/resources-generator.test.tsx@@ -1,7 +1,7 @@import { expect, test } from "vitest";import {renderData,- $,+ createTemplateComponentFixture,expression,ResourceValue,} from "@webstudio-is/template";@@ -14,6 +14,9 @@ import {} from "./resources-generator";import type { DataSource } from "./schema/data-sources";+const Body = createTemplateComponentFixture("Body");+const Form = createTemplateComponentFixture("Form");+const toMap = <T extends { id: string }>(list: T[]) =>new Map(list.map((item) => [item.id, item] as const));@@ -341,7 +344,7 @@ test("generate global system variable and use in resources loader", () => {rootInstanceId: "bodyId",} as Page,...renderData(- <$.Body ws:id="bodyId" vars={expression`${myResource}`}></$.Body>+ <Body ws:id="bodyId" vars={expression`${myResource}`}></Body>),})).toMatchInlineSnapshot(`@@ -647,7 +650,7 @@ test("skip missing resource referenced by action prop", () => {test("replace form action with resource", () => {const data = renderData(- <$.Form ws:id="formId" action="https://my-url.com"></$.Form>+ <Form ws:id="formId" action="https://my-url.com"></Form>);replaceFormActionsWithResources(data);expect(data.props).toEqual(@@ -675,7 +678,7 @@ test("replace form action with resource", () => {});test("ignore empty form action", () => {- const data = renderData(<$.Form ws:id="formId" action=""></$.Form>);+ const data = renderData(<Form ws:id="formId" action=""></Form>);replaceFormActionsWithResources(data);expect(data.props).toEqual(toMap([diff --git a/packages/sdk/src/schema/component-meta.ts b/packages/sdk/src/schema/component-meta.tsindex 80c65e9b41..b496aebeb7 100644--- a/packages/sdk/src/schema/component-meta.ts+++ b/packages/sdk/src/schema/component-meta.ts@@ -104,6 +104,14 @@ export const wsComponentMeta = z.object({deprecated: z.boolean().optional(),icon: z.string().optional(),presetStyle: z.optional(z.record(z.string(), z.array(presetStyleDecl))),+ /** Selects the rendered HTML tag from a serializable component prop. */+ renderedTag: z+ .object({+ prop: z.string(),+ values: z.record(z.string(), z.string()),+ default: z.string(),+ })+ .optional(),states: z.optional(z.array(componentState)),order: z.number().optional(),// properties and html attributes that will be always visible in properties paneldiff --git a/packages/sdk/src/schema/content-block.test.ts b/packages/sdk/src/schema/content-block.test.tsindex 4a6aee2604..0da8195ddf 100644--- a/packages/sdk/src/schema/content-block.test.ts+++ b/packages/sdk/src/schema/content-block.test.ts@@ -108,6 +108,18 @@ describe("content block diagnostics", () => {code: "unresolved-template",templateName: "Hero Card",});+ expect(+ contentBlockDiagnostic.parse({+ code: "ambiguous-template",+ severity: "warning",+ blockInstanceId: "block",+ semanticKey: "element:h1",+ templateNames: ["Primary Heading", "Alternate Heading"],+ })+ ).toMatchObject({+ code: "ambiguous-template",+ semanticKey: "element:h1",+ });});test("rejects mismatched severities and payloads", () => {diff --git a/packages/sdk/src/schema/content-block.ts b/packages/sdk/src/schema/content-block.tsindex 049351ebc9..93077ce4fe 100644--- a/packages/sdk/src/schema/content-block.ts+++ b/packages/sdk/src/schema/content-block.ts@@ -78,6 +78,13 @@ export const contentBlockDiagnostic = z.discriminatedUnion("code", [severity: z.literal("warning"),templateName: z.string().min(1),}),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("ambiguous-template"),+ severity: z.literal("warning"),+ semanticKey: z.string().min(1),+ templateNames: z.array(z.string().min(1)).min(2),+ }),z.strictObject({...diagnosticContext,code: z.literal("ignored-template-prop"),diff --git a/packages/sdk/src/schema/instances.test.ts b/packages/sdk/src/schema/instances.test.tsindex ef3b3f8802..2e1c70af44 100644--- a/packages/sdk/src/schema/instances.test.ts+++ b/packages/sdk/src/schema/instances.test.ts@@ -52,6 +52,19 @@ test("shares instance field validation with create and filter inputs", () => {expect(instanceFilterInput.safeParse({ tag: "" }).success).toBe(false);});+test("stores a template identifier independently from its display label", () => {+ expect(+ instance.parse({+ type: "instance",+ id: "card",+ component: "Box",+ name: "PromotionCard",+ label: "Promotion Card",+ children: [],+ })+ ).toMatchObject({ name: "PromotionCard", label: "Promotion Card" });+});+test("shares text child value validation", () => {expect(textChild.safeParse({ type: "text", value: "" }).success).toBe(true);});diff --git a/packages/sdk/src/schema/instances.ts b/packages/sdk/src/schema/instances.tsindex a6ade64cb0..0712f3e00e 100644--- a/packages/sdk/src/schema/instances.ts+++ b/packages/sdk/src/schema/instances.ts@@ -22,6 +22,9 @@ export const instanceTag = zexport const instanceAttributes = z.object({component: instanceComponent,tag: instanceTag.optional(),+ // Stable authoring identifier for contexts such as Content Block templates.+ // It is independent from the user-facing instance label.+ name: z.string().min(1).optional(),// The component or tag provides the default instance name. Renaming stores// the user-defined name in label without changing the component identity.label: z.string().optional(),@@ -54,6 +57,7 @@ export const instance = z.object({id: instanceId,component: instanceAttributes.shape.component,tag: instanceAttributes.shape.tag,+ name: instanceAttributes.shape.name,label: instanceAttributes.shape.label,children: z.array(instanceChild),});diff --git a/packages/template/package.json b/packages/template/package.jsonindex a807fd7c1d..7156ff5bdd 100644--- a/packages/template/package.json+++ b/packages/template/package.json@@ -8,7 +8,15 @@"private": true,"type": "module","exports": {- "webstudio": "./src/index.ts"+ ".": {+ "webstudio": "./src/index.ts"+ },+ "./jsx-runtime": {+ "webstudio": "./src/jsx-runtime.ts"+ },+ "./jsx-dev-runtime": {+ "webstudio": "./src/jsx-dev-runtime.ts"+ }},"sideEffects": false,"scripts": {@@ -21,7 +29,6 @@"@webstudio-is/css-engine": "workspace:*","@webstudio-is/react-sdk": "workspace:*","@webstudio-is/sdk": "workspace:*",- "change-case": "^5.4.4","react": "18.3.0-canary-14898b6a9-20240318"},"devDependencies": {diff --git a/packages/template/src/jsx-dev-runtime.ts b/packages/template/src/jsx-dev-runtime.tsnew file mode 100644index 0000000000..6475fe25a9--- /dev/null+++ b/packages/template/src/jsx-dev-runtime.ts@@ -0,0 +1,3 @@+/** Provides the development entry point for template-specific JSX types. */+export { Fragment, jsxDEV } from "react/jsx-dev-runtime";+export type { JSX } from "./jsx-runtime";diff --git a/packages/template/src/jsx-runtime.ts b/packages/template/src/jsx-runtime.tsnew file mode 100644index 0000000000..44dfdfbbca--- /dev/null+++ b/packages/template/src/jsx-runtime.ts@@ -0,0 +1,61 @@+/** Uses React's runtime with JSX types widened only for template definitions. */+export { Fragment, jsx, jsxs } from "react/jsx-runtime";+import type { JSX as ReactJSX, ReactNode } from "react";+import type {+ ActionValue,+ AssetValue,+ PageValue,+ Parameter,+ PlaceholderValue,+ ResourceValue,+ Token,+ Variable,+} from "./jsx";+import type { TemplateStyleDecl } from "./css";++type Expression = ReturnType<typeof import("./jsx").expression>;++type TemplateValue =+ | ActionValue+ | AssetValue+ | Expression+ | PageValue+ | Parameter+ | ResourceValue+ | Variable;++type TemplateChild = ReactNode | Expression | PlaceholderValue;++type TemplateProps<Props> = {+ [Name in keyof Props]?: Name extends "children"+ ? TemplateChild | TemplateChild[]+ : Props[Name] | TemplateValue;+} & {+ "ws:id"?: string;+ "ws:label"?: string;+ "ws:tag"?: string;+ "ws:style"?: TemplateStyleDecl[];+ "ws:tokens"?: Token[];+ "ws:show"?: boolean | Expression;+};++export namespace JSX {+ export type Element = ReactJSX.Element;+ export type ElementType = ReactJSX.ElementType;+ export type ElementClass = ReactJSX.ElementClass;+ export interface ElementAttributesProperty+ extends ReactJSX.ElementAttributesProperty {}+ export interface ElementChildrenAttribute+ extends ReactJSX.ElementChildrenAttribute {}+ export type LibraryManagedAttributes<Component, Props> = TemplateProps<+ ReactJSX.LibraryManagedAttributes<Component, Props>+ >;+ export type IntrinsicAttributes = ReactJSX.IntrinsicAttributes;+ export type IntrinsicClassAttributes<Instance> =+ ReactJSX.IntrinsicClassAttributes<Instance>;+ export type IntrinsicElements = {+ [Name in keyof ReactJSX.IntrinsicElements]: TemplateProps<+ ReactJSX.IntrinsicElements[Name]+ >;+ };+}diff --git a/packages/template/src/jsx.test.tsx b/packages/template/src/jsx.test.tsxindex b0693473f2..faebe0d929 100644--- a/packages/template/src/jsx.test.tsx+++ b/packages/template/src/jsx.test.tsx@@ -1,17 +1,19 @@import { expect, test } from "vitest";+import { createElement } from "react";import { showAttribute } from "@webstudio-is/react-sdk";import type { WsComponentMeta } from "@webstudio-is/sdk";import {- $,ActionValue,AssetValue,- createProxy,expression,PageValue,Parameter,PlaceholderValue,- renderTemplate,+ renderTemplate as renderTemplateWithOptions,+ type RenderTemplateOptions,ResourceValue,+ setInstanceMeta,+ setTemplateMeta,token,Variable,ws,@@ -44,14 +46,45 @@ const viewAnimationAction = {],} as const;-const animation = createProxy("@webstudio-is/sdk-components-animation:");+type TestComponentProps = { children?: unknown } & Record<string, unknown>;+const createTestComponent = () => (_props: TestComponentProps) => undefined;++const Body = createTestComponent();+const Box = createTestComponent();+const Button = createTestComponent();+const Span = createTestComponent();+const Text = createTestComponent();+const AnimateChildren = createTestComponent();++const testComponentIds = new Map([+ [Body, "Body"],+ [Box, "Box"],+ [Button, "Button"],+ [Span, "Span"],+ [Text, "Text"],+ [AnimateChildren, "@webstudio-is/sdk-components-animation:AnimateChildren"],+]);++const renderTemplate = (+ root: Parameters<typeof renderTemplateWithOptions>[0],+ generateId?: () => string,+ initialBreakpoints: Parameters<typeof renderTemplateWithOptions>[2] = [],+ options: RenderTemplateOptions = {}+) =>+ renderTemplateWithOptions(root, generateId, initialBreakpoints, {+ ...options,+ componentIds: new Map([+ ...testComponentIds,+ ...(options.componentIds ?? []),+ ]),+ });test("render jsx into instances with generated id", () => {const { instances } = renderTemplate(- <$.Body>- <$.Box></$.Box>- <$.Box></$.Box>- </$.Body>+ <Body>+ <Box></Box>+ <Box></Box>+ </Body>);expect(instances).toEqual([{@@ -78,11 +111,45 @@ test("render jsx into instances with generated id", () => {]);});+test("uses component object identity instead of displayName", () => {+ const BaseLabel = () => undefined;+ BaseLabel.displayName = "Label";+ const RadixLabel = () => undefined;+ RadixLabel.displayName = "Label";++ const { instances } = renderTemplate(+ <>+ <BaseLabel />+ <RadixLabel />+ </>,+ undefined,+ [],+ {+ componentIds: new Map([+ [BaseLabel, "Label"],+ [RadixLabel, "@webstudio-is/sdk-components-react-radix:Label"],+ ]),+ }+ );++ expect(instances.map(({ component }) => component)).toEqual([+ "Label",+ "@webstudio-is/sdk-components-react-radix:Label",+ ]);+});++test("rejects an unregistered real component even when it has a displayName", () => {+ const Unregistered = () => undefined;+ Unregistered.displayName = "Box";++ expect(() => renderTemplate(<Unregistered />)).toThrow(+ "Invalid JSX component"+ );+});+test("uses component metas to convert animation action props", () => {const { props } = renderTemplate(- <animation.AnimateChildren- action={viewAnimationAction}- ></animation.AnimateChildren>,+ <AnimateChildren action={viewAnimationAction}></AnimateChildren>,undefined,[],{@@ -113,7 +180,7 @@ test("uses component metas to convert animation action props", () => {test("reports invalid animation action props from component metas", () => {expect(() =>renderTemplate(- <animation.AnimateChildren action="fade"></animation.AnimateChildren>,+ <AnimateChildren action="fade"></AnimateChildren>,undefined,[],{@@ -136,11 +203,11 @@ test("reports invalid animation action props from component metas", () => {test("override generated ids with ws:id prop", () => {const { instances } = renderTemplate(- <$.Body ws:id="custom1">- <$.Box ws:id="custom2">- <$.Span ws:id="custom3"></$.Span>- </$.Box>- </$.Body>+ <Body ws:id="custom1">+ <Box ws:id="custom2">+ <Span ws:id="custom3"></Span>+ </Box>+ </Body>);expect(instances).toEqual([{@@ -165,7 +232,7 @@ test("override generated ids with ws:id prop", () => {});test("render text children", () => {- const { instances } = renderTemplate(<$.Body>children</$.Body>);+ const { instances } = renderTemplate(<Body>children</Body>);expect(instances).toEqual([{type: "instance",@@ -176,17 +243,40 @@ test("render text children", () => {]);});+test("normalizes numeric and non-rendering React children", () => {+ const { instances } = renderTemplate(+ <Body>+ {0}+ {false}+ <Box />+ </Body>+ );++ expect(instances).toEqual([+ {+ type: "instance",+ id: "0",+ component: "Body",+ children: [+ { type: "text", value: "0" },+ { type: "id", value: "1" },+ ],+ },+ { type: "instance", id: "1", component: "Box", children: [] },+ ]);+});+test("render template children with top level instance", () => {- const { children } = renderTemplate(<$.Box></$.Box>);+ const { children } = renderTemplate(<Box></Box>);expect(children).toEqual([{ type: "id", value: "0" }]);});test("render template children with multiple instances from fragment", () => {const { children, instances } = renderTemplate(<>- <$.Box></$.Box>- <$.Text></$.Text>- <$.Button></$.Button>+ <Box></Box>+ <Text></Text>+ <Button></Button></>);expect(children).toEqual([@@ -204,28 +294,61 @@ test("render template children with multiple instances from fragment", () => {test("rejects nested react fragments", () => {expect(() =>renderTemplate(- <$.Body>+ <Body><>- <$.Box></$.Box>+ <Box></Box></>- </$.Body>+ </Body>)).toThrow("Do not use React fragment shorthand <>...</> inside Webstudio JSX");});-test("rejects raw html tags", () => {- expect(() => renderTemplate(<div>Hello</div>)).toThrow(- "Do not use raw HTML tag <div> in Webstudio JSX"+test("renders raw HTML tags as intrinsic elements", () => {+ expect(renderTemplate(<div>Hello</div>).instances[0]).toEqual({+ type: "instance",+ id: "0",+ component: "ws:element",+ tag: "div",+ children: [{ type: "text", value: "Hello" }],+ });+});++test("keeps structured instance and template metadata out of JSX props", () => {+ const { instances, props } = renderTemplate(+ setTemplateMeta(+ { name: "PromotionCard", label: "Promotion card" },+ <Box>{setInstanceMeta({ label: "Eyebrow" }, <span>New</span>)}</Box>+ )+ );++ expect(instances).toEqual([+ expect.objectContaining({+ component: "Box",+ name: "PromotionCard",+ label: "Promotion card",+ }),+ expect.objectContaining({+ component: "ws:element",+ tag: "span",+ label: "Eyebrow",+ }),+ ]);+ expect(props).toEqual([]);+});++test("rejects invalid structured template names", () => {+ expect(() => setTemplateMeta({ name: "Promotion Card" }, <Box />)).toThrow(+ "Template name must be a PascalCase JavaScript identifier");});test("render literal props", () => {const { props } = renderTemplate(- <$.Body data-string="string" data-number={0}>- <$.Box data-bool={true} data-json={{ param: "value" }}></$.Box>- </$.Body>+ <Body data-string="string" data-number={0}>+ <Box data-bool={true} data-json={{ param: "value" }}></Box>+ </Body>);expect(props).toEqual([{@@ -260,18 +383,14 @@ test("render literal props", () => {});test("validates json-compatible prop values", () => {- expect(() => renderTemplate(<$.Body data-value={NaN}></$.Body>)).toThrow(+ expect(() => renderTemplate(<Body data-value={NaN}></Body>)).toThrow('Invalid JSX prop "data-value". Do not pass NaN or Infinity. Use a finite number instead.');- expect(() =>- renderTemplate(<$.Body data-value={new Date(0)}></$.Body>)- ).toThrow(+ expect(() => renderTemplate(<Body data-value={new Date(0)}></Body>)).toThrow('Invalid JSX prop "data-value". Do not pass Date objects. Use plain JSON-compatible values instead.');expect(() =>- renderTemplate(- <$.Body data-config={{ values: [1, Symbol("bad")] }}></$.Body>- )+ renderTemplate(<Body data-config={{ values: [1, Symbol("bad")] }}></Body>)).toThrow('Invalid JSX prop "data-config" at "values.1". Do not pass Symbol values. Use a string, finite number, or expression instead.');@@ -279,13 +398,13 @@ test("validates json-compatible prop values", () => {test("render defined props", () => {const { props } = renderTemplate(- <$.Body>- <$.Box+ <Body>+ <Boxdata-asset={new AssetValue("assetId")}data-page={new PageValue("pageId")}data-instance={new PageValue("pageId", "instanceId")}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);expect(props).toEqual([{@@ -314,7 +433,7 @@ test("render defined props", () => {test("render placeholder value", () => {const { instances } = renderTemplate(- <$.Body>{new PlaceholderValue("Placeholder text")}</$.Body>+ <Body>{new PlaceholderValue("Placeholder text")}</Body>);expect(instances).toEqual([{@@ -331,17 +450,17 @@ test("render placeholder value", () => {test("generate local styles", () => {const { breakpoints, styleSources, styleSourceSelections, styles } =renderTemplate(- <$.Body+ <Bodyws:style={css`color: red;`}>- <$.Box+ <Boxws:style={css`font-size: 10px;`}- ></$.Box>- </$.Body>+ ></Box>+ </Body>);expect(breakpoints).toEqual([{ id: "base", label: "" }]);expect(styleSources).toEqual([@@ -370,25 +489,25 @@ test("generate local styles", () => {test("validates local style input", () => {expect(() =>- renderTemplate(<$.Body ws:style={"color: red;" as never}></$.Body>)+ renderTemplate(<Body ws:style={"color: red;" as never}></Body>)).toThrow("ws:style must come from css`...`");- expect(() =>- renderTemplate(<$.Body ws:style={[] as never}></$.Body>)- ).toThrow("ws:style must include at least one valid CSS declaration");- expect(() => renderTemplate(<$.Body ws:style={css``}></$.Body>)).toThrow(+ expect(() => renderTemplate(<Body ws:style={[] as never}></Body>)).toThrow(+ "ws:style must include at least one valid CSS declaration"+ );+ expect(() => renderTemplate(<Body ws:style={css``}></Body>)).toThrow("ws:style must include at least one valid CSS declaration");});test("generates local styles from react style object", () => {const { props, styleSources, styleSourceSelections, styles } = renderTemplate(- <$.Body+ <Bodystyle={{color: "red",padding: 24,opacity: 0.5,}}- ></$.Body>+ ></Body>);expect(props).toEqual([]);expect(styleSources).toEqual([{ id: "0:ws:style", type: "local" }]);@@ -440,26 +559,26 @@ test("generates local styles from react style object", () => {test("validates react style object input", () => {expect(() =>- renderTemplate(<$.Body style={"color: red;" as never}></$.Body>)+ renderTemplate(<Body style={"color: red;" as never}></Body>)).toThrow("style prop must be a plain object");expect(() =>- renderTemplate(<$.Body style={{ padding: Number.NaN }}></$.Body>)+ renderTemplate(<Body style={{ padding: Number.NaN }}></Body>)).toThrow('Invalid style prop "padding"');expect(() =>- renderTemplate(<$.Body style={{ color: false as never }}></$.Body>)+ renderTemplate(<Body style={{ color: false as never }}></Body>)).toThrow('Invalid style prop "color"');});test("generate local styles with states", () => {const { styles } = renderTemplate(- <$.Body+ <Bodyws:style={css`color: red;&:hover {color: blue;}`}- ></$.Body>+ ></Body>);expect(styles).toEqual([{@@ -480,7 +599,7 @@ test("generate local styles with states", () => {test("avoid generating style data without styles", () => {const { breakpoints, styleSources, styleSourceSelections, styles } =- renderTemplate(<$.Body></$.Body>);+ renderTemplate(<Body></Body>);expect(breakpoints).toEqual([]);expect(styleSources).toEqual([]);expect(styleSourceSelections).toEqual([]);@@ -490,7 +609,7 @@ test("avoid generating style data without styles", () => {test("generate token styles", () => {const { breakpoints, styleSources, styleSourceSelections, styles } =renderTemplate(- <$.Body+ <Bodyws:id="body"ws:tokens={[token(@@ -500,7 +619,7 @@ test("generate token styles", () => {`),]}- ></$.Body>+ ></Body>);expect(breakpoints).toEqual([{ id: "base", label: "" }]);expect(styleSources).toEqual([{ id: "0", type: "token", name: "primary" }]);@@ -520,19 +639,19 @@ test("generate token styles", () => {test("validates token helper input", () => {expect(() =>renderTemplate(- <$.Body+ <Bodyws:tokens={[token("primary","color: red;" as unknown as Parameters<typeof token>[1]),]}- ></$.Body>+ ></Body>)).toThrow("token() styles must come from css`...`");expect(() =>renderTemplate(- <$.Body+ <Bodyws:tokens={[token("",@@ -541,35 +660,35 @@ test("validates token helper input", () => {`),]}- ></$.Body>+ ></Body>)).toThrow("token() requires a non-empty string name");expect(() =>renderTemplate(- <$.Body+ <Bodyws:tokens={[token("primary", [] as unknown as Parameters<typeof token>[1]),]}- ></$.Body>+ ></Body>)).toThrow("token() styles must include at least one valid CSS declaration");expect(() =>- renderTemplate(<$.Body ws:tokens={[token("primary", css``)]}></$.Body>)+ renderTemplate(<Body ws:tokens={[token("primary", css``)]}></Body>)).toThrow("token() styles must include at least one valid CSS declaration");});test("validates ws:tokens values", () => {expect(() =>- renderTemplate(<$.Body ws:tokens={"primary" as never}></$.Body>)+ renderTemplate(<Body ws:tokens={"primary" as never}></Body>)).toThrow("ws:tokens must be an array of token(...) values");expect(() =>- renderTemplate(<$.Body ws:tokens={["primary"] as never}></$.Body>)+ renderTemplate(<Body ws:tokens={["primary"] as never}></Body>)).toThrow("ws:tokens must be an array of token(...) values");});test("generate multiple tokens on single instance", () => {const { styleSources, styleSourceSelections, styles } = renderTemplate(- <$.Body+ <Bodyws:id="body"ws:tokens={[token(@@ -585,7 +704,7 @@ test("generate multiple tokens on single instance", () => {`),]}- ></$.Body>+ ></Body>);expect(styleSources).toEqual([{ id: "0", type: "token", name: "primary" },@@ -605,9 +724,9 @@ test("reuse same token across multiple instances", () => {`);const { styleSources, styleSourceSelections, styles } = renderTemplate(- <$.Body ws:id="body" ws:tokens={[primary]}>- <$.Box ws:id="box" ws:tokens={[primary]}></$.Box>- </$.Body>+ <Body ws:id="body" ws:tokens={[primary]}>+ <Box ws:id="box" ws:tokens={[primary]}></Box>+ </Body>);// Token should only be created onceexpect(styleSources).toEqual([{ id: "0", type: "token", name: "primary" }]);@@ -629,7 +748,7 @@ test("reuse same token across multiple instances", () => {test("combine local styles with tokens", () => {const { styleSources, styleSourceSelections, styles } = renderTemplate(- <$.Body+ <Bodyws:id="body"ws:style={css`font-size: 16px;@@ -642,7 +761,7 @@ test("combine local styles with tokens", () => {`),]}- ></$.Body>+ ></Body>);// Both local and token style sourcesexpect(styleSources).toEqual([@@ -658,7 +777,7 @@ test("combine local styles with tokens", () => {test("generate token with breakpoints", () => {const { breakpoints, styles } = renderTemplate(- <$.Body+ <Bodyws:id="body"ws:tokens={[token(@@ -671,7 +790,7 @@ test("generate token with breakpoints", () => {`),]}- ></$.Body>+ ></Body>);expect(breakpoints).toEqual([{ id: "base", label: "" },@@ -695,7 +814,7 @@ test("generate token with breakpoints", () => {test("generate token with state", () => {const { styles } = renderTemplate(- <$.Body+ <Bodyws:id="body"ws:tokens={[token(@@ -708,7 +827,7 @@ test("generate token with state", () => {`),]}- ></$.Body>+ ></Body>);expect(styles).toEqual([{@@ -730,14 +849,14 @@ test("generate token with state", () => {test("generate breakpoints", () => {const { breakpoints, styleSources, styleSourceSelections, styles } =renderTemplate(- <$.Body+ <Bodyws:style={css`color: red;@media (min-width: 1024px) {color: blue;}`}- ></$.Body>+ ></Body>);expect(breakpoints).toEqual([{ id: "base", label: "" },@@ -766,7 +885,7 @@ test("generate breakpoints", () => {test("render variable used in prop expression", () => {const count = new Variable("count", 1);const { props, dataSources } = renderTemplate(- <$.Body ws:id="body" data-count={expression`${count}`}></$.Body>+ <Body ws:id="body" data-count={expression`${count}`}></Body>);expect(props).toEqual([{@@ -792,7 +911,7 @@ test("render variable used in prop expression", () => {test("render variable used in child expression", () => {const count = new Variable("count", 1);const { instances, dataSources } = renderTemplate(- <$.Body ws:id="body">{expression`${count}`}</$.Body>+ <Body ws:id="body">{expression`${count}`}</Body>);expect(instances).toEqual([{@@ -819,10 +938,10 @@ test("compose expression from multiple variables", () => {const count = new Variable("count", 1);const step = new Variable("step", 2);const { props, dataSources } = renderTemplate(- <$.Body+ <Bodyws:id="body"data-count={expression`Count is ${count} + ${step}`}- ></$.Body>+ ></Body>);expect(props).toEqual([{@@ -855,9 +974,9 @@ test("compose expression from multiple variables", () => {test("preserve same variable on multiple instances", () => {const count = new Variable("count", 1);const { props, dataSources } = renderTemplate(- <$.Body ws:id="body" data-count={expression`${count}`}>- <$.Box ws:id="box" data-count={expression`${count}`}></$.Box>- </$.Body>+ <Body ws:id="body" data-count={expression`${count}`}>+ <Box ws:id="box" data-count={expression`${count}`}></Box>+ </Body>);expect(props).toEqual([{@@ -891,11 +1010,11 @@ test("preserve same variable on multiple instances", () => {test("render variable inside of action", () => {const count = new Variable("count", 1);const { props, dataSources } = renderTemplate(- <$.Body+ <Bodyws:id="body"data-count={expression`${count}`}onInc={new ActionValue(["step"], expression`${count} = ${count} + step`)}- ></$.Body>+ ></Body>);expect(props).toEqual([{@@ -934,11 +1053,11 @@ test("render variable inside of action", () => {test("render parameter bound to prop expression", () => {const system = new Parameter("system");const { props, dataSources } = renderTemplate(- <$.Body+ <Bodyws:id="body"data-param={system}data-value={expression`${system}`}- ></$.Body>+ ></Body>);expect(props).toEqual([{@@ -977,7 +1096,7 @@ test("render resource variable", () => {body: expression`${value}`,});const { dataSources, resources } = renderTemplate(- <$.Body ws:id="body">{expression`${myResource}.title`}</$.Body>+ <Body ws:id="body">{expression`${myResource}.title`}</Body>);expect(dataSources).toEqual([{@@ -1018,7 +1137,7 @@ test("render resource prop", () => {body: expression`${value}`,});const { props, dataSources, resources } = renderTemplate(- <$.Body ws:id="body" action={myResource}></$.Body>+ <Body ws:id="body" action={myResource}></Body>);expect(props).toEqual([{@@ -1060,7 +1179,7 @@ test("render resource with control and omitted search params", () => {body: expression`({ query: "query { viewer { id } }" })`,});const { props, resources } = renderTemplate(- <$.Body ws:id="body" action={myResource}></$.Body>+ <Body ws:id="body" action={myResource}></Body>);expect(props).toEqual([{@@ -1086,9 +1205,7 @@ test("render resource with control and omitted search params", () => {});test("render ws:show attribute", () => {- const { props } = renderTemplate(- <$.Body ws:id="body" ws:show={true}></$.Body>- );+ const { props } = renderTemplate(<Body ws:id="body" ws:show={true}></Body>);expect(props).toEqual([{id: "body:data-ws-show",@@ -1102,9 +1219,9 @@ test("render ws:show attribute", () => {test("render ws:tag property", () => {const { instances, props } = renderTemplate(- <$.Body ws:id="body">- <$.Box ws:tag="span"></$.Box>- </$.Body>+ <Body ws:id="body">+ <Box ws:tag="span"></Box>+ </Body>);expect(instances).toEqual([{@@ -1126,7 +1243,7 @@ test("render ws:tag property", () => {test("converts JSX attributes when ws:tag enables HTML attributes", () => {const { props } = renderTemplate(- <$.Box ws:tag="label" tabIndex={0} readOnly={true}></$.Box>+ <Box ws:tag="label" tabIndex={0} readOnly={true}></Box>);expect(props).toEqual([@@ -1148,15 +1265,15 @@ test("converts JSX attributes when ws:tag enables HTML attributes", () => {});test("preserves empty ws:tag for schema validation", () => {- const { instances } = renderTemplate(<$.Box ws:tag=""></$.Box>);+ const { instances } = renderTemplate(<Box ws:tag=""></Box>);expect(instances[0]?.tag).toEqual("");});test("render ws:element with ws:tag prop", () => {const { instances, props } = renderTemplate(- <$.Body ws:id="body">+ <Body ws:id="body"><ws.element ws:tag="span"></ws.element>- </$.Body>+ </Body>);expect(instances).toEqual([{@@ -1176,6 +1293,46 @@ test("render ws:element with ws:tag prop", () => {expect(props).toEqual([]);});+test("renders intrinsic JSX as the persisted Webstudio element component", () => {+ const { instances, props } = renderTemplate(+ <section id="intro">+ <h2>Introduction</h2>+ </section>+ );++ expect(instances).toEqual([+ {+ type: "instance",+ id: "0",+ component: "ws:element",+ tag: "section",+ children: [{ type: "id", value: "1" }],+ },+ {+ type: "instance",+ id: "1",+ component: "ws:element",+ tag: "h2",+ children: [{ type: "text", value: "Introduction" }],+ },+ ]);+ expect(props).toEqual([+ {+ id: "0:id",+ instanceId: "0",+ name: "id",+ type: "string",+ value: "intro",+ },+ ]);+});++test("rejects unknown lowercase intrinsic JSX", () => {+ expect(() => renderTemplate(createElement("not-a-standard-element"))).toThrow(+ 'Invalid intrinsic JSX element "not-a-standard-element"'+ );+});+test("render camel-cased ws component as canonical kebab-case", () => {const { instances } = renderTemplate(<ws.blockTemplate />);diff --git a/packages/template/src/jsx.ts b/packages/template/src/jsx.tsindex 0a9abfc7bf..5356e4bce4 100644--- a/packages/template/src/jsx.ts+++ b/packages/template/src/jsx.ts@@ -1,10 +1,10 @@import { Fragment, type JSX, type ReactNode } from "react";-import { kebabCase } from "change-case";import { hyphenateProperty } from "@webstudio-is/css-engine";import {animationAction,encodeDataSourceVariable,getStyleDeclKey,+ tags,} from "@webstudio-is/sdk";import type {Breakpoint,@@ -21,9 +21,64 @@ import type {} from "@webstudio-is/sdk";import { showAttribute } from "@webstudio-is/react-sdk";import { mapAttributeNames } from "@webstudio-is/content-engine/jsx-attributes";+import { isMdxTemplateComponentName } from "@webstudio-is/content-engine/mdx";import { parseTemplateCss, type TemplateStyleDecl } from "./css";import { camelCaseProperty, parseMediaQuery } from "@webstudio-is/css-data";+declare module "react" {+ interface HTMLAttributes<T> {+ "ws:id"?: string;+ "ws:style"?: TemplateStyleDecl[];+ "ws:tokens"?: Token[];+ "ws:show"?: boolean | Expression;+ }++ interface SVGAttributes<T> {+ "ws:id"?: string;+ "ws:style"?: TemplateStyleDecl[];+ "ws:tokens"?: Token[];+ "ws:show"?: boolean | Expression;+ }+}++const instanceMetaByElement = new WeakMap<+ JSX.Element,+ Readonly<{ name?: string; label?: string }>+>();+const componentIdByMarker = new WeakMap<object, Instance["component"]>();+const intrinsicTags = new Set(tags);++export type TemplateComponent = Exclude<JSX.Element["type"], string>;++export type RenderTemplateOptions = {+ allowManualIds?: boolean;+ componentIds?: ReadonlyMap<TemplateComponent, Instance["component"]>;+ componentMetas?: ReadonlyMap<Instance["component"], WsComponentMeta>;+};++/** Associates instance metadata without exposing it as JSX properties. */+export const setInstanceMeta = (+ meta: Readonly<{ label?: string }>,+ element: JSX.Element+): JSX.Element => {+ instanceMetaByElement.set(element, meta);+ return element;+};++/** Associates structured Content Block template metadata without JSX props. */+export const setTemplateMeta = (+ meta: Readonly<{ name: string; label?: string }>,+ element: JSX.Element+): JSX.Element => {+ if (isMdxTemplateComponentName(meta.name) === false) {+ throw new Error(+ "Template name must be a PascalCase JavaScript identifier, for example PromotionCard"+ );+ }+ instanceMetaByElement.set(element, meta);+ return element;+};+export class Token {name: string;styles: TemplateStyleDecl[];@@ -153,14 +208,29 @@ const isChildValue = (child: unknown) =>child instanceof PlaceholderValue ||child instanceof Expression;-const getElementChildren = (element: JSX.Element): JSX.Element[] => {- if (Array.isArray(element.props?.children)) {- return element.props?.children;+type ElementChild = JSX.Element | string | PlaceholderValue | Expression;++const appendElementChildren = (children: ElementChild[], child: unknown) => {+ if (Array.isArray(child)) {+ for (const item of child) {+ appendElementChildren(children, item);+ }+ return;+ }+ if (child === undefined || child === null || typeof child === "boolean") {+ return;}- if (element.props?.children) {- return [element.props?.children];+ if (typeof child === "number") {+ children.push(String(child));+ return;}- return [];+ children.push(child as ElementChild);+};++const getElementChildren = (element: JSX.Element): ElementChild[] => {+ const children: ElementChild[] = [];+ appendElementChildren(children, element.props?.children);+ return children;};const findUnsupportedSerializableValue = (@@ -347,10 +417,7 @@ export const renderTemplate = (root: JSX.Element,generateId?: () => string,initialBreakpoints: Breakpoint[] = [],- options: {- allowManualIds?: boolean;- componentMetas?: Map<Instance["component"], WsComponentMeta>;- } = {}+ options: RenderTemplateOptions = {}): WebstudioFragment => {const instances: Instance[] = [];const props: Prop[] = [];@@ -523,12 +590,17 @@ export const renderTemplate = (): Instance["children"][number] => {if (element.type === Fragment) {throw new Error(- "Do not use React fragment shorthand <>...</> inside Webstudio JSX. Pass sibling Webstudio components directly at the top level, or wrap text in a component such as <$.Box><$.Paragraph>Text</$.Paragraph></$.Box>."+ "Do not use React fragment shorthand <>...</> inside Webstudio JSX. Pass sibling Webstudio components directly at the top level, or wrap text in an element such as <section><p>Text</p></section>.");}- if (typeof element.type === "string") {+ const intrinsicTag =+ typeof element.type === "string" ? element.type : undefined;+ if (+ intrinsicTag !== undefined &&+ intrinsicTags.has(intrinsicTag) === false+ ) {throw new Error(- `Do not use raw HTML tag <${element.type}> in Webstudio JSX. Use Webstudio components such as <$.Box>...</$.Box>, or use <ws.element ws:tag="${element.type}">...</ws.element> when a specific HTML tag is required.`+ `Invalid intrinsic JSX element "${intrinsicTag}". Use a standard lowercase HTML or SVG tag.`);}if (@@ -539,20 +611,31 @@ export const renderTemplate = ("Do not set ws:id in JSX fragments. Webstudio runtime generates system ids automatically.");}- const component = element.type.displayName;+ const component =+ intrinsicTag === undefined+ ? (options.componentIds?.get(element.type) ??+ componentIdByMarker.get(element.type))+ : "ws:element";if (typeof component !== "string") {+ const componentName =+ typeof element.type === "function"+ ? (element.type.displayName ?? element.type.name)+ : typeof element.type === "object" && element.type !== null+ ? element.type.displayName+ : undefined;throw new Error(- "Invalid JSX component in Webstudio JSX. Use Webstudio component helpers such as <$.Box>...</$.Box>."+ `Invalid JSX component${componentName ? ` "${componentName}"` : ""} in Webstudio JSX. Use a lowercase HTML element or an available PascalCase component identifier.`);}const instanceId = element.props?.["ws:id"] ?? getIdByKey(element);const componentMeta = options.componentMetas?.get(component);const componentPropNames = new Set(Object.keys(componentMeta?.props ?? {}));const acceptsHtmlAttributes =+ intrinsicTag !== undefined ||component === "ws:element" ||typeof element.props?.["ws:tag"] === "string" ||Object.keys(componentMeta?.presetStyle ?? {}).length > 0;- let tag: string | undefined;+ let tag: string | undefined = intrinsicTag;const mappedProps = mapAttributeNames({attributes: Object.entries({ ...element.props }).flatMap(([name, value]) =>@@ -568,6 +651,11 @@ export const renderTemplate = (let { name } = mappedProp;const { value } = mappedProp;if (name === "ws:tag") {+ if (intrinsicTag !== undefined) {+ throw new Error(+ `Do not set ws:tag on intrinsic JSX <${intrinsicTag}>. Use the intended HTML tag directly.`+ );+ }tag = value as string;continue;}@@ -686,8 +774,16 @@ export const renderTemplate = (component,children: [],};+ const templateMeta = instanceMetaByElement.get(element);+ if (templateMeta !== undefined) {+ instance.name = templateMeta.name;+ instance.label = templateMeta.label;+ if (instance.label === undefined) {+ delete instance.label;+ }+ }instances.push(instance);- if (element.props?.["ws:label"]) {+ if (element.props?.["ws:label"] && templateMeta === undefined) {instance.label = element.props?.["ws:label"];}if (tag !== undefined) {@@ -726,7 +822,7 @@ export const renderTemplate = ((children.length === 0 || instances.length === 0)) {throw new Error(- "JSX fragment must contain at least one Webstudio component, for example <$.Box><$.Paragraph>Text</$.Paragraph></$.Box>."+ "JSX fragment must contain at least one element or component, for example <section><p>Text</p></section>.");}for (const [instanceId, localStyles] of localStylesByInstanceId) {@@ -814,7 +910,8 @@ export const renderTemplate = (export const renderData = (root: JSX.Element,generateId?: () => string,- initialBreakpoints: Breakpoint[] = []+ initialBreakpoints: Breakpoint[] = [],+ options: RenderTemplateOptions = {}): Omit<WebstudioData, "pages"> => {const {instances,@@ -826,7 +923,7 @@ export const renderData = (dataSources,resources,assets,- } = renderTemplate(root, generateId, initialBreakpoints);+ } = renderTemplate(root, generateId, initialBreakpoints, options);return {instances: new Map(instances.map((item) => [item.id, item])),props: new Map(props.map((item) => [item.id, item])),@@ -857,22 +954,41 @@ type Component = { displayName: string } & ((props: ComponentProps) => ReactNode);-export const createProxy = (- prefix: string,- transformName: (name: string) => string = (name) => name-): Record<string, Component> => {- return new Proxy(- {},- {- get(_target, prop) {- const component: Component = () => undefined;- component.displayName = `${prefix}${transformName(String(prop))}`;- return component;- },- }- );+const createComponentMarker = (+ componentId: Instance["component"]+): Component => {+ const component: Component = () => undefined;+ component.displayName = componentId;+ componentIdByMarker.set(component, componentId);+ return component;};-export const $: Record<string, Component> = createProxy("");+/** @internal Creates an explicit component marker for test fixtures. */+export const createTemplateComponentFixture = (+ componentId: Instance["component"]+): Component => createComponentMarker(componentId);-export const ws: Record<string, Component> = createProxy("ws:", kebabCase);+const createCompilerPrimitive = (name: string): Component => {+ return createComponentMarker(`ws:${name}`);+};++type CompilerPrimitives = {+ root: Component;+ element: Component;+ collection: Component;+ descendant: Component;+ block: Component;+ contentBlockBody: Component;+ blockTemplate: Component;+};++/** Compiler-only primitives that have no React component implementation. */+export const ws: CompilerPrimitives = {+ root: createCompilerPrimitive("root"),+ element: createCompilerPrimitive("element"),+ collection: createCompilerPrimitive("collection"),+ descendant: createCompilerPrimitive("descendant"),+ block: createCompilerPrimitive("block"),+ contentBlockBody: createCompilerPrimitive("content-block-body"),+ blockTemplate: createCompilerPrimitive("block-template"),+};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1c97e58359..d2d4672510 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1534,9 +1534,15 @@ importers:canonicalize:specifier: 3.0.0version: 3.0.0+ estree-util-is-identifier-name:+ specifier: 3.0.0+ version: 3.0.0hast-util-to-mdast:specifier: 9.0.0version: 9.0.0+ html-tags:+ specifier: ^4.0.0+ version: 4.0.0lru-cache:specifier: 10.4.3version: 10.4.3@@ -1576,6 +1582,9 @@ importers:remark-parse:specifier: 10.0.2version: 10.0.2+ svg-tags:+ specifier: 1.0.0+ version: 1.0.0unified:specifier: 10.1.2version: 10.1.2@@ -1586,6 +1595,9 @@ importers:specifier: ^4.4.3version: 4.4.3devDependencies:+ '@types/svg-tags':+ specifier: 1.0.2+ version: 1.0.2'@webstudio-is/tsconfig':specifier: workspace:*version: link:../tsconfig@@ -2646,6 +2658,9 @@ importers:'@webstudio-is/sdk':specifier: workspace:*version: link:../sdk+ '@webstudio-is/sdk-components-react':+ specifier: workspace:*+ version: link:../sdk-components-reactchange-case:specifier: ^5.4.4version: 5.4.4@@ -2680,9 +2695,6 @@ importers:'@webstudio-is/sdk-cli':specifier: workspace:^version: link:../sdk-cli- '@webstudio-is/sdk-components-react':- specifier: workspace:*- version: link:../sdk-components-react'@webstudio-is/template':specifier: workspace:*version: link:../template@@ -2873,6 +2885,9 @@ importers:'@webstudio-is/sdk':specifier: workspace:*version: link:../sdk+ '@webstudio-is/sdk-components-react':+ specifier: workspace:*+ version: link:../sdk-components-reactawait-interaction-response:specifier: ^0.0.2version: 0.0.2@@ -2898,9 +2913,6 @@ importers:'@webstudio-is/sdk-cli':specifier: workspace:^version: link:../sdk-cli- '@webstudio-is/sdk-components-react':- specifier: workspace:*- version: link:../sdk-components-react'@webstudio-is/template':specifier: workspace:*version: link:../template@@ -2996,6 +3008,9 @@ importers:packages/sdk-components-registry:dependencies:+ '@webstudio-is/icons':+ specifier: workspace:*+ version: link:../icons'@webstudio-is/sdk':specifier: workspace:*version: link:../sdk@@ -3018,6 +3033,9 @@ importers:'@types/react-dom':specifier: ^18.2.25version: 18.2.25+ '@webstudio-is/template':+ specifier: workspace:*+ version: link:../template'@webstudio-is/tsconfig':specifier: workspace:*version: link:../tsconfig@@ -3073,9 +3091,6 @@ importers:'@webstudio-is/sdk':specifier: workspace:*version: link:../sdk- change-case:- specifier: ^5.4.4- version: 5.4.4react:specifier: 18.3.0-canary-14898b6a9-20240318version: 18.3.0-canary-14898b6a9-20240318@@ -6894,6 +6909,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-D8rhCFfpmWzXvzVqdXo40EXNeropfqp4gvwn8fcVfzYIci8M1C1tk/L26Yacn/U9vaPM7FlS73BNoUtfjAjwAw==}+'@types/[email protected]':resolution: {integrity: sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ==}@@ -11233,6 +11251,9 @@ packages:resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-ovssysQTa+luh7A5Weu3Rta6FJlFBBbInjOh722LIt6klpU2/HtdUbszju/G4devcvk8PGt7FCLv5wftu3THUA==}+resolution: {integrity: sha512-Z706C1U2pb1+JGP48fbazf3KxHrWOsLme6Rv7imFBn5EnuanDW1GPaA/P1/dvObE670JDePC3mnj0k0B7P0jjQ==}engines: {node: '>=14.0.0'}@@ -16378,6 +16399,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -21682,6 +21705,8 @@ snapshots:+ [email protected]: {}+dependencies:'@trysound/sax': 0.2.0