Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: route deprecated Webhook Forms through Form backend (#6553)
Oleg Isonen13eb7527ef1f
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 f0ae5ae96a..fd0bee0523 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@@ -93,7 +93,7 @@ describe("canWrapInstance for components", () => {"box",["box", "body"],"body",- "Form",+ "ResourceForm",undefined,$instances.get(),$props.get(),diff --git a/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsxindex 3bf3af636b..ac7551a7fc 100644--- a/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx@@ -54,7 +54,7 @@ const wrapperComponentNames = ["AnimateText","StaggerAnimation","VideoAnimation",- "Form",+ "ResourceForm",];const $wrapOptions = computed(diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsxindex 64ae696594..576fbee177 100644--- a/apps/builder/app/builder/features/publish/publish.tsx+++ b/apps/builder/app/builder/features/publish/publish.tsx@@ -145,39 +145,54 @@ const PrePublishAuditMessage = ({return (<>{message}{" "}- <PrePublishInstanceLink instanceId={instanceId}>+ <PrePublishInstanceLink+ instanceId={instanceId}+ pageId={finding.location.pageId}+ instanceSelector={finding.location.instanceSelector}+ >Show element</PrePublishInstanceLink></>);};-const getPrePublishInstanceTarget = (instanceId: string) => {+const getPrePublishInstanceTarget = (+ instanceId: string,+ pageId?: string,+ instanceSelector?: string[]+) => {const pages = $pages.get();const instances = $instances.get();if (pages === undefined || instances.has(instanceId) === false) {return;}- const { pageId, instanceSelector } = findPageAndSelectorByInstanceId(- pages,- instances,- instanceId- );- const href = getInstanceLink(instanceSelector);+ const target =+ pageId === undefined || instanceSelector === undefined+ ? findPageAndSelectorByInstanceId(pages, instances, instanceId)+ : { pageId, instanceSelector };+ const href = getInstanceLink(target.instanceSelector);if (href === undefined) {return;}- return { pageId, instanceSelector, href };+ return { ...target, href };};const PrePublishInstanceLink = ({instanceId,+ pageId,+ instanceSelector,children,}: {instanceId: string;+ pageId?: string;+ instanceSelector?: string[];children: ReactNode;}) => {- const target = getPrePublishInstanceTarget(instanceId);+ const target = getPrePublishInstanceTarget(+ instanceId,+ pageId,+ instanceSelector+ );if (target === undefined) {return null;}@@ -220,7 +235,9 @@ const getPrePublishAuditFindings = (): PublishValidationFinding[] => {return [];}const context = Object.entries(finding.location)- .filter(([, value]) => value !== undefined)+ .filter(+ ([key, value]) => key !== "instanceSelector" && value !== undefined+ ).map(([key, value]) => `${key}: ${value}`);const reportText = [`${finding.severity.toUpperCase()}: ${formatPrePublishAuditFinding(diff --git a/apps/builder/app/builder/features/settings-panel/controls/form-action-picker.browser.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/form-action-picker.browser.test.tsxindex ae0c1a321a..30594be965 100644--- a/apps/builder/app/builder/features/settings-panel/controls/form-action-picker.browser.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/form-action-picker.browser.test.tsx@@ -30,7 +30,7 @@ const setup = (resourceNames: readonly string[]) => {{type: "instance" as const,id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],diff --git a/apps/builder/app/builder/features/settings-panel/controls/form-action.integration.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/form-action.integration.test.tsxindex ad8c763f63..7a49434d59 100644--- a/apps/builder/app/builder/features/settings-panel/controls/form-action.integration.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/form-action.integration.test.tsx@@ -64,7 +64,7 @@ test("Actions references an existing Resource without creating another", async ({type: "instance" as const,id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],diff --git a/apps/builder/app/builder/features/settings-panel/controls/form-action.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/form-action.test.tsxindex b3e8fe2f0c..0618bc6dd5 100644--- a/apps/builder/app/builder/features/settings-panel/controls/form-action.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/form-action.test.tsx@@ -61,7 +61,7 @@ test("Action + explains how to add a resource when none are available", async (){type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -107,7 +107,12 @@ test("Action header and menu align while items sit below the full header", asyncnew Map([["form",- { type: "instance", id: "form", component: "Form", children: [] },+ {+ type: "instance",+ id: "form",+ component: "ResourceForm",+ children: [],+ },],]));@@ -315,7 +320,7 @@ test("Action control handles an empty Resource list and can select an in-scope d{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -500,7 +505,7 @@ test("a Form can select a Resource defined outside its scope", async () => {{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -581,7 +586,7 @@ test("stored Form selection renders and a deleted Resource can be removed", asyn{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -665,7 +670,7 @@ test("Actions only offers eligible in-scope Resources and disables an added one"{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -772,7 +777,7 @@ test("a legacy Action stays visible and can be removed", async () => {{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -902,7 +907,7 @@ test.each([{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],diff --git a/apps/builder/app/builder/features/settings-panel/form-context-preview.test.ts b/apps/builder/app/builder/features/settings-panel/form-context-preview.test.tsindex baae6eece0..db0857ed44 100644--- a/apps/builder/app/builder/features/settings-panel/form-context-preview.test.ts+++ b/apps/builder/app/builder/features/settings-panel/form-context-preview.test.ts@@ -69,7 +69,10 @@ test("Form parameter resolver gives the Resource scope the same public occurrencscopeInstanceId: "other",};const instances: Instances = new Map([- ["form", { id: "form", type: "instance", component: "Form", children: [] }],+ [+ "form",+ { id: "form", type: "instance", component: "ResourceForm", children: [] },+ ],["other",{ id: "other", type: "instance", component: "Box", children: [] },diff --git a/apps/builder/app/builder/features/settings-panel/form-context-preview.ts b/apps/builder/app/builder/features/settings-panel/form-context-preview.tsindex 0cbd1ea665..eacb8afdfd 100644--- a/apps/builder/app/builder/features/settings-panel/form-context-preview.ts+++ b/apps/builder/app/builder/features/settings-panel/form-context-preview.ts@@ -53,7 +53,7 @@ export const getFormParameterName = ((formId === undefined && instances === undefined) ||(formId !== undefined && source.scopeInstanceId !== formId) ||(instances !== undefined &&- instances.get(source.scopeInstanceId)?.component !== "Form")+ instances.get(source.scopeInstanceId)?.component !== "ResourceForm")) {return;}diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts b/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.tsindex 73aebd3f8d..a8bcc7f93c 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts@@ -23,21 +23,21 @@ test("keeps a standalone Form redirect when Content mode hides Action", () => {expect(getStandaloneInitialProps({- component: "Form",+ component: "ResourceForm",addedProps: [],initialProps: [redirect],})).toEqual([redirect]);expect(getStandaloneInitialProps({- component: "Form",+ component: "ResourceForm",addedProps: [],initialProps: [action, redirect],})).toEqual([action]);expect(getStandaloneInitialProps({- component: "Form",+ component: "ResourceForm",addedProps: [action],initialProps: [redirect],})@@ -45,7 +45,7 @@ test("keeps a standalone Form redirect when Content mode hides Action", () => {});test("Form and generic components render their property sections", () => {- for (const component of ["Form", "Box"]) {+ for (const component of ["ResourceForm", "Box"]) {expect(shouldRenderPropsSectionContainer({component,diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsxindex e7d61ce79e..5be5057a44 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx@@ -196,7 +196,7 @@ const getStandaloneInitialProps = ({initialProps: PropAndMeta[];}) => {const hasVisibleFormActionControl =- component === "Form" &&+ component === "ResourceForm" &&[...addedProps, ...initialProps].some((item) => item.meta.control === "form-action");@@ -236,7 +236,7 @@ const renderProperty = (getInstanceKey(item.instanceSelector)) ?? propValues);- if (component === "Form" && meta.control === "form-action") {+ if (component === "ResourceForm" && meta.control === "form-action") {const redirect = logic.initialProps.find((item) => item.propName === "successRedirect");diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.test.ts b/apps/builder/app/builder/features/settings-panel/resource-panel.test.tsindex 461cc38570..8e8321079d 100644--- a/apps/builder/app/builder/features/settings-panel/resource-panel.test.ts+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.test.ts@@ -624,6 +624,9 @@ test("Email Resource recipient modes and attachment radios", async () => {).toBeVisible();expect(container.textContent).toContain("Attach submitted files");expect(container.textContent).toContain("Do not attach files");+ expect(container.textContent).toContain(+ "Attach up to 32 files. The email request is limited to 7 MiB, including encoded files. Cloudflare also limits the complete email to 5 MiB for most recipients, or 25 MiB for verified destinations."+ );await act(async () => await userEvent.click(attachmentOptions[1] as HTMLElement));@@ -646,7 +649,7 @@ test.each(["sender", "recipients"] as const)({id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "contact-input" }],},],@@ -1068,7 +1071,7 @@ test("visitor Email Resource selects a named Form email field", async () => {{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "email-input" }],},],@@ -1333,7 +1336,7 @@ test("unrelated Resource edits preserve recipient scope and aliases", async () ={type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -1443,7 +1446,7 @@ test("body controls follow the effective method for standalone GET and Form Acti{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -2227,7 +2230,7 @@ test.each([{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "contact-input" }],},],diff --git a/apps/builder/app/builder/features/settings-panel/resource-scope.ts b/apps/builder/app/builder/features/settings-panel/resource-scope.tsindex f8381420a8..61ef0e56a3 100644--- a/apps/builder/app/builder/features/settings-panel/resource-scope.ts+++ b/apps/builder/app/builder/features/settings-panel/resource-scope.ts@@ -190,8 +190,8 @@ const createResourceScopeStore = (variable: DataSource | undefined) => {? undefined: instancePath?.slice(variablePathIndex)- .find(({ instance }) => instance.component === "Form")?.instance- .id;+ .find(({ instance }) => instance.component === "ResourceForm")+ ?.instance.id;const formScopeSelector =formScopeInstanceId === undefined? undefineddiff --git a/apps/builder/app/builder/features/settings-panel/selected-instance-props-meta.test.ts b/apps/builder/app/builder/features/settings-panel/selected-instance-props-meta.test.tsindex 900558130d..0b0d46086a 100644--- a/apps/builder/app/builder/features/settings-panel/selected-instance-props-meta.test.ts+++ b/apps/builder/app/builder/features/settings-panel/selected-instance-props-meta.test.ts@@ -21,14 +21,14 @@ test("does not expose rendered form attributes for the managed Form", () => {const form = {type: "instance" as const,id: "form",- component: "Form",+ component: "ResourceForm",tag: "form",children: [],};$instances.set(new Map([[form.id, form]]));$props.set(new Map());const nativeFormMeta: WsComponentMeta = {- label: "Form",+ label: "ResourceForm",htmlAttributes: "hide",props: {action: {@@ -40,7 +40,7 @@ test("does not expose rendered form attributes for the managed Form", () => {},};$registeredComponentMetas.set(- new Map([...Object.entries(coreMetas), ["Form", nativeFormMeta]])+ new Map([...Object.entries(coreMetas), ["ResourceForm", nativeFormMeta]]));selectInstance([form.id]);@@ -60,7 +60,7 @@ test("keeps rendered form attributes for components without the opt-out", () =>const form = {type: "instance" as const,id: "form",- component: "Form",+ component: "ResourceForm",tag: "form",children: [],};@@ -70,9 +70,9 @@ test("keeps rendered form attributes for components without the opt-out", () =>new Map([...Object.entries(coreMetas),[- "Form",+ "ResourceForm",{- label: "Form",+ label: "ResourceForm",props: {custom: { type: "string", control: "text", required: false },className: { type: "string", control: "text", required: false },diff --git a/apps/builder/app/builder/features/settings-panel/variable-editors/email-request-preview.test.ts b/apps/builder/app/builder/features/settings-panel/variable-editors/email-request-preview.test.tsindex 102abe1185..3062e39e7f 100644--- a/apps/builder/app/builder/features/settings-panel/variable-editors/email-request-preview.test.ts+++ b/apps/builder/app/builder/features/settings-panel/variable-editors/email-request-preview.test.ts@@ -64,7 +64,7 @@ test("Email Request preview uses current Form data and settings without sending"{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "password-input" }],},],@@ -136,7 +136,7 @@ test("Email Request preview formats formData in an explicit body expression", as{id: "form",type: "instance" as const,- component: "Form",+ component: "ResourceForm",children: [],},],@@ -170,7 +170,7 @@ test("Email Request preview formats uploaded files like the submitted Email", as{id: "form",type: "instance" as const,- component: "Form",+ component: "ResourceForm",children: [],},],@@ -209,7 +209,7 @@ test("Email Request preview includes the known submission page URL", async () =>{id: "form",type: "instance" as const,- component: "Form",+ component: "ResourceForm",children: [],},],@@ -251,7 +251,7 @@ test("Visitor Email Request preview leaves missing addresses empty and never fab{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -284,7 +284,7 @@ test("Visitor Email Request preview uses sender defaults without rewriting custo{id: "form",type: "instance" as const,- component: "Form",+ component: "ResourceForm",children: [],},],@@ -375,7 +375,7 @@ test.each(["name", "type"] as const)({id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "input" }],},],@@ -447,7 +447,7 @@ test("Email Request preview blocks explicit access to known password and interna{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "password-input" }],},],@@ -503,7 +503,7 @@ test("Email Request preview does not fall back to scoped Form data when current{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -541,7 +541,7 @@ test("Email Request preview preserves user variables named like managed Form par{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],diff --git a/apps/builder/app/builder/features/settings-panel/variable-editors/email-request-preview.ts b/apps/builder/app/builder/features/settings-panel/variable-editors/email-request-preview.tsindex 38ff6ae6c0..3bb8fa7aa2 100644--- a/apps/builder/app/builder/features/settings-panel/variable-editors/email-request-preview.ts+++ b/apps/builder/app/builder/features/settings-panel/variable-editors/email-request-preview.ts@@ -71,11 +71,11 @@ export const buildEmailRequestPreviewFromEditor = async ({const selected = $selectedInstanceSelector.get();const formId =selected?.find(- (instanceId) => instances.get(instanceId)?.component === "Form"+ (instanceId) => instances.get(instanceId)?.component === "ResourceForm") ??Array.from(instances.values()).find((instance) =>- instance.component === "Form" &&+ instance.component === "ResourceForm" &&variable?.scopeInstanceId !== undefined &&findTreeInstanceIds(instances, instance.id).has(variable.scopeInstanceIddiff --git a/apps/builder/app/builder/features/settings-panel/variable-editors/email-resource-editor.tsx b/apps/builder/app/builder/features/settings-panel/variable-editors/email-resource-editor.tsxindex 759993d08c..4e5b0cc04a 100644--- a/apps/builder/app/builder/features/settings-panel/variable-editors/email-resource-editor.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-editors/email-resource-editor.tsx@@ -41,6 +41,7 @@ import {RadioAndLabel,RadioGroup,Select,+ Text,TextArea,} from "@webstudio-is/design-system";import { $selectedInstance } from "~/shared/nano-states";@@ -187,7 +188,7 @@ export const EmailResourceForm = forwardRef<variable?.scopeInstanceId ?? $selectedInstance.get()?.id;const formId = Array.from(instances.values()).find((instance) =>- instance.component === "Form" &&+ instance.component === "ResourceForm" &&scopeInstanceId !== undefined &&findTreeInstanceIds(instances, instance.id).has(scopeInstanceId))?.id;@@ -517,6 +518,7 @@ export const EmailResourceForm = forwardRef<<Label id={`${attachmentId}-label`}>Attachments</Label><RadioGrouparia-labelledby={`${attachmentId}-label`}+ aria-describedby={`${attachmentId}-limits`}value={settings.includeAttachments === false ? "exclude" : "include"}@@ -537,6 +539,11 @@ export const EmailResourceForm = forwardRef<</Label></RadioAndLabel></RadioGroup>+ <Text id={`${attachmentId}-limits`} variant="small" color="subtle">+ Attach up to 32 files. The email request is limited to 7 MiB,+ including encoded files. Cloudflare also limits the complete email+ to 5 MiB for most recipients, or 25 MiB for verified destinations.+ </Text></Grid></Row></>diff --git a/apps/builder/app/builder/features/settings-panel/variable-editors/http-resource-editor.tsx b/apps/builder/app/builder/features/settings-panel/variable-editors/http-resource-editor.tsxindex b132e75cb6..86278ccf44 100644--- a/apps/builder/app/builder/features/settings-panel/variable-editors/http-resource-editor.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-editors/http-resource-editor.tsx@@ -46,7 +46,7 @@ export const HttpResourceForm = forwardRef<variable !== undefined &&Array.from(props.values()).some((prop) =>- instances.get(prop.instanceId)?.component === "Form" &&+ instances.get(prop.instanceId)?.component === "ResourceForm" &&prop.name === "action" &&prop.type === "json" &&isFormSubmission(prop.value) &&diff --git a/apps/builder/app/builder/features/settings-panel/variable-menu.test.tsx b/apps/builder/app/builder/features/settings-panel/variable-menu.test.tsxindex 999dd65988..418789e373 100644--- a/apps/builder/app/builder/features/settings-panel/variable-menu.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-menu.test.tsx@@ -149,7 +149,7 @@ test.each(["formState", "results", "errors"])({id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -222,7 +222,7 @@ test.each(["formState", "results", "errors"])({id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -295,7 +295,7 @@ test.each(["formState", "results", "errors"])({id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -377,7 +377,7 @@ test.each(["formState", "results", "errors"])({id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -463,7 +463,7 @@ test("ordinary Form-scoped variable remains deletable from the row context menu"{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover-preview.test.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover-preview.test.tsxindex 0bd98109ef..d3043d2fab 100644--- a/apps/builder/app/builder/features/settings-panel/variable-popover-preview.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-popover-preview.test.tsx@@ -236,7 +236,7 @@ test("Edit variable preview shows server browser info for a Form variable", asyn{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -299,7 +299,7 @@ test.each([{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "email-input" }],},],diff --git a/apps/builder/app/builder/features/settings-panel/variable-response.test.tsx b/apps/builder/app/builder/features/settings-panel/variable-response.test.tsxindex b8b96fc923..a91b8b5897 100644--- a/apps/builder/app/builder/features/settings-panel/variable-response.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-response.test.tsx@@ -64,7 +64,7 @@ test("Form context Preview shows live data and server browser info", async () =>{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.test.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.test.tsxindex 24e0e8e535..4065e693d3 100644--- a/apps/builder/app/builder/features/settings-panel/variables-section.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/variables-section.test.tsx@@ -145,7 +145,7 @@ test.each(["formState", "results", "errors"] as const)({id: "form",type: "instance" as const,- component: "Form",+ component: "ResourceForm",children: [],},],@@ -272,7 +272,7 @@ test("Variables list preview uses server browser info after Preview submission",{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -332,7 +332,7 @@ test.each([{id: "form",type: "instance" as const,- component: "Form",+ component: "ResourceForm",children: [],},],diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsxindex 12a5deae63..e554e06d9d 100644--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx@@ -237,7 +237,7 @@ const VariablesItem = ({const valueSourceId = variable.scopeInstanceId ?? ROOT_INSTANCE_ID;const valueSource = instances.get(valueSourceId);const formVariableDescription =- valueSource?.component === "Form"+ valueSource?.component === "ResourceForm"? formVariableDescriptions[variable.name]: undefined;const valueSourceName =diff --git a/apps/builder/app/canvas/features/webstudio-component/preview-form-lifecycle.test.tsx b/apps/builder/app/canvas/features/webstudio-component/preview-form-lifecycle.test.tsxindex e1e6e3f616..94c9ae4fd1 100644--- a/apps/builder/app/canvas/features/webstudio-component/preview-form-lifecycle.test.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/preview-form-lifecycle.test.tsx@@ -199,7 +199,7 @@ test.each([const form: Instance = {type: "instance" as const,id: "form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id" as const, value: slot.id }],};$instances.set(diff --git a/apps/builder/app/canvas/features/webstudio-component/preview-resource-form.tsx b/apps/builder/app/canvas/features/webstudio-component/preview-resource-form.tsxindex 0f62c61fed..d1cc305894 100644--- a/apps/builder/app/canvas/features/webstudio-component/preview-resource-form.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/preview-resource-form.tsx@@ -8,7 +8,7 @@ import {import { useStore } from "@nanostores/react";import { mergeRefs } from "@react-aria/utils";import { selectorIdAttribute } from "@webstudio-is/react-sdk";-import { Form as ResourceForm } from "@webstudio-is/sdk-components-react/components";+import { ResourceForm } from "@webstudio-is/sdk-components-react/components";import type { submitManagedForm } from "@webstudio-is/sdk-components-react";import type { ManagedFormResponse } from "@webstudio-is/sdk/runtime";import { $selectedPageHash } from "~/shared/nano-states/pages";diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex 8e8beec5b8..8f07a1b915 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -1039,7 +1039,7 @@ const WebstudioComponentPreviewInner = forwardRef<[componentAttribute]: instance.component,[selectorIdAttribute]: instanceSelector.join(","),};- if (instance.component === "Form") {+ if (instance.component === "ResourceForm") {Object.assign(props, getPreviewResourceFormProps(instance.id));}if (show === false) {@@ -1077,7 +1077,7 @@ const WebstudioComponentPreviewInner = forwardRef<instance.component);- if (instance.component === "Form") {+ if (instance.component === "ResourceForm") {Component = PreviewResourceForm as AnyComponent;}diff --git a/apps/builder/app/services/api-build.server.test.ts b/apps/builder/app/services/api-build.server.test.tsindex 845addc886..450798a2dc 100644--- a/apps/builder/app/services/api-build.server.test.ts+++ b/apps/builder/app/services/api-build.server.test.ts@@ -436,7 +436,6 @@ describe("api build snapshot", () => {version: 7,homePageId: build.pages.homePageId,rootFolderId: build.pages.rootFolderId,- formComponentIdentityVersion: 1,projectSettings: {meta: { siteName: "Acme" },compiler: { atomicStyles: true },@@ -459,9 +458,8 @@ describe("api build snapshot", () => {);});- test("does not assign a Form identity version to an unmarked legacy build", () => {+ test("omits the historical Form identity version from public snapshots", () => {const pages = createDefaultPages({ rootInstanceId: "root-1" });- pages.formComponentIdentityVersion = undefined;const snapshot = createBuildSnapshot({build: {id: "build-1",@@ -472,7 +470,7 @@ describe("api build snapshot", () => {projectId: "project-1",});- expect(snapshot.formComponentIdentityVersion).toBeUndefined();+ expect("formComponentIdentityVersion" in snapshot).toBe(false);});});diff --git a/apps/builder/app/services/api-build.server.ts b/apps/builder/app/services/api-build.server.tsindex 276ab3d4a3..e713e8841d 100644--- a/apps/builder/app/services/api-build.server.ts+++ b/apps/builder/app/services/api-build.server.ts@@ -101,8 +101,6 @@ export const createBuildSnapshot = ({snapshot.homePageId = pages.homePageId;snapshot.rootFolderId = pages.rootFolderId;if (include.has("pages")) {- snapshot.formComponentIdentityVersion =- pages.formComponentIdentityVersion;snapshot.redirects = pages.redirects;snapshot.pageTemplates = pages.pageTemplates;}diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.tsindex 9569353cd3..492e0a8e15 100644--- a/apps/builder/app/services/api-router.server.test.ts+++ b/apps/builder/app/services/api-router.server.test.ts@@ -150,6 +150,37 @@ describe("api router build operation adapters", () => {expect(simulate).toHaveBeenCalledWith(expect.objectContaining({ projectId: "project-1", formId: "form-1" }));+ simulate.mockResolvedValueOnce({+ success: false,+ status: 502,+ results: [],+ errors: [+ {+ status: 429,+ resourceId: "email-resource",+ code: "E_DAILY_LIMIT_EXCEEDED",+ body: { error: { code: "E_DAILY_LIMIT_EXCEEDED" } },+ message:+ "Cloudflare's daily email sending limit was reached. Try again later.",+ },+ ],+ });+ await expect(+ createCaller(createContext(true)).forms.simulateSubmission(input)+ ).resolves.toEqual({+ success: false,+ status: 502,+ results: [],+ errors: [+ {+ status: 429,+ resourceId: "email-resource",+ code: "E_DAILY_LIMIT_EXCEEDED",+ message:+ "Cloudflare's daily email sending limit was reached. Try again later.",+ },+ ],+ });});test("enforces plan contact-address limits through project settings updates", async () => {server.use(postgrestDb.get("Project", () => json({ userId: "owner-1" })));diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.tsindex 813b822e8f..169148d71b 100644--- a/apps/builder/app/services/api-router.server.ts+++ b/apps/builder/app/services/api-router.server.ts@@ -855,10 +855,14 @@ export const apiRouter = router({status,resourceId,})),- errors: result.errors.map(({ status, message }) => ({- status,- message,- })),+ errors: result.errors.map(+ ({ status, message, code, resourceId }) => ({+ status,+ message,+ ...(resourceId === undefined ? {} : { resourceId }),+ ...(code === undefined ? {} : { code }),+ })+ ),};},{ command: "simulate-form-submission", client: "simulateFormSubmission" }diff --git a/apps/builder/app/services/api-runtime.server.test.ts b/apps/builder/app/services/api-runtime.server.test.tsindex 5e1e043f75..256e83c364 100644--- a/apps/builder/app/services/api-runtime.server.test.ts+++ b/apps/builder/app/services/api-runtime.server.test.ts@@ -132,7 +132,7 @@ describe("api runtime adapter", () => {input: {projectId: "project-1",parentInstanceId: "root-1",- component: "Form",+ component: "ResourceForm",},});diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.tsindex 4a22c41929..62eff5ba73 100644--- a/apps/builder/app/services/build-router.server.ts+++ b/apps/builder/app/services/build-router.server.ts@@ -28,6 +28,7 @@ import {importProjectBundleInput,bundleVersion,publishedProjectBundle,+ historicalPublishedProjectBundle,} from "@webstudio-is/protocol";import { removeAgentInstructionsFromProjectSettings } from "@webstudio-is/project-build";import { hydrateRestorePointTransaction } from "@webstudio-is/project-build/project-session";@@ -151,7 +152,7 @@ const createImportProjectBundleHandler =});return await importPublishedProjectBundle({ctx,- data: publishedProjectBundle.parse(JSON.parse(text)),+ data: historicalPublishedProjectBundle.parse(JSON.parse(text)),ignoreVersionCheck: input.ignoreVersionCheck,projectId: input.projectId,});diff --git a/apps/builder/app/services/preview-form-route.server.test.ts b/apps/builder/app/services/preview-form-route.server.test.tsindex 83d4c571e6..c41d412081 100644--- a/apps/builder/app/services/preview-form-route.server.test.ts+++ b/apps/builder/app/services/preview-form-route.server.test.ts@@ -89,7 +89,7 @@ const draftBuild = {component: "Body",children: [{ type: "id", value: "form" }],},- { type: "instance", id: "form", component: "Form", children: [] },+ { type: "instance", id: "form", component: "ResourceForm", children: [] },],props: [{@@ -577,11 +577,11 @@ test.each([false, true])(contents: `import { createElement } from "react";import { createRoot } from "react-dom/client";- import { Form } from "./resource-form";+ import { ResourceForm } from "./resource-form";import { submitPreviewForm } from "~/shared/preview-form-bridge";createRoot(document.getElementById("root")).render(- createElement(Form, {+ createElement(ResourceForm, {"data-ws-managed-form-id": "form",action: [{ dataSourceId: "destination" }],onManagedSubmit: (values, signal) => submitPreviewForm({@@ -1000,7 +1000,7 @@ test("Preview binds each page's submitted values and browser context to its owncomponent: "Body",children: [{ type: "id", value: formId }],},- { type: "instance", id: formId, component: "Form", children: [] },+ { type: "instance", id: formId, component: "ResourceForm", children: [] },]),props: pages.map(({ formId }) => ({id: `${formId}-action`,diff --git a/apps/builder/app/services/project-import.server.test.ts b/apps/builder/app/services/project-import.server.test.tsindex 2ae02f55fb..e7f6d5e3c3 100644--- a/apps/builder/app/services/project-import.server.test.ts+++ b/apps/builder/app/services/project-import.server.test.ts@@ -301,6 +301,39 @@ describe("build import helpers", () => {]);});+ test.each([+ { marker: 1, expected: "ResourceForm" },+ { marker: undefined, expected: "WebhookForm" },+ ])(+ "imports historical Form as $expected with canonical pages",+ ({ marker, expected }) => {+ const data = createData();+ if (marker !== undefined) {+ Object.assign(data.build.pages, {+ formComponentIdentityVersion: marker,+ });+ }+ data.build.instances.push([+ "form",+ { id: "form", type: "instance", component: "Form", children: [] },+ ]);+ const update = createBuildImportUpdate({+ data,+ lastTransactionId: "import-tx",+ updatedAt: "2024-02-01T00:00:00.000Z",+ version: 4,+ });+ expect(JSON.parse(update.pages)).not.toHaveProperty(+ "formComponentIdentityVersion"+ );+ expect(+ JSON.parse(update.instances).find(+ (instance: { id: string }) => instance.id === "form"+ )?.component+ ).toBe(expected);+ }+ );+test("uses imported home social image only when corresponding asset exists", () => {expect(getImportedPreviewImageAssetId(createData())).toBe("asset-1");diff --git a/apps/builder/app/services/project-import.server.ts b/apps/builder/app/services/project-import.server.tsindex 1bc7b53a77..3c42781387 100644--- a/apps/builder/app/services/project-import.server.ts+++ b/apps/builder/app/services/project-import.server.ts@@ -20,9 +20,11 @@ import {} from "@webstudio-is/asset-uploader/server";import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";import {+ hasHistoricalFormComponentIdentityVersion,migratePages,serializePages,} from "@webstudio-is/project-migrations/pages";+import { migrateResourceFormInstancesMutable } from "@webstudio-is/project-migrations";import {createProjectSettingsFromPages,removeLegacyProjectSettingsFromPages,@@ -96,7 +98,14 @@ const createBuildImportUpdate = ({updatedAt: string;version: number;}) => {+ const hasModernFormMarker = hasHistoricalFormComponentIdentityVersion(+ data.build.pages+ );const pages = migratePages(data.build.pages);+ const instances = toMap(+ data.build.instances.map(([id, instance]) => [id, { ...instance }])+ );+ migrateResourceFormInstancesMutable(instances.values(), hasModernFormMarker);const projectSettings =data.build.projectSettings ?? createProjectSettingsFromPages(pages);return {@@ -121,7 +130,7 @@ const createBuildImportUpdate = ({props: serializeData<Prop>(toMap(data.build.props)),dataSources: serializeData<DataSource>(toMap(data.build.dataSources)),resources: serializeData<Resource>(toMap(data.build.resources)),- instances: serializeData<Instance>(toMap(data.build.instances)),+ instances: serializeData<Instance>(instances),};};diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.tsindex c55ec041b0..3842d3b8a9 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts@@ -92,6 +92,33 @@ const getIdValuePair = <T extends { id: string }>(item: T) =>const toMap = <T extends { id: string }>(list: T[]) =>new Map(list.map(getIdValuePair));+test("rejects historical Form clipboard data before importing or inserting", async () => {+ const importAssets = vi.spyOn(builderApiTesting.api, "importAssets");+ const before = structuredClone($instances.get());+ const clipboardData = JSON.stringify({+ "@webstudio/instance/v0.1": {+ instanceSelector: ["form", "body0"],+ children: [{ type: "id", value: "form" }],+ instances: [createInstance("form", "Form", [])],+ assets: [],+ dataSources: [],+ resources: [],+ props: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ },+ });++ expect(await instanceText.onPaste?.(clipboardData)).toMatchObject({+ success: false,+ error: expect.stringMatching(/Copy it again/),+ });+ expect(importAssets).not.toHaveBeenCalled();+ expect($instances.get()).toEqual(before);+});+const getMapDifference = <Type extends Map<unknown, unknown>>(left: Type,right: Typediff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex 2acf15baae..6447b41761 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -446,7 +446,11 @@ const handlePasteInstance = async (clipboardData: string) => {return pasteIgnored;}if (transferData.valid === false) {- return { success: false, error: invalidPasteDataMessage } as const;+ return {+ success: false,+ error:+ "error" in transferData ? transferData.error : invalidPasteDataMessage,+ } as const;}const projectId = $project.get()?.id;if (projectId === undefined) {diff --git a/apps/builder/app/shared/copy-paste/plugin-page.test.ts b/apps/builder/app/shared/copy-paste/plugin-page.test.tsindex c5dca7b182..c1c8a38eb1 100644--- a/apps/builder/app/shared/copy-paste/plugin-page.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-page.test.ts@@ -69,6 +69,50 @@ const resetBuildStores = () => {$selectedPageId.set(undefined);};+test("rejects historical Form page clipboard before importing or inserting", async () => {+ const importAssets = vi.spyOn(builderApiTesting.api, "importAssets");+ const before = structuredClone($pages.get());+ const fragment = {+ children: [],+ instances: [],+ assets: [],+ dataSources: [],+ resources: [],+ props: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };+ const clipboardData = JSON.stringify({+ "@webstudio/page/v0.1": {+ type: "page",+ page: {+ id: "old-page",+ name: "Old page",+ path: "/old-page",+ title: '"Old page"',+ meta: {},+ rootInstanceId: "form",+ },+ rootFragment: fragment,+ bodyFragment: {+ ...fragment,+ instances: [+ { type: "instance", id: "form", component: "Form", children: [] },+ ],+ },+ },+ });++ expect(await handlePastePage(clipboardData, ROOT_FOLDER_ID)).toMatchObject({+ success: false,+ error: expect.stringMatching(/Copy it again/),+ });+ expect(importAssets).not.toHaveBeenCalled();+ expect($pages.get()).toEqual(before);+});+const setRootLocalStyle = ({styleSourceId,value,diff --git a/apps/builder/app/shared/copy-paste/plugin-page.ts b/apps/builder/app/shared/copy-paste/plugin-page.tsindex a23247fa38..ec38e40223 100644--- a/apps/builder/app/shared/copy-paste/plugin-page.ts+++ b/apps/builder/app/shared/copy-paste/plugin-page.ts@@ -422,7 +422,11 @@ export const handlePastePage = async (return pasteIgnored;}if (transferData.valid === false) {- return { success: false, error: invalidPasteDataMessage } as const;+ return {+ success: false,+ error:+ "error" in transferData ? transferData.error : invalidPasteDataMessage,+ } as const;}const { sourceOrigin, assetPaths, ...transferItem } = transferData.data;let item: PageTransferItem = transferItem;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 39d3be3bf3..e2ce45c27a 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@@ -1641,7 +1641,7 @@ test("RichText", async () => {`);});-test("Form", async () => {+test("ResourceForm", async () => {const fragment = await toWebstudioFragment({type: "@webflow/XscpData",payload: {diff --git a/apps/builder/app/shared/instance-utils/fragment.test.tsx b/apps/builder/app/shared/instance-utils/fragment.test.tsxindex 7092a69012..96fc29fa08 100644--- a/apps/builder/app/shared/instance-utils/fragment.test.tsx+++ b/apps/builder/app/shared/instance-utils/fragment.test.tsx@@ -520,7 +520,7 @@ describe("insert webstudio fragment copy", () => {data,fragment: {...emptyFragment,- instances: [createInstance("form", "Form", [])],+ instances: [createInstance("form", "ResourceForm", [])],dataSources: [{id: "scoped-source",diff --git a/apps/builder/app/shared/instance-utils/insert.test.tsx b/apps/builder/app/shared/instance-utils/insert.test.tsxindex fdcac4c384..375f49c40a 100644--- a/apps/builder/app/shared/instance-utils/insert.test.tsx+++ b/apps/builder/app/shared/instance-utils/insert.test.tsx@@ -934,7 +934,7 @@ describe("insert webstudio component at", () => {const body = $instances.get().get("bodyId");const formId =body?.children[0]?.type === "id" ? body.children[0].value : "";- expect($instances.get().get(formId)?.component).toBe("Form");+ expect($instances.get().get(formId)?.component).toBe("ResourceForm");const formProps = Array.from($props.get().values()).filter(({ instanceId }) => instanceId === formId);@@ -1174,7 +1174,7 @@ describe("insert webstudio component at", () => {test("inserts component through runtime template application", async () => {expect(- await insertWebstudioComponentAt("Form", {+ await insertWebstudioComponentAt("ResourceForm", {parentSelector: ["bodyId"],position: "end",})@@ -1187,7 +1187,7 @@ describe("insert webstudio component at", () => {expect(form).toEqual({type: "instance",id: formId,- component: "Form",+ component: "ResourceForm",children: expect.any(Array),});});@@ -1225,7 +1225,7 @@ describe("insert webstudio component at", () => {const notify = vi.spyOn(toast, "error");try {expect(- await insertWebstudioComponentAt("Form", {+ await insertWebstudioComponentAt("ResourceForm", {parentSelector: ["mdx", "block", "bodyId"],position: "end",})diff --git a/apps/builder/app/shared/nano-states/components.test.tsx b/apps/builder/app/shared/nano-states/components.test.tsxindex 6706fece0e..344be1dfdc 100644--- a/apps/builder/app/shared/nano-states/components.test.tsx+++ b/apps/builder/app/shared/nano-states/components.test.tsx@@ -35,7 +35,7 @@ test("renders templates that import an alternate registered implementation", ()expect(template?.instances[0]?.component).toBe("CodeText");});-test("lists the managed Form while retaining deprecated Webhook Form", () => {+test("lists the managed Form while retaining saved Webhook Forms", () => {for (const library of canvasComponentLibraries) {registerComponentLibrary(library);}@@ -53,26 +53,29 @@ test("lists the managed Form while retaining deprecated Webhook Form", () => {expect.objectContaining({name: "form",label: "Form (Beta)",- firstInstance: expect.objectContaining({ component: "Form" }),+ firstInstance: expect.objectContaining({ component: "ResourceForm" }),}),]);- // The legacy template remains in its original category through the next release.+ // New sites use Form while saved Webhook Forms remain registered for rendering.expect(itemsByCategory.get("data")?.some(({ name }) => name === "WebhookForm")- ).toBe(true);+ ).toBe(false);// Saved instances keep their original component IDs and implementations.- expect($registeredComponents.get().has("Form")).toBe(true);- expect($registeredComponents.get().has("ResourceForm")).toBe(false);+ expect($registeredComponents.get().has("ResourceForm")).toBe(true);+ expect($registeredComponents.get().has("Form")).toBe(false);expect($registeredComponents.get().has("WebhookForm")).toBe(true);expect($registeredComponents.get().has("RemixForm")).toBe(true);- expect($registeredComponentMetas.get().get("Form")?.deprecated).toBe(+ expect($registeredComponentMetas.get().get("ResourceForm")?.deprecated).toBe(undefined);expect($registeredComponentMetas.get().get("WebhookForm")?.label).toBe("Webhook Form");+ expect($registeredComponentMetas.get().get("WebhookForm")?.deprecated).toBe(+ true+ );expect($registeredComponentMetas.get().get("RemixForm")?.deprecated).toBe(true);diff --git a/apps/builder/app/shared/nano-states/selection-reveal.test.ts b/apps/builder/app/shared/nano-states/selection-reveal.test.tsindex d2841ce569..bc749ca16c 100644--- a/apps/builder/app/shared/nano-states/selection-reveal.test.ts+++ b/apps/builder/app/shared/nano-states/selection-reveal.test.ts@@ -279,8 +279,8 @@ test("an item outside the nearest owner cannot provide its value", () => {test("hidden selected path uses occurrence keys and invalid paths clear atomically", () => {const instances: Instances = new Map([["page", instance("page", "Body", "left", "right")],- ["left", instance("left", "Form", "feedback")],- ["right", instance("right", "Form", "feedback")],+ ["left", instance("left", "ResourceForm", "feedback")],+ ["right", instance("right", "ResourceForm", "feedback")],["feedback", instance("feedback", "Box")],]);const props = values([@@ -299,7 +299,7 @@ test("hidden selected path uses occurrence keys and invalid paths clear atomicalexpect(resolve(instances, ["feedback", "left", "other-page"], props).size).toBe(0);- instances.set("left", instance("left", "Form"));+ instances.set("left", instance("left", "ResourceForm"));expect(resolve(instances, ["feedback", "left", "page"], props).size).toBe(0);});@@ -475,7 +475,7 @@ test.each([test("resolved hidden feedback changes with selection without editing saved props", () => {const instances: Instances = new Map([["page", instance("page", "Body", "form")],- ["form", instance("form", "Form", "success", "error")],+ ["form", instance("form", "ResourceForm", "success", "error")],["success", instance("success", "Box")],["error", instance("error", "Box")],]);diff --git a/apps/builder/app/shared/sync/patch/patch-auth.server.test.ts b/apps/builder/app/shared/sync/patch/patch-auth.server.test.tsindex c13f3ad079..0ad3fdb302 100644--- a/apps/builder/app/shared/sync/patch/patch-auth.server.test.ts+++ b/apps/builder/app/shared/sync/patch/patch-auth.server.test.ts@@ -78,6 +78,7 @@ import {import type { NormalizedPatchRequest } from "./patch-normalize.server";const buildRow = {+ pages: JSON.stringify({}),instances: JSON.stringify([{ id: "body-1", type: "instance", component: "Body", children: [] },]),diff --git a/apps/builder/app/shared/sync/patch/patch-auth.server.ts b/apps/builder/app/shared/sync/patch/patch-auth.server.tsindex 0b72db8b25..0024da7c11 100644--- a/apps/builder/app/shared/sync/patch/patch-auth.server.ts+++ b/apps/builder/app/shared/sync/patch/patch-auth.server.ts@@ -19,6 +19,8 @@ import {parseStyleSourceSelections,parseStyles,} from "@webstudio-is/project-build/persistence";+import { migrateResourceFormInstancesMutable } from "@webstudio-is/project-migrations";+import { hasHistoricalFormComponentIdentityVersion } from "@webstudio-is/project-migrations/pages";import env from "~/env/env.server";import { readAccessToken } from "~/services/token.server";import { componentMetas } from "~/shared/component-metas.server";@@ -120,6 +122,7 @@ const hasProjectPermit = async ({};export const createContentModeCapabilities = (build: {+ pages: string;instances: string;props: string;styleSources: string;@@ -127,8 +130,13 @@ export const createContentModeCapabilities = (build: {styles: string;breakpoints: string;}) => {+ const instances = parseInstanceData(build.instances);+ migrateResourceFormInstancesMutable(+ instances.values(),+ hasHistoricalFormComponentIdentityVersion(JSON.parse(build.pages))+ );return getContentModeCapabilities({- instances: parseInstanceData(build.instances),+ instances,metas: componentMetas,props: parseData<Prop>(build.props),styleSources: parseData<StyleSource>(build.styleSources),diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.test.ts b/apps/builder/app/shared/sync/patch/patch-service.server.test.tsindex ad7631b3af..07b46b8d66 100644--- a/apps/builder/app/shared/sync/patch/patch-service.server.test.ts+++ b/apps/builder/app/shared/sync/patch/patch-service.server.test.ts@@ -44,6 +44,7 @@ const buildRow = {projectId: "project-1",version: 3,lastTransactionId: null,+ pages: JSON.stringify({}),instances: JSON.stringify([]),props: JSON.stringify([]),styleSources: JSON.stringify([]),@@ -408,6 +409,7 @@ describe("applyPatchRequest", () => {expect(createContentModeCapabilities).toHaveBeenCalledWith({breakpoints: JSON.stringify([]),+ pages: buildRow.pages,instances: JSON.stringify([]),props: JSON.stringify([]),styleSourceSelections: JSON.stringify([]),@@ -416,7 +418,7 @@ describe("applyPatchRequest", () => {});expect(context.selectedColumns).toEqual(["projectId, version",- "instances, props, styleSources, styleSourceSelections, styles, breakpoints",+ "pages, instances, props, styleSources, styleSourceSelections, styles, breakpoints","projectId, version, lastTransactionId, props",]);expect(result).toEqual({diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.ts b/apps/builder/app/shared/sync/patch/patch-service.server.tsindex 5153e18db2..4a40d8a270 100644--- a/apps/builder/app/shared/sync/patch/patch-service.server.ts+++ b/apps/builder/app/shared/sync/patch/patch-service.server.ts@@ -28,6 +28,7 @@ const baseBuildPatchColumns = [] as const satisfies BuildColumn[];const contentModeBuildColumns = [+ "pages","instances","props","styleSources",@@ -37,10 +38,10 @@ const contentModeBuildColumns = [] as const satisfies BuildColumn[];const namespaceBuildColumns = {- pages: ["pages"],+ pages: ["pages", "instances"],projectSettings: ["projectSettings"],breakpoints: ["breakpoints"],- instances: ["instances"],+ instances: ["pages", "instances"],props: ["props"],styleSourceSelections: ["styleSourceSelections"],styleSources: ["styleSources"],@@ -332,6 +333,7 @@ export const applyPatchRequest = async (async () => {const build = await loadBuildForContentMode(context, patch.buildId);return createContentModeCapabilities({+ pages: build.pages,instances: build.instances,props: build.props,styleSources: build.styleSources,diff --git a/apps/builder/e2e/fixtures/mcp-form-callbacks-author.ts b/apps/builder/e2e/fixtures/mcp-form-callbacks-author.tsindex d6027893b1..681ad76027 100644--- a/apps/builder/e2e/fixtures/mcp-form-callbacks-author.ts+++ b/apps/builder/e2e/fixtures/mcp-form-callbacks-author.ts@@ -324,8 +324,8 @@ const author = async () => {const fragment = await call("insert-fragment", {parentInstanceId: home.rootInstanceId,fragment: verifyFieldChange- ? '<Form id="callback-form" /><Text id="callback-audit">Pending callbacks</Text><Text id="callback-error">Pending errors</Text>'- : '<Form id="callback-form"><Input name="outcome" /><Button type="submit">Submit callback form</Button></Form><Text id="callback-audit">Pending callbacks</Text><Text id="callback-error">Pending errors</Text>',+ ? '<ResourceForm id="callback-form" /><Text id="callback-audit">Pending callbacks</Text><Text id="callback-error">Pending errors</Text>'+ : '<ResourceForm id="callback-form"><Input name="outcome" /><Button type="submit">Submit callback form</Button></ResourceForm><Text id="callback-audit">Pending callbacks</Text><Text id="callback-error">Pending errors</Text>',});[formId, auditId, errorId] = fragment.rootInstanceIds as string[];if (verifyFieldChange) {diff --git a/apps/builder/e2e/flows/generated-app.ts b/apps/builder/e2e/flows/generated-app.tsindex 4bf114e13e..b990788400 100644--- a/apps/builder/e2e/flows/generated-app.ts+++ b/apps/builder/e2e/flows/generated-app.ts@@ -182,9 +182,11 @@ export const expectGeneratedAppBuild = async ({export const withGeneratedPreview = async <Result>({projectId,callback,+ evaluationReceiverPort,}: {projectId: string;callback: ({ url, html }: { url: string; html: string }) => Promise<Result>;+ evaluationReceiverPort?: string;}) => {const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));let preview: ChildProcess | undefined;@@ -218,7 +220,15 @@ export const withGeneratedPreview = async <Result>({cwd: tempDir,detached: process.platform !== "win32",stdio: ["ignore", "pipe", "pipe"],- env: { ...process.env, PWD: tempDir },+ env: {+ ...process.env,+ PWD: tempDir,+ ...(evaluationReceiverPort === undefined+ ? {}+ : {+ WEBSTUDIO_FORM_EVALUATION_RECEIVER_PORT: evaluationReceiverPort,+ }),+ },});const appendOutput = (chunk: unknown) => {diff --git a/apps/builder/e2e/tests/mcp-form-callbacks.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/mcp-form-callbacks.[shard-2].[shard-5].[shard-6].e2e.tsindex 10967621f1..a6078d0963 100644--- a/apps/builder/e2e/tests/mcp-form-callbacks.[shard-2].[shard-5].[shard-6].e2e.ts+++ b/apps/builder/e2e/tests/mcp-form-callbacks.[shard-2].[shard-5].[shard-6].e2e.ts@@ -42,7 +42,7 @@ for (const mode of ["legacy", "managed"] as const) {),fixture.projectId,mode,- receiver.url,+ "https://mcp-delivery.example/submit",],{timeout: 60_000,@@ -140,11 +140,16 @@ for (const mode of ["legacy", "managed"] as const) {expect(receiver.deliveries).toEqual([{ outcome: "success" },{ outcome: "failure" },+ { outcome: "failure" },{ outcome: "success" },]);};if (mode === "legacy") {- await withGeneratedPreview({ projectId: fixture.projectId, callback });+ await withGeneratedPreview({+ projectId: fixture.projectId,+ evaluationReceiverPort: String(receiver.port),+ callback,+ });} else {await withGeneratedFormDeliveryPreview({projectId: fixture.projectId,diff --git a/apps/builder/e2e/tests/mcp-legacy-form-query.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/mcp-legacy-form-query.[shard-2].[shard-5].[shard-6].e2e.tsindex 9bac921811..97b70b25df 100644--- a/apps/builder/e2e/tests/mcp-legacy-form-query.[shard-2].[shard-5].[shard-6].e2e.ts+++ b/apps/builder/e2e/tests/mcp-legacy-form-query.[shard-2].[shard-5].[shard-6].e2e.ts@@ -10,7 +10,7 @@ import { test } from "../test";const execFileAsync = promisify(execFile);-test("MCP-edited saved legacy Webhook Form preserves single and repeated query bindings through navigation and submission", async ({+test("MCP-edited saved deprecated Webhook Form preserves single and repeated query bindings through navigation and submission", async ({page,context,}) => {@@ -42,7 +42,7 @@ test("MCP-edited saved legacy Webhook Form preserves single and repeated query b)),fixture.projectId,- receiver.url,+ "https://mcp-delivery.example/submit",],{timeout: 60_000,@@ -59,6 +59,7 @@ test("MCP-edited saved legacy Webhook Form preserves single and repeated query b);await withGeneratedPreview({projectId: fixture.projectId,+ evaluationReceiverPort: new URL(receiver.url).port,callback: async ({ url }) => {await page.route("**/*", (route) =>new URL(route.request().url()).hostname === "127.0.0.1"diff --git a/apps/builder/e2e/tests/mcp-legacy-form-route.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/mcp-legacy-form-route.[shard-2].[shard-5].[shard-6].e2e.tsindex df7b6775eb..68cf2a2679 100644--- a/apps/builder/e2e/tests/mcp-legacy-form-route.[shard-2].[shard-5].[shard-6].e2e.ts+++ b/apps/builder/e2e/tests/mcp-legacy-form-route.[shard-2].[shard-5].[shard-6].e2e.ts@@ -10,7 +10,7 @@ import { test } from "../test";const execFileAsync = promisify(execFile);-test("MCP-edited saved legacy Webhook Form action uses current dynamic route params in generated Preview", async ({+test("MCP-edited saved deprecated Webhook Form action uses current dynamic route params in generated Preview", async ({page,context,}) => {@@ -42,7 +42,7 @@ test("MCP-edited saved legacy Webhook Form action uses current dynamic route par)),fixture.projectId,- receiver.url,+ "https://mcp-delivery.example/submit",],{timeout: 60_000,@@ -59,6 +59,7 @@ test("MCP-edited saved legacy Webhook Form action uses current dynamic route par);await withGeneratedPreview({projectId: fixture.projectId,+ evaluationReceiverPort: new URL(receiver.url).port,callback: async ({ url }) => {await page.route("**/*", (route) =>new URL(route.request().url()).hostname === "127.0.0.1"diff --git a/apps/builder/e2e/tests/preview-managed-form.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/preview-managed-form.[shard-2].[shard-5].[shard-6].e2e.tsindex ab75c8e071..ffd67c4f9c 100644--- a/apps/builder/e2e/tests/preview-managed-form.[shard-2].[shard-5].[shard-6].e2e.ts+++ b/apps/builder/e2e/tests/preview-managed-form.[shard-2].[shard-5].[shard-6].e2e.ts@@ -36,7 +36,7 @@ test("Preview Form posts to the authenticated Builder and sets error state witho{type: "instance",id: formId,- component: "Form",+ component: "ResourceForm",children: [inputId, buttonId].map((value) => ({ type: "id", value })),},{@@ -199,7 +199,7 @@ test("Preview Form success redirects navigate matched pages and keep feedback fo{type: "instance",id: formId,- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: buttonId }],},{@@ -403,7 +403,7 @@ test("Preview Form preserves browser FormData and runs legacy disabled actions i{type: "instance",id: formId,- component: "Form",+ component: "ResourceForm",children: [firstInputId,secondInputId,@@ -721,7 +721,7 @@ test("Preview Form with no Actions navigates query values without a Resource POS{type: "instance",id: formId,- component: "Form",+ component: "ResourceForm",children: [firstInputId, secondInputId, buttonId].map((value) => ({type: "id",value,diff --git a/apps/builder/e2e/tests/props-runtime.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/props-runtime.[shard-2].[shard-5].[shard-6].e2e.tsindex d42a5988ee..c1b92af5d8 100644--- a/apps/builder/e2e/tests/props-runtime.[shard-2].[shard-5].[shard-6].e2e.ts+++ b/apps/builder/e2e/tests/props-runtime.[shard-2].[shard-5].[shard-6].e2e.ts@@ -630,7 +630,7 @@ test("Webhook Form action submits once and persists after reload", async ({});const webhook = await startWebhookServer();const text = "Initial content";- const actionUrl = webhook.url;+ const actionUrl = "https://mcp-delivery.example/submit";try {await seedSavedWebhookForm(fixture.projectId);@@ -670,6 +670,7 @@ test("Webhook Form action submits once and persists after reload", async ({await measure("props runtime submit generated webhook form", async () => {await withGeneratedPreview({projectId: fixture.projectId,+ evaluationReceiverPort: new URL(webhook.url).port,callback: async ({ url }) => {await page.goto(url);if (webhook.requests.length !== 0) {diff --git a/docs/SUMMARY.md b/docs/SUMMARY.mdindex 759ca3a214..24d41620fe 100644--- a/docs/SUMMARY.md+++ b/docs/SUMMARY.md@@ -66,7 +66,7 @@* [⚠️ Alert](university/core-components/alert.md)* [📄 Code Text](university/core-components/code-text.md)* [✍️ Form](university/core-components/form.md)- * [✍️ Webhook Form](university/core-components/webhook-form.md)+ * [✍️ Webhook Form (deprecated)](university/core-components/webhook-form.md)* [🔘 Button](university/core-components/button.md)* [🏷️ Label](university/core-components/label.md)* [📝 Input](university/core-components/input.md)@@ -137,14 +137,14 @@* [🔗 Integrations](university/integrations/README.md)* [How to build a frontend for Supabase using Webstudio](university/integrations/supabase.md)* [How to build a frontend for Airtable using Webstudio](university/integrations/airtable-frontend.md)- * [How to integrate a Webhook Form with Airtable](university/integrations/airtable-form-webhook.md)+ * [How to integrate a Webhook Form with Airtable (deprecated)](university/integrations/airtable-form-webhook.md)* [How to build a frontend for Baserow using Webstudio](university/integrations/baserow.md)* [How to build a frontend for Hygraph using Webstudio](university/integrations/hygraph.md)* [How to build a WordPress frontend using Webstudio (no-code builder)](university/integrations/wordpress.md)* [How to integrate a Notion database with Webstudio](university/integrations/notion.md)- * [How to integrate Webhook Form with Pabbly](university/integrations/pabbly.md)- * [How to integrate Webhook Form with Zapier](university/integrations/zapier.md)- * [How to integrate Webhook Form with N8N](university/integrations/n8n.md)+ * [How to integrate Webhook Form with Pabbly (deprecated)](university/integrations/pabbly.md)+ * [How to integrate Webhook Form with Zapier (deprecated)](university/integrations/zapier.md)+ * [How to integrate Webhook Form with N8N (deprecated)](university/integrations/n8n.md)* [How to integrate Flotiq with Webstudio](university/integrations/flotiq.md)* [Craft](university/craft.md)* [Use Craft](university/craft-guide.md)diff --git a/docs/university/core-components/README.md b/docs/university/core-components/README.mdindex aec19df94f..2245272a75 100644--- a/docs/university/core-components/README.md+++ b/docs/university/core-components/README.md@@ -79,7 +79,7 @@{% endcontent-ref %}{% content-ref url="webhook-form.md" %}-[webhook-form.md](webhook-form.md)+[Webhook Form (deprecated)](webhook-form.md){% endcontent-ref %}{% content-ref url="input.md" %}diff --git a/docs/university/core-components/button.md b/docs/university/core-components/button.mdindex 0bc6e4e270..dedb85f9bc 100644--- a/docs/university/core-components/button.md+++ b/docs/university/core-components/button.md@@ -43,7 +43,7 @@ Some commonly used properties (see the Settings panel for all available options)### Submit Button-Submits the parent form when clicked. Use inside [Form](form.md) or [Webhook Form](webhook-form.md).+Submits the parent form when clicked. Use inside [Form](form.md), or inside an existing [deprecated Webhook Form](webhook-form.md).### Reset Buttondiff --git a/docs/university/core-components/form.md b/docs/university/core-components/form.mdindex 25f03ba623..7ab14d804e 100644--- a/docs/university/core-components/form.md+++ b/docs/university/core-components/form.md@@ -23,21 +23,21 @@ For a selected email resource that sends to project or custom recipients, an unsIn a resource created inside the Form, add these headers in the resource editor when your destination needs them:-| Header | Value expression |-| --- | --- |-| `X-Forwarded-For` | `browserInfo.ip` |-| `User-Agent` | `browserInfo.userAgent` |-| `Accept-Language` | `browserInfo.language` |+| Header | Value expression |+| ----------------- | ----------------------- |+| `X-Forwarded-For` | `browserInfo.ip` |+| `User-Agent` | `browserInfo.userAgent` |+| `Accept-Language` | `browserInfo.language` |These values are sent only when you configure the headers. `browserInfo` also provides `referrer`. It does not expose cookies, authorization, or raw request headers. On Cloudflare Workers, `browserInfo.ip` comes from Cloudflare's `CF-Connecting-IP` request header. The generated React Router Cloudflare Worker supplies the Cloudflare hosting context; the Remix Cloudflare adapter also supplies it. On Node-based hosts, including the generated Docker, Netlify, and Vercel adapters, no trusted visitor-IP source is configured, so `browserInfo.ip` is absent. The Form does not derive it from visitor-supplied `X-Forwarded-For` or `X-Real-IP` headers. If an IP header is required on another host, configure a trusted source at the hosting boundary before relying on it.On a published Webstudio Cloud site, an email resource sends through Webstudio's private Cloudflare email service when the `EMAIL_SERVICE` binding is configured. Set project recipients and Reply to in [project settings](../foundations/project-settings.md#emails); set subject and body on the email resource. The resource Reply to override is empty by default. The server rejects a submission if an email resource cannot send because the binding is missing. Other hosts need their own server-side email integration; a static export cannot send managed Form email. [Existing Webhook Forms](webhook-form.md) keep their separate behavior.-Each email from a Form submission includes an `X-Message-ID` header. Email actions from the same submission share the header value, and a retry keeps it. The configured subject stays unchanged.+Each email from a Form submission includes an `X-Message-ID` header. Email actions from the same submission share the header value. The configured subject stays unchanged. Email actions are sent once and are not retried after dispatch.The **Visitor** email resource in a newly inserted Form uses its named `email` input. To configure another Form manually, add an email resource in **Variables**, select **Visitor** as its recipient, choose one named email input, and add that resource to the Form's Action. The server requires exactly one valid address in the chosen field. A fixed preamble says the request came from the website and includes its URL. The resource body starts empty; you can add plain text and bindings after the preamble. When a Form includes file inputs, submitted files are attached to the outgoing email resource message by default. Turn off ‘Attach submitted files’ to omit them. It runs alongside other actions; a delivery error appears in `errors` without making the overall Form submission fail. It requires Webstudio Cloud email service configuration.-A Form can send up to **five team-recipient deliveries** across all of its email resources. Duplicate addresses count as separate deliveries; one visitor-addressed email resource is allowed in addition. The server checks this total before running any destination. Webstudio Cloud also limits email to **50 recipient deliveries per project, per Cloudflare location, in a rolling 60-second window**. A rate-limited primary email resource fails before delivery and makes the Form show its error state; a visitor-addressed email resource failure remains nonfatal. Other parallel destinations may still finish.+A Form can send up to **five team-recipient deliveries** across all of its email resources. Duplicate addresses count as separate deliveries; one visitor-addressed email resource is allowed in addition. The server checks this total before running any destination. Webstudio Cloud also applies an approximate limit of **50 recipient deliveries per project, per Cloudflare location, per minute**; Preview and published sites use separate project keys. Cloudflare's account-level daily sending quota can be lower and varies by account. A rate-limited primary email resource fails before delivery and makes the Form show its error state; a visitor-addressed email resource failure remains nonfatal. Other parallel destinations may still finish.## Inputs and responses@@ -45,11 +45,13 @@ Add inputs from **Components > Forms**. Each value you want to send needs a **NaFor uploads, add **File Input** and set **Name**, **Required**, **Accept**, and **Multiple** in Settings. **Accept** guides the browser's file picker; it does not validate file types on the server. A required empty file input blocks submission. An optional empty file input submits without a file.-The entire managed Form request is limited to **25 MiB**, including all selected files, other fields, and multipart encoding. This is a combined limit, not an allowance for each file: selecting multiple files can exceed it even when each file is smaller than 25 MiB. If the request is too large, the server rejects it before sending to any resource and the Form reports `Form submission is too large`. Reduce the number or size of files and submit again. Outbound HTTP resource request bodies have a separate 25 MiB limit, and the receiving service may impose a lower limit. Cloud email resources have additional limits of 32 attachments, 5 MiB of encoded email content, and a 7 MiB service request. The server checks these limits before sending to any selected destination.+The entire managed Form request is limited to **25 MiB**, including all selected files, other fields, and multipart encoding. This is a combined limit, not an allowance for each file. If the request is too large, the server rejects it before sending to any resource and reports `Form submission exceeds the 25 MiB limit. Reduce file sizes and try again.` Outbound HTTP resource request bodies have a separate 25 MiB limit, and the receiving service may impose a lower limit.-Cloud email can also fail because the provider rejects a recipient or Reply to address, suppresses a recipient, reaches an account sending limit, or is temporarily unavailable. The Form reports the resulting resource error and does not claim successful owner delivery. A timeout may leave delivery uncertain; its single retry can produce a duplicate email with the same `X-Message-ID` header.+When files are attached to an email, the server checks for at most **32 attachments** and no more than **7 MiB of aggregate Base64 attachment data** before starting the selected destinations. The private email Worker separately caps its complete serialized JSON request at **7 MiB**, including email text and Base64 files. Cloudflare measures the final email, including MIME encoding, against its **5 MiB general limit**; **25 MiB** applies only to verified destination addresses. The Worker does not calculate final MIME size before sending, so Cloudflare can reject a message after other selected destinations have started. See [Cloudflare Email Service limits](https://developers.cloudflare.com/email-service/platform/limits/) and [Workers binding error codes](https://developers.cloudflare.com/email-service/api/send-emails/workers-api/#error-codes).-The inserted Form has **Form content**, **Success message**, and **Error message** sections. When every primary destination succeeds, the success state appears; otherwise the error state appears. A failed visitor-addressed email resource is reported in `errors` but does not change the overall success state. The Form exposes `formState` (the current Form state: initial, success, or error), `results` (responses from selected actions, in order, including each resource's HTTP status code and response body), and `errors` (failed actions in order, including each resource's HTTP status code, response body, and message). A configured **Success redirect** runs only after overall success. Without a redirect, successful submissions refresh the current page's resources without a full-page reload or a second submission.+Cloud email can also fail because the provider rejects a recipient or Reply to address, suppresses a recipient, reaches an account sending limit, or is temporarily unavailable. The Form reports the resulting resource error and does not claim successful owner delivery. A timeout can leave delivery uncertain; the Form does not retry an email because another send could create a duplicate.++The inserted Form has **Form content**, **Success message**, and **Error message** sections. When every primary destination succeeds, the success state appears; otherwise the error state appears. A failed visitor-addressed email resource is reported in `errors` but does not change the overall success state. The Form exposes `formState` (the current Form state: initial, success, or error), `results` (responses from selected actions, in order, including each resource's HTTP status code and response body), and `errors` (failed actions in order, including each resource's HTTP status code, response body, message, and an error code for managed email when available). A configured **Success redirect** runs only after overall success. Without a redirect, successful submissions refresh the current page's resources without a full-page reload or a second submission.## Hosting and plain HTML forms@@ -61,5 +63,5 @@ For ordinary browser form behavior, add **Element**, set its tag to `form`, and- [Input](input.md) – Name fields and choose input types- [Element](element.md) – Use native HTML form behavior-- [Webhook Form](webhook-form.md) – Configure an existing legacy form+- [Webhook Form](webhook-form.md) – Configure an existing deprecated form- [Self-Hosting](../self-hosting/README.md) – Choose a dynamic or static exportdiff --git a/docs/university/core-components/input.md b/docs/university/core-components/input.mdindex 84458f33f4..4744316ac2 100644--- a/docs/university/core-components/input.md+++ b/docs/university/core-components/input.md@@ -46,7 +46,7 @@ Input is a fundamental form control used to collect various types of user data i## Form Usage-Inputs should be placed within a [Form](form.md) or [Webhook Form](webhook-form.md):+Place inputs within a [Form](form.md). Existing projects can also keep inputs within a [deprecated Webhook Form](webhook-form.md):```Form@@ -137,7 +137,7 @@ Common `autocomplete` values:## Related Components- [Form](form.md) - Form container-- [Webhook Form](webhook-form.md) - Form with webhook submission+- [Webhook Form](webhook-form.md) - Deprecated form for existing webhook submissions- [Label](label.md) - Input labels- [Textarea](textarea.md) - Multi-line text input- [Select](select.md) - Dropdown selectiondiff --git a/docs/university/core-components/webhook-form.md b/docs/university/core-components/webhook-form.mdindex 7f18f8dd06..a1d48db531 100644--- a/docs/university/core-components/webhook-form.md+++ b/docs/university/core-components/webhook-form.md@@ -1,6 +1,6 @@---description: >-- Webhook Forms enable form submissions to get sent to an email address and+ Deprecated. Existing Webhook Forms send submissions to an email address oroptionally third-party services like Airtable, n8n, or Zapier.---diff --git a/docs/university/foundations/project-settings.md b/docs/university/foundations/project-settings.mdindex 18e8cf37eb..392115b4a8 100644--- a/docs/university/foundations/project-settings.md+++ b/docs/university/foundations/project-settings.md@@ -30,7 +30,7 @@ Each email from a Form submission includes an `X-Message-ID` header. Email actioAn email resource without a custom body includes submitted Form fields and browser information by default when used on a Form. The automatic text includes submitted hidden fields, but excludes password inputs and Webstudio's internal bot fields. Set the resource body to customize the message, including an explicitly empty body. To use `formData` or `browserInfo` in a resource expression, define the resource on the Form; resources on an ancestor or global root cannot bind that Form's data.-Email resources inherit project recipients and Reply to unless overridden. Republish to update the settings included in a published site. On Webstudio Cloud, published email resources use the private Cloudflare email service when the `EMAIL_SERVICE` binding is configured. Saving settings or publishing does not itself send email; a visitor must submit the Form. Delivery fails explicitly if the service is unavailable. Self-hosted sites need a custom server-side email integration. The existing Contact email recipient setting continues to serve legacy Webhook Forms.+Email resources inherit project recipients and Reply to unless overridden. Republish to update the settings included in a published site. On Webstudio Cloud, published email resources use the private Cloudflare email service when the `EMAIL_SERVICE` binding is configured. Saving settings or publishing does not itself send email; a visitor must submit the Form. Delivery fails explicitly if the service is unavailable. Self-hosted sites need a custom server-side email integration. The existing Contact email recipient setting continues to serve deprecated Webhook Forms.## Publishingdiff --git a/docs/university/integrations/airtable-form-webhook.md b/docs/university/integrations/airtable-form-webhook.mdindex e51f8dde0a..d7a7b3384a 100644--- a/docs/university/integrations/airtable-form-webhook.md+++ b/docs/university/integrations/airtable-form-webhook.md@@ -6,6 +6,10 @@ description: >-# How to integrate a Webhook Form with Airtable+{% hint style="info" %}+**Deprecated:** This guide uses the [Webhook Form](../core-components/webhook-form.md). Use [Form](../core-components/form.md) for new forms.+{% endhint %}+{% embed url="https://www.youtube.com/watch?v=xYJFh_u-8Tc" %}Out of the box, Webstudio automatically sends form data to the site owner’s registered email, effectively creating singular records. To expand this functionality, we can seamlessly integrate it with a relational database like Airtable. This will centralize, access, and analyze all your form submission data in one place, making data management a breeze and enabling efficient team collaboration.diff --git a/docs/university/integrations/airtable-frontend.md b/docs/university/integrations/airtable-frontend.mdindex 524653fe69..35a4f42fad 100644--- a/docs/university/integrations/airtable-frontend.md+++ b/docs/university/integrations/airtable-frontend.md@@ -217,7 +217,7 @@ The flexibility of Resources enables you to fetch exactly what you need from one- [Using filters to dynamically display Airtable content](../how-tos/using-filters-to-dynamically-display-content.md)- [Building dynamic pages for Airtable data](https://youtu.be/3mW7cPDXIxY)-- [Using Webstudio Webhook form to send data to an Airtable automation (doc)](airtable-form-webhook.md)+- [Using the deprecated Webhook Form to send data to an Airtable automation (doc)](airtable-form-webhook.md)- [Airtable filters API (doc)](https://support.airtable.com/docs/airtable-web-api-using-filterbyformula-or-sort-parameters)## Relateddiff --git a/docs/university/integrations/n8n.md b/docs/university/integrations/n8n.mdindex 163c6e2623..7a33890b94 100644--- a/docs/university/integrations/n8n.md+++ b/docs/university/integrations/n8n.md@@ -4,6 +4,10 @@ description: Connect Webstudio forms to n8n for workflow automation.# How to integrate Webhook Form with N8N+{% hint style="info" %}+**Deprecated:** This guide uses the [Webhook Form](../core-components/webhook-form.md). Use [Form](../core-components/form.md) for new forms.+{% endhint %}+This guide shows you how to link Webstudio Forms with [n8n](https://n8n.io/) for workflow automation. We will move data from Webstudio to n8n, save it in a Supabase table, and then ping a Slack channel when certain conditions are met.{% embed url="https://www.youtube.com/watch?v=zeJVpfemwj0" %}diff --git a/docs/university/integrations/pabbly.md b/docs/university/integrations/pabbly.mdindex da2372d724..0b2a245277 100644--- a/docs/university/integrations/pabbly.md+++ b/docs/university/integrations/pabbly.md@@ -4,6 +4,10 @@ description: Connect Webstudio forms to Pabbly Connect for automation.# How to integrate Webhook Form with Pabbly+{% hint style="info" %}+**Deprecated:** This guide uses the [Webhook Form](../core-components/webhook-form.md). Use [Form](../core-components/form.md) for new forms.+{% endhint %}+{% embed url="https://youtu.be/gKNsyYKxuDA" %}How to integrate Webstudio with Pabbly{% endembed %}diff --git a/docs/university/integrations/zapier.md b/docs/university/integrations/zapier.mdindex c6bac7a8dc..7b79886e75 100644--- a/docs/university/integrations/zapier.md+++ b/docs/university/integrations/zapier.md@@ -4,6 +4,10 @@ description: Connect Webstudio forms to Zapier for workflow automation.# How to integrate Webhook Form with Zapier+{% hint style="info" %}+**Deprecated:** This guide uses the [Webhook Form](../core-components/webhook-form.md). Use [Form](../core-components/form.md) for new forms.+{% endhint %}+{% embed url="https://youtu.be/FDm4mz5FBD8" %}How to integrate Webstudio with Zapier{% endembed %}diff --git a/docs/university/mcp.md b/docs/university/mcp.mdindex 9304132ae5..36f8ba2d92 100644--- a/docs/university/mcp.md+++ b/docs/university/mcp.md@@ -70,8 +70,9 @@ the saved Form instance ID and page path. The server uses this project'spublisher origin. It can trigger the Form's configured HTTP and Email Resources, so verifyevery destination and recipient first. For dynamic checkbox or multiple-select fields,pass `arrayNames` to preserve an empty or single-value array when the saved-field props do not identify the control. The result reports destination statuses-and errors without Resource bodies. This server simulation does not exercise+field props do not identify the control. The result reports destination IDs,+statuses, and errors without Resource bodies. Managed Email errors include a+code when available. This server simulation does not exerciseclient validation, browser event handlers, navigation, file bytes, or actualbrowser information. The Builder server loads the saved draft and holds theEmail service credentials; the CLI does not receive those credentials.diff --git a/docs/university/self-hosting/README.md b/docs/university/self-hosting/README.mdindex b00182ff0c..aaba1daae6 100644--- a/docs/university/self-hosting/README.md+++ b/docs/university/self-hosting/README.md@@ -139,7 +139,7 @@ If you want the export to contain human-readable class names, disable atomic CSSThis is the default behavior if you were to publish to Webstudio Cloud.-The JavaScript application supports dynamic functionality like [CMS integrations](../foundations/cms.md), [Forms](../core-components/form.md) with HTTP Resource actions, Webhook Forms, [image optimization](../core-components/image.md#optimize), and redirects.+The JavaScript application supports dynamic functionality like [CMS integrations](../foundations/cms.md), [Forms](../core-components/form.md) with HTTP Resource actions, existing [deprecated Webhook Forms](../core-components/webhook-form.md), [image optimization](../core-components/image.md#optimize), and redirects.JavaScript applications require a hosting environment that handles server-side code execution, fetching data from CMS integrations, and more.@@ -207,7 +207,7 @@ While static site exporting and hosting are less technical, this comes at the co* Redirects* Statuses* Client navigation-* Webhook form+* Webhook Form (deprecated)* Form submission to Resource actions* Image optimization* No robots.txtdiff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.jsonindex bf69abdee2..8486b77227 100644--- a/fixtures/react-router-cloudflare/.webstudio/data.json+++ b/fixtures/react-router-cloudflare/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-17o6sch",+ "bundleVersion": "bundle-1sh9iaz","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsxindex dd50bcc1a9..ca28d4f895 100644--- a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsxindex 5dfc8c9b48..d110c5ba0a 100644--- a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/react-router-cloudflare/app/extension.ts b/fixtures/react-router-cloudflare/app/extension.tsindex b807c76536..3545f72720 100644--- a/fixtures/react-router-cloudflare/app/extension.ts+++ b/fixtures/react-router-cloudflare/app/extension.ts@@ -1,14 +1,8 @@-import type { ResourceRequest } from "@webstudio-is/sdk";+import "react-router";declare module "react-router" {interface AppLoadContext {EXCLUDE_FROM_SEARCH: boolean;WEBSTUDIO_AUTOMATION_TOKEN?: string;- getDefaultActionResource?: (options: {- url: URL;- projectId: string;- contactEmail: string;- formData: FormData;- }) => ResourceRequest;}}diff --git a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsxindex 38a9ab0b52..33082a08a6 100644--- a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/react-router-cloudflare/app/routes/_index.tsx b/fixtures/react-router-cloudflare/app/routes/_index.tsxindex 42e5f97bbc..840dca4f76 100644--- a/fixtures/react-router-cloudflare/app/routes/_index.tsx+++ b/fixtures/react-router-cloudflare/app/routes/_index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/react-router-cloudflare/workers/app.ts b/fixtures/react-router-cloudflare/workers/app.tsindex 6d6f866722..45e3c89694 100644--- a/fixtures/react-router-cloudflare/workers/app.ts+++ b/fixtures/react-router-cloudflare/workers/app.ts@@ -19,7 +19,6 @@ export default {async fetch(request, env, ctx) {return requestHandler(request, {EXCLUDE_FROM_SEARCH: false,- getDefaultActionResource: undefined,cloudflare: { env, ctx },});},diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.jsonindex bf69abdee2..8486b77227 100644--- a/fixtures/react-router-docker/.webstudio/data.json+++ b/fixtures/react-router-docker/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-17o6sch",+ "bundleVersion": "bundle-1sh9iaz","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsxindex dd50bcc1a9..ca28d4f895 100644--- a/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/react-router-docker/app/__generated__/_index.server.tsx b/fixtures/react-router-docker/app/__generated__/_index.server.tsxindex 5dfc8c9b48..d110c5ba0a 100644--- a/fixtures/react-router-docker/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-docker/app/__generated__/_index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/react-router-docker/app/extension.ts b/fixtures/react-router-docker/app/extension.tsindex b807c76536..3545f72720 100644--- a/fixtures/react-router-docker/app/extension.ts+++ b/fixtures/react-router-docker/app/extension.ts@@ -1,14 +1,8 @@-import type { ResourceRequest } from "@webstudio-is/sdk";+import "react-router";declare module "react-router" {interface AppLoadContext {EXCLUDE_FROM_SEARCH: boolean;WEBSTUDIO_AUTOMATION_TOKEN?: string;- getDefaultActionResource?: (options: {- url: URL;- projectId: string;- contactEmail: string;- formData: FormData;- }) => ResourceRequest;}}diff --git a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx b/fixtures/react-router-docker/app/routes/[another-page]._index.tsxindex 38a9ab0b52..33082a08a6 100644--- a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/react-router-docker/app/routes/_index.tsx b/fixtures/react-router-docker/app/routes/_index.tsxindex 42e5f97bbc..840dca4f76 100644--- a/fixtures/react-router-docker/app/routes/_index.tsx+++ b/fixtures/react-router-docker/app/routes/_index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.jsonindex bf69abdee2..8486b77227 100644--- a/fixtures/react-router-netlify/.webstudio/data.json+++ b/fixtures/react-router-netlify/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-17o6sch",+ "bundleVersion": "bundle-1sh9iaz","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsxindex dd50bcc1a9..ca28d4f895 100644--- a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx b/fixtures/react-router-netlify/app/__generated__/_index.server.tsxindex 5dfc8c9b48..d110c5ba0a 100644--- a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-netlify/app/__generated__/_index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/react-router-netlify/app/extension.ts b/fixtures/react-router-netlify/app/extension.tsindex b807c76536..3545f72720 100644--- a/fixtures/react-router-netlify/app/extension.ts+++ b/fixtures/react-router-netlify/app/extension.ts@@ -1,14 +1,8 @@-import type { ResourceRequest } from "@webstudio-is/sdk";+import "react-router";declare module "react-router" {interface AppLoadContext {EXCLUDE_FROM_SEARCH: boolean;WEBSTUDIO_AUTOMATION_TOKEN?: string;- getDefaultActionResource?: (options: {- url: URL;- projectId: string;- contactEmail: string;- formData: FormData;- }) => ResourceRequest;}}diff --git a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsxindex 38a9ab0b52..33082a08a6 100644--- a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/react-router-netlify/app/routes/_index.tsx b/fixtures/react-router-netlify/app/routes/_index.tsxindex 42e5f97bbc..840dca4f76 100644--- a/fixtures/react-router-netlify/app/routes/_index.tsx+++ b/fixtures/react-router-netlify/app/routes/_index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.jsonindex bf69abdee2..8486b77227 100644--- a/fixtures/react-router-vercel/.webstudio/data.json+++ b/fixtures/react-router-vercel/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-17o6sch",+ "bundleVersion": "bundle-1sh9iaz","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsxindex dd50bcc1a9..ca28d4f895 100644--- a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx b/fixtures/react-router-vercel/app/__generated__/_index.server.tsxindex 5dfc8c9b48..d110c5ba0a 100644--- a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-vercel/app/__generated__/_index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/react-router-vercel/app/extension.ts b/fixtures/react-router-vercel/app/extension.tsindex b807c76536..3545f72720 100644--- a/fixtures/react-router-vercel/app/extension.ts+++ b/fixtures/react-router-vercel/app/extension.ts@@ -1,14 +1,8 @@-import type { ResourceRequest } from "@webstudio-is/sdk";+import "react-router";declare module "react-router" {interface AppLoadContext {EXCLUDE_FROM_SEARCH: boolean;WEBSTUDIO_AUTOMATION_TOKEN?: string;- getDefaultActionResource?: (options: {- url: URL;- projectId: string;- contactEmail: string;- formData: FormData;- }) => ResourceRequest;}}diff --git a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsxindex 38a9ab0b52..33082a08a6 100644--- a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/react-router-vercel/app/routes/_index.tsx b/fixtures/react-router-vercel/app/routes/_index.tsxindex 42e5f97bbc..840dca4f76 100644--- a/fixtures/react-router-vercel/app/routes/_index.tsx+++ b/fixtures/react-router-vercel/app/routes/_index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.jsonindex 1cec7137aa..5ca691094d 100644--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-17o6sch",+ "bundleVersion": "bundle-1sh9iaz","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsxindex dd50bcc1a9..ca28d4f895 100644--- a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsxindex 5dfc8c9b48..d110c5ba0a 100644--- a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.jsonindex 2e50bc929c..478eccbff2 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-17o6sch",+ "bundleVersion": "bundle-1sh9iaz","build": {"id": "823cc69d-b2ed-418b-823c-2efc717319cd","projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsxindex fe8b4ba1ef..bc466b0cd5 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = undefined;\ No newline at end of filediff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsxindex 4548293c0a..e356a9bd60 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = undefined;\ No newline at end of filediff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.jsonindex 1cec7137aa..5ca691094d 100644--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-17o6sch",+ "bundleVersion": "bundle-1sh9iaz","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsxindex dd50bcc1a9..ca28d4f895 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsxindex 5dfc8c9b48..d110c5ba0a 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-cloudflare-template/app/extension.ts b/fixtures/webstudio-cloudflare-template/app/extension.tsindex 8e885b92f7..c42becab9a 100644--- a/fixtures/webstudio-cloudflare-template/app/extension.ts+++ b/fixtures/webstudio-cloudflare-template/app/extension.ts@@ -1,16 +1,9 @@// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignoreimport { AppLoadContext } from "@remix-run/server-runtime";-import type { ResourceRequest } from "@webstudio-is/sdk";declare module "@remix-run/server-runtime" {interface AppLoadContext {EXCLUDE_FROM_SEARCH: boolean;- getDefaultActionResource?: (options: {- url: URL;- projectId: string;- contactEmail: string;- formData: FormData;- }) => ResourceRequest;}}diff --git a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsxindex 26fca85b4f..3d8c4b3a46 100644--- a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx@@ -13,13 +13,12 @@ import { useLoaderData } from "@remix-run/react";import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,cachedFetch,getSystemSearch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateRequest } from "@webstudio-is/wsauth";import {@@ -291,9 +289,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -306,15 +302,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -336,88 +333,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsxindex 891a27bdfc..8da265f3ed 100644--- a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx@@ -13,13 +13,12 @@ import { useLoaderData } from "@remix-run/react";import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,cachedFetch,getSystemSearch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateRequest } from "@webstudio-is/wsauth";import {@@ -291,9 +289,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -306,15 +302,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -336,88 +333,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.jsonindex 4a09a7e121..4acb973775 100644--- a/fixtures/webstudio-features/.webstudio/data.json+++ b/fixtures/webstudio-features/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-17o6sch",+ "bundleVersion": "bundle-1sh9iaz","build": {"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32","projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",@@ -4760,7 +4760,7 @@{"type": "instance","id": "isNSM3wXcnHFikwNPlEOL",- "component": "Form",+ "component": "WebhookForm","label": "Form with custom props","children": [{@@ -4908,7 +4908,7 @@{"type": "instance","id": "-1RvizaBcVpHsjvnYxn1c",- "component": "Form",+ "component": "WebhookForm","label": "Default form","children": [{diff --git a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsxindex 9f778a99ae..a4a4688f3d 100644--- a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsxindex 207979f28a..799895c354 100644--- a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsxindex 260ed04e44..17aee863de 100644--- a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx@@ -41,7 +41,7 @@ export const getResources = (_props: { system: System; resources?: Record<string}const _data: ResourceRequestGraph = {resources: [- { id: "oIYuHoIwG7GM5J9cCSsai", outputName: "assets_1", dependencies: [], createRequest: assets_1 },+ { id: "oIYuHoIwG7GM5J9cCSsai", outputName: "assets_1", dependencies: [], createRequest: assets_1, control: "system", bodyFormat: undefined },],rootIds: ["oIYuHoIwG7GM5J9cCSsai",@@ -94,5 +94,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsxindex 7ae573366e..ab1d7db271 100644--- a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsxindex 21f920b362..031c6dfe69 100644--- a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsxindex 30f922fe75..e5a0debf84 100644--- a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsxindex 5b6bd728b5..e164a1304f 100644--- a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx@@ -20,7 +20,7 @@ export const getResources = (_props: { system: System; resources?: Record<string}const _data: ResourceRequestGraph = {resources: [- { id: "fjMzCru8O2U31xY2P1Ovr", outputName: "jsonResourceVariable_1", dependencies: [], createRequest: jsonResourceVariable_1 },+ { id: "fjMzCru8O2U31xY2P1Ovr", outputName: "jsonResourceVariable_1", dependencies: [], createRequest: jsonResourceVariable_1, control: undefined, bodyFormat: undefined },],rootIds: ["fjMzCru8O2U31xY2P1Ovr",@@ -73,5 +73,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsxindex 74b0b5f3c0..4926eacdfc 100644--- a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx@@ -21,7 +21,7 @@ export const getResources = (_props: { system: System; resources?: Record<string}const _data: ResourceRequestGraph = {resources: [- { id: "isNSM3wXcnHFikwNPlEOL", outputName: "action", dependencies: [], createRequest: action },+ { id: "isNSM3wXcnHFikwNPlEOL", outputName: "action", dependencies: [], createRequest: action, control: undefined, bodyFormat: undefined },],rootIds: [],@@ -74,5 +74,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsxindex 43d53d56ee..8190ebab2c 100644--- a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsxindex 3d6542f61f..a54e03508f 100644--- a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsxindex 86597260cb..87ae17cb68 100644--- a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsxindex b82f08a0be..a865f5ef79 100644--- a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsxindex a3cbe3488b..b26b02ea54 100644--- a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx@@ -20,7 +20,7 @@ export const getResources = (_props: { system: System; resources?: Record<string}const _data: ResourceRequestGraph = {resources: [- { id: "1vX6SQdaCjJN6MvJlG_cQ", outputName: "list_1", dependencies: [], createRequest: list_1 },+ { id: "1vX6SQdaCjJN6MvJlG_cQ", outputName: "list_1", dependencies: [], createRequest: list_1, control: undefined, bodyFormat: undefined },],rootIds: ["1vX6SQdaCjJN6MvJlG_cQ",@@ -73,5 +73,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsxindex 07ca3ab88c..362994e5c1 100644--- a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsxindex 707c6682ff..fc344f6443 100644--- a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx@@ -60,5 +60,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/__generated__/_index.server.tsx b/fixtures/webstudio-features/app/__generated__/_index.server.tsxindex b3140030fd..ec2bf1a1a1 100644--- a/fixtures/webstudio-features/app/__generated__/_index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/_index.server.tsx@@ -64,5 +64,6 @@ export const getManagedFormResourceGraph = (formId: string, _managedFormProps: {[]);+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = "[email protected]";\ No newline at end of filediff --git a/fixtures/webstudio-features/app/extension.ts b/fixtures/webstudio-features/app/extension.tsindex b807c76536..3545f72720 100644--- a/fixtures/webstudio-features/app/extension.ts+++ b/fixtures/webstudio-features/app/extension.ts@@ -1,14 +1,8 @@-import type { ResourceRequest } from "@webstudio-is/sdk";+import "react-router";declare module "react-router" {interface AppLoadContext {EXCLUDE_FROM_SEARCH: boolean;WEBSTUDIO_AUTOMATION_TOKEN?: string;- getDefaultActionResource?: (options: {- url: URL;- projectId: string;- contactEmail: string;- formData: FormData;- }) => ResourceRequest;}}diff --git a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsxindex 575301c9cd..57332b9c06 100644--- a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[animations]._index.tsx b/fixtures/webstudio-features/app/routes/[animations]._index.tsxindex c5aa89e989..f0b75252dd 100644--- a/fixtures/webstudio-features/app/routes/[animations]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[animations]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx b/fixtures/webstudio-features/app/routes/[assets1]._index.tsxindex be8f59550a..16384a72ba 100644--- a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx b/fixtures/webstudio-features/app/routes/[class-names]._index.tsxindex 6fd03e17bd..be6c2f5442 100644--- a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx b/fixtures/webstudio-features/app/routes/[content-block]._index.tsxindex bee54c5a04..5ab84b3de8 100644--- a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[duration]._index.tsx b/fixtures/webstudio-features/app/routes/[duration]._index.tsxindex a7a237333d..bf5ffb4da7 100644--- a/fixtures/webstudio-features/app/routes/[duration]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[duration]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx b/fixtures/webstudio-features/app/routes/[expressions]._index.tsxindex d0da010953..c02e16acfa 100644--- a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[form]._index.tsx b/fixtures/webstudio-features/app/routes/[form]._index.tsxindex e3603f7736..db615b0850 100644--- a/fixtures/webstudio-features/app/routes/[form]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[form]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsxindex 36c0e71f6c..c59bf90c8a 100644--- a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsxindex 406e3560e7..976533e354 100644--- a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsxindex 1dfdd108e6..b2a00e190b 100644--- a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[radix]._index.tsx b/fixtures/webstudio-features/app/routes/[radix]._index.tsxindex 558a9fd63b..d53aac7455 100644--- a/fixtures/webstudio-features/app/routes/[radix]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[radix]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[resources]._index.tsx b/fixtures/webstudio-features/app/routes/[resources]._index.tsxindex 1c22947d6d..d99b4e4be9 100644--- a/fixtures/webstudio-features/app/routes/[resources]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[resources]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsxindex 345fa2f113..3a1dd3f384 100644--- a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/fixtures/webstudio-features/app/routes/_index.tsx b/fixtures/webstudio-features/app/routes/_index.tsxindex 42e5f97bbc..840dca4f76 100644--- a/fixtures/webstudio-features/app/routes/_index.tsx+++ b/fixtures/webstudio-features/app/routes/_index.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,88 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<- ReturnType<typeof loadResourceWithEmail>- >;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/packages/cli/evaluations/high-impact/fixture-api.test.ts b/packages/cli/evaluations/high-impact/fixture-api.test.tsindex f6203ed006..6ae94478fc 100644--- a/packages/cli/evaluations/high-impact/fixture-api.test.ts+++ b/packages/cli/evaluations/high-impact/fixture-api.test.ts@@ -38,7 +38,7 @@ import { evaluateHighImpactOutcome } from "./validate";const execFileAsync = promisify(execFile);describe("high-impact fixture API", () => {- test("preserves current Form identity metadata through CLI initialization", async () => {+ test("omits the historical Form identity marker after CLI initialization", async () => {const api = await startHighImpactFixtureApi(managedFormAuthoringFixture);const directory = await mkdtemp(join(tmpdir(), "managed-form-identity-fixture-")@@ -69,7 +69,9 @@ describe("high-impact fixture API", () => {"utf8"));- expect(snapshot.state.pages.formComponentIdentityVersion).toBe(1);+ expect(snapshot.state.pages).not.toHaveProperty(+ "formComponentIdentityVersion"+ );} finally {await api.close();await rm(directory, { recursive: true, force: true });diff --git a/packages/cli/evaluations/high-impact/fixture-api.ts b/packages/cli/evaluations/high-impact/fixture-api.tsindex d5bb1920d0..592abb688f 100644--- a/packages/cli/evaluations/high-impact/fixture-api.ts+++ b/packages/cli/evaluations/high-impact/fixture-api.ts@@ -50,7 +50,6 @@ const buildId = "high-impact-evaluation-build";const initialVersion = 1;const createPersistedPages = (project: EvaluationProject) => ({- formComponentIdentityVersion: 1,meta: { siteName: "High-impact evaluation", contactEmail: "" },compiler: { atomicStyles: true },redirects: [],diff --git a/packages/cli/evaluations/high-impact/form-runtime.test.ts b/packages/cli/evaluations/high-impact/form-runtime.test.tsindex 7d66d39ebe..ec0328435f 100644--- a/packages/cli/evaluations/high-impact/form-runtime.test.ts+++ b/packages/cli/evaluations/high-impact/form-runtime.test.ts@@ -105,7 +105,7 @@ test("runtime validator requires the observed success, failure, recovery sequenc});project.instances.push({id: "runtime-form",- component: "Form",+ component: "ResourceForm",children: ["name", "email", "subject", "message"].map((name) => ({type: "id" as const,value: `field-${name}`,diff --git a/packages/cli/evaluations/high-impact/validate.test.ts b/packages/cli/evaluations/high-impact/validate.test.tsindex 4e76cf3245..253fd8218b 100644--- a/packages/cli/evaluations/high-impact/validate.test.ts+++ b/packages/cli/evaluations/high-impact/validate.test.ts@@ -51,7 +51,7 @@ const addManagedContactPage = (): EvaluationProject => {const instances = [{id: formId,- component: "Form",+ component: "ResourceForm",children: [{ type: "id" as const, value: "form-content" },{ type: "id" as const, value: "form-success" },@@ -932,7 +932,7 @@ describe("managed Form evaluation", () => {const project = addManagedContactPage();const calls = managedFormCalls();const form = project.instances.find(- ({ component }) => component === "Form"+ ({ component }) => component === "ResourceForm")!;const button = project.instances.find(({ component }) => component === "Button"@@ -1123,12 +1123,12 @@ describe("Form modes evaluation", () => {project.instances.push({id: "mode-contact",- component: "Form",+ component: "ResourceForm",children: [],},{id: "mode-search",- component: "Form",+ component: "ResourceForm",children: [],},{@@ -2259,13 +2259,13 @@ describe("Form modes authoring evaluation", () => {instances: [{id: "contact",- component: "Form",+ component: "ResourceForm",label: "Contact",children: [],},{id: "search",- component: "Form",+ component: "ResourceForm",label: "Search",children: [],},diff --git a/packages/cli/evaluations/high-impact/validate.ts b/packages/cli/evaluations/high-impact/validate.tsindex 6a8d6e31c2..bf306e6454 100644--- a/packages/cli/evaluations/high-impact/validate.ts+++ b/packages/cli/evaluations/high-impact/validate.ts@@ -595,7 +595,7 @@ const validateManagedFormAuthoring = ("/contact");const formInstances = instances.filter(- ({ component }) => component === "Form"+ ({ component }) => component === "ResourceForm");const form = formInstances[0];const propsByInstance = new Map<string, EvaluationProject["props"]>();@@ -2099,7 +2099,7 @@ const validateFormModesAuthoring = ((prop) => prop.instanceId === id && prop.name === name)?.value;const resourceForms = input.project.instances.filter(- (instance) => instance.component === "Form"+ (instance) => instance.component === "ResourceForm");const contact = resourceForms.find((instance) => {const actions = getProp(instance.id, "action");@@ -2122,7 +2122,7 @@ const validateFormModesAuthoring = (failures,"resourceFormMode",resourceForms.length >= 2 &&- contact?.component === "Form" &&+ contact?.component === "ResourceForm" &&Array.isArray(contactActions) &&contactActions.length > 0,"Contact must be a Form with connected Resource actions."@@ -2132,7 +2132,7 @@ const validateFormModesAuthoring = (failures,"navigationFormMode",resourceForms.length >= 2 &&- search?.component === "Form" &&+ search?.component === "ResourceForm" &&Array.isArray(searchActions) &&searchActions.length === 0,"Search must be a Form with an explicitly empty Action array."@@ -2179,7 +2179,7 @@ const validateManagedFormRuntime = (route === undefined? undefined: descendants(input.project, route.rootInstanceId).find(- ({ component }) => component === "Form"+ ({ component }) => component === "ResourceForm");const formDescendants =form === undefined ? [] : descendants(input.project, form.id);diff --git a/packages/cli/scripts/runtime-fixture-api.ts b/packages/cli/scripts/runtime-fixture-api.tsindex abb032cf50..f35da62b73 100644--- a/packages/cli/scripts/runtime-fixture-api.ts+++ b/packages/cli/scripts/runtime-fixture-api.ts@@ -71,7 +71,6 @@ export const createRuntimeFixtureBuildSnapshot = ({folders: pages.folders,homePageId: pages.homePageId,rootFolderId: pages.rootFolderId,- formComponentIdentityVersion: pages.formComponentIdentityVersion,redirects: pages.redirects,variables: dataSources,};diff --git a/packages/cli/src/commands/import.ts b/packages/cli/src/commands/import.tsindex 3d3a2f8859..587c44e065 100644--- a/packages/cli/src/commands/import.ts+++ b/packages/cli/src/commands/import.ts@@ -6,7 +6,7 @@ import {bundleVersion,getBundleVersion,getBundleVersionMismatchMessage,- publishedProjectBundle,+ historicalPublishedProjectBundle,} from "@webstudio-is/protocol";import { importProjectBundleWithAssets } from "@webstudio-is/http-client";import { LOCAL_DATA_FILE } from "../config";@@ -135,7 +135,7 @@ export const importProject = async (throw new HandledCliError();}- const parsedData = publishedProjectBundle.safeParse(data);+ const parsedData = historicalPublishedProjectBundle.safeParse(data);if (parsedData.success === false) {importing.stop(`${invalidProjectBundleMessage} Invalid fields: ${formatZodIssues(diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.tsindex 502e5078da..eb4cde96b1 100644--- a/packages/cli/src/commands/sync.test.ts+++ b/packages/cli/src/commands/sync.test.ts@@ -207,6 +207,51 @@ test("adds current bundle version when synchronizing data from old API", async ();});+test.each([+ { marker: 1, expected: "ResourceForm" },+ { marker: undefined, expected: "WebhookForm" },+])(+ "exports an old API Form as $expected without a marker",+ async ({ marker, expected }) => {+ const bundle = createProjectBundle();+ if (marker !== undefined) {+ Object.assign(bundle.build.pages, {+ formComponentIdentityVersion: marker,+ });+ }+ bundle.build.instances.push([+ "historical-form",+ {+ type: "instance",+ id: "historical-form",+ component: "Form",+ children: [],+ },+ ]);+ loadProjectBundleByBuildId.mockResolvedValue(bundle);++ await sync(+ {+ authToken: "token-1",+ buildId: "build-1",+ origin: "https://example.com",+ },+ dependencies+ );++ const exported = JSON.parse(await readFile(".webstudio/data.json", "utf8"));+ expect(exported.bundleVersion).toBe(bundleVersion);+ expect(exported.build.pages).not.toHaveProperty(+ "formComponentIdentityVersion"+ );+ expect(+ exported.build.instances.find(+ ([id]: [string]) => id === "historical-form"+ )?.[1].component+ ).toBe(expected);+ }+);+test("downloads project bundle asset files into local project bundle", async () => {const assets = [createImageAssetFixture()];loadProjectBundleByBuildId.mockResolvedValue(createProjectBundle({ assets }));diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.tsindex 867338d4d5..f449fa1d90 100644--- a/packages/cli/src/commands/sync.ts+++ b/packages/cli/src/commands/sync.ts@@ -4,6 +4,7 @@ import { cwd } from "node:process";import { spinner } from "@clack/prompts";import {bundleVersion,+ historicalPublishedProjectBundle,publishedProjectBundle,type PublishedProjectBundle,} from "@webstudio-is/protocol";@@ -30,7 +31,12 @@ import {createBuilderStateFromBuildData,createSerializedBuilderBuildDataFromState,} from "@webstudio-is/project-build/state";-import { migratePages } from "@webstudio-is/project-migrations/pages";+import { migrateResourceFormInstancesMutable } from "@webstudio-is/project-migrations";+import {+ hasHistoricalFormComponentIdentityVersion,+ migratePages,+ serializePages,+} from "@webstudio-is/project-migrations/pages";import {createBuildContentCompilationPlan,createPublishedBuildContentCompilationPlan,@@ -64,6 +70,7 @@ import {// Builder data uses arrays rather than the keyed pairs in an export bundle.const builderData = serializedBuild.extend({+ pages: historicalPublishedProjectBundle.shape.build.shape.pages,breakpoints: breakpoint.array(),styles: styleDecl.array(),styleSources: styleSource.array(),@@ -87,7 +94,11 @@ const loadCurrentProjectBundle = async () {throw new Error("Source project does not match the linked project");}+ const hasModernFormMarker = hasHistoricalFormComponentIdentityVersion(+ data.pages+ );const pages = migratePages(data.pages);+ migrateResourceFormInstancesMutable(data.instances, hasModernFormMarker);const state = createBuilderStateFromBuildData({ ...data, pages });return publishedProjectBundle.parse({bundleVersion,@@ -245,6 +256,25 @@ export const sync = async (throw new HandledCliError();}+ const hasModernFormMarker = hasHistoricalFormComponentIdentityVersion(+ project.build.pages+ );+ const canonicalInstances = project.build.instances.map(+ ([id, instance]) => [id, { ...instance }] as [string, typeof instance]+ );+ migrateResourceFormInstancesMutable(+ canonicalInstances.map(([, instance]) => instance),+ hasModernFormMarker+ );+ project = publishedProjectBundle.parse({+ ...project,+ build: {+ ...project.build,+ pages: serializePages(migratePages(project.build.pages)),+ instances: canonicalInstances,+ },+ });+const createContentSource = () =>createFileSystemContentSource({projectId: project.build.projectId,diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex dbf954eb59..7f6225d3f8 100644--- a/packages/cli/src/docs.generated.ts+++ b/packages/cli/src/docs.generated.ts@@ -2,13 +2,13 @@// 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 uses npm when available and otherwise falls back to pnpm.\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` and `path` are plain values. Page `title` and metadata text fields contain expression source; quote fixed text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- CLI flags such as `--title` treat values as fixed text. Add `--expressions` to `webstudio create-page` when passing expression source through these flags; quote any fixed text in the same call as a JavaScript string expression.\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- For fixed page `title` and metadata text, quote the text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\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- For `webstudio update-page`, add `--expressions` when page title or metadata flags contain expression source. Without it, those flags are fixed text.\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\nCLI `create-page-template` and `update-page-template` use fixed text flags by default. Add `--expressions` when passing expression source through title or metadata flags.\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section ws:style={css`padding: 32px;`}><h2>Product OS</h2><Switch><SwitchThumb /></Switch></section>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- Use lowercase HTML JSX such as `<div>` and `<form>`. The internal `ws:` namespace is not HTML-tag shorthand.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside exactly one direct `ws:block-template` child. A missing or second template container makes the Content Block invalid. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before implementation, inventory every editor-owned field and its intended control and write destination, whether or not the block uses MDX. Check that templates contain the required styling, but do not treat containment or a successful text edit as proof that the whole block is editable. Test every field through Content mode, inspect its saved project data or source file, reload, and restore the original value. Report passed, failed, or not tested for each field; missing or read-only required controls are unfinished requirements.\n- Use controls that match the content: a calendar for dates and an image picker for image replacement. Keep fixed punctuation and units out of directly bound value elements. Preserve stored types and wording: when reading time is already a complete string such as `4 min read`, bind that string directly rather than assuming it is a number.\n- For MDX-backed blocks, containment alone is not enough: the MDX body is editable through its source mapping, but the designed shell needs writable document-frontmatter bindings. Follow the binding recipe below rather than binding editable article fields to query results.\n\n## Store Content Block content in MDX\n\nCommands:\n\n- MCP tool: list-assets {"type":"file"}\n- MCP tool: upload-asset {"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\n- MCP tool: connect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\n- MCP tool: switch-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<otherMdxAssetId>"}}\n- MCP tool: inspect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: edit-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":"# Article title\\n\\nArticle body."}\n- MCP tool: update-content-block-frontmatter {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","properties":{"title":"Article title","draft":false}}\n- MCP tool: reload-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: migrate-content-block-template-references {"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\n- MCP tool: disconnect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n\nNotes:\n\n- Create the local `.mdx` file under `.webstudio/assets` before calling `upload-asset`. Use the returned Asset ID when connecting it.\n- Use the Content Block source operations for connecting, switching, inspecting, editing, reloading, and disconnecting. Do not create or delete the `src` prop with generic prop tools; the source operations preserve the Body outlet and Content Block lifecycle.\n- `renderScope` accepts any non-empty stable key for one rendered occurrence. Use a page-based key for a direct Content Block and a distinct key for each repeated Collection occurrence. It does not load a page, route parameters, or resource results. Supply the concrete scoped values needed to resolve an expression through `variables`.\n- For a result-one Assets resource, preview the concrete query, then connect its persisted expression with the previewed item supplied as `variables`, for example `source:{"type":"expression","value":"post.data.id"}` and `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`.\n- Connecting replaces existing Body content. If the result returns `requiresConfirmation:true`, report that replacement to the user and repeat the same call with `confirmReplacement:true` only after approval.\n- Prefer Markdown for standard document content; it automatically uses a unique matching semantic template when one exists. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG with authored properties that Markdown cannot express.\n- Verify that the Content Block has exactly one direct Templates container before connecting or editing MDX. Zero or multiple containers block materialization and publication.\n- Read the Content Block\'s Templates children before writing a custom reference. Use capitalized JSX such as `<PromotionCard />` for its stable **Name**, which is independent from the display label. A matching template wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. JSX attributes accept quoted static values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported.\n- When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants and retain template styles. A mismatched child structure replaces the root defaults, while each authored child still resolves through a matching template when possible. An explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, so adding a matching semantic or named template later updates existing MDX. Preserve unresolved names and report their diagnostics instead of deleting them.\n- When a template is renamed or deleted, use `migrate-content-block-template-references` to update a selected set of affected MDX files. The first call returns a plan. Report its changed-file, update, omission, and diagnostic counts, then repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its authored children; removing a self-closing reference removes the node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n- `edit-content-block-source` replaces the complete MDX source. Preserve frontmatter and unrelated source when making a bounded edit.\n- `update-content-block-frontmatter` replaces the complete frontmatter mapping. Inspect the current source first and include every property that must remain.\n- Store frontmatter images as exact `$ref` objects. Bind an editable Image source to the resolved `.src` with explicit `binding.mode:"readwrite"`; use `mode:"read"` for its alt binding to `.description`. Omitting the source mode leaves the image visible but not replaceable in Content mode.\n- Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n- Inspect every returned diagnostic. Invalid MDX is saved rather than silently repaired; preserve the source, report the source range, and fix only the requested or invalid part.\n- If an edit in a long-lived MCP session reports a conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly.\n\n## Make an MDX article header editable\n\nUse the resource only to select the connected source, for example `post.data.id`.\nBind article values inside the Content Block to its document parameter instead\nof `post.data.properties.*`. Inspect the block\'s variables first; `document` is\nthe default name, not a name to assume.\n\nThese commands target persistent designed instances inside the connected block.\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<headingInstanceId>","childIndex":0,"text":"document.frontmatter.title","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: update-text {"instanceId":"<readingTimeValueInstanceId>","childIndex":0,"text":"document.frontmatter.readingTime","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<dateInstanceId>","name":"datetime","binding":{"type":"expression","value":"document.frontmatter.publishedAt","mode":"readwrite"}}]}\n\nNotes:\n\n- Create writable bindings explicitly; the default is read-only. Merely moving a heading or Link inside the Content Block does not make its query-bound text editable.\n- The MDX body uses its source mapping. Static designed content outside that body remains protected unless its text or supported props bind to writable frontmatter fields. Do not apply these generic instance tools to MDX-generated instances.\n- Use direct static paths. Property access is already safe. Fallbacks and formatted expressions, such as `document.frontmatter.title ?? "Untitled"`, remain read-only.\n- Keep every intended editable value in its own text element with a single direct read-write binding. For reading time, use three inline siblings: static `— `, the bound reading-time value, and static ` min read`. Preserve whitespace and the stored field type. Do not combine them into a template literal or concatenate strings, and do not put literal siblings inside the value element itself. Keep fixed wording protected in the designed shell.\n- Prefer component formatting controls, such as Date Time formatting with a directly bound date prop, over transforming the expression. Do not silently sacrifice editability for formatting or a fallback; explain unsupported cases and ask before making an intended editable field read-only.\n- A direct writable binding such as `document.frontmatter.author.name` can edit a shared author loaded through `../authors/acme.md#frontmatter`. The edit saves to the author file and affects every article using it; preserve the article\'s `$ref` marker.\n- Before handoff, inventory every article-owned field, including header text, author details, dates, reading time, categories, hero and inline image sources, alternative text, captions, links, and custom-component content. For each field, inspect its binding and source, edit it through the Content-mode UI, verify the saved MDX or referenced file, reload, and restore the test value. Record passed, failed, or not tested for each field. A correct preview, a successful MCP write, and one representative text edit do not prove the whole article is editable. Do not claim completion while required fields fail or remain untested.\n- Bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. Content mode\'s **Choose source** replaces the article\'s frontmatter image `$ref`; the resolved URL stays read-only. Verify selection, the saved reference, and reload instead of treating a missing write mode as a platform limitation. For alternative text bound to `.description`, use **Choose source → asset actions → Settings → Description** to edit shared Asset metadata. This affects every use of the Asset and is separate from replacing an article\'s image.\n\n## Make an article image replaceable in Content mode\n\nUse this for a persistent designed Image inside a connected Content Block,\nwith `featureImage: { $ref: "./images/hero.png" }` in its MDX frontmatter.\nRead the instance ID and document variable name before adapting the example.\n\nCommands:\n\n- MCP tool: bind-props {"bindings":[{"instanceId":"<imageInstanceId>","name":"src","binding":{"type":"expression","value":"document.frontmatter.featureImage.src","mode":"readwrite"}},{"instanceId":"<imageInstanceId>","name":"alt","binding":{"type":"expression","value":"document.frontmatter.featureImage.description","mode":"read"}}]}\n\nNotes:\n\n- The source mode must be explicit: the default `read` mode displays the image but prevents Content-mode replacement. Do not bind to query-result properties or add a fallback expression.\n- **Choose source** replaces the article\'s `featureImage.$ref`; the disabled resolved-URL input is expected. Do not store a resolved URL string or replace the shared Asset itself.\n- Shared alternative text is a separate action: **Choose source → asset actions → Settings → Description**. Its read-only binding does not require the image source binding to be read-only.\n- If the picker is missing or disabled, inspect the source mode, document scope, loaded reference, and permissions before claiming a product limitation.\n- Verify through Content mode with an approved temporary replacement. Check the saved `$ref`, unchanged unrelated MDX and original shared Asset, reload persistence, and restoration. If that test is not authorized, report it as not tested, not passed.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<jsonLdInstanceId>","name":"code","binding":{"type":"expression","value":"({ \'@context\': \'https://schema.org\', \'@type\': \'Article\', headline: post.title })"}}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- For fixed structured data, store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- For structured data containing runtime values, use `bind-props` with an expression that evaluates directly to an object or array. Do not call `JSON.stringify` or assemble JSON with string concatenation. Webstudio stores the expression as source text, evaluates it at runtime, and the `JsonLd` component validates and serializes the resulting value.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":{"--color-primary":"#2d3748","--color-accent":"#e53e3e","--space-card":"1.5rem"},"overwrite":true}\n\nNotes:\n\n- Define or overwrite multiple CSS variables atomically by including every name and value in one `vars` object.\n- Pass colors as CSS strings. Structured `hex` color components use normalized values from `0` to `1`, not `0` to `255`.\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":["--color-primary","--color-accent","--space-card"],"force":true}\n\nNotes:\n\n- Delete multiple CSS variables atomically by including every name in one `names` array. Destructive MCP calls still require the returned confirmation token before they commit.\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\'https://api.example.com/posts?tag=\' + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\'Bearer \' + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`. A query key with one value is a string; repeated values are an ordered array. For `?tag=red&tag=blue`, `system.search.tag` is `["red", "blue"]`.\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## Configure Form (Beta) through MCP\n\nUse the exact component id returned by `components.search` for **Form (Beta)**.\nAfter inserting its registered template, use the Form instance id for the\nForm-scoped Resource and Action settings.\n\nThe new Form\'s canonical component id is `Form`. The deprecated legacy\nWebhook Form remains available in Builder for existing projects until the next\nrelease, but is omitted from MCP component discovery. `RemixForm` is deprecated\ncompatibility and should not be used for new projects. Always use registry\ndiscovery instead of assuming the display label is its component id.\n\nThe new Form has two modes derived from its Action array:\n\n- One or more connected Resources: the rendered action is\n `?__webstudio__=resources` and submission runs the Resource actions.\n- No connected Resources (`action: []`): the rendered action is\n `?__webstudio__=navigate` and submission updates URL query parameters through\n client-side navigation. Use this for search and filters with page Resources\n bound to `system.search`. Removing the last Action switches to Navigation mode.\n- For ordinary browser submission, insert an `Element` with `tag: "form"`.\n It has no managed action marker and retains native browser behavior.\n\nDo not write the `__webstudio__` marker as a project Action value: that prop holds\nResource selections, and the runtime derives the HTML action URL from it.\nVerify both modes through MCP in a real project: add Resource actions, remove\nall actions for a search/filter form, then reconnect them. Check the rendered\naction, query navigation without a full reload, and Resource execution. Also\nverify a plain form Element remains native. A saved project snapshot alone does\nnot prove these runtime behaviors.\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<parentInstanceId>","component":"<componentId from components.search>"}\n- MCP tool: create-resource {"resource":{"name":"Send submission","method":"post","url":"https://api.example.com/submit","headers":[],"body":"formData"},"scopeInstanceId":"<formInstanceId>","dataSourceName":"Send submission","exposeAsDataSource":true}\n- MCP tool: update-props {"updates":[{"instanceId":"<formInstanceId>","name":"action","type":"json","value":[{"dataSourceId":"<returned dataSourceId>"}]}]}\n- MCP tool: update-resource {"resourceId":"<emailResourceId>","values":{"email":{"recipientMode":"visitor","visitorEmailField":"email","includeAttachments":true}}}\n- MCP tool: update-project-settings {"meta":{"emailSender":"Acme <[email protected]>"}}\n\nNotes:\n\n- Use `update-props` with a JSON Action array to add, order, or remove destinations. The Action entries use `{ "dataSourceId": "..." }` and support up to ten Resources, matching the Builder control. Each connected Action runs in its configured order. An extra `enabled` key in older saved settings is ignored.\n- Create each destination Resource in the Form\'s scope so it can use `formData` and `browserInfo`. Set `exposeAsDataSource:true` to receive the data-source id used by the Action array. When a Resource uses Form-only parameters, it is kept out of page-load requests and runs with the Form submission.\n- `update-resource` accepts the same Email settings as the Builder: project, custom, or visitor recipients; sender; subject; body; and submitted-file attachments. Use expressions in string fields for dynamic values.\n- `update-project-settings` edits the project-wide Email recipients and Reply to. `update-props` also sets Form fields and Success redirect, while `bind-props` supplies dynamic expressions. `insert-component` uses the registered Form template, including its default contact fields and Email Actions. Set subject and body on each Email Resource.\n- MCP mutations update saved project configuration. To test real delivery, submit the Form in Preview or on a published test site and inspect the configured destinations.\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- Choose `.mdx` connected to a Content Block when editors must edit article bodies visually in Content mode. Publishing downloads and compiles every reachable MDX article, so more articles can slow publishing. Choose `.md` with Markdown Embed when editing the source in Assets is enough; Content mode editors can still edit the Markdown file there, but not its body on the canvas. `.md` needs no per-article MDX compilation, though the publish runner still synchronizes Asset files for both formats and static generation may read Markdown bodies.\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading the source files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown or MDX files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown or MDX, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the document\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- Use `result:"many"` for listings. It returns the ID-keyed map at `<dataSourceName>.data`, with `totalCount` and `hasMore` at `<dataSourceName>.meta`, and remains the default for existing queries. Bind a listing Collection to `posts.data`.\n- Use `result:"one"` for a unique detail route. It returns the selected item or `null` directly at `post.data`, always includes its `id`, and omits pagination. Bind components and page settings directly with expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404`. `result:"first"` and `result:"last"` also return a direct item or `null` but require explicit sorting.\n- Assets always executes a structured query. Omit `query` to use the default many-result query, which selects URL and optional image dimensions. Set `values.query:null` to restore it.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\nNotes:\n\n- Multi-file uploads return `uploaded`, `failed`, and `ambiguous` lists with the\n original input index. Retry only `failed` files. A forced upload in\n `ambiguous` may already be committed; inspect the Assets list before deciding\n whether to upload it again. Successful uploads remain committed.\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- webstudio search-project \'{"query":"pricing"}\'\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","namespaces":["resources"]}\n- MCP tool: search-project {"query":"Brand","namespaces":["styles","styleSources","styleSourceSelections"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- `search-project` is a standalone local-session command over every Builder namespace. It returns matching values with stable match ids, namespace paths, owning entities, references, and affected pages.\n- Use it when a value or id is known. Use list/get tools when the project structure or target is not known.\n- The command synchronizes its required Builder namespaces, then searches locally and returns only matches. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. This reduces data passed to the model, not the initial project-data synchronization.\n- Asset records and file metadata are searchable. Asset binary or document contents are not Builder namespace data and are not searched.\n- Values in recognized credential fields are excluded and counted in `excludedSensitiveValueCount`.\n- Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\""}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\""}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<article><h2>{expression`collectionItem.title`}</h2></article>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page","taskScope":"structural-project-change","workflow":"authenticated-page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page","taskScope":"visual-change","workflow":"design-input"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<section><p>Section copy</p></section>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpoint":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Ask whether the user wants visual verification unless they explicitly requested\n it. If they decline, stop after focused reads and a static audit. If they opt\n in, verify one familiar viewport inside every distinct Builder breakpoint\n range, then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with `workflow:"authenticated-page"`, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with `workflow:"design-input"`, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Enter this workflow only when the user explicitly requests visual verification or opts in after being asked. Do not start preview, screenshots, diffs, OCR, or rendered audits automatically after a mutation.\n- `preview.status` reports whether generated output is `stale`. When no preview is running, `url`, `pid`, and `mode` are omitted. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- MCP preview and path-based screenshot tools select an available loopback port and return the preview URL. Do not pass `host` or `port`.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- After opt-in, use this so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Calling `preview.start` after a committed mutation restarts a stale iterative server so external browsers and HTTP clients receive the newly generated project.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- When launcher metadata is available, Preview reuses a supported npm or pnpm launcher. Without launcher metadata, it uses npm when available and otherwise falls back to pnpm.\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` and `path` are plain values. Page `title` and metadata text fields contain expression source; quote fixed text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- CLI flags such as `--title` treat values as fixed text. Add `--expressions` to `webstudio create-page` when passing expression source through these flags; quote any fixed text in the same call as a JavaScript string expression.\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- For fixed page `title` and metadata text, quote the text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\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- For `webstudio update-page`, add `--expressions` when page title or metadata flags contain expression source. Without it, those flags are fixed text.\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\nCLI `create-page-template` and `update-page-template` use fixed text flags by default. Add `--expressions` when passing expression source through title or metadata flags.\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":"ResourceForm"}\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 `"ResourceForm"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside exactly one direct `ws:block-template` child. A missing or second template container makes the Content Block invalid. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before implementation, inventory every editor-owned field and its intended control and write destination, whether or not the block uses MDX. Check that templates contain the required styling, but do not treat containment or a successful text edit as proof that the whole block is editable. Test every field through Content mode, inspect its saved project data or source file, reload, and restore the original value. Report passed, failed, or not tested for each field; missing or read-only required controls are unfinished requirements.\n- Use controls that match the content: a calendar for dates and an image picker for image replacement. Keep fixed punctuation and units out of directly bound value elements. Preserve stored types and wording: when reading time is already a complete string such as `4 min read`, bind that string directly rather than assuming it is a number.\n- For MDX-backed blocks, containment alone is not enough: the MDX body is editable through its source mapping, but the designed shell needs writable document-frontmatter bindings. Follow the binding recipe below rather than binding editable article fields to query results.\n\n## Store Content Block content in MDX\n\nCommands:\n\n- MCP tool: list-assets {"type":"file"}\n- MCP tool: upload-asset {"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\n- MCP tool: connect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\n- MCP tool: switch-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<otherMdxAssetId>"}}\n- MCP tool: inspect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: edit-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":"# Article title\\n\\nArticle body."}\n- MCP tool: update-content-block-frontmatter {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","properties":{"title":"Article title","draft":false}}\n- MCP tool: reload-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n- MCP tool: migrate-content-block-template-references {"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\n- MCP tool: disconnect-content-block-source {"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\n\nNotes:\n\n- Create the local `.mdx` file under `.webstudio/assets` before calling `upload-asset`. Use the returned Asset ID when connecting it.\n- Use the Content Block source operations for connecting, switching, inspecting, editing, reloading, and disconnecting. Do not create or delete the `src` prop with generic prop tools; the source operations preserve the Body outlet and Content Block lifecycle.\n- `renderScope` accepts any non-empty stable key for one rendered occurrence. Use a page-based key for a direct Content Block and a distinct key for each repeated Collection occurrence. It does not load a page, route parameters, or resource results. Supply the concrete scoped values needed to resolve an expression through `variables`.\n- For a result-one Assets resource, preview the concrete query, then connect its persisted expression with the previewed item supplied as `variables`, for example `source:{"type":"expression","value":"post.data.id"}` and `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`.\n- Connecting replaces existing Body content. If the result returns `requiresConfirmation:true`, report that replacement to the user and repeat the same call with `confirmReplacement:true` only after approval.\n- Prefer Markdown for standard document content; it automatically uses a unique matching semantic template when one exists. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG with authored properties that Markdown cannot express.\n- Verify that the Content Block has exactly one direct Templates container before connecting or editing MDX. Zero or multiple containers block materialization and publication.\n- Read the Content Block\'s Templates children before writing a custom reference. Use capitalized JSX such as `<PromotionCard />` for its stable **Name**, which is independent from the display label. A matching template wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. JSX attributes accept quoted static values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported.\n- When explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants and retain template styles. A mismatched child structure replaces the root defaults, while each authored child still resolves through a matching template when possible. An explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, so adding a matching semantic or named template later updates existing MDX. Preserve unresolved names and report their diagnostics instead of deleting them.\n- When a template is renamed or deleted, use `migrate-content-block-template-references` to update a selected set of affected MDX files. The first call returns a plan. Report its changed-file, update, omission, and diagnostic counts, then repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its authored children; removing a self-closing reference removes the node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n- `edit-content-block-source` replaces the complete MDX source. Preserve frontmatter and unrelated source when making a bounded edit.\n- `update-content-block-frontmatter` replaces the complete frontmatter mapping. Inspect the current source first and include every property that must remain.\n- Store frontmatter images as exact `$ref` objects. Bind an editable Image source to the resolved `.src` with explicit `binding.mode:"readwrite"`; use `mode:"read"` for its alt binding to `.description`. Omitting the source mode leaves the image visible but not replaceable in Content mode.\n- Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n- Inspect every returned diagnostic. Invalid MDX is saved rather than silently repaired; preserve the source, report the source range, and fix only the requested or invalid part.\n- If an edit in a long-lived MCP session reports a conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly.\n\n## Make an MDX article header editable\n\nUse the resource only to select the connected source, for example `post.data.id`.\nBind article values inside the Content Block to its document parameter instead\nof `post.data.properties.*`. Inspect the block\'s variables first; `document` is\nthe default name, not a name to assume.\n\nThese commands target persistent designed instances inside the connected block.\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<headingInstanceId>","childIndex":0,"text":"document.frontmatter.title","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: update-text {"instanceId":"<readingTimeValueInstanceId>","childIndex":0,"text":"document.frontmatter.readingTime","mode":"expression","expressionBindingMode":"readwrite"}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<dateInstanceId>","name":"datetime","binding":{"type":"expression","value":"document.frontmatter.publishedAt","mode":"readwrite"}}]}\n\nNotes:\n\n- Create writable bindings explicitly; the default is read-only. Merely moving a heading or Link inside the Content Block does not make its query-bound text editable.\n- The MDX body uses its source mapping. Static designed content outside that body remains protected unless its text or supported props bind to writable frontmatter fields. Do not apply these generic instance tools to MDX-generated instances.\n- Use direct static paths. Property access is already safe. Fallbacks and formatted expressions, such as `document.frontmatter.title ?? "Untitled"`, remain read-only.\n- Keep every intended editable value in its own text element with a single direct read-write binding. For reading time, use three inline siblings: static `— `, the bound reading-time value, and static ` min read`. Preserve whitespace and the stored field type. Do not combine them into a template literal or concatenate strings, and do not put literal siblings inside the value element itself. Keep fixed wording protected in the designed shell.\n- Prefer component formatting controls, such as Date Time formatting with a directly bound date prop, over transforming the expression. Do not silently sacrifice editability for formatting or a fallback; explain unsupported cases and ask before making an intended editable field read-only.\n- A direct writable binding such as `document.frontmatter.author.name` can edit a shared author loaded through `../authors/acme.md#frontmatter`. The edit saves to the author file and affects every article using it; preserve the article\'s `$ref` marker.\n- Before handoff, inventory every article-owned field, including header text, author details, dates, reading time, categories, hero and inline image sources, alternative text, captions, links, and custom-component content. For each field, inspect its binding and source, edit it through the Content-mode UI, verify the saved MDX or referenced file, reload, and restore the test value. Record passed, failed, or not tested for each field. A correct preview, a successful MCP write, and one representative text edit do not prove the whole article is editable. Do not claim completion while required fields fail or remain untested.\n- Bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. Content mode\'s **Choose source** replaces the article\'s frontmatter image `$ref`; the resolved URL stays read-only. Verify selection, the saved reference, and reload instead of treating a missing write mode as a platform limitation. For alternative text bound to `.description`, use **Choose source → asset actions → Settings → Description** to edit shared Asset metadata. This affects every use of the Asset and is separate from replacing an article\'s image.\n\n## Make an article image replaceable in Content mode\n\nUse this for a persistent designed Image inside a connected Content Block,\nwith `featureImage: { $ref: "./images/hero.png" }` in its MDX frontmatter.\nRead the instance ID and document variable name before adapting the example.\n\nCommands:\n\n- MCP tool: bind-props {"bindings":[{"instanceId":"<imageInstanceId>","name":"src","binding":{"type":"expression","value":"document.frontmatter.featureImage.src","mode":"readwrite"}},{"instanceId":"<imageInstanceId>","name":"alt","binding":{"type":"expression","value":"document.frontmatter.featureImage.description","mode":"read"}}]}\n\nNotes:\n\n- The source mode must be explicit: the default `read` mode displays the image but prevents Content-mode replacement. Do not bind to query-result properties or add a fallback expression.\n- **Choose source** replaces the article\'s `featureImage.$ref`; the disabled resolved-URL input is expected. Do not store a resolved URL string or replace the shared Asset itself.\n- Shared alternative text is a separate action: **Choose source → asset actions → Settings → Description**. Its read-only binding does not require the image source binding to be read-only.\n- If the picker is missing or disabled, inspect the source mode, document scope, loaded reference, and permissions before claiming a product limitation.\n- Verify through Content mode with an approved temporary replacement. Check the saved `$ref`, unchanged unrelated MDX and original shared Asset, reload persistence, and restoration. If that test is not authorized, report it as not tested, not passed.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<jsonLdInstanceId>","name":"code","binding":{"type":"expression","value":"({ \'@context\': \'https://schema.org\', \'@type\': \'Article\', headline: post.title })"}}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- For fixed structured data, store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- For structured data containing runtime values, use `bind-props` with an expression that evaluates directly to an object or array. Do not call `JSON.stringify` or assemble JSON with string concatenation. Webstudio stores the expression as source text, evaluates it at runtime, and the `JsonLd` component validates and serializes the resulting value.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":{"--color-primary":"#2d3748","--color-accent":"#e53e3e","--space-card":"1.5rem"},"overwrite":true}\n\nNotes:\n\n- Define or overwrite multiple CSS variables atomically by including every name and value in one `vars` object.\n- Pass colors as CSS strings. Structured `hex` color components use normalized values from `0` to `1`, not `0` to `255`.\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":["--color-primary","--color-accent","--space-card"],"force":true}\n\nNotes:\n\n- Delete multiple CSS variables atomically by including every name in one `names` array. Destructive MCP calls still require the returned confirmation token before they commit.\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\'https://api.example.com/posts?tag=\' + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\'Bearer \' + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`. A query key with one value is a string; repeated values are an ordered array. For `?tag=red&tag=blue`, `system.search.tag` is `["red", "blue"]`.\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## Configure Form (Beta) through MCP\n\nUse the exact component id returned by `components.search` for **Form (Beta)**.\nAfter inserting its registered template, use the Form instance id for the\nForm-scoped Resource and Action settings.\n\nThe new Form\'s canonical component id is `ResourceForm`. The deprecated\nWebhook Form remains available in Builder for existing projects until the next\nrelease, but is omitted from MCP component discovery. `RemixForm` is deprecated\ncompatibility and should not be used for new projects. Always use registry\ndiscovery instead of assuming the display label is its component id.\n\nThe new Form has two modes derived from its Action array:\n\n- One or more connected Resources: the rendered action is\n `?__webstudio__=resources` and submission runs the Resource actions.\n- No connected Resources (`action: []`): the rendered action is\n `?__webstudio__=navigate` and submission updates URL query parameters through\n client-side navigation. Use this for search and filters with page Resources\n bound to `system.search`. Removing the last Action switches to Navigation mode.\n- For ordinary browser submission, insert an `Element` with `tag: "form"`.\n It has no managed action marker and retains native browser behavior.\n\nDo not write the `__webstudio__` marker as a project Action value: that prop holds\nResource selections, and the runtime derives the HTML action URL from it.\nVerify both modes through MCP in a real project: add Resource actions, remove\nall actions for a search/filter form, then reconnect them. Check the rendered\naction, query navigation without a full reload, and Resource execution. Also\nverify a plain form Element remains native. A saved project snapshot alone does\nnot prove these runtime behaviors.\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<parentInstanceId>","component":"<componentId from components.search>"}\n- MCP tool: create-resource {"resource":{"name":"Send submission","method":"post","url":"https://api.example.com/submit","headers":[],"body":"formData"},"scopeInstanceId":"<formInstanceId>","dataSourceName":"Send submission","exposeAsDataSource":true}\n- MCP tool: update-props {"updates":[{"instanceId":"<formInstanceId>","name":"action","type":"json","value":[{"dataSourceId":"<returned dataSourceId>"}]}]}\n- MCP tool: update-resource {"resourceId":"<emailResourceId>","values":{"email":{"recipientMode":"visitor","visitorEmailField":"email","includeAttachments":true}}}\n- MCP tool: update-project-settings {"meta":{"emailSender":"Acme <[email protected]>"}}\n\nNotes:\n\n- Use `update-props` with a JSON Action array to add, order, or remove destinations. The Action entries use `{ "dataSourceId": "..." }` and support up to ten Resources, matching the Builder control. Each connected Action runs in its configured order. An extra `enabled` key in older saved settings is ignored.\n- Create each destination Resource in the Form\'s scope so it can use `formData` and `browserInfo`. Set `exposeAsDataSource:true` to receive the data-source id used by the Action array. When a Resource uses Form-only parameters, it is kept out of page-load requests and runs with the Form submission.\n- `update-resource` accepts the same Email settings as the Builder: project, custom, or visitor recipients; sender; subject; body; and submitted-file attachments. Use expressions in string fields for dynamic values.\n- `update-project-settings` edits the project-wide Email recipients and Reply to. `update-props` also sets Form fields and Success redirect, while `bind-props` supplies dynamic expressions. `insert-component` uses the registered Form template, including its default contact fields and Email Actions. Set subject and body on each Email Resource.\n- MCP mutations update saved project configuration. To test real delivery, submit the Form in Preview or on a published test site and inspect the configured destinations.\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- Choose `.mdx` connected to a Content Block when editors must edit article bodies visually in Content mode. Publishing downloads and compiles every reachable MDX article, so more articles can slow publishing. Choose `.md` with Markdown Embed when editing the source in Assets is enough; Content mode editors can still edit the Markdown file there, but not its body on the canvas. `.md` needs no per-article MDX compilation, though the publish runner still synchronizes Asset files for both formats and static generation may read Markdown bodies.\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`,\n`system.search`. A query key with one value is a string; a repeated key is an\narray of values in their original order. For `?tag=red&tag=blue`,\n`system.search.tag` is `["red", "blue"]`; missing keys are absent.\n\nFor a saved Webhook Form on `/products/:slug`, a Resource URL can use\n`"https://api.example.com/products/" + system.params.slug + "/comments"`.\nOn `/products/chair?source=newsletter&tag=red&tag=blue`, use\n`system.search.source` for `"newsletter"` and `system.search.tag` for\n`["red", "blue"]` in a header or object body expression. A missing key stays\nabsent; use `system.search.source ?? "direct"` when a fallback is needed.\nThese values come from the page being submitted, including after navigation.\nFor a saved Webhook Form action, object body bindings are combined with the\nsubmitted fields; a submitted field wins when both use the same key.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',"manual-llm":'# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the readable payload in `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nSingle quotes inside the JSX keep the JSON valid without backslash-escaped attributes. The same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS. For simpler cases, use React-style object syntax such as`style={{ padding: 24 }}`. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in exactly one direct `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes editable Content Block body content. A missing or second template container makes the block invalid. Verify this structure before handoff.\n\nWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.\n\nWhen the Content Block body must be stored in an `.mdx` Asset, use the dedicated `connect-content-block-source`, `switch-content-block-source`, `inspect-content-block-source`, `edit-content-block-source`, `update-content-block-frontmatter`, `reload-content-block-source`, and `disconnect-content-block-source` tools. Do not manipulate its `src` with generic prop tools. Connecting replaces existing Body content, so report `requiresConfirmation:true` and retry with `confirmReplacement:true` only after user approval. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep their template styles. A mismatched child structure replaces defaults, while an explicit empty pair clears defaults and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, including when a matching template is added after the MDX element. Preserve invalid MDX and unresolved template names, inspect all source-located diagnostics, and resolve revision conflicts by reloading before reapplying the change. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy updates across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nFrontmatter is part of the same MDX source. `update-content-block-frontmatter` receives the complete replacement property map, so inspect and preserve properties the user did not ask to remove. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits; MDX-rendered elements are not persistent targets for generic prop or text mutations. Preserve existing `mode:"readwrite"` bindings, which are valid only for exact direct frontmatter paths. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. For an expression-bound source inside a Collection, pass the occurrence\'s scoped values and a distinct stable `renderScope`; for example, resolve `post.assetId` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<button onClick={new ActionValue(["event"], expression`console.log(event)`)}>\n Open\n</button>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<Switch><SwitchThumb /></Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <section\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <h2>Launch metrics</h2>\n <p>A polished card that fades up as it enters the viewport.</p>\n </section>\n</AnimateChildren>\n```\n\nFor Text Animation, keep `AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <AnimateText splitBy="space" slidingWindow={5} easing="easeOutQuart">\n <h2>Animate words with controlled rhythm</h2>\n </AnimateText>\n</AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `StaggerAnimation`:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <StaggerAnimation>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </article>\n </StaggerAnimation>\n</AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <VideoAnimation timeline={true}>\n <Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </VideoAnimation>\n</AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. When a value or id is known, call `search-project` once instead of passing broad snapshots or several lists to the model. Use semantic list/get reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, and `list-breakpoints` when the structure or target is not known. Use `snapshot` only when exact raw patch paths are needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n For a Builder link from **Copy link to instance**, parse the URL with `URL`/`URLSearchParams`. The decoded `instance` query parameter is a comma-separated selector ordered from the target instance to the page root. Pass its first entry to `inspect-instance`, for example `?pageId=page-id&instance=heading-id%2Cslot-id%2Cbody-id` becomes `{"instanceId":"heading-id","include":["props","styles","children","ancestors"]}`. Use `pageId` and the remaining selector entries to check the page and shared Slot occurrence before changing it. Shared Slot descendants are shared records; editing one changes all occurrences. Verify that the configured MCP project matches the linked project before editing; stop if they differ. The URL does not authorize switching projects. If the instance is missing, ask for an updated link instead of guessing another target. Never send a Builder link to screenshot tools or echo its `authToken`.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, ask whether the user wants visual verification unless they explicitly requested it. Only after they opt in, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Ask whether the user wants visual verification unless they explicitly requested screenshots, visual verification, or a rendered audit. Do not start preview, screenshots, screenshot diffs, OCR installation, or rendered audits until they opt in.\n5. After they opt in, keep generated project files current, start preview, and capture the changed page with `screenshot`.\n6. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n7. If the user declines or vision tooling is unavailable, use focused non-visual assertions and state that vision was not run.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Ask whether the user wants visual verification unless they explicitly requested it. Do not capture responsive screenshots until they opt in.\n4. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n5. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n6. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n7. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\nAlways write direct property access in authored expressions, such as\n`formData.subject`. Never type optional property access (`?.`) in an authored\nbinding. The expression compiler inserts it into generated JavaScript to make\nmissing intermediate values safe; that generated syntax is not an authoring\nexample and must not be copied into a binding. Use\n`formData.subject ?? "New message"` when a missing value needs a meaningful\nfallback.\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 contain JavaScript expression source. For fixed text, pass a quoted string expression such as `"Pricing | Acme"`; for computed values, pass code such as `pageTitle ?? "Pricing | Acme"`. An unquoted word is a variable reference, not fixed text.\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- Choose the article format before building a blog. Use `.mdx` with a Content Block for Notion-style visual body editing in Content mode; publishing downloads and compiles each reachable MDX article, which can slow publishing as the blog grows. Use `.md` with Markdown Embed when editors can work in the Markdown file editor in Assets instead; they can edit the source in Content mode but not the body visually on the canvas. `.md` needs no per-article MDX compilation, but the current publish sync still downloads Asset files for both formats, and static generation may read Markdown bodies.\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`. A query key with one value is a string, while repeated values are an ordered array. For `?tag=red&tag=blue`, `system.search.tag` is `["red", "blue"]`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access. Use nullish coalescing when a fallback is required.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use expression source for page metadata. Quote fixed text as a JavaScript string literal within the JSON string.\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\n### Server-side Form simulation\n\n`forms.simulate-submission` evaluates a saved Form using synthetic string fields\nand the same trusted Builder server Form handler used by Builder Preview. Supply\nthe saved Form instance ID and page path. The server uses this project\'s\npublisher origin. It can trigger the Form\'s configured HTTP and Email Resources, so verify\nevery destination and recipient first. For dynamic checkbox or multiple-select fields,\npass `arrayNames` to preserve an empty or single-value array when the saved\nfield props do not identify the control. The result reports destination statuses\nand errors without Resource bodies. This server simulation does not exercise\nclient validation, browser event handlers, navigation, file bytes, or actual\nbrowser information. The Builder server loads the saved draft and holds the\nEmail service credentials; the CLI does not receive those credentials.\n\n```json\n{\n "path": "/contact",\n "formId": "saved-form-instance-id",\n "values": [{ "name": "email", "value": "[email protected]" }]\n}\n```\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 ws:tokens={[token("accent")]}>Reuse an existing accent token</section>\n\n<section>\n <Switch>\n <SwitchThumb />\n </Switch>\n</section>\n```\n\nUse the two-argument `token` form with a `css` template to define styles in the\nfragment. Use `token("name")` to attach an existing project token; an unknown\nname is an error.\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\nChoose this format before building a blog: each reachable connected MDX article is downloaded and compiled when publishing, so publishing can take longer as the blog grows. If editors only need to edit Markdown source in Assets, use `.md` with Markdown Embed instead. Content mode editors can edit those files in the Markdown file editor, but cannot edit the article body visually on the canvas. `.md` does not need per-article MDX compilation; the current publish sync still transfers Asset files for either format, and static generation may read Markdown bodies.\n\n### Connect a collection to its entry page\n\nWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.\n\n```json\n{\n "x-webstudio": {\n "template": "template.mdx",\n "entries": ["*.mdx"],\n "entryPageId": "<dynamic-entry-page-id>"\n }\n}\n```\n\n1. Create the `.mdx` file under `.webstudio/assets`, then upload it and keep the returned Asset ID.\n2. Inspect the Content Block and verify that it has exactly one direct Templates container. Every custom template referenced from MDX needs a unique top-level instance name. A missing or second Templates container blocks connected MDX materialization and publication.\n3. Connect the Asset with `connect-content-block-source`. Use a stable page-based `renderScope` for a direct occurrence.\n4. If the result returns `requiresConfirmation:true`, tell the user that connecting will replace the existing Body content. Repeat the same call with `confirmReplacement:true` only after approval.\n5. Edit the complete source with `edit-content-block-source`, or replace the complete frontmatter map with `update-content-block-frontmatter`.\n6. Inspect every returned diagnostic. Invalid MDX is preserved, not silently repaired.\n\n```sh\nwebstudio upload-asset \'{"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\'\nwebstudio connect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\'\nwebstudio inspect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio edit-content-block-source --input-file .temp/edit-content-block-source.json\nwebstudio reload-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio migrate-content-block-template-references \'{"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\'\n```\n\nPrefer Markdown for standard document content. Markdown nodes automatically use a unique matching semantic template when one exists and keep their normal semantic fallback otherwise. Use lowercase JSX such as `<section>` or `<svg>` for a standard HTML or SVG element with authored properties Markdown cannot express.\n\nReference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template\'s stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.\n\nWhen explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants so template styles stay intact. A mismatched child structure replaces the root defaults, and each authored child still resolves through a matching template when possible. An explicit empty pair such as `<PromotionCard></PromotionCard>` clears the defaults. A self-closing reference such as `<PromotionCard />` keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live: adding a missing semantic or named template later also updates existing MDX without rewriting it. Preserve unresolved template names and report their diagnostics.\n\nWhen a template is renamed or deleted, use `migrate-content-block-template-references` to update the affected MDX files. Its first call returns a plan with changed-file, update, omission, and diagnostic counts. Report the plan and repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its explicit authored children; removing a self-closing reference removes that node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n\nUse the dedicated connect, switch, inspect, edit, update-frontmatter, reload, and disconnect operations instead of creating or deleting the Content Block\'s `src` with generic prop tools. An expression-bound source inside a Collection also needs the occurrence\'s scoped values and a distinct stable `renderScope`. For example, use `source:{"type":"expression","value":"post.assetId"}` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\n`renderScope` is any non-empty stable identity for one rendered occurrence, such as `page:/articles/example`. It does not load that page, its route parameters, or its resource results. To connect a result-one Assets resource, run `preview-asset-query` with concrete values, keep the saved source expression such as `post.data.id`, and supply the previewed item for this occurrence with `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`. The operation validates that concrete Asset while persisting the dynamic expression.\n\nA source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nIf an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n- `search-project`: find a known value or id with `webstudio search-project \'{"query":"pricing"}\'` or MCP `search-project {"query":"pricing"}`; use focused list/get tools when the target structure is unknown\n\n`meta.guide` returns structured `routing` with the selected workflow and any broad context bundle it recommends. Authentication and design context bundles appear only when their specialized workflow is selected. Set `authoredFragment` when using an authored fragment and `reuseDesignSystem` when its recommendations should retain design-system discovery tools.\n\nSet `taskScope` and `workflow` explicitly; `meta.guide` does not infer them or the authored-fragment flags from the brief. Specialized workflows are `markdown-blog`, `json-ld`, `collection`, `expression`, `authenticated-page`, `font-assets`, `design-input`, `content-block-source`, and `craft`; otherwise use `general`. Use `content-block-source` to connect or edit a Markdown/MDX-backed Content Block, including writable bindings for its designed header. 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### Converting a composite component to HTML\n\n`convert-instance` changes one instance and validates its entire descendant tree after that change. For a Tabs tree, changing `Tabs` to a `div` first fails because `TabsList`, `TabsTrigger`, and `TabsContent` still require their composite parents. Convert from the leaves upward instead: `TabsTrigger` to `ws:element` with tag `button`, `TabsContent` to `ws:element` with tag `div`, `TabsList` to `ws:element` with tag `div`, then `Tabs` to `ws:element` with tag `div`. Pass the complete, current `instanceSelector` for each call, starting with the target. Read the actual tree first; convert every remaining required part before its parent. Each step is a separate mutation, so this recipe is not atomic.\n\nConversion retains instance ids, children (including editable copy), styles, and most props; it removes a legacy `tag` prop and normalizes React prop aliases when converting to `ws:element`. Review component-specific props and behavior afterward: replacing Tabs with HTML does not recreate tab selection, keyboard behavior, or accessibility semantics. If a project requires the whole tree to change in one commit, use `snapshot` to read the current build version and exact records, then a single versioned `apply-patch` transaction for the existing instance component/tag fields. Preserve all existing ids and child references, include any needed prop changes in that same transaction, and verify the final tree.\n\nFor composite media such as Vimeo, inspect the player subtree and surrounding content first. A native `video` cannot retain provider-only parts such as `VimeoPlayButton`, `VimeoSpinner`, or `VimeoPreviewImage`. Use `delete-instance` with `instanceIds` containing the exact obsolete part ids (deleting a part also cleans its descendants and owned data), then `convert-instance` on the player root with `component: "ws:element"`, `tag: "video"`, and its current `instanceSelector`. Keep surrounding wrappers, captions, and other content outside the deletion set; move any content that must survive out of an obsolete part before deleting it. The player keeps its id and styles. Remove the provider-specific props with `delete-props`, using `{"deletions":[{"instanceId":"<player-id>","name":"url"}]}` for the old Vimeo URL prop and adding one entry for each other obsolete prop found during inspection. Then use `update-props` to set the native video source and playback props, and `update-styles` for any styling changes. A native video source must be a playable media URL or asset, not a Vimeo watch-page URL. These are separate semantic mutations; no raw instance patch is needed for this sequence.\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\n### Server-side Form simulation\n\n`forms.simulate-submission` evaluates a saved Form using synthetic string fields\nand the same trusted Builder server Form handler used by Builder Preview. Supply\nthe saved Form instance ID and page path. The server uses this project\'s\npublisher origin. It can trigger the Form\'s configured HTTP and Email Resources, so verify\nevery destination and recipient first. For dynamic checkbox or multiple-select fields,\npass `arrayNames` to preserve an empty or single-value array when the saved\nfield props do not identify the control. The result reports destination IDs,\nstatuses, and errors without Resource bodies. Managed Email errors include a\ncode when available. This server simulation does not exercise\nclient validation, browser event handlers, navigation, file bytes, or actual\nbrowser information. The Builder server loads the saved draft and holds the\nEmail service credentials; the CLI does not receive those credentials.\n\n```json\n{\n "path": "/contact",\n "formId": "saved-form-instance-id",\n "values": [{ "name": "email", "value": "[email protected]" }]\n}\n```\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 ws:tokens={[token("accent")]}>Reuse an existing accent token</section>\n\n<section>\n <Switch>\n <SwitchThumb />\n </Switch>\n</section>\n```\n\nUse the two-argument `token` form with a `css` template to define styles in the\nfragment. Use `token("name")` to attach an existing project token; an unknown\nname is an error.\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\nChoose this format before building a blog: each reachable connected MDX article is downloaded and compiled when publishing, so publishing can take longer as the blog grows. If editors only need to edit Markdown source in Assets, use `.md` with Markdown Embed instead. Content mode editors can edit those files in the Markdown file editor, but cannot edit the article body visually on the canvas. `.md` does not need per-article MDX compilation; the current publish sync still transfers Asset files for either format, and static generation may read Markdown bodies.\n\n### Connect a collection to its entry page\n\nWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.\n\n```json\n{\n "x-webstudio": {\n "template": "template.mdx",\n "entries": ["*.mdx"],\n "entryPageId": "<dynamic-entry-page-id>"\n }\n}\n```\n\n1. Create the `.mdx` file under `.webstudio/assets`, then upload it and keep the returned Asset ID.\n2. Inspect the Content Block and verify that it has exactly one direct Templates container. Every custom template referenced from MDX needs a unique top-level instance name. A missing or second Templates container blocks connected MDX materialization and publication.\n3. Connect the Asset with `connect-content-block-source`. Use a stable page-based `renderScope` for a direct occurrence.\n4. If the result returns `requiresConfirmation:true`, tell the user that connecting will replace the existing Body content. Repeat the same call with `confirmReplacement:true` only after approval.\n5. Edit the complete source with `edit-content-block-source`, or replace the complete frontmatter map with `update-content-block-frontmatter`.\n6. Inspect every returned diagnostic. Invalid MDX is preserved, not silently repaired.\n\n```sh\nwebstudio upload-asset \'{"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\'\nwebstudio connect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\'\nwebstudio inspect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio edit-content-block-source --input-file .temp/edit-content-block-source.json\nwebstudio reload-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio migrate-content-block-template-references \'{"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\'\n```\n\nPrefer Markdown for standard document content. Markdown nodes automatically use a unique matching semantic template when one exists and keep their normal semantic fallback otherwise. Use lowercase JSX such as `<section>` or `<svg>` for a standard HTML or SVG element with authored properties Markdown cannot express.\n\nReference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template\'s stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.\n\nWhen explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants so template styles stay intact. A mismatched child structure replaces the root defaults, and each authored child still resolves through a matching template when possible. An explicit empty pair such as `<PromotionCard></PromotionCard>` clears the defaults. A self-closing reference such as `<PromotionCard />` keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live: adding a missing semantic or named template later also updates existing MDX without rewriting it. Preserve unresolved template names and report their diagnostics.\n\nWhen a template is renamed or deleted, use `migrate-content-block-template-references` to update the affected MDX files. Its first call returns a plan with changed-file, update, omission, and diagnostic counts. Report the plan and repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its explicit authored children; removing a self-closing reference removes that node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n\nUse the dedicated connect, switch, inspect, edit, update-frontmatter, reload, and disconnect operations instead of creating or deleting the Content Block\'s `src` with generic prop tools. An expression-bound source inside a Collection also needs the occurrence\'s scoped values and a distinct stable `renderScope`. For example, use `source:{"type":"expression","value":"post.assetId"}` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\n`renderScope` is any non-empty stable identity for one rendered occurrence, such as `page:/articles/example`. It does not load that page, its route parameters, or its resource results. To connect a result-one Assets resource, run `preview-asset-query` with concrete values, keep the saved source expression such as `post.data.id`, and supply the previewed item for this occurrence with `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`. The operation validates that concrete Asset while persisting the dynamic expression.\n\nA source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nIf an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n- `search-project`: find a known value or id with `webstudio search-project \'{"query":"pricing"}\'` or MCP `search-project {"query":"pricing"}`; use focused list/get tools when the target structure is unknown\n\n`meta.guide` returns structured `routing` with the selected workflow and any broad context bundle it recommends. Authentication and design context bundles appear only when their specialized workflow is selected. Set `authoredFragment` when using an authored fragment and `reuseDesignSystem` when its recommendations should retain design-system discovery tools.\n\nSet `taskScope` and `workflow` explicitly; `meta.guide` does not infer them or the authored-fragment flags from the brief. Specialized workflows are `markdown-blog`, `json-ld`, `collection`, `expression`, `authenticated-page`, `font-assets`, `design-input`, `content-block-source`, and `craft`; otherwise use `general`. Use `content-block-source` to connect or edit a Markdown/MDX-backed Content Block, including writable bindings for its designed header. 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### Converting a composite component to HTML\n\n`convert-instance` changes one instance and validates its entire descendant tree after that change. For a Tabs tree, changing `Tabs` to a `div` first fails because `TabsList`, `TabsTrigger`, and `TabsContent` still require their composite parents. Convert from the leaves upward instead: `TabsTrigger` to `ws:element` with tag `button`, `TabsContent` to `ws:element` with tag `div`, `TabsList` to `ws:element` with tag `div`, then `Tabs` to `ws:element` with tag `div`. Pass the complete, current `instanceSelector` for each call, starting with the target. Read the actual tree first; convert every remaining required part before its parent. Each step is a separate mutation, so this recipe is not atomic.\n\nConversion retains instance ids, children (including editable copy), styles, and most props; it removes a legacy `tag` prop and normalizes React prop aliases when converting to `ws:element`. Review component-specific props and behavior afterward: replacing Tabs with HTML does not recreate tab selection, keyboard behavior, or accessibility semantics. If a project requires the whole tree to change in one commit, use `snapshot` to read the current build version and exact records, then a single versioned `apply-patch` transaction for the existing instance component/tag fields. Preserve all existing ids and child references, include any needed prop changes in that same transaction, and verify the final tree.\n\nFor composite media such as Vimeo, inspect the player subtree and surrounding content first. A native `video` cannot retain provider-only parts such as `VimeoPlayButton`, `VimeoSpinner`, or `VimeoPreviewImage`. Use `delete-instance` with `instanceIds` containing the exact obsolete part ids (deleting a part also cleans its descendants and owned data), then `convert-instance` on the player root with `component: "ws:element"`, `tag: "video"`, and its current `instanceSelector`. Keep surrounding wrappers, captions, and other content outside the deletion set; move any content that must survive out of an obsolete part before deleting it. The player keeps its id and styles. Remove the provider-specific props with `delete-props`, using `{"deletions":[{"instanceId":"<player-id>","name":"url"}]}` for the old Vimeo URL prop and adding one entry for each other obsolete prop found during inspection. Then use `update-props` to set the native video source and playback props, and `update-styles` for any styling changes. A native video source must be a playable media URL or asset, not a Vimeo watch-page URL. These are separate semantic mutations; no raw instance patch is needed for this sequence.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n{{contentEngineReferenceMarkdown}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',"mcp-startup-epilogue":'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\n}\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in exactly one direct `ws:block-template` child. A missing or second template container makes the block invalid. Templates themselves are protected; an editor\'s inserted copy becomes editable Content Block body content. Verify this structure before handoff.\n\nFor an MDX-backed Content Block, use the dedicated content-source tools instead of generic prop mutations: connect, switch, inspect, edit, update frontmatter, reload, or disconnect the source. Confirm before replacing existing Body content. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep template styles. A mismatched child structure replaces defaults, an explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live when matching templates are added later. Preserve invalid source and unresolved names, inspect all diagnostics, and reload before retrying a revision conflict. A frontmatter update replaces the complete property map; preserve fields the user did not ask to remove. Store frontmatter images as exact `$ref` objects; bind editable Image sources to `.src` with explicit `binding.mode:"readwrite"` and alt properties to the Asset `.description` with `mode:"read"`. Omitting the source mode leaves the image visible but not replaceable in Content mode. Only exact direct frontmatter bindings may use `mode:"readwrite"`. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy changes across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get-more-tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nWhen `report-issue` is available, use it when the user explicitly asks to report a problem. Also use it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. Write a complete technical 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. The CLI attaches the project ID and recognized entity IDs from the failed tool input; do not copy additional IDs into the authored text. Never include names, usernames, emails, phone numbers, organizations, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, other exact unique values, or raw contextual tool data.\n\nIf a mutation returns an unclear transport or response error, make one read-only check to see whether it committed and include that outcome in the report. For browser startup failures, include the selected browser family, whether fallback was attempted, and any shown exit signal or code, but never an executable path. The CLI adds bounded failure diagnostics automatically; do not paraphrase missing values as facts.\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":diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.mdindex 8d56c68111..1a7fee43ab 100644--- a/packages/cli/src/docs/api-use-cases.md+++ b/packages/cli/src/docs/api-use-cases.md@@ -424,14 +424,14 @@ Commands:- 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"}+- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ResourceForm"}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.- 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"`.+- For Webstudio's complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"ResourceForm"`.- 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.- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.@@ -839,7 +839,7 @@ Use the exact component id returned by `components.search` for **Form (Beta)**.After inserting its registered template, use the Form instance id for theForm-scoped Resource and Action settings.-The new Form's canonical component id is `Form`. The deprecated legacy+The new Form's canonical component id is `ResourceForm`. The deprecatedWebhook Form remains available in Builder for existing projects until the nextrelease, but is omitted from MCP component discovery. `RemixForm` is deprecatedcompatibility and should not be used for new projects. Always use registrydiff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.mdindex e37c2066e3..d8830eb446 100644--- a/packages/cli/src/docs/manual-mcp.md+++ b/packages/cli/src/docs/manual-mcp.md@@ -43,8 +43,9 @@ the saved Form instance ID and page path. The server uses this project'spublisher origin. It can trigger the Form's configured HTTP and Email Resources, so verifyevery destination and recipient first. For dynamic checkbox or multiple-select fields,pass `arrayNames` to preserve an empty or single-value array when the saved-field props do not identify the control. The result reports destination statuses-and errors without Resource bodies. This server simulation does not exercise+field props do not identify the control. The result reports destination IDs,+statuses, and errors without Resource bodies. Managed Email errors include a+code when available. This server simulation does not exerciseclient validation, browser event handlers, navigation, file bytes, or actualbrowser information. The Builder server loads the saved draft and holds theEmail service credentials; the CLI does not receive those credentials.diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.tsindex 39981a2f69..5dc14dc631 100644--- a/packages/cli/src/prebuild.test.ts+++ b/packages/cli/src/prebuild.test.ts@@ -86,6 +86,23 @@ const rootFolderId = "root";const elementComponent = "ws:element";const slowPrebuildTestTimeout = 15_000;+const loadGeneratedIndexAction = async () => {+ await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");+ await build({+ stdin: {+ contents: 'export { action } from "./app/routes/_index"',+ resolveDir: tempDir,+ },+ outfile: join(tempDir, "action.mjs"),+ bundle: true,+ platform: "node",+ format: "esm",+ packages: "external",+ loader: { ".css": "text" },+ });+ return import(pathToFileURL(join(tempDir, "action.mjs")).href);+};+const runGeneratedCommand = async (command: "react-router" | "remix" | "tsc" | "vite" | "vike",args: string[]@@ -3311,7 +3328,7 @@ sitemap.map((page) => page.path);`);test.each(["defaults", "react-router"])(- "uses route params and query values in a legacy Form Resource (%s)",+ "uses route params and query values in a deprecated Webhook Form Resource (%s)",async (template) => {const system = encodeDataSourceVariable(SYSTEM_VARIABLE_ID);const siteData = createSiteData({@@ -3359,6 +3376,13 @@ sitemap.map((page) => page.path);`] as never;await writeSiteData(siteData);await prebuild({ assets: false, template: [template] });+ await writeFile(+ join(+ tempDir,+ "app/__generated__/$resources.managed-form-fetch.server.ts"+ ),+ "export const createManagedFormEmailSender = () => undefined;\nexport const validateManagedFormEmail = () => undefined;\nexport const createManagedFormResourceFetch = () => Object.assign(globalThis.__deprecatedWebhookFormRouteFetch, { validateDestination: () => undefined });\n"+ );await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");await build({stdin: {@@ -3366,7 +3390,7 @@ sitemap.map((page) => page.path);`'export { action } from "./app/routes/[products].$slug._index"',resolveDir: tempDir,},- outfile: join(tempDir, "legacy-action.mjs"),+ outfile: join(tempDir, "deprecated-webhook-form-action.mjs"),bundle: true,platform: "node",format: "esm",@@ -3374,7 +3398,7 @@ sitemap.map((page) => page.path);`loader: { ".css": "text" },});const { action } = await import(- pathToFileURL(join(tempDir, "legacy-action.mjs")).href+ pathToFileURL(join(tempDir, "deprecated-webhook-form-action.mjs")).href);const received: Array<{url: string;@@ -3382,7 +3406,7 @@ sitemap.map((page) => page.path);`body: unknown;}> = [];vi.stubGlobal(- "fetch",+ "__deprecatedWebhookFormRouteFetch",vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {const request = new Request(input, init);received.push({@@ -3530,7 +3554,246 @@ sitemap.map((page) => page.path);`);test.each(["defaults", "react-router"])(- "submits identical forms twice while caching dependencies (%s)",+ "keeps a saved Webhook Form URL method and rejects its own host (%s)",+ async (template) => {+ const siteData = createSiteData({+ instances: [+ ["root", { id: "root", component: "WebhookForm", children: [] }],+ ],+ props: [+ [+ "action",+ {+ id: "action",+ instanceId: "root",+ name: "action",+ type: "string",+ value: "https://receiver.example/hook",+ },+ ],+ [+ "method",+ {+ id: "method",+ instanceId: "root",+ name: "method",+ type: "string",+ value: "put",+ },+ ],+ ],+ });+ await writeSiteData(siteData);+ await prebuild({ assets: false, template: [template] });+ await writeFile(+ join(+ tempDir,+ "app/__generated__/$resources.managed-form-fetch.server.ts"+ ),+ `import { createProtectedResourceFetch } from "@webstudio-is/sdk/protected-resource-fetch";+export const createManagedFormEmailSender = () => undefined;+export const validateManagedFormEmail = () => undefined;+export const createManagedFormResourceFetch = ({ request }) => createProtectedResourceFetch({+ deniedHostnames: [new URL(request.url).hostname],+ transport: async ({ url, method, headers, body }) => ({+ response: await globalThis.__testManagedFormFetch(url, { method, headers, body }),+ }),+});+`+ );+ const { action } = await loadGeneratedIndexAction();+ const received: Array<{ method: string; body: unknown }> = [];+ vi.stubGlobal(+ "__testManagedFormFetch",+ async (input: RequestInfo | URL, init?: RequestInit) => {+ const request = new Request(input, init);+ received.push({ method: request.method, body: await request.json() });+ return Response.json({ accepted: true });+ }+ );+ const submit = (host: string) => {+ const form = new FormData();+ form.set(formIdFieldName, "action");+ form.set(formBotFieldName, "brave");+ form.set("message", "Hello");+ return action({+ request: new Request(`https://${host}/`, {+ method: "POST",+ headers: { host },+ body: form,+ }),+ context: {},+ });+ };+ await expect(submit("example.com")).resolves.toEqual({ success: true });+ expect(received).toEqual([{ method: "PUT", body: { message: "Hello" } }]);+ const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ await expect(submit("receiver.example")).resolves.toEqual({+ success: false,+ errors: ["Resource destination is not allowed"],+ });+ } finally {+ errorLog.mockRestore();+ }+ expect(received).toHaveLength(1);+ }+ );++ test.each(+ ["defaults", "react-router"].flatMap((template) =>+ [0, 1, 6].map((recipients) => [template, recipients] as const)+ )+ )(+ "sends and preflights deprecated Webhook Form emails through the Form sender (%s, %i configured recipients)",+ async (template, recipientCount) => {+ const siteData = createSiteData({+ instances: [+ ["root", { id: "root", component: "WebhookForm", children: [] }],+ ],+ pageMeta: { contactEmail: "[email protected]" },+ });+ if (recipientCount > 0) {+ siteData.build.props = [+ [+ "action",+ {+ id: "action",+ instanceId: "root",+ name: "action",+ type: "resource",+ value: "email",+ },+ ],+ ];+ siteData.build.resources = [+ [+ "email",+ {+ id: "email",+ name: "Email",+ control: "email",+ method: "post",+ url: '""',+ headers: [],+ email: {+ recipientMode: "custom",+ recipients: Array.from(+ { length: recipientCount },+ (_, index) => `person${index}@example.com`+ ).join(", "),+ subject: '"Saved subject"',+ body: '"Saved message"',+ },+ },+ ],+ ];+ }+ await writeSiteData(siteData);+ await prebuild({ assets: false, template: [template] });+ await writeFile(+ join(+ tempDir,+ "app/__generated__/$resources.managed-form-fetch.server.ts"+ ),+ "export const createManagedFormEmailSender = () => globalThis.__testSendEmail;\nexport const validateManagedFormEmail = (...args) => globalThis.__testValidateEmail(...args);\nexport const createManagedFormResourceFetch = () => Object.assign(fetch, { validateDestination: () => undefined });\n"+ );+ const { action } = await loadGeneratedIndexAction();+ const validateEmail = vi.fn();+ vi.stubGlobal("__testValidateEmail", validateEmail);+ const messages: ResourceRequest[] = [];+ vi.stubGlobal("__testSendEmail", async (resource: ResourceRequest) => {+ messages.push(resource);+ return {+ ok: true,+ status: 200,+ statusText: "OK",+ data: { id: "sent" },+ };+ });+ const form = new FormData();+ form.set(formBotFieldName, "brave");+ if (recipientCount > 0) {+ form.set(formIdFieldName, "action");+ }+ form.set("message", "Hello");+ if (recipientCount > 5) {+ const errorLog = vi+ .spyOn(console, "error")+ .mockImplementation(() => {});+ try {+ await expect(+ action({+ request: new Request("https://example.com/", {+ method: "POST",+ headers: { host: "example.com" },+ body: form,+ }),+ context: {},+ })+ ).resolves.toEqual({+ success: false,+ errors: [+ "Select no more than 5 team email recipients per Form submission",+ ],+ });+ } finally {+ errorLog.mockRestore();+ }+ expect(messages).toHaveLength(0);+ return;+ }+ await expect(+ action({+ request: new Request("https://example.com/", {+ method: "POST",+ headers: { host: "example.com" },+ body: form,+ }),+ context: {},+ })+ ).resolves.toEqual({ success: true });+ expect(messages).toHaveLength(1);+ expect(messages[0]?.control).toBe("email");+ expect(messages[0]?.email?.recipients).toEqual([+ {+ address:+ recipientCount > 0 ? "[email protected]" : "[email protected]",+ },+ ]);+ expect(messages[0]?.email?.headers?.["X-Message-ID"]).toEqual(+ expect.any(String)+ );+ expect(validateEmail).toHaveBeenCalledOnce();+ vi.stubGlobal("__testSendEmail", async () => ({+ ok: false,+ status: 503,+ statusText: "Email service is unavailable",+ data: {+ error: {+ code: "EMAIL_SERVICE_UNAVAILABLE",+ message: "Email service is unavailable",+ },+ },+ }));+ await expect(+ action({+ request: new Request("https://example.com/", {+ method: "POST",+ headers: { host: "example.com" },+ body: form,+ }),+ context: {},+ })+ ).resolves.toEqual({+ success: false,+ errors: ["Email service is unavailable"],+ });+ }+ );++ test.each(["defaults", "react-router"])(+ "submits identical deprecated Webhook Forms twice while caching dependencies (%s)",async (template) => {const siteData = createSiteData({instances: [["root", { id: "root", component: "Form", children: [] }]],@@ -3566,7 +3829,7 @@ sitemap.map((page) => page.path);`id: "author",name: "Author",method: "post",- url: '"https://example.com/author"',+ url: '"https://receiver.example/author"',body: '{ query: "author" }',headers: [{ name: "Cache-Control", value: '"public, max-age=60"' }],},@@ -3577,7 +3840,7 @@ sitemap.map((page) => page.path);`id: "submit",name: "Submit",method: "post",- url: `"https://example.com/submit/" + ${encodeDataSourceVariable(+ url: `"https://receiver.example/submit/" + ${encodeDataSourceVariable("author")}.data.id`,headers: [{ name: "Cache-Control", value: '"public, max-age=60"' }],@@ -3586,22 +3849,14 @@ sitemap.map((page) => page.path);`];await writeSiteData(siteData);await prebuild({ assets: false, template: [template] });- await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");- await build({- stdin: {- contents: 'export { action } from "./app/routes/_index"',- resolveDir: tempDir,- },- outfile: join(tempDir, "action.mjs"),- bundle: true,- platform: "node",- format: "esm",- packages: "external",- loader: { ".css": "text" },- });- const { action } = await import(- pathToFileURL(join(tempDir, "action.mjs")).href+ await writeFile(+ join(+ tempDir,+ "app/__generated__/$resources.managed-form-fetch.server.ts"+ ),+ "export const createManagedFormEmailSender = () => undefined;\nexport const validateManagedFormEmail = () => undefined;\nexport const createManagedFormResourceFetch = () => Object.assign(fetch, { validateDestination: () => undefined });\n");+ const { action } = await loadGeneratedIndexAction();const cached = new Map<string, Response>();vi.stubGlobal("caches", {open: async () => ({@@ -3666,13 +3921,13 @@ sitemap.map((page) => page.path);`).resolves.toEqual({ success: true });}expect(received).toEqual([- { url: "https://example.com/author", body: { query: "author" } },+ { url: "https://receiver.example/author", body: { query: "author" } },{- url: "https://example.com/submit/author-123",+ url: "https://receiver.example/submit/author-123",body: { message: "Hello" },},{- url: "https://example.com/submit/author-123",+ url: "https://receiver.example/submit/author-123",body: { message: "Hello" },},]);diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex de8d4b36a2..60875f4ba1 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -71,6 +71,7 @@ import {migratePages,migrateResourceFormInstancesMutable,} from "@webstudio-is/project-migrations";+import { hasHistoricalFormComponentIdentityVersion } from "@webstudio-is/project-migrations/pages";import {collectFontFamiliesFromStyleDecls,createWebstudioDataFromFragment,@@ -119,7 +120,7 @@ import {} from "@webstudio-is/query-builder/runtime";import {bundleVersion,- publishedProjectBundle,+ historicalPublishedProjectBundle,type PublishedProjectBundle,} from "@webstudio-is/protocol";import { createAuthConfigResources, LOCAL_AUTH_FILE } from "./auth-config";@@ -970,7 +971,8 @@ export const prebuild = async (options: {`Project bundle is missing, please make sure the project is synced.`);}- const parsedSiteData = publishedProjectBundle.safeParse(loadedSiteData);+ const parsedSiteData =+ historicalPublishedProjectBundle.safeParse(loadedSiteData);if (parsedSiteData.success === false) {throw Object.assign(new Error(@@ -989,9 +991,10 @@ export const prebuild = async (options: {const siteData = parsedSiteData.data;const pages = migratePages(siteData.build.pages);const migratedInstances = new Map(siteData.build.instances);+ // Saved Form identities may still need the deprecated Webhook Form migration.migrateResourceFormInstancesMutable(migratedInstances.values(),- pages.formComponentIdentityVersion === undefined+ hasHistoricalFormComponentIdentityVersion(siteData.build.pages));const publicationBuild = { ...siteData.build, pages };const allAssetIds = new Set(siteData.assets.map(({ id }) => id));@@ -1051,14 +1054,14 @@ export const prebuild = async (options: {const testFetch = async (input: RequestInfo | URL, init?: RequestInit) => {const outgoing = new Request(input, init);const url = new URL(outgoing.url);- if (url.origin !== "https://mcp-delivery.example" || (url.pathname !== "/submit" && url.pathname !== "/reject") || url.search !== "" || url.hash !== "" || outgoing.method !== "POST") {+ if (url.origin !== "https://mcp-delivery.example" || (url.pathname !== "/submit" && url.pathname !== "/reject") || [...url.searchParams.keys()].some((key) => key !== "slug" && key !== "tag") || url.hash !== "" || outgoing.method !== "POST") {throw new Error("Unexpected evaluation Form destination");}protectedFetch.validateDestination(url);- return fetch(new Request("http://127.0.0.1:${evaluationReceiverPort}" + url.pathname, outgoing));+ return fetch(new Request("http://127.0.0.1:${evaluationReceiverPort}" + url.pathname + url.search, outgoing));};return Object.assign(testFetch, { validateDestination: (url: URL) => {- if (url.origin !== "https://mcp-delivery.example" || (url.pathname !== "/submit" && url.pathname !== "/reject") || url.search !== "" || url.hash !== "") {+ if (url.origin !== "https://mcp-delivery.example" || (url.pathname !== "/submit" && url.pathname !== "/reject") || [...url.searchParams.keys()].some((key) => key !== "slug" && key !== "tag") || url.hash !== "") {throw new Error("Unexpected evaluation Form destination");}protectedFetch.validateDestination(url);@@ -1789,6 +1792,7 @@ export const createManagedFormResourceFetch = ({ request, context, projectDomainconst dataSources = new Map(pageData.build.dataSources);const resources = new Map(pageData.build.resources);+ // Deprecated Webhook Form-only conversion of saved action props.replaceFormActionsWithResources({instances,resources,@@ -1796,7 +1800,7 @@ export const createManagedFormResourceFetch = ({ request, context, projectDomain});const formInstances = Array.from(instances.values());const managedFormSubmissions = formInstances- .filter((instance) => instance.component === "Form")+ .filter((instance) => instance.component === "ResourceForm").map((instance) => {const actionProp = Array.from(props.values()).filter(@@ -1859,6 +1863,8 @@ export const createManagedFormResourceFetch = ({ request, context, projectDomain});const projectMeta = siteData.build.projectSettings?.meta ?? pages.meta;+ // The generated contactEmail export serves only saved Webhook Forms.+ // projectMeta.contactEmail itself also serves managed Email Resources.const contactEmail: undefined | string =// fallback to user email when contact email is empty stringprojectMeta?.contactEmail || siteData.user?.email || undefined;@@ -2010,6 +2016,7 @@ export const createManagedFormResourceFetch = ({ request, context, projectDomain${JSON.stringify(managedFormSubmissions)});+ /** @deprecated Generated only for saved Webhook Forms. */export const contactEmail = ${JSON.stringify(contactEmail)};`;diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.tsindex b8b02cc0d5..503d8d7936 100644--- a/packages/cli/src/project-session.test.ts+++ b/packages/cli/src/project-session.test.ts@@ -1,4 +1,4 @@-import { mkdtemp, readFile, rm } from "node:fs/promises";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { join } from "node:path";import { tmpdir } from "node:os";import { afterEach, describe, expect, test, vi } from "vitest";@@ -684,6 +684,105 @@ describe("cli project session storage", () => {)).resolves.toEqual({ revision: expect.any(String) });});++ test.each([+ { marker: 1, expected: "ResourceForm" },+ { marker: undefined, expected: "WebhookForm" },+ ])(+ "normalizes historical $expected in session and restore storage",+ async ({ marker, expected }) => {+ const directory = await createTemporaryDirectory();+ const sessionPath = join(directory, ".webstudio", "project-session.json");+ const restorePath = join(directory, ".webstudio", "restore-points.json");+ const sessionStorage = createCliProjectSessionStorage(sessionPath);+ const restoreStorage = createCliProjectRestorePointStorage(restorePath);+ const state = createBuilderStateFromSnapshot({+ pages: {+ homePageId: "home",+ rootFolderId: "root",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ rootInstanceId: "form",+ meta: {},+ },+ ],+ ]),+ folders: new Map([+ [+ "root",+ { id: "root", name: "Root", slug: "", children: ["home"] },+ ],+ ]),+ },+ instances: [+ [+ "form",+ {+ type: "instance",+ id: "form",+ component: "ResourceForm",+ children: [],+ },+ ],+ ],+ });+ const snapshot = {+ projectId: "project-1",+ buildId: "build-1",+ version: 3,+ state,+ freshness: createBuilderStateFreshness({ state, version: 3 }),+ compatibilityVersion: "test",+ compatibility: {+ sessionVersion: "test",+ runtimeContractVersion: "test-runtime",+ projectSchemaVersion: "test-schema",+ },+ };+ const { revision } = (await sessionStorage.save(snapshot, {}))!;+ const point = await restoreStorage.create("Historical", snapshot);++ const makeHistorical = (saved: {+ state: {+ instances: [string, { component: string }][];+ pages: Record<string, unknown>;+ };+ }) => {+ saved.state.instances[0][1].component = "Form";+ if (marker !== undefined) {+ saved.state.pages.formComponentIdentityVersion = marker;+ }+ return saved;+ };+ await writeFile(+ sessionPath,+ JSON.stringify(+ makeHistorical(JSON.parse(await readFile(sessionPath, "utf8")))+ )+ );+ const restoreFile = JSON.parse(await readFile(restorePath, "utf8"));+ makeHistorical(restoreFile.points[0].snapshot);+ await writeFile(restorePath, JSON.stringify(restoreFile));++ const loaded = await sessionStorage.load();+ const restored = await restoreStorage.get(point.id);+ for (const result of [loaded, restored]) {+ expect(result?.state.instances?.get("form")?.component).toBe(expected);+ expect(result?.state.pages).not.toHaveProperty(+ "formComponentIdentityVersion"+ );+ expect(result?.compatibilityVersion).toBe("test");+ expect(result?.version).toBe(3);+ }+ expect(loaded?.revision).toBe(revision);+ }+ );});describe("CLI/server operation contract", () => {@@ -1081,6 +1180,12 @@ describe("cli project session transport", () => {type: "instance",id: "body",component: "Body",+ children: [{ type: "id", value: "form" }],+ },+ {+ type: "instance",+ id: "form",+ component: "Form",children: [],},],@@ -1094,7 +1199,9 @@ describe("cli project session transport", () => {});expect(snapshot.state.pages?.pages.get("home")?.name).toBe("Home");- expect(snapshot.state.pages?.formComponentIdentityVersion).toBe(1);+ expect("formComponentIdentityVersion" in (snapshot.state.pages ?? {})).toBe(+ false+ );expect(snapshot.state.pages?.pageTemplates?.get("template-1")?.name).toBe("Landing");@@ -1107,44 +1214,60 @@ describe("cli project session transport", () => {"home",]);expect(snapshot.state.instances?.get("body")?.component).toBe("Body");+ expect(snapshot.state.instances?.get("form")?.component).toBe(+ "ResourceForm"+ );expect(snapshot.state.projectSettings).toEqual({meta: { siteName: "Canonical Acme" },compiler: { atomicStyles: false },});});- test("preserves an absent Form identity version in legacy public snapshots", async () => {+ test("reconstructs unmarked old-server Form snapshots as WebhookForm", async () => {+ const includes: string[][] = [];const transport = createCliProjectSessionTransport({connection: {projectId: "project-1",origin: "https://example.com",authToken: "token",},- getBuildSnapshot: async () => ({- projectId: "project-1",- buildId: "build-1",- version: 1,- homePageId: "home",- rootFolderId: "root",- pages: [- {- id: "home",- name: "Home",- path: "",- title: "Home",- rootInstanceId: "body",- meta: {},- },- ],- folders: [{ id: "root", name: "Root", slug: "", children: ["home"] }],- }),+ getBuildSnapshot: async ({ include }) => {+ includes.push(include ?? []);+ return {+ projectId: "project-1",+ buildId: "build-1",+ version: 1,+ homePageId: "home",+ rootFolderId: "root",+ pages: [+ {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ rootInstanceId: "body",+ meta: {},+ },+ ],+ folders: [{ id: "root", name: "Root", slug: "", children: ["home"] }],+ instances: [+ { type: "instance", id: "form", component: "Form", children: [] },+ ],+ };+ },});const snapshot = await transport.fetchNamespaces({projectId: "project-1",- namespaces: ["pages"],+ namespaces: ["instances"],});- expect(snapshot.state.pages?.formComponentIdentityVersion).toBeUndefined();+ expect("formComponentIdentityVersion" in (snapshot.state.pages ?? {})).toBe(+ false+ );+ expect(snapshot.state.instances?.get("form")?.component).toBe(+ "WebhookForm"+ );+ expect(includes[0]).toContain("pages");});test("falls back to legacy page settings when the server rejects projectSettings", async () => {diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.tsindex 542d5ba75f..f26a316ce0 100644--- a/packages/cli/src/project-session.ts+++ b/packages/cli/src/project-session.ts@@ -6,9 +6,11 @@ import { cwd } from "node:process";import { parseContentDatabaseMaxBytes } from "@webstudio-is/content-engine";import { compileContentSource } from "@webstudio-is/content-engine/compiler";import {+ hasHistoricalFormComponentIdentityVersion,migratePages,serializePages,} from "@webstudio-is/project-migrations/pages";+import { migrateResourceFormInstancesMutable } from "@webstudio-is/project-migrations";import * as httpClient from "@webstudio-is/http-client";import { createHttpAssetContentRepository } from "@webstudio-is/content-engine/asset-content-repository";import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";@@ -187,6 +189,7 @@ type PublicBuildSnapshot = Omit<version: number;homePageId?: string;rootFolderId?: string;+ /** Keep while unversioned saved projects are supported; tracks the Form identity migration. */formComponentIdentityVersion?: number;pages?: unknown;pageTemplates?: unknown;@@ -280,7 +283,6 @@ const toPages = (snapshot: PublicBuildSnapshot) => {return migratePages({homePageId: snapshot.homePageId,rootFolderId: snapshot.rootFolderId,- formComponentIdentityVersion: snapshot.formComponentIdentityVersion,pages: snapshot.pages,pageTemplates: snapshot.pageTemplates,folders: snapshot.folders,@@ -292,16 +294,32 @@ const toPages = (snapshot: PublicBuildSnapshot) => {const toRemoteSnapshot = (snapshot: PublicBuildSnapshot-): ProjectSessionRemoteSnapshot => ({- projectId: snapshot.projectId,- buildId: snapshot.buildId,- version: snapshot.version,- state: createBuilderStateFromBuildData({- ...snapshot,- pages: toPages(snapshot),- dataSources: snapshot.dataSources ?? snapshot.variables ?? [],- }),-});+): ProjectSessionRemoteSnapshot => {+ if (+ snapshot.pages === undefined &&+ snapshot.instances?.some((instance) => instance.component === "Form")+ ) {+ throw new Error("A snapshot with instances must include pages.");+ }+ const instances = snapshot.instances?.map((instance) => ({ ...instance }));+ if (instances !== undefined) {+ migrateResourceFormInstancesMutable(+ instances,+ hasHistoricalFormComponentIdentityVersion(snapshot)+ );+ }+ return {+ projectId: snapshot.projectId,+ buildId: snapshot.buildId,+ version: snapshot.version,+ state: createBuilderStateFromBuildData({+ ...snapshot,+ instances,+ pages: toPages(snapshot),+ dataSources: snapshot.dataSources ?? snapshot.variables ?? [],+ }),+ };+};const publicOperationById = new Map(publicApiOperations.map((operation) => [operation.id, operation])@@ -641,10 +659,32 @@ const withMappedRemoteError = async <Result>(task: () => Promise<Result>) => {const parsePersistedSnapshot = (value: PersistedCliProjectSessionSnapshot-): ProjectSessionPersistedSnapshot => ({- ...value,- state: createBuilderStateFromSerializedSnapshot(value.state),-});+): ProjectSessionPersistedSnapshot => {+ const instances = value.state.instances?.map(+ ([id, instance]) => [id, { ...instance }] as const+ );+ if (+ value.state.pages === undefined &&+ instances?.some(([, instance]) => instance.component === "Form")+ ) {+ throw new Error(+ "A persisted snapshot with Form instances must include pages."+ );+ }+ if (instances !== undefined) {+ migrateResourceFormInstancesMutable(+ instances.map(([, instance]) => instance),+ hasHistoricalFormComponentIdentityVersion(value.state.pages)+ );+ }+ return {+ ...value,+ state: createBuilderStateFromSerializedSnapshot({+ ...value.state,+ instances,+ }),+ };+};const serializePersistedSnapshot = (snapshot: ProjectSessionPersistedSnapshot@@ -793,7 +833,11 @@ export const createCliProjectSessionTransport = ({include,})) as Promise<PublicBuildSnapshot>;- const includes = getPublicBuildIncludes(namespaces);+ // Older servers need pages to disambiguate historical Form instances.+ const readNamespaces = namespaces.includes("instances")+ ? [...namespaces, "pages" as const]+ : namespaces;+ const includes = getPublicBuildIncludes(readNamespaces);let snapshot: PublicBuildSnapshot;try {snapshot = await fetchSnapshot(includes);@@ -804,7 +848,7 @@ export const createCliProjectSessionTransport = ({) {throw error;}- snapshot = await fetchSnapshot(getLegacyPublicApiInclude(namespaces));+ snapshot = await fetchSnapshot(getLegacyPublicApiInclude(readNamespaces));}return toRemoteSnapshot(snapshot);},diff --git a/packages/cli/templates/defaults/app/extension.ts b/packages/cli/templates/defaults/app/extension.tsindex 8e885b92f7..c42becab9a 100644--- a/packages/cli/templates/defaults/app/extension.ts+++ b/packages/cli/templates/defaults/app/extension.ts@@ -1,16 +1,9 @@// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignoreimport { AppLoadContext } from "@remix-run/server-runtime";-import type { ResourceRequest } from "@webstudio-is/sdk";declare module "@remix-run/server-runtime" {interface AppLoadContext {EXCLUDE_FROM_SEARCH: boolean;- getDefaultActionResource?: (options: {- url: URL;- projectId: string;- contactEmail: string;- formData: FormData;- }) => ResourceRequest;}}diff --git a/packages/cli/templates/defaults/app/route-templates/html.tsx b/packages/cli/templates/defaults/app/route-templates/html.tsxindex 4c64f97709..fb3e5561e1 100644--- a/packages/cli/templates/defaults/app/route-templates/html.tsx+++ b/packages/cli/templates/defaults/app/route-templates/html.tsx@@ -13,13 +13,12 @@ import { useLoaderData } from "@remix-run/react";import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,cachedFetch,getSystemSearch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateRequest } from "@webstudio-is/wsauth";import {@@ -291,9 +289,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -306,15 +302,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -336,86 +333,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<ReturnType<typeof loadResourceWithEmail>>;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/packages/cli/templates/react-router-cloudflare/workers/app.ts b/packages/cli/templates/react-router-cloudflare/workers/app.tsindex 6d6f866722..45e3c89694 100644--- a/packages/cli/templates/react-router-cloudflare/workers/app.ts+++ b/packages/cli/templates/react-router-cloudflare/workers/app.ts@@ -19,7 +19,6 @@ export default {async fetch(request, env, ctx) {return requestHandler(request, {EXCLUDE_FROM_SEARCH: false,- getDefaultActionResource: undefined,cloudflare: { env, ctx },});},diff --git a/packages/cli/templates/react-router/app/extension.ts b/packages/cli/templates/react-router/app/extension.tsindex b807c76536..845fc4363a 100644--- a/packages/cli/templates/react-router/app/extension.ts+++ b/packages/cli/templates/react-router/app/extension.ts@@ -1,14 +1,9 @@-import type { ResourceRequest } from "@webstudio-is/sdk";+import "react-router";+declare module "react-router" {interface AppLoadContext {EXCLUDE_FROM_SEARCH: boolean;WEBSTUDIO_AUTOMATION_TOKEN?: string;- getDefaultActionResource?: (options: {- url: URL;- projectId: string;- contactEmail: string;- formData: FormData;- }) => ResourceRequest;}}diff --git a/packages/cli/templates/react-router/app/route-templates/html.tsx b/packages/cli/templates/react-router/app/route-templates/html.tsxindex a33e64714c..e21bf1942a 100644--- a/packages/cli/templates/react-router/app/route-templates/html.tsx+++ b/packages/cli/templates/react-router/app/route-templates/html.tsx@@ -13,13 +13,12 @@ import {import {isLocalResource,loadResources,- loadResourceWithEmail,- loadResourcesWithEmail,getSystemSearch,cachedFetch,} from "@webstudio-is/sdk/runtime";import {handleManagedFormSubmission,+ handleDeprecatedWebhookFormSubmission,getManagedFormFailure,readFormDataWithLimit,type ManagedFormResponse,@@ -28,7 +27,6 @@ import {managedFormRequestParamName,formIdFieldName,managedFormIdFieldName,- formBotFieldName,} from "@webstudio-is/sdk/form";import { authenticateProjectRequest } from "@webstudio-is/wsauth";import {@@ -276,9 +274,7 @@ export const action = async ({if (!isManagedFormRequest) {url.host = getRequestHost(request);}- const formData = isManagedFormRequest- ? await readFormDataWithLimit(request)- : await request.formData();+ const formData = await readFormDataWithLimit(request);const system = {params: getRemixParams(params ?? {}),@@ -291,15 +287,16 @@ export const action = async ({if (!isManagedFormRequest && managedFormIds.length > 0) {throw new Error("Invalid Form submission");}+ const protectedFetch = createManagedFormResourceFetch({+ request,+ context,+ projectDomain,+ });if (isManagedFormRequest) {+ // Reject deprecated Webhook Form IDs on the new Form submission path.if (managedFormIds.length !== 1 || formData.has(formIdFieldName)) {throw new Error("Invalid Form submission");}- const protectedFetch = createManagedFormResourceFetch({- request,- context,- projectDomain,- });return await handleManagedFormSubmission({request,formData,@@ -321,86 +318,23 @@ export const action = async ({});}- const resourceName = formData.get(formIdFieldName);- const generatedResources = getResources({ system });- const actionResource =- typeof resourceName === "string"- ? generatedResources.action.get(resourceName)- : undefined;-- const formBotValue = formData.get(formBotFieldName);-- if (formBotValue == null || typeof formBotValue !== "string") {- throw new Error("Form bot field not found");- }-- // Skip timestamp validation for Brave browser- // Brave Shields blocks matchMedia fingerprinting detection used in bot protection- // See: https://github.com/brave/brave-browser/issues/46541- if (formBotValue !== "brave") {- const submitTime = parseInt(formBotValue, 16);- // Assumes that the difference between the server time and the form submission time,- // including any client-server time drift, is within a 5-minute range.- // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.- // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`- if (- Number.isNaN(submitTime) ||- Math.abs(Date.now() - submitTime) > 1000 * 60 * 5- ) {- throw new Error(`Form bot value invalid ${formBotValue}`);- }- }-- formData.delete(formIdFieldName);- formData.delete(formBotFieldName);-- let result: Awaited<ReturnType<typeof loadResourceWithEmail>>;- if (actionResource === undefined) {- if (contactEmail === undefined) {- throw new Error("Contact email not found");- }- const resource = context.getDefaultActionResource?.({- url,- projectId,- contactEmail,- formData,- });- if (resource === undefined) {- throw Error("Resource not found");- }- result = await loadResourceWithEmail(fetch, resource);- } else {- const actionFetch = await createGeneratedAssetResourceFetch({+ // Compatibility path for saved, deprecated Webhook Forms.+ return await handleDeprecatedWebhookFormSubmission({+ request,+ formData,+ url,+ resources: getResources({ system }),+ contactEmail,+ resourceFetch: protectedFetch,+ dependencyFetch: await createGeneratedAssetResourceFetch({request,context,fallback: customFetch,- });- const results = await loadResourcesWithEmail(- actionFetch,- {- ...generatedResources.data,- rootIds: [actionResource.id],- },- url,- {- requestOverrides: new Map([- // Mutations must reach the backend on every submission, even when- // the resource has caching enabled. Dependencies can stay cached.- [actionResource.id, { body: Object.fromEntries(formData), fetch }],- ]),- }- );- const actionResult = results[actionResource.outputName];- if (actionResult === undefined) {- throw Error("Resource not found");- }- result = actionResult as Awaited<ReturnType<typeof loadResourceWithEmail>>;- }- const { ok, statusText } = result;- if (ok) {- return { success: true };- }- return { success: false, errors: [statusText] };+ }),+ createEmailSender: (data) =>+ createManagedFormEmailSender({ context, formData: data, projectId }),+ validateEmail: validateManagedFormEmail,+ });} catch (error) {console.error(error);diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex 851f52ce5d..b6b495ea39 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -40,6 +40,7 @@ import {bundleVersion as currentBundleVersion,importProjectBundleResult,getMissingImportedAssetFiles,+ historicalPublishedProjectBundle,publishedProjectBundle,maxProjectBundleSize,stagedUploadPath,@@ -1286,7 +1287,7 @@ export const loadProjectBundleByBuildId = async (if (missingJsonPropValues !== undefined) {throw new MissingJsonPropValueError(missingJsonPropValues);}- return publishedProjectBundle.parse(data);+ return historicalPublishedProjectBundle.parse(data);};export const loadProjectBundleByProjectId = async (@@ -1297,10 +1298,21 @@ export const loadProjectBundleByProjectId = async (projectId: params.projectId,bundleVersion: currentBundleVersion,});- return publishedProjectBundle.parse(data);+ return historicalPublishedProjectBundle.parse(data);};export const toLocalProjectBundle = (project: PublishedProjectBundle) => {+ if (+ "formComponentIdentityVersion" in project.build.pages ||+ project.build.instances.some(+ ([, instance]) =>+ instance.component === "Form" || instance.component === "NativeForm"+ )+ ) {+ throw new Error(+ "Historical form identities must be normalized before export."+ );+ }const normalizedProject = publishedProjectBundle.parse(project);const {assets,diff --git a/packages/icons/icons/webhook-form.svg b/packages/icons/icons/webhook-form.svgindex 86b67e1fe6..345d4b46ec 100644--- a/packages/icons/icons/webhook-form.svg+++ b/packages/icons/icons/webhook-form.svg@@ -1,3 +1,4 @@+<!-- Deprecated: icon used only by the deprecated Webhook Form component. Remove with Webhook Form. --><svgwidth="16"height="16"diff --git a/packages/project-build/src/db/build.test.ts b/packages/project-build/src/db/build.test.tsindex 17ee53111f..9d707b0d65 100644--- a/packages/project-build/src/db/build.test.ts+++ b/packages/project-build/src/db/build.test.ts@@ -108,6 +108,39 @@ describe("loadRawBuildById (msw)", () => {// ---------------------------------------------------------------------------describe("loadBuildById (msw)", () => {+ test.each([+ { marker: 1, expected: "ResourceForm" },+ { marker: undefined, expected: "WebhookForm" },+ ])(+ "normalizes stored Form as $expected before exposing pages",+ async ({ marker, expected }) => {+ server.use(+ db.get("Build", () =>+ json([+ {+ ...buildRow,+ pages: JSON.stringify({+ ...JSON.parse(buildRow.pages),+ formComponentIdentityVersion: marker,+ }),+ instances: JSON.stringify([+ {+ id: "form",+ type: "instance",+ component: "Form",+ children: [],+ },+ ]),+ },+ ])+ )+ );+ const result = await loadBuildById(createContext(), "build-1");+ expect(result.instances[0]?.component).toBe(expected);+ expect(result.pages).not.toHaveProperty("formComponentIdentityVersion");+ }+ );+test("returns parsed build with id and projectId", async () => {server.use(db.get("Build", () => json([buildRow])));const result = await loadBuildById(createContext(), "build-1");diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.tsindex e90d2d7136..70c6c9818b 100644--- a/packages/project-build/src/db/build.ts+++ b/packages/project-build/src/db/build.ts@@ -21,9 +21,11 @@ import {type StyleDecl,} from "@webstudio-is/sdk";import {+ hasHistoricalFormComponentIdentityVersion,migratePages,serializePages,} from "@webstudio-is/project-migrations/pages";+import { migrateResourceFormInstancesMutable } from "@webstudio-is/project-migrations";import { migrateResourcesMutable } from "@webstudio-is/project-migrations/resources";import type { Build, CompactBuild } from "../types";import { parseDeployment } from "./deployment";@@ -95,7 +97,12 @@ const parseCompactContentEngineData = (build: ContentEngineBuildRow) => {const parseCompactBuild = async (build: Database["public"]["Tables"]["Build"]["Row"]) => {- const pages = migratePages(parseConfig<unknown>(build.pages));+ const rawPages = parseConfig<unknown>(build.pages);+ const hasModernFormMarker =+ hasHistoricalFormComponentIdentityVersion(rawPages);+ const pages = migratePages(rawPages);+ const instances = parseCompactInstanceData(build.instances);+ migrateResourceFormInstancesMutable(instances, hasModernFormMarker);const contentEngineData = parseCompactContentEngineData(build);const parsedProjectSettings =build.projectSettings === undefined || build.projectSettings === null@@ -116,7 +123,7 @@ const parseCompactBuild = async (build.styleSourceSelections),...contentEngineData,- instances: parseCompactInstanceData(build.instances),+ instances,deployment: parseDeployment(build.deployment),marketplaceProduct: parseMarketplaceProduct(build.marketplaceProduct),} satisfies CompactBuild;diff --git a/packages/project-build/src/mcp-form.integration.test.ts b/packages/project-build/src/mcp-form.integration.test.tsindex 58dd15e5af..a5602aa4f7 100644--- a/packages/project-build/src/mcp-form.integration.test.ts+++ b/packages/project-build/src/mcp-form.integration.test.ts@@ -302,7 +302,7 @@ test("discovers, commits, and reads back the new Form through MCP", async () =>const variables = await call("list-variables", { limit: 50 });const form = (instances.data.instances as Array<{ id: string; component: string }>- ).find(({ component }) => component === "Form");+ ).find(({ component }) => component === "ResourceForm");expect(form).toBeDefined();const formInspection = await call("inspect-instance", {instanceId: form?.id,diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex b766ac33af..997694bd84 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -6052,7 +6052,7 @@ describe("project session mcp adapter", () => {).toHaveLength(1);});- test("omits the legacy Webhook Form from MCP discovery", async () => {+ test("omits the deprecated Webhook Form from MCP discovery", async () => {const adapter = createProjectSessionMcpCore({operations: publicMcpOperations,createProjectSession: createSessionFactory(),@@ -6079,7 +6079,7 @@ describe("project session mcp adapter", () => {({ template }) => template === "template:form");expect(formResult?.component).toBe("form");- for (const component of [formResult!.component, "Form"]) {+ for (const component of [formResult!.component, "ResourceForm"]) {const formDetails = await adapter.callTool({name: "components.get",input: { component },@@ -6087,7 +6087,7 @@ describe("project session mcp adapter", () => {expect(formDetails.structuredContent.data).toEqual(expect.objectContaining({found: true,- component: "Form",+ component: "ResourceForm",props: expect.objectContaining({ action: expect.any(Object) }),}));@@ -6101,7 +6101,7 @@ describe("project session mcp adapter", () => {);const formTemplateByRoot = await adapter.callTool({name: "templates.get",- input: { component: "Form" },+ input: { component: "ResourceForm" },});expect(formTemplateByRoot.structuredContent.data).toEqual(expect.objectContaining({@@ -6164,7 +6164,7 @@ describe("project session mcp adapter", () => {} while (cursor !== undefined);});- test("rejects new legacy Webhook Forms through MCP insertion paths", async () => {+ test("rejects new deprecated Webhook Forms through MCP insertion paths", async () => {const executeOperation = createExecuteOperation();const operations = [...publicMcpOperations,@@ -6274,13 +6274,14 @@ describe("project session mcp adapter", () => {})).rejects.toThrow("Webhook Form is deprecated");}- const legacyFragment = await parseWebstudioJsxFragment("<WebhookForm />");+ const deprecatedFormFragment =+ await parseWebstudioJsxFragment("<WebhookForm />");for (const structure of [- { type: "fragment", fragment: legacyFragment },+ { type: "fragment", fragment: deprecatedFormFragment },{type: "collection",data: { type: "json", value: [{ name: "example" }] },- itemFragment: legacyFragment,+ itemFragment: deprecatedFormFragment,},]) {await expect(@@ -6320,7 +6321,7 @@ describe("project session mcp adapter", () => {expect(executeOperation).not.toHaveBeenCalled();});- test("rejects cloning a saved legacy Webhook Form subtree through MCP", async () => {+ test("rejects cloning a saved deprecated Webhook Form subtree through MCP", async () => {const executeOperation = createExecuteOperation(async ({ command }) => {if (command === "list-instances") {return createEnvelope({@@ -6386,7 +6387,7 @@ describe("project session mcp adapter", () => {expect(executeOperation).toHaveBeenCalledTimes(2);});- test("rejects page and template copies that would create legacy Webhook Forms", async () => {+ test("rejects page and template copies that would create deprecated Webhook Forms", async () => {const inputs = [["insert-mdx-text", { parentInstanceId: "body", source: "<Contact />" }],["duplicate-page", { projectId: "project", pageId: "page" }],@@ -6477,7 +6478,7 @@ describe("project session mcp adapter", () => {).toBe(true);});- test("rejects a copied legacy form in a root Map replacement", async () => {+ test("rejects a copied deprecated Webhook Form in a root Map replacement", async () => {const executeOperation = createExecuteOperation(async ({ dryRun }) => {if (dryRun === false) {throw new Error("Unexpected committed copy");@@ -6536,7 +6537,7 @@ describe("project session mcp adapter", () => {expect(executeOperation).toHaveBeenCalledTimes(1);});- test("keeps copying pages without legacy forms available through MCP", async () => {+ test("keeps copying pages without deprecated Webhook Forms available through MCP", async () => {const executeOperation = createExecuteOperation(async ({ dryRun }) =>createEnvelope({operationId: "pages.duplicate",@@ -6592,7 +6593,7 @@ describe("project session mcp adapter", () => {).toEqual([true, false]);});- test("rejects raw MCP patches that create a legacy Webhook Form", async () => {+ test("rejects raw MCP patches that create a deprecated Webhook Form", async () => {const executeOperation = createExecuteOperation();const adapter = createProjectSessionMcpCore({operations: publicMcpOperations,diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex f3df7d4509..a1c11341ab 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -4906,7 +4906,11 @@ const normalizeMcpOperationInput = async (name: string, input: unknown) => {return input;};-const assertNoLegacyWebhookFormInsertion = (name: string, input: unknown) => {+/** @deprecated Guard only for the deprecated Webhook Form component. */+const assertNoDeprecatedWebhookFormInsertion = (+ name: string,+ input: unknown+) => {if (isRecord(input) === false) {return;}@@ -4935,7 +4939,7 @@ const assertNoLegacyWebhookFormInsertion = (name: string, input: unknown) => {))) {throw new Error(- 'Webhook Form is deprecated and cannot be inserted through MCP. Use component "Form".'+ 'Webhook Form is deprecated and cannot be inserted through MCP. Use component "ResourceForm".');}if (@@ -4944,16 +4948,17 @@ const assertNoLegacyWebhookFormInsertion = (name: string, input: unknown) => {input.transactions.some((transaction) =>isRecord(transaction) &&- hasLegacyWebhookFormInstancePatch(transaction.payload)+ hasDeprecatedWebhookFormInstancePatch(transaction.payload))) {throw new Error(- 'Webhook Form is deprecated and cannot be created through MCP patches. Use component "Form".'+ 'Webhook Form is deprecated and cannot be created through MCP patches. Use component "ResourceForm".');}};-const legacyWebhookFormCopyCommands = new Set([+/** @deprecated Copy operations inspected only for saved Webhook Forms. */+const deprecatedWebhookFormCopyCommands = new Set(["insert-mdx-text","duplicate-page","duplicate-page-template",@@ -4963,23 +4968,27 @@ const legacyWebhookFormCopyCommands = new Set(["insert-page-transfer-item",]);-const containsLegacyWebhookFormInstance = (value: unknown): boolean => {+/** @deprecated Detects only saved Webhook Form instances. */+const containsDeprecatedWebhookFormInstance = (value: unknown): boolean => {if (value instanceof Map) {- return Array.from(value.values()).some(containsLegacyWebhookFormInstance);+ return Array.from(value.values()).some(+ containsDeprecatedWebhookFormInstance+ );}if (Array.isArray(value)) {- return value.some(containsLegacyWebhookFormInstance);+ return value.some(containsDeprecatedWebhookFormInstance);}if (isRecord(value)) {return (value.component === "WebhookForm" ||- Object.values(value).some(containsLegacyWebhookFormInstance)+ Object.values(value).some(containsDeprecatedWebhookFormInstance));}return false;};-const hasLegacyWebhookFormInstancePatch = (payload: unknown) =>+/** @deprecated Detects only patches that create Webhook Form instances. */+const hasDeprecatedWebhookFormInstancePatch = (payload: unknown) =>Array.isArray(payload) &&payload.some((change) =>@@ -4993,17 +5002,20 @@ const hasLegacyWebhookFormInstancePatch = (payload: unknown) =>((Array.isArray(patch.path) &&patch.path.at(-1) === "component" &&patch.value === "WebhookForm") ||- containsLegacyWebhookFormInstance(patch.value))+ containsDeprecatedWebhookFormInstance(patch.value))));-const assertNoLegacyWebhookFormCopy = (envelope: ProjectSessionEnvelope) => {+/** @deprecated Copy guard only for saved Webhook Forms. */+const assertNoDeprecatedWebhookFormCopy = (+ envelope: ProjectSessionEnvelope+) => {if (envelope.transaction === undefined) {throw new Error("MCP could not inspect the planned copy transaction.");}- if (hasLegacyWebhookFormInstancePatch(envelope.transaction.payload)) {+ if (hasDeprecatedWebhookFormInstancePatch(envelope.transaction.payload)) {throw new Error(- 'Webhook Form is deprecated and cannot be copied through MCP. Use component "Form".'+ 'Webhook Form is deprecated and cannot be copied through MCP. Use component "ResourceForm".');}};@@ -5640,6 +5652,7 @@ const isComponentAvailableInMcpCatalog = (component: string,meta: WsComponentMeta) =>+ // The explicit check hides the deprecated Webhook Form even with older metadata.component !== "WebhookForm" &&isComponentMetaUnavailableInCatalog(meta) === false;@@ -5734,6 +5747,7 @@ const getComponentSummaryEntry = ({));if (+ // Keep the deprecated Webhook Form out of component search and templates.component === "WebhookForm" ||(hiddenRequiredPart === false &&(isComponentMetaUnavailableInCatalog(meta) ||@@ -5894,6 +5908,7 @@ const getComponentSummary = (input: unknown) => {};};+// The final filter hides the deprecated Webhook Form from registry discovery.const getComponentRegistryItems = () =>listComponentRegistryItems({metas: componentMetas,@@ -9490,7 +9505,10 @@ export const createProjectSessionMcpCore = <Command extends string = string>({insertionOperation,await getInsertFragmentInput(transportInput.input));- assertNoLegacyWebhookFormInsertion("insert-fragment", insertionInput);+ assertNoDeprecatedWebhookFormInsertion(+ "insert-fragment",+ insertionInput+ );const verificationInput = getNormalizedOperationInput(verificationOperation,{ pagePath: transportInput.input.pagePath, limit: 200 }@@ -9602,8 +9620,9 @@ export const createProjectSessionMcpCore = <Command extends string = string>({const toolInput = transportInput.input;dryRun = dryRun || transportInput.dryRun;const normalizedInput = await normalizeMcpOperationInput(name, toolInput);- assertNoLegacyWebhookFormInsertion(name, normalizedInput);+ assertNoDeprecatedWebhookFormInsertion(name, normalizedInput);if (+ // Block duplication of a saved, deprecated Webhook Form.(name === "clone-instance" || name === "duplicate-instance") &&isRecord(normalizedInput) &&typeof normalizedInput.sourceInstanceId === "string"@@ -9619,7 +9638,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({source.result.instances.length > 0) {throw new Error(- 'Webhook Form is deprecated and cannot be duplicated through MCP. Use component "Form".'+ 'Webhook Form is deprecated and cannot be duplicated through MCP. Use component "ResourceForm".');}}@@ -9725,7 +9744,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({): normalizedInput);- const plannedCopy = legacyWebhookFormCopyCommands.has(name)+ const plannedCopy = deprecatedWebhookFormCopyCommands.has(name)? await executeOperation({command: name as Command,input: operationInput,@@ -9733,7 +9752,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({}): undefined;if (plannedCopy !== undefined) {- assertNoLegacyWebhookFormCopy(plannedCopy);+ assertNoDeprecatedWebhookFormCopy(plannedCopy);}const [envelope, response] = operation.requiresConfirm? await executeDestructiveMcpOperation({diff --git a/packages/project-build/src/project-session.test.ts b/packages/project-build/src/project-session.test.tsindex e5417f9914..4a6547cd52 100644--- a/packages/project-build/src/project-session.test.ts+++ b/packages/project-build/src/project-session.test.ts@@ -331,6 +331,48 @@ describe("project session", () => {});});+ test("hydrates a canonical instances-only restore without pages", () => {+ const transaction = {+ id: "restore",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [],+ value: [+ [+ "form",+ {+ id: "form",+ type: "instance",+ component: "ResourceForm",+ children: [],+ },+ ],+ ],+ },+ ],+ },+ ],+ } as BuilderPatchTransaction;+ const hydrated = hydrateRestorePointTransaction(transaction);+ expect(hydrated.payload[0]?.patches[0]).toMatchObject({+ value: new Map([+ [+ "form",+ {+ id: "form",+ type: "instance",+ component: "ResourceForm",+ children: [],+ },+ ],+ ]),+ });+ });+test("rejects malformed serialized restore namespace values", () => {expect(() =>hydrateRestorePointTransaction({diff --git a/packages/project-build/src/project-session.ts b/packages/project-build/src/project-session.tsindex 451b91a1d4..69ee95c9c1 100644--- a/packages/project-build/src/project-session.ts+++ b/packages/project-build/src/project-session.ts@@ -1,6 +1,8 @@import hash from "@emotion/hash";import deepEqual from "fast-deep-equal";import { z } from "zod";+import { migrateResourceFormInstancesMutable } from "@webstudio-is/project-migrations";+import { hasHistoricalFormComponentIdentityVersion } from "@webstudio-is/project-migrations/pages";import type {RuntimeOperationContract,RuntimeOperationId,@@ -204,11 +206,28 @@ export const hydrateRestorePointTransaction = (transaction: BuilderPatchTransaction) =>transformRestorePointTransaction(transaction, (state) => {+ const hasModernFormMarker = hasHistoricalFormComponentIdentityVersion(+ state.pages+ );const serialized = serializedRestorePointState.parse(state);const hydrated = createBuilderStateFromSerializedSnapshot({...serialized,marketplaceProduct: serialized.marketplaceProduct ?? undefined,}) as Record<string, unknown>;+ if (hydrated.instances instanceof Map) {+ if (+ state.pages === undefined &&+ Array.from(hydrated.instances.values()).some(+ (instance) => instance.component === "Form"+ )+ ) {+ throw new Error("A restore point with instances must include pages.");+ }+ migrateResourceFormInstancesMutable(+ hydrated.instances.values(),+ hasModernFormMarker+ );+ }if (serialized.marketplaceProduct === null) {hydrated.marketplaceProduct = undefined;}diff --git a/packages/project-build/src/runtime/binding-verification.test-fixtures.ts b/packages/project-build/src/runtime/binding-verification.test-fixtures.tsindex ebbc90e827..3c463d1ce7 100644--- a/packages/project-build/src/runtime/binding-verification.test-fixtures.ts+++ b/packages/project-build/src/runtime/binding-verification.test-fixtures.ts@@ -131,7 +131,7 @@ export const createBindingVerificationFixture = (): BuilderState => {{type: "instance",id: "checkout",- component: "Form",+ component: "ResourceForm",children: [],},],diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.tsindex ca8417133c..702af74e3c 100644--- a/packages/project-build/src/runtime/components.test.ts+++ b/packages/project-build/src/runtime/components.test.ts@@ -1913,7 +1913,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")} />`+ `<ResourceForm action={new ResourceValue("resource-id")} />`)).rejects.toThrow("ResourceValue requires a resource definition. Existing resource ids are not supported in JSX"diff --git a/packages/project-build/src/runtime/data-formats/instance-transfer.test.ts b/packages/project-build/src/runtime/data-formats/instance-transfer.test.tsindex 9ce24218b6..3012615ff2 100644--- a/packages/project-build/src/runtime/data-formats/instance-transfer.test.ts+++ b/packages/project-build/src/runtime/data-formats/instance-transfer.test.ts@@ -64,3 +64,49 @@ test("accepts optional source origin metadata", () => {},});});++test.each([+ ["@webstudio/instance/v0.1", { instanceSelector: ["form", "body"] }],+ ["@webstudio/instances/v0.1", { rootInstanceIds: ["form"] }],+] as const)(+ "rejects ambiguous historical Form in %s before paste",+ (version, metadata) => {+ const formFragment = {+ ...fragment,+ children: [{ type: "id", value: "form" }],+ instances: [+ { type: "instance", id: "form", component: "Form", children: [] },+ ],+ };+ const data =+ version === "@webstudio/instance/v0.1"+ ? { ...formFragment, ...metadata }+ : { fragment: formFragment, ...metadata };+ expect(+ parseInstanceTransferData(JSON.stringify({ [version]: data }))+ ).toMatchObject({+ owned: true,+ valid: false,+ error: expect.stringMatching(/Copy it again/),+ });+ }+);++test.each(["ResourceForm", "WebhookForm", "NativeForm"])(+ "accepts unambiguous %s clipboard data",+ (component) => {+ expect(+ parseInstanceTransferData(+ JSON.stringify({+ "@webstudio/instance/v0.1": {+ ...fragment,+ instanceSelector: ["form", "body"],+ instances: [+ { type: "instance", id: "form", component, children: [] },+ ],+ },+ })+ )+ ).toMatchObject({ owned: true, valid: true });+ }+);diff --git a/packages/project-build/src/runtime/data-formats/instance-transfer.ts b/packages/project-build/src/runtime/data-formats/instance-transfer.tsindex 5c9f1a4a4b..9a387ffe86 100644--- a/packages/project-build/src/runtime/data-formats/instance-transfer.ts+++ b/packages/project-build/src/runtime/data-formats/instance-transfer.ts@@ -1,6 +1,10 @@import { webstudioFragment } from "@webstudio-is/sdk";import { z } from "zod";import { parseDataEnvelope } from "./data-envelope";+import {+ ambiguousFormClipboardMessage,+ hasAmbiguousFormInstance,+} from "../fragment-identity";export const instanceTransferDataVersion = "@webstudio/instance/v0.1";export const instancesTransferDataVersion = "@webstudio/instances/v0.1";@@ -32,6 +36,17 @@ export const parseInstanceTransferData = (serializedData: string) => {if (transferData.valid === false) {return transferData;}+ const fragment =+ transferData.version === instanceTransferDataVersion+ ? transferData.data+ : transferData.data.fragment;+ if (hasAmbiguousFormInstance(fragment)) {+ return {+ owned: true,+ valid: false,+ error: ambiguousFormClipboardMessage,+ } as const;+ }if (transferData.version === instanceTransferDataVersion) {return { ...transferData, type: "single-root" } as const;}diff --git a/packages/project-build/src/runtime/data-formats/page-transfer.test.ts b/packages/project-build/src/runtime/data-formats/page-transfer.test.tsindex cc30bb4c18..c245f7d4e9 100644--- a/packages/project-build/src/runtime/data-formats/page-transfer.test.ts+++ b/packages/project-build/src/runtime/data-formats/page-transfer.test.ts@@ -93,3 +93,51 @@ test("keeps clipboard source metadata out of the runtime input", () => {})).toEqual(pageTransferItem);});++test("rejects ambiguous Form in a nested folder page before paste", () => {+ const bodyFragment = {+ ...fragment,+ instances: [+ { type: "instance", id: "form", component: "Form", children: [] },+ ],+ };+ const folder = {+ type: "folder",+ folder: { id: "folder", name: "Folder", slug: "folder", children: [] },+ children: [+ {+ type: "folder",+ folder: { id: "nested", name: "Nested", slug: "nested", children: [] },+ children: [{ ...pageTransferItem, bodyFragment }],+ },+ ],+ };+ expect(+ parsePageTransferData(JSON.stringify({ "@webstudio/page/v0.1": folder }))+ ).toMatchObject({+ owned: true,+ valid: false,+ error: expect.stringMatching(/Copy it again/),+ });+});++test.each(["ResourceForm", "WebhookForm", "NativeForm"])(+ "accepts unambiguous %s page clipboard data",+ (component) => {+ expect(+ parsePageTransferData(+ JSON.stringify({+ "@webstudio/page/v0.1": {+ ...pageTransferItem,+ bodyFragment: {+ ...fragment,+ instances: [+ { type: "instance", id: "form", component, children: [] },+ ],+ },+ },+ })+ )+ ).toMatchObject({ owned: true, valid: true });+ }+);diff --git a/packages/project-build/src/runtime/data-formats/page-transfer.ts b/packages/project-build/src/runtime/data-formats/page-transfer.tsindex edb05c8151..1cd1c46149 100644--- a/packages/project-build/src/runtime/data-formats/page-transfer.ts+++ b/packages/project-build/src/runtime/data-formats/page-transfer.ts@@ -7,6 +7,10 @@ import {} from "@webstudio-is/sdk";import { z } from "zod";import { parseDataEnvelope } from "./data-envelope";+import {+ ambiguousFormClipboardMessage,+ hasAmbiguousFormInstance,+} from "../fragment-identity";export type PageCopyData = {page: Page;@@ -98,6 +102,19 @@ export const parsePageTransferData = (serializedData: string) => {if (transferData.valid === false) {return transferData;}+ if (+ collectPageTransferItems(transferData.data).some(+ (item) =>+ hasAmbiguousFormInstance(item.rootFragment) ||+ hasAmbiguousFormInstance(item.bodyFragment)+ )+ ) {+ return {+ owned: true,+ valid: false,+ error: ambiguousFormClipboardMessage,+ } as const;+ }return {owned: true,valid: true,diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsxindex 100207d632..1e409eec7b 100644--- a/packages/project-build/src/runtime/data.test.tsx+++ b/packages/project-build/src/runtime/data.test.tsx@@ -89,7 +89,7 @@ const Box = createTemplateComponentFixture("Box");const Fragment = createTemplateComponentFixture("Fragment");const Slot = createTemplateComponentFixture("Slot");const Text = createTemplateComponentFixture("Text");-const ResourceForm = createTemplateComponentFixture("Form");+const ResourceForm = createTemplateComponentFixture("ResourceForm");test("deleting a Resource removes it from a new Form's destinations", () => {const data = renderData(@@ -3961,7 +3961,7 @@ describe("resource patch helpers", () => {state.instances.set("form", {type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],});for (const [id, scopeInstanceId] of [@@ -4008,7 +4008,7 @@ describe("resource patch helpers", () => {state.instances.set("form", {type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],});state.resources.set("email-id", {@@ -4079,7 +4079,7 @@ describe("resource patch helpers", () => {state.instances.set("form", {type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],});state.resources.set("email-id", {@@ -4151,7 +4151,7 @@ describe("resource patch helpers", () => {state.instances.set("form", {type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],});state.resources.set("email-id", {@@ -4444,7 +4444,7 @@ describe("resource patch helpers", () => {const form: Instance = {type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],};const ids = ["resource-id", "prop-id"];@@ -5050,7 +5050,7 @@ describe("resource patch helpers", () => {expect(createResourceDeletePayload({resource,- instances: new Map([["form", { component: "Form" }]]),+ instances: new Map([["form", { component: "ResourceForm" }]]),props: [submission],dataSources: [dataSource],}).isUsed@@ -5058,7 +5058,7 @@ describe("resource patch helpers", () => {expect(createResourceDeletePayload({resource,- instances: new Map([["form", { component: "Form" }]]),+ instances: new Map([["form", { component: "ResourceForm" }]]),props: [submission],dataSources: [dataSource],force: true,diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.tsindex 7a5ff8c3db..a2488385f3 100644--- a/packages/project-build/src/runtime/data.ts+++ b/packages/project-build/src/runtime/data.ts@@ -1174,7 +1174,7 @@ export const deleteVariableMutable = (if (prop.type !== "json" ||prop.name !== "action" ||- data.instances.get(prop.instanceId)?.component !== "Form" ||+ data.instances.get(prop.instanceId)?.component !== "ResourceForm" ||!isFormSubmission(prop.value) ||!prop.value.some((action) => action.dataSourceId === variableId)) {@@ -1594,7 +1594,8 @@ export const isManagedFormParameter = (dataSource?.type === "parameter" &&(dataSource.name === formDataParameterName ||dataSource.name === browserInfoParameterName) &&- instances?.get(dataSource.scopeInstanceId ?? "")?.component === "Form";+ instances?.get(dataSource.scopeInstanceId ?? "")?.component ===+ "ResourceForm";export const isRequiredManagedFormVariable = (dataSource: DataSource | undefined,@@ -1605,7 +1606,7 @@ export const isRequiredManagedFormVariable = (if (dataSourceId === undefined ||scopeInstanceId === undefined ||- state.instances?.get(scopeInstanceId)?.component !== "Form"+ state.instances?.get(scopeInstanceId)?.component !== "ResourceForm") {return false;}@@ -2886,7 +2887,7 @@ export const createResourceDeletePayload = ({if (prop.type !== "json" ||prop.name !== "action" ||- instances.get(prop.instanceId)?.component !== "Form" ||+ instances.get(prop.instanceId)?.component !== "ResourceForm" ||!isFormSubmission(prop.value) ||!prop.value.some((action) =>resourceDataSourceIds.has(action.dataSourceId)diff --git a/packages/project-build/src/runtime/form-actions.ts b/packages/project-build/src/runtime/form-actions.tsindex 5ffb10afca..cdbf9e0f36 100644--- a/packages/project-build/src/runtime/form-actions.ts+++ b/packages/project-build/src/runtime/form-actions.ts@@ -42,7 +42,7 @@ const validateFormActionMutation = ();for (const prop of changedProps) {if (- instances.get(prop.instanceId)?.component === "Form" &&+ instances.get(prop.instanceId)?.component === "ResourceForm" &&prop.name === "action" &&prop.type === "json" &&Array.isArray(prop.value) &&diff --git a/packages/project-build/src/runtime/fragment-identity.ts b/packages/project-build/src/runtime/fragment-identity.tsnew file mode 100644index 0000000000..7049a219e3--- /dev/null+++ b/packages/project-build/src/runtime/fragment-identity.ts@@ -0,0 +1,8 @@+import type { WebstudioFragment } from "@webstudio-is/sdk";++export const ambiguousFormClipboardMessage =+ "This copied Form uses an older format that cannot identify its component. Copy it again in the updated Builder, then paste.";++export const hasAmbiguousFormInstance = (+ fragment: Pick<WebstudioFragment, "instances">+) => fragment.instances.some((instance) => instance.component === "Form");diff --git a/packages/project-build/src/runtime/fragment.test.tsx b/packages/project-build/src/runtime/fragment.test.tsxindex 400fffb75c..3bfa8b4681 100644--- a/packages/project-build/src/runtime/fragment.test.tsx+++ b/packages/project-build/src/runtime/fragment.test.tsx@@ -47,7 +47,24 @@ const HtmlEmbed = createTemplateComponentFixture("HtmlEmbed");const Paragraph = createTemplateComponentFixture("Paragraph");const Slot = createTemplateComponentFixture("Slot");const Text = createTemplateComponentFixture("Text");-const ResourceForm = createTemplateComponentFixture("Form");+const ResourceForm = createTemplateComponentFixture("ResourceForm");++test("rejects an ambiguous historical Form before mutating fragment data", () => {+ const data = renderData(<Body ws:id="bodyId" />);+ const fragment = renderTemplate(<Box ws:id="boxId" />);+ fragment.instances[0].component = "Form";+ const before = structuredClone(data);++ expect(() =>+ insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "project",+ })+ ).toThrow(/Copy it again/);+ expect(data).toEqual(before);+});test("copying Email Resources restores parent bindings by name in the target scope", () => {const parentVariable = new Variable("Owner", "Source owner");@@ -159,7 +176,7 @@ test("copying a Form remaps its local Resource actions", () => {projectId: "",});const copiedForm = Array.from(data.instances.values()).find(- ({ id, component }) => id !== "formId" && component === "Form"+ ({ id, component }) => id !== "formId" && component === "ResourceForm");const copiedSubmission = Array.from(data.props.values()).find(({ instanceId, name }) => instanceId === copiedForm?.id && name === "action"diff --git a/packages/project-build/src/runtime/fragment.ts b/packages/project-build/src/runtime/fragment.tsindex 3db459b01f..e6db9d7ebd 100644--- a/packages/project-build/src/runtime/fragment.ts+++ b/packages/project-build/src/runtime/fragment.ts@@ -58,6 +58,21 @@ import {} from "./style-utils";import { countDataSourceAssetReferences } from "./assets";import { throwBuilderRuntimeError } from "./errors";+import {+ ambiguousFormClipboardMessage,+ hasAmbiguousFormInstance,+} from "./fragment-identity";++export const assertNoAmbiguousFormInstance = (+ fragment: Pick<WebstudioFragment, "instances">+) => {+ if (hasAmbiguousFormInstance(fragment)) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ ambiguousFormClipboardMessage+ );+ }+};const createNanoId = () => createId("nano");@@ -105,6 +120,13 @@ export const listFragmentExpressions = (fragment: WebstudioFragment) => [export const webstudioFragmentMutationInput = webstudioFragment.superRefine((fragment, context) => {+ if (hasAmbiguousFormInstance(fragment)) {+ context.addIssue({+ code: "custom",+ message: ambiguousFormClipboardMessage,+ path: ["instances"],+ });+ }for (const entry of listFragmentExpressions(fragment)) {const errors = getExpressionErrorMessages({expression: entry.expression,@@ -610,6 +632,7 @@ export const insertWebstudioFragmentCopy = ({createId?: () => string;contentMode?: boolean;}) => {+ assertNoAmbiguousFormInstance(fragment);const newInstanceIds = new Map<Instance["id"], Instance["id"]>();const newDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();const newDataIds = {@@ -858,7 +881,7 @@ export const insertWebstudioFragmentCopy = ({}const isResourceFormAction =prop.name === "action" &&- fragmentInstances.get(prop.instanceId)?.component === "Form";+ fragmentInstances.get(prop.instanceId)?.component === "ResourceForm";prop = clonePropForInstance({prop: structuredClone(unwrap(prop)),propId: createId(),diff --git a/packages/project-build/src/runtime/managed-form-draft.ts b/packages/project-build/src/runtime/managed-form-draft.tsindex fd5ab0fe3b..ec9003c5a8 100644--- a/packages/project-build/src/runtime/managed-form-draft.ts+++ b/packages/project-build/src/runtime/managed-form-draft.ts@@ -61,7 +61,7 @@ export const prepareManagedFormDraft = ({if (match === undefined ||!findTreeInstanceIds(instances, match.value.rootInstanceId).has(formId) ||- instances.get(formId)?.component !== "Form"+ instances.get(formId)?.component !== "ResourceForm") {throw new Error("Form not found on this page");}diff --git a/packages/project-build/src/runtime/page-copy.test.tsx b/packages/project-build/src/runtime/page-copy.test.tsxindex 50c68e7e63..c9443c78a7 100644--- a/packages/project-build/src/runtime/page-copy.test.tsx+++ b/packages/project-build/src/runtime/page-copy.test.tsx@@ -34,12 +34,14 @@ import {duplicatePageTemplate,insertPageCopyMutable,insertPageTransferItem,+ insertFolderCopyFromDataMutable,insertPageFromTemplateMutable,insertTemplateCopyFromFragmentsMutable,listPageTemplates,reorderPageTemplates,updatePageTemplate,} from "./page-copy";+import type { FolderCopyData } from "./data-formats/page-transfer";import {createTemplateComponentFixture,css,@@ -90,6 +92,34 @@ test("requires an explicit resolution for conflicting transferred root styles",).toThrow(/root style conflicts require an explicit/i);});+test("rejects a nested historical Form before creating any folder or page", () => {+ const { sourcePages, source, target } = createConflictingRootStyleProjects();+ const page = createPageCopyData({+ data: source,+ page: getHomePage(sourcePages),+ });+ page.bodyFragment.instances[0].component = "Form";+ const folder: FolderCopyData = {+ folder: { id: "outer", name: "Outer", slug: "outer", children: [] },+ children: [+ {+ folder: { id: "inner", name: "Inner", slug: "inner", children: [] },+ children: [page],+ },+ ],+ };+ const before = structuredClone(target);++ expect(() =>+ insertFolderCopyFromDataMutable({+ source: folder,+ target: { data: target, parentFolderId: ROOT_FOLDER_ID },+ projectId: "target-project",+ })+ ).toThrow(/Copy it again/);+ expect(target).toEqual(before);+});+test("requires an explicit resolution for conflicting copied root styles", () => {const { source, target } = createConflictingRootStyleProjects();diff --git a/packages/project-build/src/runtime/page-copy.ts b/packages/project-build/src/runtime/page-copy.tsindex 6cfe7bbdb1..655ea7d834 100644--- a/packages/project-build/src/runtime/page-copy.ts+++ b/packages/project-build/src/runtime/page-copy.ts@@ -4,6 +4,7 @@ import {extractWebstudioFragment,insertWebstudioFragmentCopy,resolveFragmentRootStyleConflicts,+ assertNoAmbiguousFormInstance,} from "./fragment";import { isFragmentContentModeCopyableProp } from "./content-mode-copy-policy";import { z } from "zod";@@ -356,6 +357,10 @@ const copyPageFragmentsMutable = ({createId?: CreateId;contentMode?: boolean;}) => {+ if (rootFragment !== undefined) {+ assertNoAmbiguousFormInstance(rootFragment);+ }+ assertNoAmbiguousFormInstance(bodyFragment);if (projectId === undefined) {return;}@@ -1576,6 +1581,17 @@ export const insertFolderCopyFromDataMutable = ({forceFolderCopySuffix?: boolean;createId?: CreateId;}) => {+ const assertFolderFragments = (folder: FolderCopyData) => {+ for (const child of folder.children) {+ if ("folder" in child) {+ assertFolderFragments(child);+ } else {+ assertNoAmbiguousFormInstance(child.rootFragment);+ assertNoAmbiguousFormInstance(child.bodyFragment);+ }+ }+ };+ assertFolderFragments(source);const copyContext = {didCopyRootFragment: false,};@@ -1599,6 +1615,10 @@ export const insertPageTransferItem = (input: z.infer<typeof pageTransferInsertInput>,context: { createId: CreateId }) => {+ for (const item of collectPageTransferItems(input.item)) {+ assertNoAmbiguousFormInstance(item.rootFragment);+ assertNoAmbiguousFormInstance(item.bodyFragment);+ }const data = getRequiredWebstudioData(state);if (data.pages.folders.has(input.targetFolderId) === false) {return throwBuilderRuntimeError("NOT_FOUND", "Target folder not found");diff --git a/packages/project-build/src/runtime/pre-publish-audit.test.tsx b/packages/project-build/src/runtime/pre-publish-audit.test.tsxindex 9755a3f4df..8aa9fc3759 100644--- a/packages/project-build/src/runtime/pre-publish-audit.test.tsx+++ b/packages/project-build/src/runtime/pre-publish-audit.test.tsx@@ -3,10 +3,12 @@ import {ROOT_FOLDER_ID,blockComponent,type Folder,+ type Instance,type Page,type Pages,} from "@webstudio-is/sdk";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { migrateResourceFormInstancesMutable } from "@webstudio-is/project-migrations";import {createTemplateComponentFixture,renderData,@@ -98,6 +100,139 @@ test("warns without blocking legacy invalid HTML", () => {);});+test("warns for nested and shared Webhook Forms on every published page", () => {+ const pages = createPages(marketEdgePage);+ pages.pages.set("other", {+ ...marketEdgePage,+ id: "other",+ name: "Other",+ path: "/other",+ rootInstanceId: "other-body",+ });+ pages.pages.set("draft", {+ ...marketEdgePage,+ id: "draft",+ name: "Draft",+ path: "/draft",+ rootInstanceId: "draft-body",+ isDraft: true,+ });+ pages.folders.get(ROOT_FOLDER_ID)!.children.push("other", "draft");++ const instance = (+ id: string,+ component: string,+ children: string[] = []+ ): Instance => ({+ type: "instance" as const,+ id,+ component,+ children: children.map((value) => ({ type: "id" as const, value })),+ });+ const instances = new Map<string, Instance>([+ ["body", instance("body", "Body", ["box", "modern", "native"])],+ ["box", instance("box", "Box", ["nested", "shared"])],+ ["nested", instance("nested", "WebhookForm")],+ ["shared", instance("shared", "WebhookForm")],+ ["modern", instance("modern", "ResourceForm")],+ ["native", { ...instance("native", "Element"), tag: "form" }],+ ["other-body", instance("other-body", "Body", ["shared"])],+ ["draft-body", instance("draft-body", "Body", ["draft-form"])],+ ["draft-form", instance("draft-form", "WebhookForm")],+ ["orphan", instance("orphan", "WebhookForm")],+ ]);+ const findings = runAudit({ pages, instances, props: new Map() }).filter(+ ({ ruleId }) => ruleId === "deprecated-webhook-form"+ );++ expect(findings).toEqual([+ {+ ruleId: "deprecated-webhook-form",+ severity: "warning",+ message:+ "Webhook Form is deprecated. Replace it with the Form component.",+ location: {+ pageId: "marketedge",+ pageName: "MarketEdge",+ pagePath: "/marketedge",+ instanceId: "nested",+ instanceSelector: ["nested", "box", "body"],+ },+ },+ {+ ruleId: "deprecated-webhook-form",+ severity: "warning",+ message:+ "Webhook Form is deprecated. Replace it with the Form component.",+ location: {+ pageId: "marketedge",+ pageName: "MarketEdge",+ pagePath: "/marketedge",+ instanceId: "shared",+ instanceSelector: ["shared", "box", "body"],+ },+ },+ {+ ruleId: "deprecated-webhook-form",+ severity: "warning",+ message:+ "Webhook Form is deprecated. Replace it with the Form component.",+ location: {+ pageId: "other",+ pageName: "Other",+ pagePath: "/other",+ instanceId: "shared",+ instanceSelector: ["shared", "other-body"],+ },+ },+ ]);+ expect(formatPrePublishAuditFinding(findings[0]!)).toBe(+ 'Publish warning for "MarketEdge" (/marketedge): Webhook Form is deprecated. Replace it with the Form component.'+ );+});++test("historical unmarked Form becomes a warning while marked Form is modern", () => {+ const createData = () => {+ const instances = new Map([+ [+ "body",+ {+ type: "instance" as const,+ id: "body",+ component: "Body",+ children: [{ type: "id" as const, value: "form" }],+ },+ ],+ [+ "form",+ {+ type: "instance" as const,+ id: "form",+ component: "Form",+ children: [],+ },+ ],+ ]);+ return instances;+ };+ const legacyInstances = createData();+ migrateResourceFormInstancesMutable(legacyInstances.values(), false);+ expect(+ runAudit({ instances: legacyInstances, props: new Map() }).filter(+ ({ ruleId }) => ruleId === "deprecated-webhook-form"+ )+ ).toHaveLength(1);++ const modernInstances = createData();+ migrateResourceFormInstancesMutable(modernInstances.values(), true);+ expect(modernInstances.get("form")?.component).toBe("ResourceForm");+ expect(+ runAudit({ instances: modernInstances, props: new Map() }).filter(+ ({ ruleId }) => ruleId === "deprecated-webhook-form"+ )+ ).toEqual([]);+});+test("blocks publishing when a JSON prop has no value", () => {const { instances, props } = renderData(<Body ws:id="body" />);props.set("missing-value", {diff --git a/packages/project-build/src/runtime/pre-publish-audit.ts b/packages/project-build/src/runtime/pre-publish-audit.tsindex f8149f2da5..77a113679a 100644--- a/packages/project-build/src/runtime/pre-publish-audit.ts+++ b/packages/project-build/src/runtime/pre-publish-audit.ts@@ -24,6 +24,7 @@ export type PrePublishAuditFinding = {pageName?: string;pagePath?: string;instanceId?: string;+ instanceSelector?: string[];dataSourceId?: string;propId?: string;resourceId?: string;@@ -155,8 +156,52 @@ const checkJsonPropValues: PrePublishAuditCheck = ({ props, instances }) =>};});+const checkDeprecatedWebhookForms: PrePublishAuditCheck = ({+ pages,+ instances,+}) => {+ const findings: PrePublishAuditFinding[] = [];+ for (const page of getPublishablePages(pages)) {+ const visited = new Set<string>();+ const visit = (instanceId: string, parentSelector: string[]) => {+ if (visited.has(instanceId)) {+ return;+ }+ visited.add(instanceId);+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ return;+ }+ const instanceSelector = [instanceId, ...parentSelector];+ if (instance.component === "WebhookForm") {+ findings.push({+ ruleId: "deprecated-webhook-form",+ severity: "warning",+ message:+ "Webhook Form is deprecated. Replace it with the Form component.",+ location: {+ pageId: page.id,+ pageName: page.name,+ pagePath: getPagePath(page.id, pages) || "/",+ instanceId,+ instanceSelector,+ },+ });+ }+ for (const child of instance.children ?? []) {+ if (child.type === "id") {+ visit(child.value, instanceSelector);+ }+ }+ };+ visit(page.rootInstanceId, []);+ }+ return findings;+};+const prePublishAuditChecks: PrePublishAuditCheck[] = [checkHtmlContentModel,+ checkDeprecatedWebhookForms,checkJsonPropValues,checkBuildIntegrity,];diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.tsindex ef464b1bbf..d3ab400b44 100644--- a/packages/project-build/src/runtime/registry.test.ts+++ b/packages/project-build/src/runtime/registry.test.ts@@ -111,7 +111,7 @@ test("rejects a fragment containing a Form with more than 10 actions", () => {{type: "instance",id: "new-form",- component: "Form",+ component: "ResourceForm",children: [],},],diff --git a/packages/project-build/src/shared/pages-utils.test.ts b/packages/project-build/src/shared/pages-utils.test.tsindex 1b23522b99..87085763c5 100644--- a/packages/project-build/src/shared/pages-utils.test.ts+++ b/packages/project-build/src/shared/pages-utils.test.ts@@ -9,7 +9,6 @@ test("createDefaultPages", () => {homePageId: "homePageId",})).toEqual({- formComponentIdentityVersion: 1,meta: {},homePageId: "homePageId",rootFolderId: "root",diff --git a/packages/project-build/src/shared/pages-utils.ts b/packages/project-build/src/shared/pages-utils.tsindex a77281605c..1cd9a68d4a 100644--- a/packages/project-build/src/shared/pages-utils.ts+++ b/packages/project-build/src/shared/pages-utils.ts@@ -37,7 +37,6 @@ export const createDefaultPages = ({systemDataSourceId,};return {- formComponentIdentityVersion: 1,meta: {},homePageId,rootFolderId: ROOT_FOLDER_ID,diff --git a/packages/project-migrations/src/index.test.ts b/packages/project-migrations/src/index.test.tsindex 02293f5d5e..81e56b399e 100644--- a/packages/project-migrations/src/index.test.ts+++ b/packages/project-migrations/src/index.test.ts@@ -81,7 +81,6 @@ test("migrates legacy pages inside webstudio data", () => {migrateWebstudioDataMutable(data);expect(data.pages).toEqual({- formComponentIdentityVersion: 1,meta: undefined,compiler: undefined,redirects: undefined,@@ -106,7 +105,7 @@ test("migrates legacy pages inside webstudio data", () => {});});-test("migrates saved legacy and managed form identities exactly once", () => {+test("migrates unmarked historical and mixed form identities exactly once", () => {const data = structuredClone(emptyData);data.instances.set("native", {type: "instance",@@ -126,29 +125,60 @@ test("migrates saved legacy and managed form identities exactly once", () => {component: "Form",children: [],});+ data.instances.set("webhook", {+ type: "instance",+ id: "webhook",+ component: "WebhookForm",+ children: [],+ });migrateWebstudioDataMutable(data);- expect(data.instances.get("native")?.component).toBe("Form");- expect(data.instances.get("managed")?.component).toBe("Form");+ expect(data.instances.get("native")?.component).toBe("ResourceForm");+ expect(data.instances.get("managed")?.component).toBe("ResourceForm");expect(data.instances.get("legacy")?.component).toBe("WebhookForm");- expect(data.pages.formComponentIdentityVersion).toBe(1);+ expect(data.instances.get("webhook")?.component).toBe("WebhookForm");+ expect("formComponentIdentityVersion" in data.pages).toBe(false);data.instances.set("new", {type: "instance",id: "new",- component: "Form",+ component: "ResourceForm",children: [],});migrateWebstudioDataMutable(data);- expect(data.instances.get("native")?.component).toBe("Form");- expect(data.instances.get("managed")?.component).toBe("Form");+ expect(data.instances.get("native")?.component).toBe("ResourceForm");+ expect(data.instances.get("managed")?.component).toBe("ResourceForm");expect(data.instances.get("legacy")?.component).toBe("WebhookForm");- expect(data.instances.get("new")?.component).toBe("Form");+ expect(data.instances.get("webhook")?.component).toBe("WebhookForm");+ expect(data.instances.get("new")?.component).toBe("ResourceForm");const reloaded = structuredClone(data);reloaded.pages = migratePages(serializePages(data.pages));- expect(reloaded.pages.formComponentIdentityVersion).toBe(1);+ expect("formComponentIdentityVersion" in reloaded.pages).toBe(false);migrateWebstudioDataMutable(reloaded);- expect(reloaded.instances.get("new")?.component).toBe("Form");+ expect(reloaded.instances.get("new")?.component).toBe("ResourceForm");+});++test("migrates marked modern Form and preserves all instance data", () => {+ const data = structuredClone(emptyData);+ (+ data.pages as Pages & { formComponentIdentityVersion: number }+ ).formComponentIdentityVersion = 1;+ data.instances.set("modern", {+ type: "instance",+ id: "modern",+ component: "Form",+ children: [{ type: "text", value: "keep" }],+ });+ migrateWebstudioDataMutable(data);+ expect(data.instances.get("modern")).toEqual({+ type: "instance",+ id: "modern",+ component: "ResourceForm",+ children: [{ type: "text", value: "keep" }],+ });+ expect("formComponentIdentityVersion" in data.pages).toBe(false);+ migrateWebstudioDataMutable(data);+ expect(data.instances.get("modern")?.component).toBe("ResourceForm");});test("migrates styles inside webstudio data", () => {diff --git a/packages/project-migrations/src/index.ts b/packages/project-migrations/src/index.tsindex 4a8a4242e8..2892ba464b 100644--- a/packages/project-migrations/src/index.ts+++ b/packages/project-migrations/src/index.ts@@ -8,7 +8,10 @@ import {type StyleDecl,type WebstudioData,} from "@webstudio-is/sdk";-import { migratePages } from "./pages";+import {+ hasHistoricalFormComponentIdentityVersion,+ migratePages,+} from "./pages";import { migrateResourcesMutable } from "./resources";import { migrateStylesMutable } from "./styles";@@ -67,18 +70,24 @@ export const migrateContentBlockDocumentBindingsMutable = (export const migrateResourceFormInstancesMutable = (instances: Iterable<Instance>,- migrateLegacyForm: boolean+ hasModernFormMarker: boolean) => {+ const changedInstanceIds = new Set<Instance["id"]>();for (const instance of instances) {- if (migrateLegacyForm && instance.component === "Form") {- instance.component = "WebhookForm";+ const originalComponent = instance.component;+ if (instance.component === "Form") {+ instance.component = hasModernFormMarker ? "ResourceForm" : "WebhookForm";} else if (instance.component === "NativeForm" ||instance.component === "ResourceForm") {- instance.component = "Form";+ instance.component = "ResourceForm";+ }+ if (instance.component !== originalComponent) {+ changedInstanceIds.add(instance.id);}}+ return changedInstanceIds;};export const migrateCodeTextContentMutable = (@@ -193,12 +202,14 @@ const migrateContentBlockImageStylesMutable = (* load boundaries before all callers stop seeing older persisted shapes.*/export const migrateWebstudioDataMutable = (data: WebstudioData) => {+ const hasModernFormMarker = hasHistoricalFormComponentIdentityVersion(+ data.pages+ );data.pages = migratePages(data.pages);migrateResourceFormInstancesMutable(data.instances.values(),- data.pages.formComponentIdentityVersion === undefined+ hasModernFormMarker);- data.pages.formComponentIdentityVersion = 1;migrateResourcesMutable(data.resources.values());migrateStylesMutable(data.styles);migrateCodeTextContentMutable(data);diff --git a/packages/project-migrations/src/pages.ts b/packages/project-migrations/src/pages.tsindex dee60012d9..3d59aced45 100644--- a/packages/project-migrations/src/pages.ts+++ b/packages/project-migrations/src/pages.ts@@ -15,7 +15,8 @@ import { isRootFolder, ROOT_FOLDER_ID } from "@webstudio-is/sdk";import { z } from "zod";type LegacyPages = {- formComponentIdentityVersion?: Pages["formComponentIdentityVersion"];+ /** Historical input only; read before normalizing paired pages and instances. */+ formComponentIdentityVersion?: number;meta?: Pages["meta"];compiler?: Pages["compiler"];redirects?: Pages["redirects"];@@ -24,6 +25,14 @@ type LegacyPages = {folders?: Folder[];};+export const hasHistoricalFormComponentIdentityVersion = (+ pagesData: unknown+): boolean =>+ typeof pagesData === "object" &&+ pagesData !== null &&+ "formComponentIdentityVersion" in pagesData &&+ pagesData.formComponentIdentityVersion !== undefined;+export type SerializedPages = Omit<Pages,"pages" | "pageTemplates" | "folders"@@ -34,7 +43,6 @@ export type SerializedPages = Omit<};export const serializedPages: z.ZodType<SerializedPages, unknown> = z.object({- formComponentIdentityVersion: z.number().int().optional(),meta: projectMeta.optional(),compiler: compilerSettings.optional(),redirects: z.array(pageRedirect).optional(),@@ -115,7 +123,6 @@ const removeOrphanFolderChildren = (export const serializePages = (pagesData: Pages): SerializedPages => {const parsedPages = pages.parse(pagesData);return {- formComponentIdentityVersion: parsedPages.formComponentIdentityVersion,meta: parsedPages.meta,compiler: parsedPages.compiler,redirects: parsedPages.redirects,@@ -139,9 +146,12 @@ export const migratePages = (pagesData: unknown): Pages => {const currentPages = pagesData as Pages;const result = pages.safeParse(currentPages);if (result.success && currentPages.pageTemplates !== undefined) {+ if (hasHistoricalFormComponentIdentityVersion(currentPages)) {+ return result.data;+ }return currentPages;}- return {+ const normalizedPages = {...currentPages,pageTemplates: currentPages.pageTemplates ?? new Map(),folders: removeOrphanFolderChildren(@@ -149,13 +159,16 @@ export const migratePages = (pagesData: unknown): Pages => {currentPages.folders),};+ if (hasHistoricalFormComponentIdentityVersion(currentPages)) {+ return pages.parse(normalizedPages);+ }+ return normalizedPages;}if (isSerializedPages(pagesData)) {const nextPages = toMap<Page>(pagesData.pages, normalizePage);const nextFolders = toMap<Folder>(pagesData.folders);return {- formComponentIdentityVersion: pagesData.formComponentIdentityVersion,meta: pagesData.meta,compiler: pagesData.compiler,redirects: pagesData.redirects,@@ -230,7 +243,6 @@ export const migratePages = (pagesData: unknown): Pages => {}return {- formComponentIdentityVersion: pagesData.formComponentIdentityVersion,meta: pagesData.meta,compiler: pagesData.compiler,redirects: pagesData.redirects,diff --git a/packages/project/src/db/build-patch-core.ts b/packages/project/src/db/build-patch-core.tsindex 88e84588ba..d0873ed52f 100644--- a/packages/project/src/db/build-patch-core.ts+++ b/packages/project/src/db/build-patch-core.ts@@ -1,4 +1,9 @@import type { Patch } from "immer";+import { migrateResourceFormInstancesMutable } from "@webstudio-is/project-migrations";+import {+ hasHistoricalFormComponentIdentityVersion,+ migratePages,+} from "@webstudio-is/project-migrations/pages";import {type Breakpoints,breakpoints,@@ -203,6 +208,31 @@ export const createBuildPatchUpdate = async ({const assetPatches: Patch[][] = [];const assetFolderPatches: Patch[][] = [];+ // Persist the identity transition in the same Build update as either namespace.+ // A pages-only edit must not erase the historical discriminator while Form+ // instances still depend on it.+ const touchesFormIdentity = transactions.some((transaction) =>+ transaction.payload.some(+ ({ namespace, patches }) =>+ patches.length > 0 &&+ (namespace === "pages" || namespace === "instances")+ )+ );+ if (touchesFormIdentity) {+ const rawPages = parseConfig<unknown>(build.pages);+ const hasModernFormMarker =+ hasHistoricalFormComponentIdentityVersion(rawPages);+ buildData.pages = migratePages(rawPages);+ buildData.instances = parseInstanceData(build.instances);+ const changedInstanceIds = migrateResourceFormInstancesMutable(+ buildData.instances.values(),+ hasModernFormMarker+ );+ for (const instanceId of changedInstanceIds) {+ touchedInstances.keys.add(instanceId);+ }+ }+for (const transaction of transactions) {for (const change of transaction.payload) {const { namespace, patches } = change;@@ -241,12 +271,29 @@ export const createBuildPatchUpdate = async ({const instances =buildData.instances ?? parseInstanceData(build.instances);- buildData.instances = applyBuildNamespacePatches(+ const patchedInstances = applyBuildNamespacePatches("instances",instances,patches);+ // The stored instances were migrated before applying patches. A stale+ // client may still send Form for a managed form, while an existing+ // WebhookForm must keep its identity if that client replaces it.+ let normalizedInstances: Instances | undefined;+ for (const [instanceId, instance] of patchedInstances) {+ if (instance.component !== "Form") {+ continue;+ }+ const component =+ instances.get(instanceId)?.component === "WebhookForm"+ ? "WebhookForm"+ : "ResourceForm";+ normalizedInstances ??= new Map(patchedInstances);+ normalizedInstances.set(instanceId, { ...instance, component });+ }+ buildData.instances = normalizedInstances ?? patchedInstances;+const cycles = findCycles(buildData.instances?.values() ?? []);if (cycles.length > 0) {console.error(diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.tsindex 3987680fb1..62581a6602 100644--- a/packages/project/src/db/build-patch.test.ts+++ b/packages/project/src/db/build-patch.test.ts@@ -8,6 +8,10 @@ import {} from "@webstudio-is/postgrest/testing";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import { defaultPlanFeatures } from "@webstudio-is/plans";+import {+ parseInstanceData,+ parsePages,+} from "@webstudio-is/project-build/persistence";import {patchBuild,patchLoadedBuild,@@ -96,6 +100,192 @@ const transaction = (...overrides,});+test("a pages-only save persists marked modern Form as ResourceForm with pages", async () => {+ const markedPages = {+ ...JSON.parse(buildRow.pages),+ formComponentIdentityVersion: 1,+ };+ const build = {+ ...buildRow,+ pages: JSON.stringify(markedPages),+ instances: JSON.stringify([+ {+ id: "body-1",+ type: "instance",+ component: "Body",+ children: [{ type: "id", value: "form-1" }],+ },+ {+ id: "form-1",+ type: "instance",+ component: "Form",+ children: [{ type: "text", value: "Keep me" }],+ },+ ]),+ };+ const result = await createBuildPatchUpdate({+ build,+ clientVersion: 3,+ transactions: [+ transaction({+ payload: [+ {+ namespace: "pages",+ patches: [+ { op: "add", path: ["meta", "siteName"], value: "Updated" },+ ],+ },+ ],+ }),+ ],+ });+ expect(result.status).toBe("ok");+ if (result.status !== "ok" || result.update === undefined) {+ return;+ }+ expect(result.update.pages).toBeDefined();+ expect(result.update.instances).toBeDefined();+ expect(JSON.parse(result.update.pages ?? "{}")).not.toHaveProperty(+ "formComponentIdentityVersion"+ );+ const reloadedPages = parsePages(result.update.pages ?? "{}");+ const reloadedInstances = parseInstanceData(result.update.instances ?? "[]");+ expect(reloadedPages.meta?.siteName).toBe("Updated");+ expect(reloadedInstances.get("form-1")).toEqual({+ id: "form-1",+ type: "instance",+ component: "ResourceForm",+ children: [{ type: "text", value: "Keep me" }],+ });+});++test("marked modern Form patches persist as ResourceForm without changing WebhookForm", async () => {+ const result = await createBuildPatchUpdate({+ build: {+ ...buildRow,+ pages: JSON.stringify({+ ...JSON.parse(buildRow.pages),+ formComponentIdentityVersion: 1,+ }),+ instances: JSON.stringify([+ { id: "body-1", type: "instance", component: "Body", children: [] },+ {+ id: "webhook-1",+ type: "instance",+ component: "WebhookForm",+ children: [],+ },+ ]),+ },+ clientVersion: 3,+ transactions: [+ transaction({+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["form-1"],+ value: {+ id: "form-1",+ type: "instance",+ component: "Form",+ children: [],+ },+ },+ {+ op: "replace",+ path: ["webhook-1", "component"],+ value: "Form",+ },+ ],+ },+ ],+ }),+ ],+ });++ expect(result.status).toBe("ok");+ if (result.status !== "ok" || result.update === undefined) {+ return;+ }+ expect(result.update.pages).toBeDefined();+ expect(JSON.parse(result.update.pages ?? "{}")).not.toHaveProperty(+ "formComponentIdentityVersion"+ );+ const reloadedInstances = parseInstanceData(result.update.instances ?? "[]");+ expect(reloadedInstances.get("form-1")?.component).toBe("ResourceForm");+ expect(reloadedInstances.get("webhook-1")?.component).toBe("WebhookForm");+});++test("historical Form instances retain WebhookForm identity after a stale patch", async () => {+ const result = await createBuildPatchUpdate({+ build: {+ ...buildRow,+ instances: JSON.stringify([+ { id: "body-1", type: "instance", component: "Body", children: [] },+ { id: "form-1", type: "instance", component: "Form", children: [] },+ ]),+ },+ clientVersion: 3,+ transactions: [+ transaction({+ payload: [+ {+ namespace: "instances",+ patches: [+ { op: "replace", path: ["form-1", "component"], value: "Form" },+ ],+ },+ ],+ }),+ ],+ });++ expect(result.status).toBe("ok");+ if (result.status !== "ok" || result.update === undefined) {+ return;+ }+ const reloadedInstances = parseInstanceData(result.update.instances ?? "[]");+ expect(reloadedInstances.get("form-1")?.component).toBe("WebhookForm");+});++test("a Form patch from the previous Builder persists as ResourceForm after marker removal", async () => {+ const result = await createBuildPatchUpdate({+ build: buildRow,+ clientVersion: 3,+ transactions: [+ transaction({+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["form-1"],+ value: {+ id: "form-1",+ type: "instance",+ component: "Form",+ children: [],+ },+ },+ ],+ },+ ],+ }),+ ],+ });++ expect(result.status).toBe("ok");+ if (result.status !== "ok" || result.update === undefined) {+ return;+ }+ const reloadedInstances = parseInstanceData(result.update.instances ?? "[]");+ expect(reloadedInstances.get("form-1")?.component).toBe("ResourceForm");+});+describe("patchBuild", () => {test("rejects an over-limit Contact email raw patch before persistence", async () => {let didUpdateBuild = false;diff --git a/packages/protocol/src/schema.test.ts b/packages/protocol/src/schema.test.tsindex 984db366ba..1097d86f7e 100644--- a/packages/protocol/src/schema.test.ts+++ b/packages/protocol/src/schema.test.ts@@ -7,6 +7,7 @@ import {getMissingImportedAssetFiles,getBundleVersionMismatchMessage,importProjectBundleInput,+ historicalPublishedProjectBundle,publishedProjectBundle,bundleVersion,stagedUploadPath,@@ -71,6 +72,27 @@ describe("project bundle contract", () => {});});+ test("retains the historical Form marker only in input parsing", () => {+ const bundle = createPublishedProjectBundleFixture();+ const historical = {+ ...bundle,+ build: {+ ...bundle.build,+ pages: { ...bundle.build.pages, formComponentIdentityVersion: 1 },+ },+ };+ expect(+ historicalPublishedProjectBundle.parse(historical).build.pages+ ).toHaveProperty("formComponentIdentityVersion", 1);+ expect(+ importProjectBundleInput.parse({ projectId: "project", data: historical })+ .data?.build.pages+ ).toHaveProperty("formComponentIdentityVersion", 1);+ expect(+ publishedProjectBundle.parse(historical).build.pages+ ).not.toHaveProperty("formComponentIdentityVersion");+ });+test("preserves build-versioned marketplace metadata", () => {const marketplaceProduct = {category: "pageTemplates" as const,diff --git a/packages/protocol/src/schema.ts b/packages/protocol/src/schema.tsindex 95e0f15946..08103832d0 100644--- a/packages/protocol/src/schema.ts+++ b/packages/protocol/src/schema.ts@@ -87,10 +87,21 @@ export const publishedProjectBundle = projectBundle.extend({});export type PublishedProjectBundle = z.infer<typeof publishedProjectBundle>;+// Input-only compatibility for bundles produced before Form identities were+// canonicalized. Keep this out of publishedProjectBundle and bundleVersion.+export const historicalPublishedProjectBundle = publishedProjectBundle.extend({+ build: serializedBuild.extend({+ pages: z.intersection(+ serializedBuild.shape.pages,+ z.object({ formComponentIdentityVersion: z.number().int().optional() })+ ),+ }),+});+export const importProjectBundleInput = z.object({projectId: z.string().min(1),- data: publishedProjectBundle.optional(),+ data: historicalPublishedProjectBundle.optional(),uploadId: z.string().min(1).optional(),ignoreVersionCheck: z.boolean().optional(),})diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsxindex 62dace2af9..6b2455569d 100644--- a/packages/react-sdk/src/component-generator.test.tsx+++ b/packages/react-sdk/src/component-generator.test.tsx@@ -40,8 +40,7 @@ import {const Body = createTemplateComponentFixture("Body");const Box = createTemplateComponentFixture("Box");const Button = createTemplateComponentFixture("Button");-const Form = createTemplateComponentFixture("Form");-const ResourceForm = createTemplateComponentFixture("Form");+const ResourceForm = createTemplateComponentFixture("ResourceForm");const Fragment = createTemplateComponentFixture("Fragment");const HeadSlot = createTemplateComponentFixture("HeadSlot");const Heading = createTemplateComponentFixture("Heading");@@ -716,20 +715,20 @@ test("generate jsx children with nested instances", () => {usedDataSources: new Map(),indexesWithinAncestors: new Map(),...renderData(- <Form ws:id="form" prop="value">+ <ResourceForm ws:id="form" prop="value"><Input></Input><Button></Button>- </Form>+ </ResourceForm>),})).toEqual(validateJSX(clear(`- <Form+ <ResourceFormprop={"value"}><Input /><Button />- </Form>+ </ResourceForm>`)));@@ -1421,7 +1420,7 @@ test("generate resource prop with configured form method", () => {parameters: [],metas: new Map([[- "Form",+ "ResourceForm",{props: {action: {@@ -1436,22 +1435,26 @@ 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>+ <ResourceForm ws:id="form1" action={myResource}></ResourceForm>+ <ResourceForm ws:id="form2" action={anotherResource}></ResourceForm>+ <ResourceForm+ ws:id="form3"+ action={myResource}+ method="get"+ ></ResourceForm></Body>),})).toMatchInlineSnapshot(`"const Page = () => {return <Body>- <Form+ <ResourceFormaction={"action"}method={"post"} />- <Form+ <ResourceFormaction={"action_1"}method={"get"} />- <Form+ <ResourceFormaction={"action"}method={"get"} /></Body>@@ -2396,7 +2399,7 @@ test("saved managed Form errors render like Preview for malformed values while pconst form: import("@webstudio-is/sdk").Instance = {type: "instance",id: "saved-form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: slot.id }],};const dataSources: import("@webstudio-is/sdk").DataSources = new Map([@@ -2453,7 +2456,7 @@ test("saved managed Form errors render like Preview for malformed values while p"createElement","renderText","formatManagedFormErrors",- "Form",+ "ResourceForm","errors",`${code}return Page();`);diff --git a/packages/react-sdk/src/managed-form-component-generator.ts b/packages/react-sdk/src/managed-form-component-generator.tsindex 8526014d2a..aa16b58af1 100644--- a/packages/react-sdk/src/managed-form-component-generator.ts+++ b/packages/react-sdk/src/managed-form-component-generator.ts@@ -14,7 +14,7 @@ import {const managedFormPolicy: ComponentGenerationPolicy = {transformProps: (instance, props) => {- if (instance.component !== "Form") {+ if (instance.component !== "ResourceForm") {return;}for (const [name, prop] of props) {@@ -38,7 +38,8 @@ const managedFormPolicy: ComponentGenerationPolicy = {dataSource.type === "parameter" &&(dataSource.name === formDataParameterName ||dataSource.name === browserInfoParameterName) &&- instances.get(dataSource.scopeInstanceId ?? "")?.component === "Form"+ instances.get(dataSource.scopeInstanceId ?? "")?.component ===+ "ResourceForm") {// Submission values exist only while a managed submit runs.return `const ${valueName}: any = undefined\n`;diff --git a/packages/sdk-cli/src/generate-stories.test.tsx b/packages/sdk-cli/src/generate-stories.test.tsxindex 749c786781..e14a109898 100644--- a/packages/sdk-cli/src/generate-stories.test.tsx+++ b/packages/sdk-cli/src/generate-stories.test.tsx@@ -76,13 +76,13 @@ const labelMeta: WsComponentMeta = {const Box = (_props: { children?: ReactNode }) => null;Box.displayName = "Box";-const Form = (_props: {+const ResourceForm = (_props: {errors?: unknown;onResultChange?: unknown;children?: ReactNode;"ws:show"?: boolean;}) => null;-Form.displayName = "Form";+ResourceForm.displayName = "ResourceForm";const BaseLabel = () => null;BaseLabel.displayName = "Label";const RadixLabel = () => null;@@ -136,13 +136,13 @@ describe("generateStories", () => {const errorsVariable = new Variable("errors", []);await generateStories({packageName: "@webstudio-is/sdk-components-react",- components: { Box, Form },+ components: { Box, ResourceForm },templates: [{meta: {category: "general",template: hasErrors ? (- <Form+ <ResourceFormws:show={!hidden}errors={expression`${errorsVariable}`}onResultChange={@@ -155,19 +155,19 @@ describe("generateStories", () => {<ws.element ws:label="Error Message">{new PlaceholderValue("Sorry, something went wrong.")}</ws.element>- </Form>+ </ResourceForm>) : (<Box />),},},],- metas: { Box: boxMeta, Form: boxMeta },+ metas: { Box: boxMeta, ResourceForm: boxMeta },});const source = await readFile(path.join(root,- `src/__generated__/${hasErrors ? "form" : "box"}.stories.tsx`+ `src/__generated__/${hasErrors ? "resource-form" : "box"}.stories.tsx`),"utf8");diff --git a/packages/sdk-components-react-remix/src/components.ts b/packages/sdk-components-react-remix/src/components.tsindex 024b67be56..dbead0b27b 100644--- a/packages/sdk-components-react-remix/src/components.ts+++ b/packages/sdk-components-react-remix/src/components.ts@@ -1,7 +1,7 @@export { Body } from "./body";export { Link } from "./link";export { RichTextLink } from "./rich-text-link";-export { Form } from "./resource-form";-/** @deprecated Legacy Webhook Form is supported through the next release. Use Form for new forms. */+export { ResourceForm } from "./resource-form";+/** @deprecated Webhook Form is supported through the next release. Use ResourceForm for new forms. */export { WebhookForm } from "./webhook-form";export { RemixForm } from "./remix-form";diff --git a/packages/sdk-components-react-remix/src/form-feedback.browser.test.tsx b/packages/sdk-components-react-remix/src/form-feedback.browser.test.tsxindex 078741a30f..2a4e6434ee 100644--- a/packages/sdk-components-react-remix/src/form-feedback.browser.test.tsx+++ b/packages/sdk-components-react-remix/src/form-feedback.browser.test.tsx@@ -3,7 +3,7 @@ import { createRoot } from "react-dom/client";import { act } from "react-dom/test-utils";import { createMemoryRouter, RouterProvider } from "react-router-dom";import { afterEach, expect, test, vi } from "vitest";-import { Form } from "./resource-form";+import { ResourceForm } from "./resource-form";(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }@@ -46,12 +46,12 @@ test("managed Remix Form scrolls partial failure and reveals visible success", aerrors: [],});vi.stubGlobal("fetch", async () => Response.json(await action()));- const FormFixture = () => {+ const ResourceFormFixture = () => {const [state, setState] = useState<"initial" | "success" | "error">("initial");return (- <Form+ <ResourceFormdata-ws-managed-form-id="saved-managed-form"action={[{ dataSourceId: "first" }, { dataSourceId: "second" }]}state={state}@@ -60,11 +60,11 @@ test("managed Remix Form scrolls partial failure and reveals visible success", a{state !== "success" && <button type="submit">Send</button>}{state === "error" && <div data-feedback="error">Partial failure</div>}{state === "success" && <div data-feedback="success">Done</div>}- </Form>+ </ResourceForm>);};const router = createMemoryRouter([- { path: "/", element: <FormFixture />, action },+ { path: "/", element: <ResourceFormFixture />, action },]);const container = document.createElement("div");document.body.append(container);diff --git a/packages/sdk-components-react-remix/src/resource-form-refresh.browser.test.tsx b/packages/sdk-components-react-remix/src/resource-form-refresh.browser.test.tsxindex 9037b88cd8..041d76e3d1 100644--- a/packages/sdk-components-react-remix/src/resource-form-refresh.browser.test.tsx+++ b/packages/sdk-components-react-remix/src/resource-form-refresh.browser.test.tsx@@ -6,7 +6,7 @@ import {useLoaderData,} from "react-router-dom";import { afterEach, expect, test, vi } from "vitest";-import { Form } from "./resource-form";+import { ResourceForm } from "./resource-form";(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }@@ -52,13 +52,13 @@ test("managed submission refreshes mutable page data once without replaying POSTreturn (<><output>{value}</output>- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}onResultChange={(result) => results.push(result)}><button type="submit">Send</button>- </Form>+ </ResourceForm></>);};@@ -109,12 +109,12 @@ test("failed submissions skip refresh and a later successful submission refreshereturn (<><output>{value}</output>- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}><button type="submit">Send</button>- </Form>+ </ResourceForm></>);};@@ -150,13 +150,13 @@ test("a redirect skips refresh", async () => {path: "/",loader,element: (- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}successRedirect="#done"><button type="submit">Send</button>- </Form>+ </ResourceForm>),},]);@@ -193,13 +193,13 @@ test("navigation ignores an in-flight submission from the old page", async () =>path: "/",loader,element: (- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}onResultChange={(result) => results.push(result)}><button type="submit">Send</button>- </Form>+ </ResourceForm>),},{ path: "/next", element: <output>Next page</output> },@@ -253,13 +253,13 @@ test("refresh failure retains the completed success result and does not replay Preturn (<><output>{value}</output>- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}onResultChange={(result) => results.push(result)}><button type="submit">Send</button>- </Form>+ </ResourceForm></>);};diff --git a/packages/sdk-components-react-remix/src/resource-form.tsx b/packages/sdk-components-react-remix/src/resource-form.tsxindex f83c35ae07..58e9568241 100644--- a/packages/sdk-components-react-remix/src/resource-form.tsx+++ b/packages/sdk-components-react-remix/src/resource-form.tsx@@ -12,9 +12,9 @@ import {useNavigation,useRevalidator,} from "@remix-run/react";-import { Form as SharedForm } from "@webstudio-is/sdk-components-react/components";+import { ResourceForm as SharedForm } from "@webstudio-is/sdk-components-react/components";-export const Form = forwardRef<+export const ResourceForm = forwardRef<ElementRef<typeof SharedForm>,ComponentProps<typeof SharedForm>>((props, ref) => {@@ -77,4 +77,4 @@ export const Form = forwardRef<);});-Form.displayName = "Form";+ResourceForm.displayName = "ResourceForm";diff --git a/packages/sdk-components-react-remix/src/webhook-form.tsx b/packages/sdk-components-react-remix/src/webhook-form.tsxindex 0849e1c8b6..17c0ead89c 100644--- a/packages/sdk-components-react-remix/src/webhook-form.tsx+++ b/packages/sdk-components-react-remix/src/webhook-form.tsx@@ -9,9 +9,12 @@ import { useFetcher, type Fetcher, type FormProps } from "@remix-run/react";import {formIdFieldName,formBotFieldName,- isBraveBrowser,-} from "@webstudio-is/sdk/runtime";+ createFormBotValue,+} from "@webstudio-is/sdk/form/browser";+// This module serves only the deprecated Webhook Form. Remove its private+// fetch and state helpers with the component.+/** @deprecated Tag for the deprecated Webhook Form component. */export const defaultTag = "form";const useOnFetchEnd = <Data,>(@@ -36,51 +39,7 @@ const useOnFetchEnd = <Data,>(type State = "initial" | "success" | "error";-// gcd - greatest common divisor-const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));--const getAspectRatioString = (width: number, height: number) => {- const r = gcd(width, height);- const aspectRatio = `${width / r}/${height / r}`;- return aspectRatio;-};--/**- * jsdom detector, trying to check that matchMedia is working (jsdom has no support of matchMedia and usually simple stub is used)- */-const isJSDom = () => {- if (typeof matchMedia === "undefined") {- return true;- }-- const { width, height } = screen;- const deviceAspectRatio = getAspectRatioString(width, height);-- const matchAspectRatio = matchMedia(- `(device-aspect-ratio: ${deviceAspectRatio})`- ).matches;-- const matchWidthHeight = matchMedia(- `(device-width: ${width}px) and (device-height: ${height}px)`- ).matches;-- const matchWidthHeightFail = matchMedia(- `(device-width: ${width - 1}px) and (device-height: ${height}px)`- ).matches;-- const matchLight = matchMedia("(prefers-color-scheme: light)").matches;- const matchDark = matchMedia("(prefers-color-scheme: dark)").matches;-- const hasMatchMedia =- matchAspectRatio &&- matchWidthHeight &&- !matchWidthHeightFail &&- matchLight !== matchDark;-- return hasMatchMedia === false;-};--/** @deprecated Legacy Webhook Form is supported through the next release. Use Form for new forms. */+/** @deprecated Webhook Form is supported through the next release. Use Form for new forms. */export const WebhookForm = forwardRef<ElementRef<typeof defaultTag>,Omit<ComponentProps<typeof defaultTag>, "action"> & {@@ -103,11 +62,7 @@ export const WebhookForm = forwardRef<onStateChange?.(state);});- /**- * Refresh the hidden field using js with simple jsdom detector.- * This is used to protect form submission against very simple bots.- * Skipped for Brave browser due to: https://github.com/brave/brave-browser/issues/46541- */+ /** Refresh the bot field before every submission. */const handleSubmitAndAddHiddenJsField = (event: React.FormEvent<HTMLFormElement>) => {@@ -116,13 +71,7 @@ export const WebhookForm = forwardRef<event.preventDefault();return;}- // Skip bot detection for Brave - Shields blocks matchMedia fingerprinting detection- if (isBraveBrowser()) {- hiddenInput.value = "brave";- } else {- // Non-numeric values are utilized for logging purposes.- hiddenInput.value = isJSDom() ? "jsdom" : Date.now().toString(16);- }+ hiddenInput.value = createFormBotValue();};return (diff --git a/packages/sdk-components-react-router/src/components.ts b/packages/sdk-components-react-router/src/components.tsindex 024b67be56..dbead0b27b 100644--- a/packages/sdk-components-react-router/src/components.ts+++ b/packages/sdk-components-react-router/src/components.ts@@ -1,7 +1,7 @@export { Body } from "./body";export { Link } from "./link";export { RichTextLink } from "./rich-text-link";-export { Form } from "./resource-form";-/** @deprecated Legacy Webhook Form is supported through the next release. Use Form for new forms. */+export { ResourceForm } from "./resource-form";+/** @deprecated Webhook Form is supported through the next release. Use ResourceForm for new forms. */export { WebhookForm } from "./webhook-form";export { RemixForm } from "./remix-form";diff --git a/packages/sdk-components-react-router/src/form-feedback.browser.test.tsx b/packages/sdk-components-react-router/src/form-feedback.browser.test.tsxindex 21df241c5e..c328a2b8c1 100644--- a/packages/sdk-components-react-router/src/form-feedback.browser.test.tsx+++ b/packages/sdk-components-react-router/src/form-feedback.browser.test.tsx@@ -3,7 +3,7 @@ import { createRoot } from "react-dom/client";import { act } from "react-dom/test-utils";import { createMemoryRouter, RouterProvider } from "react-router";import { afterEach, expect, test, vi } from "vitest";-import { Form } from "./resource-form";+import { ResourceForm } from "./resource-form";(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }@@ -68,12 +68,12 @@ test("managed Form reveals partial failure and leaves visible success feedback ierrors: [],});mockManagedHttpAction(action);- const FormFixture = () => {+ const ResourceFormFixture = () => {const [state, setState] = useState<"initial" | "success" | "error">("initial");return (- <Form+ <ResourceFormdata-ws-managed-form-id="saved-managed-form"action={[{ dataSourceId: "first" }, { dataSourceId: "second" }]}state={state}@@ -82,7 +82,7 @@ test("managed Form reveals partial failure and leaves visible success feedback i{state !== "success" && <button type="submit">Send</button>}{state === "error" && <div data-feedback="error">Partial failure</div>}{state === "success" && <div data-feedback="success">Done</div>}- </Form>+ </ResourceForm>);};const scroll = vi@@ -95,7 +95,7 @@ test("managed Form reveals partial failure and leaves visible success feedback ireturn { top, bottom: top + 30 } as DOMRect;});- const view = await renderRoute(<FormFixture />, action);+ const view = await renderRoute(<ResourceFormFixture />, action);try {await act(async () => view.container.querySelector("button")?.click());await vi.waitFor(() => expect(scroll).toHaveBeenCalledTimes(1));@@ -139,13 +139,13 @@ test("managed Form reveals authored Error Message on repeated failures", async (],}));mockManagedHttpAction(action);- const FormFixture = () => {+ const ResourceFormFixture = () => {const [state, setState] = useState<"initial" | "success" | "error">("initial");const [errors, setErrors] = useState<Array<{ message: string }>>([]);return (- <Form+ <ResourceFormdata-ws-managed-form-id="saved-managed-form"action={[{ dataSourceId: "first" }]}state={state}@@ -158,7 +158,7 @@ test("managed Form reveals authored Error Message on repeated failures", async ({errors.map(({ message }) => message).join("\n")}</div>)}- </Form>+ </ResourceForm>);};const scroll = vi@@ -170,7 +170,7 @@ test("managed Form reveals authored Error Message on repeated failures", async (return { top, bottom: top + 30 } as DOMRect;});- const view = await renderRoute(<FormFixture />, action);+ const view = await renderRoute(<ResourceFormFixture />, action);try {await act(async () => view.container.querySelector("button")?.click());await vi.waitFor(() => expect(scroll).toHaveBeenCalledTimes(1));@@ -194,13 +194,13 @@ test("managed Form reveals authored Error Message on repeated failures", async (test("managed Form reveals a persistent configuration error", async () => {const action = vi.fn();- const FormFixture = () => {+ const ResourceFormFixture = () => {const [state, setState] = useState<"initial" | "success" | "error">("initial");const [errors, setErrors] = useState<Array<{ message: string }>>([]);return (- <Form+ <ResourceFormaction={[{ dataSourceId: "resource" }, { dataSourceId: "resource" }]}state={state}onStateChange={setState}@@ -212,10 +212,10 @@ test("managed Form reveals a persistent configuration error", async () => {{errors.map(({ message }) => message).join("\n")}</div>)}- </Form>+ </ResourceForm>);};- const view = await renderRoute(<FormFixture />, action);+ const view = await renderRoute(<ResourceFormFixture />, action);const scroll = vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});@@ -252,12 +252,12 @@ test("managed Form follows a valid success redirect without scrolling feedback",.fn().mockResolvedValue({ success: true, status: 200, results: [], errors: [] });mockManagedHttpAction(action);- const FormFixture = () => {+ const ResourceFormFixture = () => {const [state, setState] = useState<"initial" | "success" | "error">("initial");return (- <Form+ <ResourceFormdata-ws-managed-form-id="saved-managed-form"action={[{ dataSourceId: "first" }]}state={state}@@ -266,7 +266,7 @@ test("managed Form follows a valid success redirect without scrolling feedback",><button type="submit">Send</button>{state === "success" && <div data-feedback="success">Done</div>}- </Form>+ </ResourceForm>);};const previousUrl = window.location.href;@@ -280,7 +280,7 @@ test("managed Form follows a valid success redirect without scrolling feedback",bottom: window.innerHeight + 60,}) as DOMRect);- const view = await renderRoute(<FormFixture />, action);+ const view = await renderRoute(<ResourceFormFixture />, action);try {await act(async () => view.container.querySelector("button")?.click());await vi.waitFor(() => expect(window.location.hash).toBe("#after-form"));diff --git a/packages/sdk-components-react-router/src/metas.ts b/packages/sdk-components-react-router/src/metas.tsindex 36ff389920..4e5433a7d3 100644--- a/packages/sdk-components-react-router/src/metas.ts+++ b/packages/sdk-components-react-router/src/metas.ts@@ -2,7 +2,7 @@ export {Body,Link,RichTextLink,- Form,+ ResourceForm,WebhookForm,RemixForm,} from "@webstudio-is/sdk-components-react/metas";diff --git a/packages/sdk-components-react-router/src/resource-form-refresh.browser.test.tsx b/packages/sdk-components-react-router/src/resource-form-refresh.browser.test.tsxindex 1a0271c944..1ad0e594ff 100644--- a/packages/sdk-components-react-router/src/resource-form-refresh.browser.test.tsx+++ b/packages/sdk-components-react-router/src/resource-form-refresh.browser.test.tsx@@ -8,7 +8,7 @@ import {useLoaderData,} from "react-router";import { afterEach, expect, test, vi } from "vitest";-import { Form } from "./resource-form";+import { ResourceForm } from "./resource-form";(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }@@ -57,13 +57,13 @@ test("managed submission refreshes mutable page data once without replaying POSTreturn (<><output>{value}</output>- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}onResultChange={(result) => results.push(result)}><button type="submit">Send</button>- </Form>+ </ResourceForm></>);};@@ -120,7 +120,7 @@ test("success feedback scroll waits until delayed route revalidation settles", areturn (<><output>{value}</output>- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}state={state}@@ -128,7 +128,7 @@ test("success feedback scroll waits until delayed route revalidation settles", a><button type="submit">Send</button>{state === "success" && <div>Submitted</div>}- </Form>+ </ResourceForm></>);};@@ -177,7 +177,7 @@ test("success feedback stays visible when restoration follows route idle", async<><ScrollRestoration /><div style={{ height: window.innerHeight * 2 }} />- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}state={state}@@ -185,7 +185,7 @@ test("success feedback stays visible when restoration follows route idle", async><button type="submit">Send</button>{state === "success" && <div data-feedback="success">Submitted</div>}- </Form>+ </ResourceForm><div style={{ height: window.innerHeight }} /></>);@@ -262,12 +262,12 @@ test("failed submissions skip refresh and a later successful submission refreshereturn (<><output>{value}</output>- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}><button type="submit">Send</button>- </Form>+ </ResourceForm></>);};@@ -303,13 +303,13 @@ test("a redirect skips refresh", async () => {path: "/",loader,element: (- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}successRedirect="#done"><button type="submit">Send</button>- </Form>+ </ResourceForm>),},]);@@ -346,13 +346,13 @@ test("navigation ignores an in-flight submission from the old page", async () =>path: "/",loader,element: (- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}onResultChange={(result) => results.push(result)}><button type="submit">Send</button>- </Form>+ </ResourceForm>),},{ path: "/next", element: <output>Next page</output> },@@ -416,7 +416,7 @@ test("refresh failure retains the completed success result and does not replay Preturn (<><output>{value}</output>- <Form+ <ResourceFormdata-ws-managed-form-id="form"action={[{ dataSourceId: "resource" }]}state={state}@@ -425,7 +425,7 @@ test("refresh failure retains the completed success result and does not replay P><button type="submit">Send</button>{state === "success" && <div>Submitted</div>}- </Form>+ </ResourceForm></>);};diff --git a/packages/sdk-components-react-router/src/resource-form.browser.test.tsx b/packages/sdk-components-react-router/src/resource-form.browser.test.tsxindex 9a243c1b6a..f55e65c292 100644--- a/packages/sdk-components-react-router/src/resource-form.browser.test.tsx+++ b/packages/sdk-components-react-router/src/resource-form.browser.test.tsx@@ -8,7 +8,7 @@ import {managedFormIdFieldName,managedFormRequestParamName,} from "@webstudio-is/sdk/runtime";-import { Form } from "./resource-form";+import { ResourceForm } from "./resource-form";import { RemixForm } from "./remix-form";(@@ -50,12 +50,12 @@ test("an empty Resource list submits query values through client navigation", asconst location = useLocation();return (<>- <Form action={[]}>+ <ResourceForm action={[]}><input name="query" defaultValue="chairs" /><input name="tag" defaultValue="wood" /><input name="tag" defaultValue="blue" /><button type="submit">Search</button>- </Form>+ </ResourceForm><output>{location.search}</output></>);@@ -120,13 +120,13 @@ test("managed Form posts its server identity and shows the action error", asyncvi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) =>Response.json(await action({ request: new Request(input, init) })));- const FormFixture = () => {+ const ResourceFormFixture = () => {const [state, setState] = useState<"initial" | "success" | "error">("initial");const [errors, setErrors] = useState<Array<{ message: string }>>([]);return (- <Form+ <ResourceFormdata-ws-managed-form-id="form-instance"action={[{ dataSourceId: "resource-id" }]}state={state}@@ -152,14 +152,14 @@ test("managed Form posts its server identity and shows the action error", async{errors.map(({ message }) => message).join("\n")}</div>)}- </Form>+ </ResourceForm>);};const router = createMemoryRouter([{path: "/",- element: <FormFixture />,+ element: <ResourceFormFixture />,action,},],@@ -244,7 +244,7 @@ test("managed Form reports success after the action succeeds", async () => {{path: "/",element: (- <Form+ <ResourceFormdata-ws-managed-form-id="form-instance"action={[{ dataSourceId: "resource-id" }]}onStateChange={(state) => stateChanges.push(state)}@@ -252,7 +252,7 @@ test("managed Form reports success after the action succeeds", async () => {><input name="message" defaultValue="Hello" /><button type="submit">Send</button>- </Form>+ </ResourceForm>),action,},diff --git a/packages/sdk-components-react-router/src/resource-form.tsx b/packages/sdk-components-react-router/src/resource-form.tsxindex 7a62295e71..0ad9014ad4 100644--- a/packages/sdk-components-react-router/src/resource-form.tsx+++ b/packages/sdk-components-react-router/src/resource-form.tsx@@ -5,9 +5,9 @@ import {useNavigation,useRevalidator,} from "react-router";-import { Form as SharedForm } from "@webstudio-is/sdk-components-react/components";+import { ResourceForm as SharedForm } from "@webstudio-is/sdk-components-react/components";-export const Form = forwardRef<+export const ResourceForm = forwardRef<ElementRef<typeof SharedForm>,ComponentProps<typeof SharedForm>>((props, ref) => {@@ -46,4 +46,4 @@ export const Form = forwardRef<);});-Form.displayName = "Form";+ResourceForm.displayName = "ResourceForm";diff --git a/packages/sdk-components-react-router/src/webhook-form.tsx b/packages/sdk-components-react-router/src/webhook-form.tsxindex ba1879d368..d67dc59a14 100644--- a/packages/sdk-components-react-router/src/webhook-form.tsx+++ b/packages/sdk-components-react-router/src/webhook-form.tsx@@ -9,9 +9,12 @@ import { useFetcher, type Fetcher, type FormProps } from "react-router";import {formIdFieldName,formBotFieldName,- isBraveBrowser,+ createFormBotValue,} from "@webstudio-is/sdk/form/browser";+// This module serves only the deprecated Webhook Form. Remove its private+// fetch and state helpers with the component.+/** @deprecated Tag for the deprecated Webhook Form component. */export const defaultTag = "form";const useOnFetchEnd = <Data,>(@@ -36,51 +39,7 @@ const useOnFetchEnd = <Data,>(type State = "initial" | "success" | "error";-// gcd - greatest common divisor-const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));--const getAspectRatioString = (width: number, height: number) => {- const r = gcd(width, height);- const aspectRatio = `${width / r}/${height / r}`;- return aspectRatio;-};--/**- * jsdom detector, trying to check that matchMedia is working (jsdom has no support of matchMedia and usually simple stub is used)- */-const isJSDom = () => {- if (typeof matchMedia === "undefined") {- return true;- }-- const { width, height } = screen;- const deviceAspectRatio = getAspectRatioString(width, height);-- const matchAspectRatio = matchMedia(- `(device-aspect-ratio: ${deviceAspectRatio})`- ).matches;-- const matchWidthHeight = matchMedia(- `(device-width: ${width}px) and (device-height: ${height}px)`- ).matches;-- const matchWidthHeightFail = matchMedia(- `(device-width: ${width - 1}px) and (device-height: ${height}px)`- ).matches;-- const matchLight = matchMedia("(prefers-color-scheme: light)").matches;- const matchDark = matchMedia("(prefers-color-scheme: dark)").matches;-- const hasMatchMedia =- matchAspectRatio &&- matchWidthHeight &&- !matchWidthHeightFail &&- matchLight !== matchDark;-- return hasMatchMedia === false;-};--/** @deprecated Legacy Webhook Form is supported through the next release. Use Form for new forms. */+/** @deprecated Webhook Form is supported through the next release. Use Form for new forms. */export const WebhookForm = forwardRef<ElementRef<typeof defaultTag>,Omit<ComponentProps<typeof defaultTag>, "action"> & {@@ -103,11 +62,7 @@ export const WebhookForm = forwardRef<onStateChange?.(state);});- /**- * Refresh the hidden field using js with simple jsdom detector.- * This is used to protect form submission against very simple bots.- * Skipped for Brave browser due to: https://github.com/brave/brave-browser/issues/46541- */+ /** Refresh the bot field before every submission. */const handleSubmitAndAddHiddenJsField = (event: React.FormEvent<HTMLFormElement>) => {@@ -116,13 +71,7 @@ export const WebhookForm = forwardRef<event.preventDefault();return;}- // Skip bot detection for Brave - Shields blocks matchMedia fingerprinting detection- if (isBraveBrowser()) {- hiddenInput.value = "brave";- } else {- // Non-numeric values are utilized for logging purposes.- hiddenInput.value = isJSDom() ? "jsdom" : Date.now().toString(16);- }+ hiddenInput.value = createFormBotValue();};return (diff --git a/packages/sdk-components-react/src/__generated__/form.stories.tsx b/packages/sdk-components-react/src/__generated__/webhook-form.stories.tsxsimilarity index 90%rename from packages/sdk-components-react/src/__generated__/form.stories.tsxrename to packages/sdk-components-react/src/__generated__/webhook-form.stories.tsxindex 543dec291d..91b6edc6e3 100644--- a/packages/sdk-components-react/src/__generated__/form.stories.tsx+++ b/packages/sdk-components-react/src/__generated__/webhook-form.stories.tsx@@ -1,12 +1,12 @@import { useVariableState } from "@webstudio-is/react-sdk/runtime";-import { Box as Box, Form as Form } from "../components";+import { Box as Box, WebhookForm as WebhookForm } from "../components";const Component = () => {let [formState, set$formState] = useVariableState<any>("initial");return (<Box className={`w-box`}>- <Form- state={formState}+ <WebhookForm+ state={formState == null ? formState : String(formState)}onStateChange={(state: any) => {formState = state;set$formState(formState);@@ -28,13 +28,13 @@ const Component = () => {{formState === "error" && (<div className={`w-element`}>{"Sorry, something went wrong."}</div>)}- </Form>+ </WebhookForm></Box>);};export default {- title: "Components/Form",+ title: "Components/WebhookForm",};const Story = {@@ -102,4 +102,4 @@ const Story = {},};-export { Story as Form };+export { Story as WebhookForm };diff --git a/packages/sdk-components-react/src/components.ts b/packages/sdk-components-react/src/components.tsindex ebbb2cdfb9..1d1cfb07bd 100644--- a/packages/sdk-components-react/src/components.ts+++ b/packages/sdk-components-react/src/components.ts@@ -17,10 +17,10 @@ export { Superscript } from "./superscript";export { Subscript } from "./subscript";export { Button } from "./button";export { Input } from "./input";-export { Form } from "./resource-form";-/** @deprecated Legacy Webhook Form is supported through the next release. Use Form for new forms. */+export { ResourceForm } from "./resource-form";+/** @deprecated Webhook Form is supported through the next release. Use ResourceForm for new forms. */export { WebhookForm } from "./webhook-form";-/** @deprecated Use Form for managed submissions or an Element with tag form for native forms. */+/** @deprecated Use ResourceForm for managed submissions or an Element with tag form for native forms. */export { Form as RemixForm } from "./form";export { Image } from "./image";export { Blockquote } from "./blockquote";diff --git a/packages/sdk-components-react/src/form-submission.browser.test.ts b/packages/sdk-components-react/src/form-submission.browser.test.tsindex 11395bf8e1..11c9440a29 100644--- a/packages/sdk-components-react/src/form-submission.browser.test.ts+++ b/packages/sdk-components-react/src/form-submission.browser.test.ts@@ -47,7 +47,7 @@ test("generates one fresh bot field for each managed submission", () => {expect(getManagedFormValues(second)).toEqual({ name: "Visitor" });});-test("rejects a broken matchMedia browser like the legacy Webhook Form", () => {+test("rejects a broken matchMedia browser like the deprecated Webhook Form", () => {vi.stubGlobal("matchMedia", () => ({ matches: false }));const formData = submit();expect(formData.getAll(formBotFieldName)).toEqual(["jsdom"]);diff --git a/packages/sdk-components-react/src/metas.ts b/packages/sdk-components-react/src/metas.tsindex 2d54ba4314..6d4576f1ea 100644--- a/packages/sdk-components-react/src/metas.ts+++ b/packages/sdk-components-react/src/metas.ts@@ -17,7 +17,8 @@ export { meta as Superscript } from "./superscript.ws";export { meta as Subscript } from "./subscript.ws";export { meta as Button } from "./button.ws";export { meta as Input } from "./input.ws";-export { meta as Form } from "./resource-form.ws";+export { meta as ResourceForm } from "./resource-form.ws";+/** @deprecated Use ResourceForm for new forms. */export { meta as WebhookForm } from "./webhook-form.ws";export { meta as RemixForm } from "./form.ws";export { meta as Image } from "./image.ws";diff --git a/packages/sdk-components-react/src/resource-form-http.test.tsx b/packages/sdk-components-react/src/resource-form-http.test.tsxindex c7c63afa91..3aed30163c 100644--- a/packages/sdk-components-react/src/resource-form-http.test.tsx+++ b/packages/sdk-components-react/src/resource-form-http.test.tsx@@ -14,12 +14,12 @@ test("a router-free Form submits to a real JSON endpoint", async () => {contents: `import { createElement } from "react";import { createRoot } from "react-dom/client";- import { Form } from "./resource-form";+ import { ResourceForm } from "./resource-form";window.formStates = [];window.formResults = [];createRoot(document.getElementById("root")).render(- createElement(Form, {+ createElement(ResourceForm, {"data-ws-managed-form-id": "form-one",action: [{ dataSourceId: "destination" }],onStateChange: (state) => window.formStates.push(state),diff --git a/packages/sdk-components-react/src/resource-form.browser.test.tsx b/packages/sdk-components-react/src/resource-form.browser.test.tsxindex 70b749ab69..cf045693b1 100644--- a/packages/sdk-components-react/src/resource-form.browser.test.tsx+++ b/packages/sdk-components-react/src/resource-form.browser.test.tsx@@ -3,7 +3,7 @@ import { StrictMode, useState } from "react";import { createRoot } from "react-dom/client";import { act } from "react-dom/test-utils";import { expect, test, vi } from "vitest";-import { Form } from "./resource-form";+import { ResourceForm } from "./resource-form";import {managedFormRequestParamName,managedFormIdFieldName,@@ -28,14 +28,14 @@ test("a StrictMode Form submits after the effect cleanup probe", async () => {await act(async () => {root.render(<StrictMode>- <Form+ <ResourceFormaction={[{ dataSourceId: "resource-one" }]}onManagedSubmit={onManagedSubmit}onResultChange={onResultChange}><input name="email" defaultValue="[email protected]" /><button type="submit">Send</button>- </Form>+ </ResourceForm></StrictMode>);});@@ -58,7 +58,7 @@ test("a StrictMode Form aborts an active request on real unmount", async () => {await act(async () => {root.render(<StrictMode>- <Form+ <ResourceFormaction={[{ dataSourceId: "resource-one" }]}onManagedSubmit={(_values, requestSignal) => {signal = requestSignal;@@ -66,7 +66,7 @@ test("a StrictMode Form aborts an active request on real unmount", async () => {}}><button type="submit">Send</button>- </Form>+ </ResourceForm></StrictMode>);});@@ -81,10 +81,10 @@ test("a StrictMode Form aborts an active request on real unmount", async () => {test("an unconfigured Form blocks native navigation", async () => {const html = renderToStaticMarkup(- <Form method="get">+ <ResourceForm method="get"><input name="email" type="email" required /><button type="submit">Send</button>- </Form>+ </ResourceForm>);const iframe = document.createElement("iframe");document.body.append(iframe);@@ -120,7 +120,7 @@ test("empty Resource list uses query navigation instead of Resource submission",try {await act(async () => {root.render(- <Form+ <ResourceFormaction={[]}onQueryNavigate={onQueryNavigate}onResultChange={onResultChange}@@ -129,7 +129,7 @@ test("empty Resource list uses query navigation instead of Resource submission",<input name="tag" defaultValue="wood" /><input name="tag" defaultValue="blue" /><button type="submit">Send</button>- </Form>+ </ResourceForm>);});expect(container.querySelector("form")?.getAttribute("action")).toBe(@@ -157,9 +157,9 @@ test("malformed submission settings do not fall back to native delivery", asynctry {await act(async () => {root.render(- <Form action={{ destinations: "invalid" }}>+ <ResourceForm action={{ destinations: "invalid" }}><button type="submit">Send</button>- </Form>+ </ResourceForm>);});expect(container.querySelector('[role="alert"]')).toBeNull();@@ -179,7 +179,7 @@ test("a throwing submit callback cannot trigger native delivery", async () => {try {await act(async () => {root.render(- <Form+ <ResourceFormaction={[{ dataSourceId: "resource-one" }]}onSubmit={() => {throw new Error("Submit callback failed");@@ -193,7 +193,7 @@ test("a throwing submit callback cannot trigger native delivery", async () => {>Send</button>- </Form>+ </ResourceForm>);});const form = container.querySelector("form");@@ -224,12 +224,12 @@ test("legacy native-mode settings do not activate saved Resource actions", asynctry {await act(async () => {root.render(- <Form+ <ResourceFormaction={{ mode: "native", destinations: ["legacy-resource"] }}onManagedSubmit={onManagedSubmit}><button type="submit">Send</button>- </Form>+ </ResourceForm>);});expect(container.querySelector('[role="alert"]')).toBeNull();@@ -244,10 +244,10 @@ test("legacy native-mode settings do not activate saved Resource actions", asynctest("a Resource Form cannot natively submit without hydration", async () => {const html = renderToStaticMarkup(- <Form method="post" action={[{ dataSourceId: "resource" }]}>+ <ResourceForm method="post" action={[{ dataSourceId: "resource" }]}><input name="email" defaultValue="[email protected]" /><button type="submit">Send</button>- </Form>+ </ResourceForm>);const iframe = document.createElement("iframe");document.body.append(iframe);@@ -267,13 +267,13 @@ test("a Resource Form cannot natively submit without hydration", async () => {test("managed mode blocks submitter overrides before hydration", async () => {const html = renderToStaticMarkup(<>- <Form+ <ResourceFormid="managed-form"action="/__must_not_navigate__/form"method="post"><input name="email" defaultValue="[email protected]" />- </Form>+ </ResourceForm><buttontype="submit"form="managed-form"@@ -309,13 +309,13 @@ test("a hydrated Form handles submit buttons associated by form id", async () =>await act(async () => {root.render(<>- <Form+ <ResourceFormid="managed-form"action={[{ dataSourceId: "resource-one" }]}onManagedSubmit={onManagedSubmit}><input name="email" defaultValue="[email protected]" />- </Form>+ </ResourceForm><button type="submit" form="managed-form">Send</button>@@ -343,13 +343,13 @@ test("Form passes one structured submission to its dispatcher", async () => {try {await act(async () => {root.render(- <Form+ <ResourceFormaction={[{ dataSourceId: "resource-one" }]}onManagedSubmit={onManagedSubmit}><input name="name" defaultValue="Ada" /><button type="submit">Send</button>- </Form>+ </ResourceForm>);});await act(async () => {@@ -373,7 +373,7 @@ test("Form resolves Preview success redirects against the Preview page", async (try {await act(async () => {root.render(- <Form+ <ResourceFormaction={[{ dataSourceId: "resource-one" }]}successRedirect="thanks"getRedirectBaseUrl={() => "https://webstudio.local/contact"}@@ -393,7 +393,7 @@ test("Form resolves Preview success redirects against the Preview page", async (onSuccessRedirect={onSuccessRedirect}><button type="submit">Send</button>- </Form>+ </ResourceForm>);});await act(async () => container.querySelector("button")?.click());@@ -416,7 +416,7 @@ test("unmatched Preview redirect keeps successful Form feedback on the current ptry {await act(async () => {root.render(- <Form+ <ResourceFormaction={[{ dataSourceId: "resource-one" }]}successRedirect="/missing"getRedirectBaseUrl={() => "https://webstudio.local/contact"}@@ -432,7 +432,7 @@ test("unmatched Preview redirect keeps successful Form feedback on the current p><div>Submitted</div><button type="submit">Send</button>- </Form>+ </ResourceForm>);});await act(async () => container.querySelector("button")?.click());@@ -460,7 +460,7 @@ test("file-input settings enforce required uploads and keep optional or multipleconst render = async (required: boolean) =>act(async () =>root.render(- <Form+ <ResourceFormaction={[{ dataSourceId: "resource-one" }]}onManagedSubmit={onManagedSubmit}>@@ -472,7 +472,7 @@ test("file-input settings enforce required uploads and keep optional or multiplerequired={required}/><button type="submit">Send</button>- </Form>+ </ResourceForm>));try {@@ -524,7 +524,7 @@ test("managed Form submits by HTTP outside a router provider and reports pendingtry {await act(async () =>root.render(- <Form+ <ResourceFormdata-ws-managed-form-id="form-one"action={[{ dataSourceId: "destination" }]}onStateChange={(state) => states.push(state)}@@ -534,7 +534,7 @@ test("managed Form submits by HTTP outside a router provider and reports pending<input name="tag" defaultValue="b" /><input name="upload" type="file" /><button type="submit">Send</button>- </Form>+ </ResourceForm>));const files = new DataTransfer();@@ -632,14 +632,14 @@ test("Preview runs the supplied submission and reports its result without the putry {await act(async () =>root.render(- <Form+ <ResourceFormaction={[{ dataSourceId: "email" }]}onManagedSubmit={onManagedSubmit}onResultChange={onResultChange}><input name="email" defaultValue="[email protected]" /><button type="submit">Send</button>- </Form>+ </ResourceForm>));await act(async () => container.querySelector("button")?.click());@@ -679,14 +679,14 @@ test("Preview reports rejected submissions as failures and clears pending state"try {await act(async () =>root.render(- <Form+ <ResourceFormaction={[{ dataSourceId: "email" }]}onManagedSubmit={onManagedSubmit}onResultChange={onResultChange}onStateChange={(state) => states.push(state)}><button type="submit">Send</button>- </Form>+ </ResourceForm>));@@ -771,13 +771,13 @@ test("managed Form reports HTTP and network failures without native navigation",try {await act(async () =>root.render(- <Form+ <ResourceFormdata-ws-managed-form-id="form-one"action={[{ dataSourceId: "destination" }]}onResultChange={(result) => results.push(result)}><button type="submit">Send</button>- </Form>+ </ResourceForm>));await act(async () => container.querySelector("button")?.click());@@ -861,7 +861,7 @@ test.each([const [state, setState] = useState("initial");const [errors, setErrors] = useState<Array<{ message: string }>>([]);return (- <Form+ <ResourceFormaction={[{ dataSourceId: "request" }]}onManagedSubmit={async () => ({success: false,@@ -890,7 +890,7 @@ test.each([))}</div>)}- </Form>+ </ResourceForm>);};try {diff --git a/packages/sdk-components-react/src/resource-form.test.tsx b/packages/sdk-components-react/src/resource-form.test.tsxindex 7315f3a41f..afe7361349 100644--- a/packages/sdk-components-react/src/resource-form.test.tsx+++ b/packages/sdk-components-react/src/resource-form.test.tsx@@ -1,17 +1,17 @@import { renderToStaticMarkup } from "react-dom/server";import { expect, test } from "vitest";-import { Form } from "./resource-form";+import { ResourceForm } from "./resource-form";test("Form exposes a valid action URL that identifies its mode", () => {const html = renderToStaticMarkup(- <Form+ <ResourceFormaction={[{ dataSourceId: "request" }]}method="post"encType="multipart/form-data"><input name="message" /><button type="submit">Send</button>- </Form>+ </ResourceForm>);expect(html).toContain(@@ -24,9 +24,9 @@ test("Form exposes a valid action URL that identifies its mode", () => {test("Form action URL identifies Navigation mode when no Resources are connected", () => {const html = renderToStaticMarkup(- <Form action={[]}>+ <ResourceForm action={[]}><input name="query" />- </Form>+ </ResourceForm>);expect(html).toContain('<form action="?__webstudio__=navigate" method="get">'@@ -35,7 +35,7 @@ test("Form action URL identifies Navigation mode when no Resources are connectedtest("server rendering blocks an over-limit managed Form", () => {const html = renderToStaticMarkup(- <Form+ <ResourceFormaction={[{ dataSourceId: "one" },{ dataSourceId: "two" },@@ -46,7 +46,7 @@ test("server rendering blocks an over-limit managed Form", () => {]}><button type="submit">Send</button>- </Form>+ </ResourceForm>);expect(html).toContain('action="?__webstudio__=resources"');expect(html).toContain('method="dialog"');diff --git a/packages/sdk-components-react/src/resource-form.tsx b/packages/sdk-components-react/src/resource-form.tsxindex 604a9d3297..fb7e39f094 100644--- a/packages/sdk-components-react/src/resource-form.tsx+++ b/packages/sdk-components-react/src/resource-form.tsx@@ -25,7 +25,7 @@ import { useFormFeedbackScroll } from "./form-feedback-scroll";export const defaultTag = "form";-export const Form = forwardRef<+export const ResourceForm = forwardRef<ElementRef<typeof defaultTag>,Omit<ComponentProps<typeof defaultTag>, "action"> & {action?: unknown;@@ -266,4 +266,4 @@ export const Form = forwardRef<});-Form.displayName = "Form";+ResourceForm.displayName = "ResourceForm";diff --git a/packages/sdk-components-react/src/story-templates.ts b/packages/sdk-components-react/src/story-templates.tsindex 61c9154c93..54adafc623 100644--- a/packages/sdk-components-react/src/story-templates.ts+++ b/packages/sdk-components-react/src/story-templates.ts@@ -5,6 +5,7 @@import { templates as basicTemplates } from "./basic.template";import { meta as contentEmbed } from "./content-embed.template";import { meta as markdownEmbed } from "./markdown-embed.template";+// Retain stories for the deprecated Webhook Form template.import { meta as form } from "./webhook-form.template";import { meta as vimeo } from "./vimeo.template";import { meta as youtube } from "./youtube.template";diff --git a/packages/sdk-components-react/src/templates.ts b/packages/sdk-components-react/src/templates.tsindex f66b690831..f01823cf90 100644--- a/packages/sdk-components-react/src/templates.ts+++ b/packages/sdk-components-react/src/templates.ts@@ -1,5 +1,6 @@export { meta as ContentEmbed } from "./content-embed.template";export { meta as MarkdownEmbed } from "./markdown-embed.template";+/** @deprecated Use Form for new forms. */export { meta as WebhookForm } from "./webhook-form.template";export { meta as Vimeo } from "./vimeo.template";export { meta as YouTube } from "./youtube.template";diff --git a/packages/sdk-components-react/src/webhook-form.template.tsx b/packages/sdk-components-react/src/webhook-form.template.tsxindex fa1e6d7ea3..2681530b0b 100644--- a/packages/sdk-components-react/src/webhook-form.template.tsx+++ b/packages/sdk-components-react/src/webhook-form.template.tsx@@ -13,6 +13,7 @@ import { WebhookForm } from "./components";const formState = new Variable("formState", "initial");+/** @deprecated Use the Form component for new forms. */export const meta: TemplateMeta = {category: "data",order: 1,diff --git a/packages/sdk-components-react/src/webhook-form.tsx b/packages/sdk-components-react/src/webhook-form.tsxindex a747c819e5..2e8fb8746c 100644--- a/packages/sdk-components-react/src/webhook-form.tsx+++ b/packages/sdk-components-react/src/webhook-form.tsx@@ -1,5 +1,6 @@import { forwardRef, type ElementRef, type ComponentProps } from "react";+// This module serves only the deprecated Webhook Form. Remove its private Props with it.type Props = ComponentProps<"form"> & {encType?:| "application/x-www-form-urlencoded"@@ -10,7 +11,7 @@ type Props = ComponentProps<"form"> & {onStateChange: (state: "initial" | "success" | "error") => void;};-/** @deprecated Legacy Webhook Form is supported through the next release. Use Form for new forms. */+/** @deprecated Webhook Form is supported through the next release. Use Form for new forms. */export const WebhookForm = forwardRef<ElementRef<"form">, Props>(({ children, state = "initial", ...props }, ref) => (<form {...props} ref={ref}>diff --git a/packages/sdk-components-react/src/webhook-form.ws.ts b/packages/sdk-components-react/src/webhook-form.ws.tsindex 01412c8777..1ea3a52c24 100644--- a/packages/sdk-components-react/src/webhook-form.ws.ts+++ b/packages/sdk-components-react/src/webhook-form.ws.ts@@ -3,8 +3,12 @@ import type { WsComponentMeta } from "@webstudio-is/sdk";import { form } from "@webstudio-is/sdk/normalize.css";import { props } from "./__generated__/webhook-form.props";+/** @deprecated Existing Webhook Forms remain supported through the next release. Use Form for new forms. */export const meta: WsComponentMeta = {label: "Webhook Form",+ description:+ "Deprecated. Existing Webhook Forms remain supported through the next release. Use Form for new forms.",+ deprecated: true,icon: WebhookFormIcon,presetStyle: {form,diff --git a/packages/sdk-components-registry/src/core-templates.test.tsx b/packages/sdk-components-registry/src/core-templates.test.tsxindex 5eb9861f44..136ee58c8b 100644--- a/packages/sdk-components-registry/src/core-templates.test.tsx+++ b/packages/sdk-components-registry/src/core-templates.test.tsx@@ -243,7 +243,7 @@ test("Form success and error feedback render without DOM markers", () => {test("Form state stays internal while feedback uses the formState variable", () => {const fragment = renderCoreTemplate(coreTemplates.form);const form = fragment.instances.find(- ({ component }) => component === "Form"+ ({ component }) => component === "ResourceForm")!;const formProps = fragment.props.filter(({ instanceId }) => instanceId === form.id@@ -258,7 +258,9 @@ test("Form state stays internal while feedback uses the formState variable", ()test("default Form leaves layout to its Form content", () => {const fragment = renderCoreTemplate(coreTemplates.form);- const form = fragment.instances.find(({ component }) => component === "Form");+ const form = fragment.instances.find(+ ({ component }) => component === "ResourceForm"+ );const content = fragment.instances.find(({ label }) => label === "Form content");@@ -292,7 +294,7 @@ test("new Form templates select project and visitor Email Resources", () => {const fragment = renderCoreTemplate(coreTemplates.form);const renderedTemplate = JSON.stringify(fragment);const form = fragment.instances.find(- ({ component }) => component === "Form"+ ({ component }) => component === "ResourceForm")!;const action = fragment.props.find(({ instanceId, name }) => instanceId === form.id && name === "action"diff --git a/packages/sdk-components-registry/src/core-templates.tsx b/packages/sdk-components-registry/src/core-templates.tsxindex 8cfbb1efca..e982980d35 100644--- a/packages/sdk-components-registry/src/core-templates.tsx+++ b/packages/sdk-components-registry/src/core-templates.tsx@@ -36,7 +36,7 @@ import {HtmlEmbed,Input,Label,- Form,+ ResourceForm,Paragraph,Textarea,} from "@webstudio-is/sdk-components-react/components";@@ -254,7 +254,7 @@ export const coreTemplates = {label: "Form (Beta)",description: "Collect information and submit it to Resource actions.",template: (- <Form+ <ResourceFormaction={new FormActionsValue([ownerEmail, visitorEmail])}formData={formData}browserInfo={browserInfo}@@ -365,7 +365,7 @@ export const coreTemplates = {</ul></div>)}- </Form>+ </ResourceForm>),},[blockComponent]: blockMeta,diff --git a/packages/sdk/src/form/browser-submission.test.ts b/packages/sdk/src/form/browser-submission.test.tsnew file mode 100644index 0000000000..9c5f937122--- /dev/null+++ b/packages/sdk/src/form/browser-submission.test.ts@@ -0,0 +1,60 @@+import { afterEach, expect, test, vi } from "vitest";+import {+ createFormBotValue,+ createManagedSubmissionFormData,+} from "./browser-submission";+import { formBotFieldName } from "./fields";++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++test("generates a fresh timestamp and exactly one bot field per managed submission", () => {+ vi.stubGlobal("navigator", {});+ vi.stubGlobal("screen", { width: 1920, height: 1080 });+ vi.stubGlobal(+ "matchMedia",+ vi.fn((query: string) => ({+ matches:+ query.includes("device-aspect-ratio: 16/9") ||+ query.includes("device-width: 1920px") ||+ query === "(prefers-color-scheme: light)",+ }))+ );+ const now = Date.now();+ const clock = vi.spyOn(Date, "now").mockReturnValue(now);+ const first = createManagedSubmissionFormData({+ values: {},+ managedFormId: "form-id",+ });+ clock.mockReturnValue(now + 5 * 60 * 1000 + 1);+ const second = createManagedSubmissionFormData({+ values: {},+ managedFormId: "form-id",+ });+ expect(first.getAll(formBotFieldName)).toEqual([now.toString(16)]);+ expect(second.getAll(formBotFieldName)).toEqual([+ (now + 5 * 60 * 1000 + 1).toString(16),+ ]);+});++test("Brave bypasses media queries", () => {+ vi.stubGlobal("navigator", { brave: {} });+ const matchMedia = vi.fn();+ vi.stubGlobal("matchMedia", matchMedia);+ expect(createFormBotValue()).toBe("brave");+ expect(matchMedia).not.toHaveBeenCalled();+});++test("missing or nonworking media queries produce the jsdom value", () => {+ vi.stubGlobal("navigator", {});+ vi.stubGlobal("screen", { width: 1920, height: 1080 });+ vi.stubGlobal("matchMedia", undefined);+ expect(createFormBotValue()).toBe("jsdom");+ vi.stubGlobal(+ "matchMedia",+ vi.fn(() => ({ matches: false }))+ );+ expect(createFormBotValue()).toBe("jsdom");+});diff --git a/packages/sdk/src/form/browser-submission.ts b/packages/sdk/src/form/browser-submission.tsindex 8c3dfb85d4..d117d831af 100644--- a/packages/sdk/src/form/browser-submission.ts+++ b/packages/sdk/src/form/browser-submission.ts@@ -6,8 +6,6 @@ import {} from "./fields";import { internalFormFieldNames } from "./shared";-// The legacy Webhook Form rejects simple headless environments whose-// matchMedia implementation reports inconsistent device and color settings.const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));const hasWorkingBrowserMediaQueries = () => {@@ -30,6 +28,15 @@ const hasWorkingBrowserMediaQueries = () => {);};+/** Generate a fresh bot value for each form submission. */+export const createFormBotValue = () =>+ // Brave Shields blocks the media-query fingerprinting check.+ isBraveBrowser()+ ? "brave"+ : hasWorkingBrowserMediaQueries()+ ? Date.now().toString(16)+ : "jsdom";+/** Match native FormData order while retaining repeated names and File values. */export const getFormDataValue = (form: HTMLFormElement,@@ -124,13 +131,6 @@ export const createManagedSubmissionFormData = ({}formData.set(managedFormArrayNamesFieldName, JSON.stringify(arrayNames));formData.set(managedFormIdFieldName, managedFormId);- formData.set(- formBotFieldName,- isBraveBrowser()- ? "brave"- : hasWorkingBrowserMediaQueries()- ? Date.now().toString(16)- : "jsdom"- );+ formData.set(formBotFieldName, createFormBotValue());return formData;};diff --git a/packages/sdk/src/form/deprecated-webhook-form-actions.ts b/packages/sdk/src/form/deprecated-webhook-form-actions.tsnew file mode 100644index 0000000000..6d2549f8ce--- /dev/null+++ b/packages/sdk/src/form/deprecated-webhook-form-actions.ts@@ -0,0 +1,81 @@+import type { Instance, Instances } from "../schema/instances";+import type { Props } from "../schema/props";+import type { Resources } from "../schema/resources";++/** @deprecated Used only when migrating saved Webhook Form methods. */+const getMethod = (value: string | undefined) => {+ switch (value?.toLowerCase()) {+ case "get":+ return "get";+ case "delete":+ return "delete";+ case "put":+ return "put";+ default:+ return "post";+ }+};++/** @deprecated Convert saved Webhook Form action props to Resource actions. */+export const migrateDeprecatedWebhookFormActions = ({+ props,+ instances,+ resources,+}: {+ props: Props;+ instances: Instances;+ resources: Resources;+}) => {+ const formProps = new Map<+ Instance["id"],+ { method?: string; action?: string }+ >();+ for (const prop of props.values()) {+ if (+ prop.name === "method" &&+ prop.type === "string" &&+ instances.get(prop.instanceId)?.component === "WebhookForm"+ ) {+ let data = formProps.get(prop.instanceId);+ if (data === undefined) {+ data = {};+ formProps.set(prop.instanceId, data);+ }+ data.method = prop.value;+ props.delete(prop.id);+ }+ if (+ prop.name === "action" &&+ prop.type === "string" &&+ prop.value &&+ instances.get(prop.instanceId)?.component === "WebhookForm"+ ) {+ let data = formProps.get(prop.instanceId);+ if (data === undefined) {+ data = {};+ formProps.set(prop.instanceId, data);+ }+ data.action = prop.value;+ props.set(prop.id, {+ id: prop.id,+ instanceId: prop.instanceId,+ name: prop.name,+ type: "resource",+ value: prop.instanceId,+ });+ }+ }+ for (const [instanceId, { action, method }] of formProps) {+ if (action) {+ resources.set(instanceId, {+ id: instanceId,+ name: "action",+ method: getMethod(method),+ url: JSON.stringify(action),+ headers: [+ { name: "Content-Type", value: JSON.stringify("application/json") },+ ],+ });+ }+ }+};diff --git a/packages/sdk/src/form/deprecated-webhook-form.test.ts b/packages/sdk/src/form/deprecated-webhook-form.test.tsnew file mode 100644index 0000000000..05803370df--- /dev/null+++ b/packages/sdk/src/form/deprecated-webhook-form.test.ts@@ -0,0 +1,228 @@+import { expect, test, vi } from "vitest";+import type { ResourceRequestGraph } from "../resource-loader";+import type { ResourceRequest } from "../schema/resources";+import { handleDeprecatedWebhookFormSubmission } from "./deprecated-webhook-form";+import { formBotFieldName, formIdFieldName } from "./fields";++const url = new URL("https://site.example/contact");+const resourceFetch = Object.assign(+ vi.fn(async () => Response.json({ accepted: true })),+ { validateDestination: vi.fn() }+);+const submit = (+ options: Partial<+ Parameters<typeof handleDeprecatedWebhookFormSubmission>[0]+ > = {}+) => {+ const formData = new FormData();+ formData.set(formBotFieldName, "brave");+ formData.set("message", "Hello");+ return handleDeprecatedWebhookFormSubmission({+ request: new Request(url),+ formData,+ url,+ resources: { data: { rootIds: [], resources: [] }, action: new Map() },+ contactEmail: "[email protected]",+ resourceFetch,+ dependencyFetch: vi.fn(),+ createEmailSender: () => undefined,+ validateEmail: () => {},+ ...options,+ });+};++test.each(["get", "post", "put", "delete"] as const)(+ "keeps the deprecated Webhook Form %s method, request fields, and last repeated value",+ async (method) => {+ const formData = new FormData();+ formData.set(formIdFieldName, "action");+ formData.set(formBotFieldName, "brave");+ formData.append("choice", "first");+ formData.append("choice", "last");+ const data: ResourceRequestGraph = {+ rootIds: [],+ resources: [+ {+ id: "action",+ outputName: "action",+ dependencies: ["dependency"],+ createRequest: (documents) => ({+ name: "action",+ method,+ url: "https://receiver.example/",+ searchParams: [+ {+ name: "source",+ value: (documents.get("dependency") as { data: unknown }).data,+ },+ ],+ headers: [{ name: "X-Saved", value: "yes" }],+ bodyFormat: "json",+ body: "saved body",+ }),+ },+ {+ id: "dependency",+ outputName: "dependency",+ dependencies: [],+ createRequest: () => ({+ name: "dependency",+ method: "post",+ body: { lookup: "saved" },+ url: "/$resources/assets",+ searchParams: [],+ headers: [],+ }),+ },+ {+ id: "unrelated",+ outputName: "unrelated",+ dependencies: [],+ createRequest: () => {+ throw new Error("Unrelated Resource must not run");+ },+ },+ {+ id: "unrelated-email",+ outputName: "unrelated-email",+ control: "email",+ dependencies: [],+ createRequest: () => {+ throw new Error("Unrelated Email Resource must not run");+ },+ },+ ],+ };+ const rootFetch = Object.assign(+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const request = new Request(input, init);+ expect(request.method).toBe(method.toUpperCase());+ expect(request.headers.get("X-Saved")).toBe("yes");+ expect(new URL(request.url).searchParams.get("source")).toBe("saved");+ if (method !== "get") {+ expect(await request.json()).toEqual({ choice: "last" });+ }+ return Response.json({ accepted: true });+ }),+ { validateDestination: vi.fn() }+ );+ const dependencyFetch = vi.fn(+ async (_input: RequestInfo | URL, init?: RequestInit) => {+ expect(await new Response(init?.body).json()).toEqual({+ lookup: "saved",+ });+ return Response.json("saved");+ }+ );+ expect(+ await submit({+ formData,+ resources: {+ data,+ action: new Map([["action", { id: "action", outputName: "action" }]]),+ },+ resourceFetch: rootFetch,+ dependencyFetch,+ })+ ).toEqual({ success: true });+ expect(rootFetch).toHaveBeenCalledOnce();+ expect(dependencyFetch).toHaveBeenCalledOnce();+ }+);++test("sends the default owner notification with fields and uploaded files", async () => {+ const formData = new FormData();+ formData.set(formBotFieldName, "brave");+ formData.set("message", "Hello");+ formData.set("attachment", new File(["file bytes"], "hello.txt"));+ const sendEmail = vi.fn(async (_request: ResourceRequest) => ({+ ok: true,+ status: 200,+ statusText: "OK",+ data: { id: "sent" },+ }));+ const createEmailSender = vi.fn((submitted: FormData) => {+ expect(submitted.has(formBotFieldName)).toBe(false);+ expect(submitted.get("attachment")).toBeInstanceOf(File);+ return sendEmail;+ });+ expect(await submit({ formData, createEmailSender })).toEqual({+ success: true,+ });+ expect(sendEmail).toHaveBeenCalledOnce();+ expect(sendEmail.mock.calls[0]?.[0]).toMatchObject({+ control: "email",+ email: {+ recipients: [{ address: "[email protected]" }],+ subject: "New form submission from site.example",+ body: "There has been a new submission of your form at https://site.example/contact:\n\nmessage: Hello\n",+ includeAttachments: true,+ },+ });+});++test("reports a failed Email action and does not retry it", async () => {+ const sendEmail = vi.fn(async (_request: ResourceRequest) => ({+ ok: false,+ status: 503,+ statusText: "Email unavailable",+ data: {},+ }));+ expect(await submit({ createEmailSender: () => sendEmail })).toEqual({+ success: false,+ errors: ["Email unavailable"],+ });+ expect(sendEmail).toHaveBeenCalledOnce();+});++test("rejects missing bot protection before constructing an email sender", async () => {+ const createEmailSender = vi.fn();+ await expect(+ submit({ formData: new FormData(), createEmailSender })+ ).rejects.toThrow();+ expect(createEmailSender).not.toHaveBeenCalled();+});++test.each(["missing", "cycle"] as const)(+ "rejects a %s dependency before dispatch",+ async (kind) => {+ const formData = new FormData();+ formData.set(formBotFieldName, "brave");+ formData.set(formIdFieldName, "action");+ const createRequest = vi.fn(() => ({+ name: "Resource",+ method: "post" as const,+ url: "https://receiver.example/",+ searchParams: [],+ headers: [],+ }));+ await expect(+ submit({+ formData,+ resources: {+ action: new Map([["action", { id: "action", outputName: "action" }]]),+ data: {+ rootIds: [],+ resources: [+ {+ id: "action",+ outputName: "action",+ dependencies: ["dependency"],+ createRequest,+ },+ {+ id: "dependency",+ outputName: "dependency",+ dependencies: [kind === "missing" ? "absent" : "dependency"],+ createRequest,+ },+ ],+ },+ },+ })+ ).rejects.toThrow(+ kind === "missing" ? "Form Resource absent not found" : "cycle"+ );+ expect(createRequest).not.toHaveBeenCalled();+ }+);diff --git a/packages/sdk/src/form/deprecated-webhook-form.ts b/packages/sdk/src/form/deprecated-webhook-form.tsnew file mode 100644index 0000000000..731f051786--- /dev/null+++ b/packages/sdk/src/form/deprecated-webhook-form.ts@@ -0,0 +1,137 @@+import { getReachableResources } from "./resource-graph";+import {+ defaultEmailSubject,+ resolveEmailRecipientsExpression,+} from "../email-resource";+import type { EmailResourceLoadOptions } from "../email-resource-delivery";+import type { ResourceRequestGraph } from "../resource-loader";+import type { ResourceRequest } from "../schema/resources";+import {+ getManagedFormResponse,+ loadManagedFormResources,+ validateManagedFormBot,+ validateManagedFormRecipientLimit,+ shouldRetryManagedFormDestination,+ type ManagedFormResourceGraph,+} from "./server-submission";+import { prepareVisitorEmailRequest } from "./server-email";+import { formBotFieldName, formIdFieldName } from "./fields";++/** @deprecated Compatibility adapter for saved Webhook Forms. Use managed Form submissions for new forms. */+export const handleDeprecatedWebhookFormSubmission = async ({+ request,+ formData,+ url,+ resources,+ contactEmail,+ resourceFetch,+ dependencyFetch,+ createEmailSender,+ validateEmail,+}: {+ request: Request;+ formData: FormData;+ url: URL;+ resources: {+ data: ResourceRequestGraph;+ action: ReadonlyMap<string, { id: string; outputName: string }>;+ };+ contactEmail?: string;+ resourceFetch: typeof fetch & { validateDestination: (url: URL) => void };+ dependencyFetch: typeof fetch;+ createEmailSender: (+ formData: FormData+ ) => EmailResourceLoadOptions["sendEmail"];+ validateEmail: (request: ResourceRequest, formData: FormData) => void;+}) => {+ validateManagedFormBot(formData);+ const name = formData.get(formIdFieldName);+ const action =+ typeof name === "string" ? resources.action.get(name) : undefined;+ formData.delete(formIdFieldName);+ formData.delete(formBotFieldName);+ const body = Object.fromEntries(formData);+ let graph: ManagedFormResourceGraph;+ if (action === undefined) {+ if (contactEmail === undefined) {+ throw new Error("Contact email not found");+ }+ const recipients = resolveEmailRecipientsExpression(contactEmail);+ const lines = Array.from(formData).flatMap(([name, value]) =>+ typeof value === "string" ? [`${name}: ${value}`] : []+ );+ graph = {+ rootIds: ["email"],+ resources: [+ {+ id: "email",+ outputName: "email",+ dependencies: [],+ control: "email",+ createRequest: () => ({+ name: "Email",+ control: "email",+ method: "post",+ url: "",+ searchParams: [],+ headers: [],+ email: {+ recipientMode: "project",+ recipients,+ subject: `${defaultEmailSubject} from ${url.hostname}`,+ body: `There has been a new submission of your form at ${url}:\n\n${lines.join("\n")}${lines.length > 0 ? "\n" : ""}`,+ includeAttachments: true,+ },+ }),+ },+ ],+ };+ } else {+ graph = {+ rootIds: [action.id],+ resources: getReachableResources({+ ...resources.data,+ rootIds: [action.id],+ }).map((resource) => ({+ ...resource,+ createRequest: (documents) => {+ const request = resource.createRequest(documents);+ return resource.id === action.id ? { ...request, body } : request;+ },+ })),+ };+ }+ const emailRequests = new Map<string, ResourceRequest>();+ graph = {+ ...graph,+ resources: graph.resources.map((resource) => {+ if (resource.control !== "email" || resource.dependencies.length > 0) {+ return resource;+ }+ const emailRequest = prepareVisitorEmailRequest(+ resource.createRequest(new Map()),+ formData+ );+ emailRequests.set(resource.id, emailRequest);+ return { ...resource, createRequest: () => emailRequest };+ }),+ };+ validateManagedFormRecipientLimit(graph, emailRequests);+ const sendEmail = createEmailSender(formData);+ const results = await loadManagedFormResources(dependencyFetch, graph, url, {+ signal: request.signal,+ timeoutMs: 10_000,+ shouldRetryFailedRoot: shouldRetryManagedFormDestination,+ requestOverrides: new Map([[graph.rootIds[0], { fetch: resourceFetch }]]),+ sendEmail,+ validateEmail: (request) => validateEmail(request, formData),+ validateDestination: resourceFetch.validateDestination,+ });+ const response = getManagedFormResponse(graph, results);+ return response.success+ ? { success: true as const }+ : {+ success: false as const,+ errors: response.errors.map(({ message }) => message),+ };+};diff --git a/packages/sdk/src/form/fields.ts b/packages/sdk/src/form/fields.tsindex ebe5bcecfa..dea03946c8 100644--- a/packages/sdk/src/form/fields.ts+++ b/packages/sdk/src/form/fields.ts@@ -1,7 +1,3 @@-/**- * Used to identify form inside server handler- */-export const formIdFieldName = `ws--form-id`;/** Identifies a managed ResourceForm without accepting destinations from the visitor. */export const managedFormIdFieldName = `ws--managed-form-id`;/** Query marker lets the server apply managed-only parsing limits before parsing. */@@ -10,13 +6,11 @@ export const managedFormRequestParamName = `ws--managed-form-request`;export const managedFormEndpointPrefix = "/__ws-form";/** Names whose submitted values are lists, including empty checkbox groups. */export const managedFormArrayNamesFieldName = `ws--managed-form-array-names`;-/**- * Used for simlpe protection against non js bots- */+/** Bot field shared by deprecated Webhook Form and managed Form; keep for Form. */export const formBotFieldName = `ws--form-bot`;/**- * Detects if the browser is Brave.+ * Detects if the browser is Brave for both deprecated Webhook Form and managed Form.* Brave Shields blocks our bot protection mechanism (matchMedia fingerprinting detection),* causing form submissions to silently fail.* @see https://github.com/brave/brave-browser/issues/46541@@ -28,3 +22,6 @@ export const isBraveBrowser = (): boolean => {// @ts-expect-error - brave is a non-standard propertyreturn navigator.brave?.isBrave?.() === true || navigator.brave !== undefined;};++/** @deprecated Identifies deprecated Webhook Form submissions. Use managedFormIdFieldName for new Forms. */+export const formIdFieldName = `ws--form-id`;diff --git a/packages/sdk/src/form/resource-graph.ts b/packages/sdk/src/form/resource-graph.tsnew file mode 100644index 0000000000..3f3b8d76b1--- /dev/null+++ b/packages/sdk/src/form/resource-graph.ts@@ -0,0 +1,33 @@+import type { ResourceRequestResource } from "../resource-loader";++/** Resource traversal shared by deprecated Webhook Form and managed Form; keep for Form. */+export const getReachableResources = <+ Resource extends ResourceRequestResource,+>(graph: {+ resources: readonly Resource[];+ rootIds: readonly string[];+}) => {+ const resourcesById = new Map(+ graph.resources.map((resource) => [resource.id, resource])+ );+ const visited = new Set<string>();+ const reachable: Resource[] = [];+ const visit = (resourceId: string) => {+ if (visited.has(resourceId)) {+ return;+ }+ visited.add(resourceId);+ const resource = resourcesById.get(resourceId);+ if (resource === undefined) {+ return;+ }+ reachable.push(resource);+ for (const dependency of resource.dependencies) {+ visit(dependency);+ }+ };+ for (const rootId of graph.rootIds) {+ visit(rootId);+ }+ return reachable;+};diff --git a/packages/sdk/src/form/server-email.ts b/packages/sdk/src/form/server-email.tsindex 142de49150..5a6656fa48 100644--- a/packages/sdk/src/form/server-email.ts+++ b/packages/sdk/src/form/server-email.ts@@ -19,6 +19,7 @@ type EmailServiceFetch = (// Bound the extra allocation caused by Base64 before the Worker validates the// complete Email payload. The Worker owns attachment policy and payload limits.const maxEncodedAttachmentBytes = 7 * 1024 * 1024;+const maxEmailAttachments = 32;const emailWorkerHost = "webstudio-email-service.wstd.workers.dev";const emailWorkerVersionHostSuffix ="-webstudio-email-service.wstd.workers.dev";@@ -93,12 +94,20 @@ export const validateCloudflareManagedFormEmail = () => {const email = request.email;if (email?.includeAttachments) {- const encodedBytes = getEmailFiles(formData).reduce(+ const files = getEmailFiles(formData);+ if (files.length > maxEmailAttachments) {+ throw new Error(+ "An email can have at most 32 attachments. Submit fewer files."+ );+ }+ const encodedBytes = files.reduce((total, file) => total + 4 * Math.ceil(file.size / 3),0);if (encodedBytes > maxEncodedAttachmentBytes) {- throw new Error("Email attachments are too large to encode");+ throw new Error(+ "Email request exceeds the 7 MiB limit. Submit smaller files."+ );}}};diff --git a/packages/sdk/src/form/server-submission.ts b/packages/sdk/src/form/server-submission.tsindex a0a2f96ffc..2e6a8fe09a 100644--- a/packages/sdk/src/form/server-submission.ts+++ b/packages/sdk/src/form/server-submission.ts@@ -1,3 +1,4 @@+import { getReachableResources } from "./resource-graph";import { formBotFieldName, managedFormArrayNamesFieldName } from "./fields";import {internalFormFieldNames,@@ -54,6 +55,12 @@ export const shouldRetryManagedFormDestination: NonNullable<> = (_resourceId, request) => request.control !== "email";const maxFormRequestBytes = 25 * 1024 * 1024;+const formRequestTooLarge = (maximumBytes: number) =>+ new Error(+ maximumBytes === maxFormRequestBytes+ ? "Form submission exceeds the 25 MiB limit. Reduce file sizes and try again."+ : "Form submission is too large"+ );export const maxFormTeamEmailDeliveries = 5;const messageIdBytes = 8;@@ -111,9 +118,26 @@ export const getManagedFormResponse = ("statusText" in outcome && typeof outcome.statusText === "string"? outcome.statusText.trim(): "";+ const emailError =+ resource?.control === "email" &&+ typeof outcome.data === "object" &&+ outcome.data !== null &&+ "error" in outcome.data &&+ typeof outcome.data.error === "object" &&+ outcome.data.error !== null+ ? outcome.data.error+ : undefined;+ const emailCode =+ emailError !== undefined &&+ "code" in emailError &&+ typeof emailError.code === "string" &&+ /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(emailError.code)+ ? emailError.code+ : undefined;errors.push({...result,message: statusText || `Resource request failed (${outcome.status})`,+ ...(emailCode === undefined ? {} : { code: emailCode }),});}}@@ -136,7 +160,7 @@ export const readFormDataWithLimit = async () => {const contentLength = Number(request.headers.get("content-length"));if (Number.isFinite(contentLength) && contentLength > maximumBytes) {- throw new Error("Form submission is too large");+ throw formRequestTooLarge(maximumBytes);}if (request.body === null) {return new FormData();@@ -153,7 +177,7 @@ export const readFormDataWithLimit = async (totalBytes += value.byteLength;if (totalBytes > maximumBytes) {await reader.cancel();- throw new Error("Form submission is too large");+ throw formRequestTooLarge(maximumBytes);}chunks.push(value);}@@ -244,32 +268,6 @@ export const getManagedFormValues = (formData: FormData) => {return values;};-const getReachableResources = (graph: ManagedFormResourceGraph) => {- const resourcesById = new Map(- graph.resources.map((resource) => [resource.id, resource])- );- const visited = new Set<string>();- const reachable: ManagedFormResource[] = [];- const visit = (resourceId: string) => {- if (visited.has(resourceId)) {- return;- }- visited.add(resourceId);- const resource = resourcesById.get(resourceId);- if (resource === undefined) {- return;- }- reachable.push(resource);- for (const dependency of resource.dependencies) {- visit(dependency);- }- };- for (const rootId of graph.rootIds) {- visit(rootId);- }- return reachable;-};-/** Validate the original selection before optional visitor roots are removed. */export const validateManagedFormDestinationDependencies = (graph: ManagedFormResourceGraphdiff --git a/packages/sdk/src/form/server.ts b/packages/sdk/src/form/server.tsindex 57538e0219..c62342f6ab 100644--- a/packages/sdk/src/form/server.ts+++ b/packages/sdk/src/form/server.ts@@ -2,3 +2,4 @@ export * from "./shared";export * from "./server-submission";export * from "./server-handler";export * from "./server-email";+export * from "./deprecated-webhook-form";diff --git a/packages/sdk/src/form/shared.ts b/packages/sdk/src/form/shared.tsindex a835de348d..a97fd5f2d0 100644--- a/packages/sdk/src/form/shared.ts+++ b/packages/sdk/src/form/shared.ts@@ -11,6 +11,7 @@ export const formDataParameterName = "formData";export const browserInfoParameterName = "browserInfo";export const internalFormFieldNames = new Set([+ // Remove this field with the deprecated Webhook Form; the remaining fields serve Form.formIdFieldName,managedFormIdFieldName,managedFormArrayNamesFieldName,@@ -31,6 +32,8 @@ export type ManagedFormError = Omit<resourceId?: string;resourceName?: string;message: string;+ /** Safe machine-readable code for a managed Email action, when available. */+ code?: string;};export type ManagedFormResponse = {diff --git a/packages/sdk/src/managed-form-draft-graph.test.ts b/packages/sdk/src/managed-form-draft-graph.test.tsindex 25eadbd6fc..182f1f9d00 100644--- a/packages/sdk/src/managed-form-draft-graph.test.ts+++ b/packages/sdk/src/managed-form-draft-graph.test.ts@@ -40,7 +40,7 @@ test("draft Form graph resolves HTTP and Email bindings like the published gener{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "password" },{ type: "id", value: "email-input" },@@ -327,7 +327,7 @@ test("draft graph leaves Resource-output-bound recipient counts unknown for pref{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -410,7 +410,10 @@ test("draft graph leaves Resource-output-bound recipient counts unknown for preftest("draft graph counts resolved formData-bound recipients instead of stale text", () => {const instances: Instances = new Map([- ["form", { type: "instance", id: "form", component: "Form", children: [] }],+ [+ "form",+ { type: "instance", id: "form", component: "ResourceForm", children: [] },+ ],]);const dataSources: DataSources = new Map([[@@ -485,7 +488,10 @@ test("draft graph counts resolved formData-bound recipients instead of stale textest("Email Sender and custom recipients bindings resolve and validate before dispatch", () => {const instances: Instances = new Map([- ["form", { type: "instance", id: "form", component: "Form", children: [] }],+ [+ "form",+ { type: "instance", id: "form", component: "ResourceForm", children: [] },+ ],]);const dataSources: DataSources = new Map([[@@ -648,7 +654,10 @@ test("draft graph keeps scoped dependencies and external Resource roots in publichildren: [{ type: "id", value: "form" }],},],- ["form", { type: "instance", id: "form", component: "Form", children: [] }],+ [+ "form",+ { type: "instance", id: "form", component: "ResourceForm", children: [] },+ ],]);const dataSources: DataSources = new Map([[@@ -799,7 +808,10 @@ test("an external Resource cannot bind formData in Builder Preview", () => {children: [{ type: "id", value: "form" }],},],- ["form", { type: "instance", id: "form", component: "Form", children: [] }],+ [+ "form",+ { type: "instance", id: "form", component: "ResourceForm", children: [] },+ ],]);const dataSources: DataSources = new Map([[diff --git a/packages/sdk/src/managed-form-draft-graph.ts b/packages/sdk/src/managed-form-draft-graph.tsindex 09ef97e829..f6249b0ce7 100644--- a/packages/sdk/src/managed-form-draft-graph.ts+++ b/packages/sdk/src/managed-form-draft-graph.ts@@ -60,7 +60,7 @@ export const createManagedFormDraftGraph = ({values: ReadonlyMap<string, unknown>) => unknown;}): ManagedFormResourceGraph => {- if (instances.get(formId)?.component !== "Form") {+ if (instances.get(formId)?.component !== "ResourceForm") {throw new Error("Form not found");}const formDataStringifyOptions = getFormEmailStringifyOptions(diff --git a/packages/sdk/src/managed-form-email.test.ts b/packages/sdk/src/managed-form-email.test.tsindex a4fb353d0f..6e2d2585b2 100644--- a/packages/sdk/src/managed-form-email.test.ts+++ b/packages/sdk/src/managed-form-email.test.ts@@ -1272,12 +1272,34 @@ test("oversize Email preflight stops both Email and HTTP destinations", async ()validateEmail: (resource) =>validateCloudflareManagedFormEmail(resource, formData),})- ).rejects.toThrow("Email attachments are too large to encode");+ ).rejects.toThrow(+ "Email request exceeds the 7 MiB limit. Submit smaller files."+ );expect(httpFetch).not.toHaveBeenCalled();expect(emailRpc).not.toHaveBeenCalled();expect(readFile).not.toHaveBeenCalled();});+test("Email preflight enforces the 32 attachment limit before encoding", () => {+ const formData = new FormData();+ for (let index = 0; index < 32; index += 1) {+ formData.append("upload", new File(["x"], `file-${index}.txt`));+ }+ expect(() =>+ validateCloudflareManagedFormEmail(request, formData)+ ).not.toThrow();+ formData.append("upload", new File(["x"], "file-32.txt"));+ expect(() => validateCloudflareManagedFormEmail(request, formData)).toThrow(+ "An email can have at most 32 attachments. Submit fewer files."+ );+ expect(() =>+ validateCloudflareManagedFormEmail(+ { ...request, email: { ...request.email!, includeAttachments: false } },+ formData+ )+ ).not.toThrow();+});+test("dependency-bound Email stops its HTTP lookup before dispatch", async () => {const formData = new FormData();const httpFetch = vi.fn(async () => Response.json({ ok: true }));diff --git a/packages/sdk/src/managed-form-error-slot.test.ts b/packages/sdk/src/managed-form-error-slot.test.tsindex 423affe534..b8e6f9722d 100644--- a/packages/sdk/src/managed-form-error-slot.test.ts+++ b/packages/sdk/src/managed-form-error-slot.test.ts@@ -21,7 +21,7 @@ const slot: Instance = {const form: Instance = {type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: slot.id }],};const instances: Instances = new Map([diff --git a/packages/sdk/src/managed-form-error-slot.ts b/packages/sdk/src/managed-form-error-slot.tsindex c82e01e320..ab7adaa43f 100644--- a/packages/sdk/src/managed-form-error-slot.ts+++ b/packages/sdk/src/managed-form-error-slot.ts@@ -34,9 +34,10 @@ export const resolveManagedFormErrorSlot = (}const component = parent.component.split(":").at(-1);if (component === "WebhookForm") {+ // Keep the deprecated Webhook Form's authored error message unchanged.return instance;}- if (component === "Form") {+ if (component === "ResourceForm") {const resultAction = [...props.values()].find((prop) =>prop.instanceId === parent.id &&diff --git a/packages/sdk/src/managed-form-graph.ts b/packages/sdk/src/managed-form-graph.tsindex 46eb0ce49d..edd566ecd6 100644--- a/packages/sdk/src/managed-form-graph.ts+++ b/packages/sdk/src/managed-form-graph.ts@@ -35,7 +35,8 @@ export const getManagedFormSubmissionResourceIds = ({source.type === "parameter" &&(source.name === formDataParameterName ||source.name === browserInfoParameterName) &&- instances.get(source.scopeInstanceId ?? "")?.component === "Form"+ instances.get(source.scopeInstanceId ?? "")?.component ===+ "ResourceForm").map(({ id }) => id));@@ -85,7 +86,7 @@ export const getManagedFormParameterBinding = ({}if (source.scopeInstanceId === formId &&- instances.get(formId)?.component === "Form" &&+ instances.get(formId)?.component === "ResourceForm" &&(source.name === formDataParameterName ||source.name === browserInfoParameterName)) {diff --git a/packages/sdk/src/managed-form-resources-generator.test.ts b/packages/sdk/src/managed-form-resources-generator.test.tsindex 624b96faa9..09015aa480 100644--- a/packages/sdk/src/managed-form-resources-generator.test.ts+++ b/packages/sdk/src/managed-form-resources-generator.test.ts@@ -94,7 +94,7 @@ test.each([{id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -173,7 +173,7 @@ test.each([SYSTEM_VARIABLE_ID, "page-system"])({id: "form",type: "instance",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -302,7 +302,7 @@ test("a Form-scoped Email Resource gets the automatic form text and a typed emai{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "password-input" }],},],@@ -395,7 +395,7 @@ test.each([{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -497,7 +497,7 @@ test("the default Form body is used unless the Email Resource overrides it", (){type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -567,7 +567,7 @@ test("counts project and custom Email recipients across a Form, including duplic{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -669,7 +669,7 @@ test("preflights bound Email recipient counts when Resources are referenced", (){type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -816,7 +816,7 @@ test("counts an Email dependency of a selected HTTP Resource", () => {{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -909,7 +909,7 @@ test("an edited default Email body formats Form values and preserves field acces{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "password-input" }],},],@@ -1018,7 +1018,7 @@ test("Visitor Email keeps its empty receipt body instead of the submitted-fields{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "email-input" }],},],@@ -1151,7 +1151,7 @@ test("Visitor Email keeps its empty receipt body instead of the submitted-fields});test.each([- ["Form", "form"],+ ["ResourceForm", "form"],["ancestor", "ancestor"],["global", undefined],] as const)(@@ -1183,7 +1183,7 @@ test.each([{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -1351,7 +1351,7 @@ test("automatic Email body redacts Element passwords and unknown input types", ({type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "input" }],},],@@ -1583,7 +1583,7 @@ test("an external Email Resource cannot read a Form-only binding", () => {{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -1640,7 +1640,7 @@ test("builds a submit-time graph with Form bindings and dependent Resource resul{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -1760,7 +1760,10 @@ test("builds a submit-time graph with Form bindings and dependent Resource resultest("an external Resource can be selected without gaining access to Form data", () => {const instances: Instances = new Map([- ["form", { type: "instance", id: "form", component: "Form", children: [] }],+ [+ "form",+ { type: "instance", id: "form", component: "ResourceForm", children: [] },+ ],]);const dataSources: DataSources = new Map([[@@ -1856,7 +1859,7 @@ test.each(["form", "page", undefined])({type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -1922,7 +1925,10 @@ test.each(["form", "page", undefined])(test("a shared outside alias cannot promote a Resource into Form scope", () => {const instances: Instances = new Map([- ["form", { type: "instance", id: "form", component: "Form", children: [] }],+ [+ "form",+ { type: "instance", id: "form", component: "ResourceForm", children: [] },+ ],]);const dataSources: DataSources = new Map([[@@ -1986,7 +1992,7 @@ test("an invalid Form graph does not prevent another Form from building", () =>{type: "instance",id: "invalidForm",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -1995,7 +2001,7 @@ test("an invalid Form graph does not prevent another Form from building", () =>{type: "instance",id: "validForm",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -2081,7 +2087,7 @@ test("deduplicates Resource roots while preserving selection order", () => {{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -2154,7 +2160,10 @@ test("deduplicates Resource roots while preserving selection order", () => {test("an external dependency cannot read Form data through an internal destination", () => {const instances: Instances = new Map([- ["form", { type: "instance", id: "form", component: "Form", children: [] }],+ [+ "form",+ { type: "instance", id: "form", component: "ResourceForm", children: [] },+ ],]);const dataSources: DataSources = new Map([[@@ -2251,7 +2260,7 @@ test.each([{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "child" }],},],@@ -2350,7 +2359,7 @@ test.each([{type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [],},],@@ -2551,7 +2560,7 @@ test.each(["http", "email", "visitor"] as const)({type: "instance",id: "form",- component: "Form",+ component: "ResourceForm",children: [{ type: "id", value: "input" }],},],diff --git a/packages/sdk/src/managed-form-resources-generator.ts b/packages/sdk/src/managed-form-resources-generator.tsindex bca8bbe57e..4e6af6f55f 100644--- a/packages/sdk/src/managed-form-resources-generator.ts+++ b/packages/sdk/src/managed-form-resources-generator.ts@@ -48,7 +48,7 @@ export const generatePageResources = (const parentInstanceById = getParentInstanceById(instances);const isInFormScope = (instanceId: string | undefined) => {while (instanceId !== undefined) {- if (instances.get(instanceId)?.component === "Form") {+ if (instances.get(instanceId)?.component === "ResourceForm") {return true;}instanceId = parentInstanceById.get(instanceId);@@ -91,7 +91,7 @@ export const generatePageResources = (if (prop.type !== "json" ||prop.name !== "action" ||- instances.get(prop.instanceId)?.component !== "Form" ||+ instances.get(prop.instanceId)?.component !== "ResourceForm" ||!isFormSubmission(prop.value)) {continue;diff --git a/packages/sdk/src/managed-form-submission.test.ts b/packages/sdk/src/managed-form-submission.test.tsindex fd98884d63..7e2949c3ca 100644--- a/packages/sdk/src/managed-form-submission.test.ts+++ b/packages/sdk/src/managed-form-submission.test.ts@@ -86,6 +86,56 @@ test("formats ordered final outcomes without response headers", () => {);});+test("keeps safe Email error codes without copying codes from HTTP responses", () => {+ const graph = {+ rootIds: ["email", "http"],+ resources: [+ {+ id: "email",+ outputName: "email",+ control: "email" as const,+ dependencies: [],+ createRequest: vi.fn(),+ },+ {+ id: "http",+ outputName: "http",+ dependencies: [],+ createRequest: vi.fn(),+ },+ ],+ };+ const body = {+ error: { code: "E_DAILY_LIMIT_EXCEEDED", message: "Daily limit reached" },+ };+ const result = getManagedFormResponse(graph, {+ email: {+ ok: false,+ status: 429,+ statusText: "Daily limit reached",+ data: body,+ },+ http: { ok: false, status: 429, statusText: "Failed", data: body },+ });+ expect(result.errors.map(({ code }) => code)).toEqual([+ "E_DAILY_LIMIT_EXCEEDED",+ undefined,+ ]);+ expect(+ getManagedFormResponse(+ { ...graph, rootIds: ["email"] },+ {+ email: {+ ok: false,+ status: 502,+ statusText: "Failed",+ data: { error: { code: "[email protected]" } },+ },+ }+ ).errors[0].code+ ).toBeUndefined();+});+test("keeps parallel results and errors in Action order when completion is reversed", async () => {let resolveFirst: ((response: Response) => void) | undefined;let resolveSecond: ((response: Response) => void) | undefined;@@ -874,6 +924,15 @@ test("parses bounded request bodies and rejects oversized streamed bodies", asynawait expect(readFormDataWithLimit(oversized, 3)).rejects.toThrow("Form submission is too large");++ const oversizedDefault = new Request("https://example.com/submit", {+ method: "POST",+ headers: { "content-length": String(25 * 1024 * 1024 + 1) },+ body: "x",+ });+ await expect(readFormDataWithLimit(oversizedDefault)).rejects.toThrow(+ "Form submission exceeds the 25 MiB limit. Reduce file sizes and try again."+ );});test("validates the managed Form bot field and keeps the Brave exception", () => {diff --git a/packages/sdk/src/resources-generator.test.tsx b/packages/sdk/src/resources-generator.test.tsxindex 32f03a2360..c9f9c65a1c 100644--- a/packages/sdk/src/resources-generator.test.tsx+++ b/packages/sdk/src/resources-generator.test.tsx@@ -17,7 +17,7 @@ import { generatePageResources } from "./managed-form-resources-generator";import type { DataSource } from "./schema/data-sources";const Body = createTemplateComponentFixture("Body");-const Form = createTemplateComponentFixture("Form");+const Form = createTemplateComponentFixture("ResourceForm");const WebhookForm = createTemplateComponentFixture("WebhookForm");test("base request fields do not generate Email delivery configuration", () => {@@ -45,7 +45,7 @@ test("does not fetch a Form-bound Resource during page load", () => {scope: createScope(),page: { rootInstanceId: "form" } as Page,instances: toMap([- { type: "instance", id: "form", component: "Form", children: [] },+ { type: "instance", id: "form", component: "ResourceForm", children: [] },]),dataSources: toMap([{@@ -93,7 +93,7 @@ test("does not evaluate configured Form Actions during page load", () => {scope: createScope(),page: { rootInstanceId: "form" } as Page,instances: toMap([- { type: "instance", id: "form", component: "Form", children: [] },+ { type: "instance", id: "form", component: "ResourceForm", children: [] },]),dataSources: toMap([{@@ -174,7 +174,7 @@ test("keeps a page-used Resource selected as a Form Action", () => {component: "Body",children: [{ type: "id", value: "form" }],},- { type: "instance", id: "form", component: "Form", children: [] },+ { type: "instance", id: "form", component: "ResourceForm", children: [] },]),dataSources: toMap([{@@ -332,7 +332,7 @@ test("excludes transitive Form-only Resources and rejects Dynamic Content Block{type: "instance" as const,id: "form",- component: "Form",+ component: "ResourceForm",children: [],},]),@@ -448,7 +448,7 @@ test("generate resources loader", () => {}const _data: ResourceRequestGraph = {resources: [- { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName },+ { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName, control: undefined, bodyFormat: undefined },],rootIds: [],@@ -690,7 +690,7 @@ test("generate variable and use in resources loader", () => {}const _data: ResourceRequestGraph = {resources: [- { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName },+ { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName, control: undefined, bodyFormat: undefined },],rootIds: [],@@ -936,7 +936,7 @@ test("generate page system variable and use in resources loader", () => {}const _data: ResourceRequestGraph = {resources: [- { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName },+ { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName, control: undefined, bodyFormat: undefined },],rootIds: [],@@ -989,7 +989,7 @@ test("generate global system variable and use in resources loader", () => {}const _data: ResourceRequestGraph = {resources: [- { id: "resource:0", outputName: "MyResource", dependencies: [], createRequest: MyResource },+ { id: "resource:0", outputName: "MyResource", dependencies: [], createRequest: MyResource, control: "system", bodyFormat: undefined },],rootIds: ["resource:0",@@ -1089,7 +1089,7 @@ test("generate resource loader with search params", () => {}const _data: ResourceRequestGraph = {resources: [- { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName },+ { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName, control: undefined, bodyFormat: undefined },],rootIds: [],@@ -1230,7 +1230,7 @@ test("generates action resources as lazy roots without loading stale data", () =}const _data: ResourceRequestGraph = {resources: [- { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName },+ { id: "resourceId", outputName: "resourceName", dependencies: [], createRequest: resourceName, control: undefined, bodyFormat: undefined },],rootIds: [],diff --git a/packages/sdk/src/resources-generator.ts b/packages/sdk/src/resources-generator.tsindex d926c151b1..fa4bff2c1e 100644--- a/packages/sdk/src/resources-generator.ts+++ b/packages/sdk/src/resources-generator.ts@@ -2,7 +2,7 @@ import type { DataSource, DataSources } from "./schema/data-sources";import type { Page } from "./schema/pages";import type { Resource, Resources } from "./schema/resources";import type { Prop, Props } from "./schema/props";-import type { Instance, Instances } from "./schema/instances";+import type { Instances } from "./schema/instances";import type { Scope } from "./scope";import { generateExpression, SYSTEM_VARIABLE_ID } from "./expression";import { findTreeInstanceIds } from "./instances-utils";@@ -12,6 +12,7 @@ import {getResourceDependencyIds,getResourceDataSourceIds,} from "./resource-dependencies";+import { migrateDeprecatedWebhookFormActions } from "./form/deprecated-webhook-form-actions";export const generateResourceRequestFields = ({resource,@@ -378,7 +379,7 @@ export const generateResources = ({resourceId)}, outputName: ${JSON.stringify(name)}, dependencies: ${JSON.stringify(dependencies- )}, createRequest: ${name} },\n`;+ )}, createRequest: ${name}, control: ${JSON.stringify(resource.control)}, bodyFormat: ${JSON.stringify(resource.bodyFormat)} },\n`;}generated += ` ],\n`;generated += ` rootIds: [\n`;@@ -432,6 +433,9 @@ export const generateResources = ({}}+ // Deprecated Webhook Form is the only production reader of this action lookup.+ // Remove _action and its return field with the deprecated Webhook Form adapter; actionResourceProps+ // also drives the shared resource graph and must remain.generated += ` const _action = new Map<string, { id: string; outputName: string }>([\n`;for (const prop of actionResourceProps) {const resource = resources.get(prop.value);@@ -452,82 +456,14 @@ export const generateResources = ({return generated;};-const getMethod = (value: string | undefined) => {- switch (value?.toLowerCase()) {- case "get":- return "get";- case "delete":- return "delete";- case "put":- return "put";- default:- return "post";- }-};-/**- * migrate webhook forms to resource action- * @todo move to client migrations eventually+ * @deprecated Compatibility export for saved Webhook Form action migration.+ * Remove this wrapper with the deprecated Webhook Form implementation.*/-export const replaceFormActionsWithResources = ({- props,- instances,- resources,-}: {+export const replaceFormActionsWithResources = (options: {props: Props;instances: Instances;resources: Resources;}) => {- const formProps = new Map<- Instance["id"],- { method?: string; action?: string }- >();- for (const prop of props.values()) {- if (- prop.name === "method" &&- prop.type === "string" &&- instances.get(prop.instanceId)?.component === "WebhookForm"- ) {- let data = formProps.get(prop.instanceId);- if (data === undefined) {- data = {};- formProps.set(prop.instanceId, data);- }- data.method = prop.value;- props.delete(prop.id);- }- if (- prop.name === "action" &&- prop.type === "string" &&- prop.value &&- instances.get(prop.instanceId)?.component === "WebhookForm"- ) {- let data = formProps.get(prop.instanceId);- if (data === undefined) {- data = {};- formProps.set(prop.instanceId, data);- }- data.action = prop.value;- props.set(prop.id, {- id: prop.id,- instanceId: prop.instanceId,- name: prop.name,- type: "resource",- value: prop.instanceId,- });- }- }- for (const [instanceId, { action, method }] of formProps) {- if (action) {- resources.set(instanceId, {- id: instanceId,- name: "action",- method: getMethod(method),- url: JSON.stringify(action),- headers: [- { name: "Content-Type", value: JSON.stringify("application/json") },- ],- });- }- }+ migrateDeprecatedWebhookFormActions(options);};diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.tsindex 135bd2d8f6..648bc06b99 100644--- a/packages/sdk/src/schema/pages.ts+++ b/packages/sdk/src/schema/pages.ts@@ -280,8 +280,6 @@ export const getPageDraftabilityError = ({export const pages = z.object({- /** One-time migration from the legacy Form component identity. */- formComponentIdentityVersion: z.number().int().optional(),meta: projectMeta.optional(),compiler: compilerSettings.optional(),redirects: z.array(pageRedirect).optional(),