fix: allow Builder validation with view access (#6725)

Builder publish validation uses project view access, so admin share
links and owner sessions can run it without the separate API permission.
It still checks that requested domains belong to the project and are
active and verified. CLI/MCP API permissions and publish controls are
unchanged.

The diagnostics panel keeps local findings when server validation
reports a matching missing resource. Findings show the affected variable
and scope, and **Show instance** opens the relevant page and Settings
view. Warnings remain visible beside errors. Server-only IDs stay in
copied reports.

- [x] Allow Builder validation for view-authorized project sessions
without changing CLI/MCP API authorization.
- [x] Keep domain ownership and verification checks.
- [x] Link findings to the affected instance and the relevant Settings
view.
- [x] Identify missing-resource variables and their page or instance
scope.
- [x] Remove the repeated “Audit” heading and use “instance” in Builder
diagnostics and MCP documentation.
- [x] Cover deep links, page and global scopes, warnings, display, and
the 500-finding fallback with regression tests.
- [x] Run focused Builder and project-build tests, typechecks, lint,
formatting, and generated-file checks.
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-11-21 18:44:40 +01:00
1 parent bf288341a3
commit 726b288a3e
39 files changed
+1358 -411

No files matched your search

+5 -1
View File
@@ -55,6 +55,7 @@ import {
$isCloneDialogOpen,
$isUiHidden,
$loadingState,
openBuilderView,
} from "./shared/nano-states";
import { $pages } from "~/shared/sync/data-stores";
import { CloneProjectDialog } from "~/shared/clone-project";
@@ -331,7 +332,10 @@ export const Builder = (props: BuilderProps) => {
});
const dataLoadingState = useStore($dataLoadingState);
useSyncPageUrl({ isDataLoaded: dataLoadingState === "loaded" });
useSyncPageUrl({
isDataLoaded: dataLoadingState === "loaded",
onView: openBuilderView,
});
const [publish, publishRef] = usePublish();
useEffect(() => {
@@ -253,7 +253,7 @@ test("Free shows the actual short error without details, navigation, or report c
title: "article.mdx:2:3",
summary: "Invalid MDX element nesting",
details: "Private long diagnostic context",
link: <button>Show element</button>,
link: <button>Show instance</button>,
reportText: "Private long diagnostic context",
},
],
@@ -264,7 +264,7 @@ test("Free shows the actual short error without details, navigation, or report c
expect(document.body.textContent).not.toContain(
"Private long diagnostic context"
);
expect(document.body.textContent).not.toContain("Show element");
expect(document.body.textContent).not.toContain("Show instance");
expect(
document.body.querySelector('[aria-label="Copy all reports"]')
).toBeNull();
@@ -708,23 +708,24 @@ test("Free audit summaries do not expose long cached details", () => {
expect(document.body.textContent).not.toContain(longSummary);
});
test("Show element closes the diagnostics dialog on ordinary navigation", async () => {
test("Show instance closes the diagnostics dialog on ordinary navigation", async () => {
const onOpenChange = vi.fn();
render(
[
{
severity: "error",
title: "Invalid element",
link: <a href="#element">Show element</a>,
reportText: "Invalid element",
title: "Invalid instance",
link: <a href="#instance">Show instance</a>,
reportText: "Invalid instance",
},
],
{ open: true, initialTab: "errors", onOpenChange }
);
const link =
document.body.querySelector<HTMLAnchorElement>('a[href="#element"]');
const link = document.body.querySelector<HTMLAnchorElement>(
'a[href="#instance"]'
);
expect(link).not.toBeNull();
expect(document.body.textContent).toContain("Invalid element");
expect(document.body.textContent).toContain("Invalid instance");
expect(
Array.from(document.body.querySelectorAll("button")).some(
(button) => button.textContent === "Show more"
@@ -735,22 +736,23 @@ test("Show element closes the diagnostics dialog on ordinary navigation", async
});
test.each(["metaKey", "ctrlKey", "shiftKey", "altKey"] as const)(
"Show element leaves diagnostics open on %s-click",
"Show instance leaves diagnostics open on %s-click",
(modifier) => {
const onOpenChange = vi.fn();
render(
[
{
severity: "error",
title: "Invalid element",
link: <a href="#element">Show element</a>,
reportText: "Invalid element",
title: "Invalid instance",
link: <a href="#instance">Show instance</a>,
reportText: "Invalid instance",
},
],
{ open: true, initialTab: "errors", onOpenChange }
);
const link =
document.body.querySelector<HTMLAnchorElement>('a[href="#element"]');
const link = document.body.querySelector<HTMLAnchorElement>(
'a[href="#instance"]'
);
expect(link).not.toBeNull();
act(() => {
link?.dispatchEvent(
@@ -113,9 +113,9 @@ const FindingList = ({
{findings.map((finding, index) => (
<Fragment key={`${finding.severity}-${index}`}>
<Flex direction="column" gap={2}>
{finding.source !== "publish" && (
{finding.source === "build" && (
<Text color="subtle" variant="labels">
{finding.source === "build" ? "Build" : "Audit"}
Build
</Text>
)}
{finding.source === "publish" ? (
@@ -10,9 +10,20 @@ import {
vi,
} from "vitest";
import { TooltipProvider, toast } from "@webstudio-is/design-system";
import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";
import type { Project } from "@webstudio-is/project";
import { createDefaultPages } from "@webstudio-is/project-build";
import type { Instance } from "@webstudio-is/sdk";
import {
formatBuildIntegrityError,
getBuildIntegrityIssues,
} from "@webstudio-is/project-build/runtime";
import { ROOT_INSTANCE_ID, type Instance } from "@webstudio-is/sdk";
import {
createTemplateComponentFixture,
renderData,
ws,
} from "@webstudio-is/template";
import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";
import { createTrpcInterceptor } from "~/shared/trpc/trpc-test-utils";
import {
createPublishAuditFinding,
@@ -21,6 +32,8 @@ import {
} from "./publish-test-utils";
const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
const Body = createTemplateComponentFixture("Body");
const Heading = createTemplateComponentFixture("Heading");
const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT;
const originalScrollIntoView = Object.getOwnPropertyDescriptor(
Element.prototype,
@@ -32,8 +45,14 @@ let publishModule: typeof import("./publish");
let stores: typeof import("~/shared/sync/data-stores");
let nanoStates: typeof import("~/shared/nano-states");
let builderStates: typeof import("~/builder/shared/nano-states");
let assetBridge: typeof import("~/shared/asset-content-bridge.client");
let contentSession: ReturnType<typeof createAssetContentSession>;
const requests: Array<{ path: string; input: unknown }> = [];
let publishResponse: unknown = { success: false, error: "Publish blocked" };
let validationResponse: unknown = {
diagnostics: { mdxErrors: [], mdxOmissions: [] },
cssValid: true,
};
let jobStatus: "failed" | "success" = "failed";
let didPublish = false;
let interceptor: ReturnType<typeof createTrpcInterceptor>;
@@ -53,6 +72,7 @@ beforeAll(async () => {
},
},
GET: {
"build.validatePublish": () => validationResponse,
"api.publish.getJob": () => {
return { status: jobStatus, code: "BUILD_FAILED" };
},
@@ -81,10 +101,6 @@ beforeAll(async () => {
data: 0,
limit: 100,
}),
"api.publish.validate": () => ({
diagnostics: { mdxErrors: [], mdxOmissions: [] },
cssValid: true,
}),
"build.contentDatabasePublishDiagnostics": () => ({
mdxErrors: [],
mdxOmissions: [],
@@ -99,6 +115,7 @@ beforeAll(async () => {
stores = await import("~/shared/sync/data-stores");
nanoStates = await import("~/shared/nano-states");
builderStates = await import("~/builder/shared/nano-states");
assetBridge = await import("~/shared/asset-content-bridge.client");
const { updateCsrfToken } = await import("~/shared/csrf.client");
updateCsrfToken("test-token");
});
@@ -106,9 +123,33 @@ beforeAll(async () => {
beforeEach(() => {
reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
publishResponse = { success: false, error: "Publish blocked" };
validationResponse = {
diagnostics: { mdxErrors: [], mdxOmissions: [] },
cssValid: true,
};
requests.length = 0;
jobStatus = "failed";
didPublish = false;
contentSession = createAssetContentSession({
authorize: () => true,
repository: {
readContent: async () => {
throw new Error("No assets in this project");
},
updateContent: async () => {
throw new Error("No assets in this project");
},
},
});
assetBridge.__testing__.initBridge(
assetBridge.createAssetContentBridge({
origin: location.origin,
request: fetch,
authorize: () => true,
requireReload: () => {},
getContentSession: () => contentSession,
})
);
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: false,
@@ -404,6 +445,10 @@ afterEach(() => {
stores.$project.set(undefined);
stores.$pages.set(undefined);
stores.$instances.set(new Map());
stores.$dataSources.set(new Map());
nanoStates.selectInstance(undefined);
builderStates.$activeInspectorPanel.set("style");
builderStates.$variablesSectionRequested.set(false);
builderStates.$publishDialog.set("none");
});
root = undefined;
@@ -463,7 +508,7 @@ test("static export reaches the server without waiting for diagnostics", async (
});
expect(
Array.from(document.body.querySelectorAll("a, button")).some(
(element) => element.textContent?.trim() === "Show element"
(element) => element.textContent?.trim() === "Show instance"
)
).toBe(false);
}, 30_000);
@@ -573,10 +618,277 @@ test("publish audit warnings keep their instance links in Diagnostics", async ()
const link = document.body.querySelector<HTMLAnchorElement>(
'a[href*="instance=publish-warning-instance"]'
);
expect(link?.textContent).toBe("Show element");
expect(link?.textContent).toBe("Show instance");
expect(new URL(link!.href).searchParams.get("view")).toBe("settings");
expect(document.body.textContent).not.toContain("Audit");
expect(document.body.textContent).toContain(
`Publish warning for "Home" (/): A child does not match the element's content model.`
);
await act(async () => link!.click());
expect(nanoStates.$selectedInstanceSelector.get()).toEqual([instanceId]);
expect(builderStates.$activeInspectorPanel.get()).toBe("settings");
expect(builderStates.$variablesSectionRequested.get()).toBe(false);
});
const scopes = [
{
scope: "date-card",
label: "Date card",
prefix: 'Cannot publish for "Home" (/)',
selector: "date-card,validation-instance",
},
{
scope: "validation-instance",
label: "Body",
prefix: 'Cannot publish for "Home" (/)',
selector: "validation-instance",
},
{
scope: ROOT_INSTANCE_ID,
label: "Global root",
prefix: "Cannot publish",
selector: ROOT_INSTANCE_ID,
},
];
test.each(scopes)("links currentDate on $label", async (scopeCase) => {
const { scope, label, prefix, selector } = scopeCase;
const pageId = "validation-page";
const instanceId = "validation-instance";
const { instances, props } = renderData(
<Body ws:id={instanceId}>
<ws.element ws:id="date-card" ws:label="Date card" />
<ws.element ws:tag="button">
<Heading ws:id="invalid-heading" ws:tag="h3">
Heading in button
</Heading>
</ws.element>
</Body>
);
stores.$pages.set(
createDefaultPages({ rootInstanceId: instanceId, homePageId: pageId })
);
stores.$instances.set(instances);
stores.$props.set(props);
nanoStates.$registeredComponentMetas.set(componentMetas);
stores.$dataSources.set(
new Map([
[
"missing-resource-variable",
{
type: "resource",
id: "missing-resource-variable",
name: "currentDate",
resourceId: "missing-resource",
scopeInstanceId: scope,
},
],
])
);
validationResponse = Response.json(
[
{
error: {
message:
'Cannot publish: resource variable "currentDate" (missing-resource-variable) references missing resource "missing-resource".',
code: -32600,
data: {
code: "BAD_REQUEST",
httpStatus: 400,
path: "build.validatePublish",
issues: [
{
type: "missingResource",
source: "dataSource",
dataSourceId: "missing-resource-variable",
dataSourceName: "currentDate",
resourceId: "missing-resource",
},
],
},
},
},
],
{ status: 400 }
);
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: true,
});
await mount();
const domain = document.body.querySelector<HTMLInputElement>(
'input[name="domainToPublish[]"]'
);
if (domain?.checked === false) {
await act(async () =>
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
);
}
const validate = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
).find((button) => button.textContent?.trim() === "Validate");
await act(async () => validate?.click());
await waitFor(() =>
expect(document.body.textContent).toContain("See issues")
);
expect(document.body.textContent).toContain("1 error · 1 warning");
const seeIssues = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
).find((button) => button.textContent?.trim() === "See issues");
await act(async () => seeIssues?.click());
const link = Array.from(
document.body.querySelectorAll<HTMLAnchorElement>("a")
).find((link) => link.textContent === "Show instance");
expect(link).toBeDefined();
const params = new URL(link!.href).searchParams;
expect(params.get("pageId")).toBe(pageId);
expect(params.get("instance")).toBe(selector);
expect(params.get("view")).toBe("settings/variables");
expect(params.has("variableId")).toBe(false);
expect(document.body.textContent).toContain(
`${prefix}: Resource variable "currentDate" on "${label}" references a missing resource.`
);
for (const id of [
pageId,
instanceId,
"missing-resource",
"missing-resource-variable",
]) {
expect(document.body.textContent).not.toContain(id);
}
expect(document.body.textContent).not.toContain("Audit");
expect(
document.body.querySelector('[role="tablist"]')?.textContent
).toContain("Warnings");
expect(
document.body.querySelector('[role="tablist"]')?.textContent
).toContain("Errors");
await selectTab("Warnings");
expect(document.body.textContent).toContain("Publish warning");
await selectTab("Errors");
await act(async () =>
document.body
.querySelector<HTMLAnchorElement>('a[href*="settings%2Fvariables"]')
?.click()
);
expect(nanoStates.$selectedPageId.get()).toBe(pageId);
expect(nanoStates.$selectedInstanceSelector.get()).toEqual(
selector.split(",")
);
expect(builderStates.$activeInspectorPanel.get()).toBe("settings");
expect(builderStates.$variablesSectionRequested.get()).toBe(true);
});
test("missing resources beyond the audit limit keep server IDs in the copied report", async () => {
const writeText = vi
.spyOn(navigator.clipboard, "writeText")
.mockResolvedValue(undefined);
const { instances, props } = renderData(<Body ws:id="body" />);
stores.$pages.set(createDefaultPages({ rootInstanceId: "body" }));
stores.$instances.set(instances);
stores.$props.set(props);
stores.$resources.set(new Map());
const dataSources = Array.from({ length: 501 }, (_, index) => ({
type: "resource" as const,
id: `source-id-${index}`,
name: `variable${index}`,
resourceId: `resource-id-${index}`,
scopeInstanceId: "body",
}));
stores.$dataSources.set(
new Map(dataSources.map((source) => [source.id, source]))
);
const issues = getBuildIntegrityIssues({
dataSources,
props: props.values(),
instances: instances.values(),
resources: [],
});
const message = formatBuildIntegrityError(issues[0], "Cannot publish");
validationResponse = Response.json(
[
{
error: {
message,
code: -32600,
data: {
code: "BAD_REQUEST",
httpStatus: 400,
path: "build.validatePublish",
issues,
},
},
},
],
{ status: 400 }
);
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: true,
});
await mount();
const domain = document.body.querySelector<HTMLInputElement>(
'input[name="domainToPublish[]"]'
);
if (domain?.checked === false) {
await act(async () =>
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
);
}
const validate = Array.from(document.body.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "Validate"
);
await act(async () => validate?.click());
await waitFor(() =>
expect(document.body.textContent).toContain("See issues")
);
const seeIssues = Array.from(document.body.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "See issues"
);
await act(async () => seeIssues?.click());
const visibleText = document.body.textContent ?? "";
expect(visibleText.includes("Unable to complete publish validation")).toBe(
true
);
expect(visibleText.includes('Resource variable "variable0"')).toBe(true);
expect(visibleText.includes("source-id-0")).toBe(false);
expect(visibleText.includes("resource-id-0")).toBe(false);
const copy = document.body.querySelector<HTMLButtonElement>(
'button[aria-label="Copy all reports"]'
);
await act(async () => copy?.click());
expect(writeText.mock.calls[0]?.[0]).toContain(
`ERROR: Unable to complete publish validation\n${message}`
);
});
test("an unmatched missing-resource failure sends only the validation summary to the toast", async () => {
const errorToast = vi.spyOn(toast, "error").mockImplementation(() => "");
const { reportPublishValidationFailure } =
await import("./publish-validation");
reportPublishValidationFailure(
Object.assign(new Error('Resource variable references "resource-id".'), {
data: {
issues: [
{
type: "missingResource",
dataSourceId: "source-id",
resourceId: "resource-id",
},
],
},
}),
() => {}
);
expect(errorToast).toHaveBeenCalledWith(
"Unable to complete publish validation"
);
});
test.each([
@@ -49,6 +49,17 @@ beforeAll(async () => {
},
},
GET: {
"build.validatePublish": async () => {
checkRequests += 1;
try {
const result = await checks.promise;
checksRead += 1;
return result;
} catch (error) {
checksRead += 1;
throw error;
}
},
"api.publish.getJob": () => ({
status: "failed",
code: "BUILD_FAILED",
@@ -72,17 +83,6 @@ beforeAll(async () => {
data: 0,
limit: 100,
}),
"api.publish.validate": async () => {
checkRequests += 1;
try {
const result = await checks.promise;
checksRead += 1;
return result;
} catch (error) {
checksRead += 1;
throw error;
}
},
"build.contentDatabasePublishDiagnostics": async () => {
checkRequests += 1;
try {
@@ -451,6 +451,18 @@ test.each(["checks-first", "server-first"] as const)(
}
);
test("a site publish response appears while validation is still pending", async () => {
await mount("site");
await clickPublish("site");
await act(async () => {
dispatch.resolve({ success: false, error: "site request failure" });
await dispatch.promise;
});
const errors = await openErrors("site");
expect(errors?.textContent).toContain("site request failure");
await completeChecks(false);
});
test.each(["request", "transport"] as const)(
"a static %s failure does not replace an earlier site failure",
async (failure) => {
@@ -71,7 +71,7 @@ beforeAll(async () => {
POST: { "domain.publish": () => publish() },
GET: {
"domain.project": () => refresh(),
"api.publish.validate": () => validate(),
"build.validatePublish": () => validate(),
"build.contentDatabasePublishDiagnostics": () => validate(),
"api.publish.getJob": () => job(),
"domain.countTotalDomains": () => ({
@@ -69,6 +69,10 @@ beforeAll(async () => {
},
},
GET: {
"build.validatePublish": () => ({
diagnostics: { mdxErrors: [], mdxOmissions: [] },
cssValid: true,
}),
"domain.project": () => ({
success: true,
project: {
@@ -131,10 +135,6 @@ beforeAll(async () => {
mdxErrors: [],
mdxOmissions: [],
}),
"api.publish.validate": () => ({
diagnostics: { mdxErrors: [], mdxOmissions: [] },
cssValid: true,
}),
},
});
interceptor.start();
@@ -1,6 +1,6 @@
import { type ReactNode } from "react";
import { Link, toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
import { getPageById, getPagePath, ROOT_INSTANCE_ID } from "@webstudio-is/sdk";
import {
findPageAndSelectorByInstanceId,
formatPrePublishAuditFinding,
@@ -9,6 +9,7 @@ import {
} from "@webstudio-is/project-build/runtime";
import {
$registeredComponentMetas,
$selectedPage,
$selectedPageId,
selectInstance,
} from "~/shared/nano-states";
@@ -21,8 +22,10 @@ import {
$dataSources,
$resources,
} from "~/shared/sync/data-stores";
import { $publishDialog } from "~/builder/shared/nano-states";
import { $publishDialog, openBuilderView } from "~/builder/shared/nano-states";
import { getInstanceLabel } from "~/builder/shared/instance-label";
import { getInstanceLink } from "~/shared/instance-utils/link";
import type { BuilderView } from "~/shared/router-utils/path-utils";
import { flushExternalContentProject } from "~/shared/external-content-roots";
import { nativeClient } from "~/shared/trpc/trpc-client";
import { getContentDatabasePublishFindings } from "./content-database-publish-warning";
@@ -30,45 +33,42 @@ import { getPublishValidationErrorMessage } from "./publish-error";
import type { DiagnosticFinding } from "./diagnostics";
const getPrePublishInstanceTarget = (
instanceId: string,
pageId?: string,
instanceSelector?: string[]
{ instanceId, pageId, instanceSelector }: PrePublishAuditFinding["location"],
view: BuilderView
) => {
const pages = $pages.get();
const instances = $instances.get();
if (pages === undefined || instances.has(instanceId) === false) {
if (
pages === undefined ||
instanceId === undefined ||
(instanceId !== ROOT_INSTANCE_ID && instances.has(instanceId) === false)
) {
return;
}
const target =
pageId === undefined || instanceSelector === undefined
? findPageAndSelectorByInstanceId(pages, instances, instanceId)
: { pageId, instanceSelector };
const href = getInstanceLink(target.instanceSelector);
instanceId === ROOT_INSTANCE_ID
? {
pageId: $selectedPage.get()?.id ?? pages.homePageId,
instanceSelector: [instanceId],
}
: pageId !== undefined && instanceSelector !== undefined
? { pageId, instanceSelector }
: findPageAndSelectorByInstanceId(pages, instances, instanceId);
const href = getInstanceLink(target.instanceSelector, {
pageId: target.pageId,
view,
});
if (href === undefined) {
return;
}
return { ...target, href };
return { ...target, href, view };
};
const PrePublishInstanceLink = ({
instanceId,
pageId,
instanceSelector,
children,
target,
}: {
instanceId: string;
pageId?: string;
instanceSelector?: string[];
children: ReactNode;
target: NonNullable<ReturnType<typeof getPrePublishInstanceTarget>>;
}) => {
const target = getPrePublishInstanceTarget(
instanceId,
pageId,
instanceSelector
);
if (target === undefined) {
return null;
}
return (
<Link
href={target.href}
@@ -85,10 +85,11 @@ const PrePublishInstanceLink = ({
event.preventDefault();
$selectedPageId.set(target.pageId);
selectInstance(target.instanceSelector);
openBuilderView(target.view);
$publishDialog.set("none");
}}
>
{children}
Show instance
</Link>
);
};
@@ -100,8 +101,59 @@ type DiagnosticPrePublishAuditFinding = PrePublishAuditFinding & {
const toPrePublishDiagnosticFinding = (
finding: DiagnosticPrePublishAuditFinding
): DiagnosticFinding => {
const title = formatPrePublishAuditFinding(finding);
const context = Object.entries(finding.location)
const location = finding.location;
const isMissingResource = finding.ruleId === "resource-integrity";
const isVariable = isMissingResource && location.dataSourceId !== undefined;
const variable =
isMissingResource && location.dataSourceId !== undefined
? $dataSources.get().get(location.dataSourceId)
: undefined;
const prop =
isMissingResource && location.propId !== undefined
? $props.get().get(location.propId)
: undefined;
const instanceId =
variable !== undefined
? (variable.scopeInstanceId ?? ROOT_INSTANCE_ID)
: location.instanceId;
const target = getPrePublishInstanceTarget(
{ ...location, instanceId },
isVariable ? "settings/variables" : "settings"
);
const reportTitle = formatPrePublishAuditFinding(finding);
let title = reportTitle;
if (isMissingResource) {
const sourceName = variable?.name ?? prop?.name;
const source = isVariable ? "Resource variable" : "Resource prop";
const instance =
instanceId === undefined ? undefined : $instances.get().get(instanceId);
const scope =
instanceId === ROOT_INSTANCE_ID
? "Global root"
: instance === undefined
? undefined
: getInstanceLabel(instance);
const pages = $pages.get();
const page =
pages !== undefined &&
target !== undefined &&
instanceId !== ROOT_INSTANCE_ID
? getPageById(pages, target.pageId)
: undefined;
title = formatPrePublishAuditFinding({
...finding,
message: `${source}${sourceName === undefined ? "" : ` "${sourceName}"`}${scope === undefined ? "" : ` on "${scope}"`} references a missing resource.`,
location:
page === undefined || pages === undefined
? location
: {
...location,
pageName: page.name,
pagePath: getPagePath(page.id, pages) || "/",
},
});
}
const context = Object.entries(location)
.filter(([key, value]) => key !== "instanceSelector" && value !== undefined)
.map(([key, value]) => `${key}: ${value}`);
return {
@@ -110,18 +162,11 @@ const toPrePublishDiagnosticFinding = (
title,
summary: title.slice(0, 160),
link:
finding.location.instanceId === undefined ? undefined : (
<PrePublishInstanceLink
instanceId={finding.location.instanceId}
pageId={finding.location.pageId}
instanceSelector={finding.location.instanceSelector}
>
Show element
</PrePublishInstanceLink>
target === undefined ? undefined : (
<PrePublishInstanceLink target={target} />
),
details: context.length === 0 ? undefined : context.join(" · "),
reportText: [
`${finding.severity.toUpperCase()}: ${title}`,
`${finding.severity.toUpperCase()}: ${reportTitle}`,
`Rule: ${finding.ruleId}`,
...context,
].join("\n"),
@@ -138,18 +183,70 @@ export const getPublishAuditFindings = (
)
.map(toPrePublishDiagnosticFinding);
const getPrePublishAuditFindings = (): DiagnosticFinding[] =>
getPublishAuditFindings(
runPrePublishAudit({
pages: $pages.get(),
instances: $instances.get(),
props: $props.get(),
dataSources: $dataSources.get(),
resources: $resources.get(),
assets: $assets.get(),
metas: $registeredComponentMetas.get(),
})
const getPrePublishAudit = () =>
runPrePublishAudit({
pages: $pages.get(),
instances: $instances.get(),
props: $props.get(),
dataSources: $dataSources.get(),
resources: $resources.get(),
assets: $assets.get(),
metas: $registeredComponentMetas.get(),
});
const getMissingResourceIssueSources = (error: unknown) => {
if (typeof error !== "object" || error === null || !("data" in error)) {
return [];
}
const data = error.data;
if (typeof data !== "object" || data === null || !("issues" in data)) {
return [];
}
const issues = data.issues;
if (Array.isArray(issues) === false) {
return [];
}
const issueSources = issues.flatMap(
(
issue
): { source: "dataSource" | "prop"; id: string; resourceId: string }[] => {
if (
typeof issue !== "object" ||
issue === null ||
!("type" in issue) ||
issue.type !== "missingResource"
) {
return [];
}
if (
"dataSourceId" in issue &&
typeof issue.dataSourceId === "string" &&
"resourceId" in issue &&
typeof issue.resourceId === "string"
) {
return [
{
source: "dataSource",
id: issue.dataSourceId,
resourceId: issue.resourceId,
},
];
}
if (
"propId" in issue &&
typeof issue.propId === "string" &&
"resourceId" in issue &&
typeof issue.resourceId === "string"
) {
return [
{ source: "prop", id: issue.propId, resourceId: issue.resourceId },
];
}
return [];
}
);
return issueSources.length === issues.length ? issueSources : [];
};
export const runPublishDiagnostics = async (
projectId: Project["id"],
@@ -157,30 +254,57 @@ export const runPublishDiagnostics = async (
) => {
const cssBuildWarningText =
"Some project styles cannot be processed for publishing. Publishing can continue using base and font styles.";
const auditFindings = getPrePublishAuditFindings();
const validation =
domains === undefined
? undefined
: await nativeClient.api.publish.validate.query({
projectId,
target: "staging",
domains,
});
const audit = getPrePublishAudit();
const auditFindings = getPublishAuditFindings(audit);
let validation;
try {
validation =
domains === undefined
? undefined
: await nativeClient.build.validatePublish.query({
projectId,
target: "staging",
domains,
});
} catch (error) {
const issueSources = getMissingResourceIssueSources(error);
if (
issueSources.length > 0 &&
issueSources.every(({ source, id, resourceId }) =>
audit.some(
(finding) =>
finding.severity === "error" &&
finding.ruleId === "resource-integrity" &&
finding.location.resourceId === resourceId &&
(source === "dataSource"
? finding.location.dataSourceId === id
: finding.location.propId === id)
)
)
) {
return { passed: false, findings: auditFindings };
}
throw error;
}
const diagnostics =
validation?.diagnostics ??
(await nativeClient.build.contentDatabasePublishDiagnostics.query({
projectId,
}));
const contentFindings = getContentDatabasePublishFindings(diagnostics).map(
(finding) => ({
...finding,
link:
finding.relatedInstanceId === undefined ? undefined : (
<PrePublishInstanceLink instanceId={finding.relatedInstanceId}>
Open Content Block
</PrePublishInstanceLink>
),
})
(finding) => {
const target = getPrePublishInstanceTarget(
{ instanceId: finding.relatedInstanceId },
"settings"
);
return {
...finding,
link:
target === undefined ? undefined : (
<PrePublishInstanceLink target={target} />
),
};
}
);
const cssWarning =
validation?.cssValid === false
@@ -215,6 +339,8 @@ export const reportPublishValidationFailure = (
showToast = true,
}: { publishingContinues?: boolean; showToast?: boolean } = {}
) => {
const failureTitle = "Unable to complete publish validation";
const hideDetails = getMissingResourceIssueSources(error).length > 0;
const diagnosticMessage = getPublishValidationErrorMessage(error, {
assets: $assets.get(),
assetFolders: $assetFolders.get(),
@@ -222,32 +348,33 @@ export const reportPublishValidationFailure = (
const message = publishingContinues
? `${diagnosticMessage}\n\nThe publish request was sent without waiting for these diagnostics.`
: diagnosticMessage;
const visibleMessage = hideDetails ? failureTitle : message;
if (showToast) {
toast.error(message.slice(0, 200));
toast.error(visibleMessage.slice(0, 200));
}
const mcpUrl = "https://wstd.us/mcp";
const mcpUrlIndex = message.indexOf(mcpUrl);
const details =
mcpUrlIndex === -1 ? (
message
) : (
<>
{message.slice(0, mcpUrlIndex)}
<Link href={mcpUrl} target="_blank" rel="noreferrer">
Webstudio MCP
</Link>
{message.slice(mcpUrlIndex + mcpUrl.length)}
</>
);
const details = hideDetails ? undefined : mcpUrlIndex === -1 ? (
message
) : (
<>
{message.slice(0, mcpUrlIndex)}
<Link href={mcpUrl} target="_blank" rel="noreferrer">
Webstudio MCP
</Link>
{message.slice(mcpUrlIndex + mcpUrl.length)}
</>
);
setFindings([
...getPublishAuditFindings(getPrePublishAudit()),
{
severity: "error",
title: publishingContinues
? "Publish checks couldn’t complete"
: "Unable to complete publish validation",
summary: message.slice(0, 160),
: failureTitle,
summary: visibleMessage.slice(0, 160),
details,
reportText: `ERROR: Unable to complete publish validation\n${message}`,
reportText: `ERROR: ${failureTitle}\n${message}`,
},
]);
};
@@ -4,6 +4,10 @@ import { userEvent } from "@vitest/browser/context";
import { afterEach, expect, test, vi } from "vitest";
import { createDefaultPages } from "@webstudio-is/project-build";
import { CollapsibleProvider } from "~/builder/shared/collapsible-section";
import {
$variablesSectionRequested,
openBuilderView,
} from "~/builder/shared/nano-states";
import {
$selectedInstanceSelector,
$selectedPageId,
@@ -35,6 +39,7 @@ afterEach(() => {
document.body.innerHTML = "";
$variableToFocus.set(undefined);
$variableToOpen.set(undefined);
$variablesSectionRequested.set(false);
selectInstance(undefined);
$pages.set(undefined);
$props.set(new Map());
@@ -87,6 +92,35 @@ const setup = () => {
return { container, local };
};
test("opening the Variables view expands and scrolls the section without opening a variable", async () => {
const { container } = setup();
$pages.set(createDefaultPages({ rootInstanceId: "parent" }));
$selectedPageId.set("home");
selectInstance(["child", "parent"]);
const scrollIntoView = vi.spyOn(Element.prototype, "scrollIntoView");
await act(async () =>
root?.render(
<TooltipProvider>
<VariablesSection />
</TooltipProvider>
)
);
const trigger = container.querySelector<HTMLButtonElement>(
'button[aria-expanded="true"][aria-controls]'
)!;
await act(async () => trigger.click());
expect(trigger.getAttribute("aria-expanded")).toBe("false");
await act(async () => openBuilderView("settings/variables"));
expect(trigger.getAttribute("aria-expanded")).toBe("true");
expect(scrollIntoView).toHaveBeenCalledOnce();
expect(scrollIntoView.mock.instances[0]).toBe(trigger);
expect(document.body.querySelector('[role="dialog"]')).toBeNull();
await act(async () => trigger.click());
expect(trigger.getAttribute("aria-expanded")).toBe("false");
});
test("Option-click local variable label opens Delete confirmation without editing", async () => {
const { container, local } = setup();
$pages.set(createDefaultPages({ rootInstanceId: "parent" }));
@@ -24,6 +24,7 @@ import {
} from "@webstudio-is/design-system";
import { AlertIcon, PlusIcon, TrashIcon } from "@webstudio-is/icons";
import { ROOT_INSTANCE_ID, type DataSource } from "@webstudio-is/sdk";
import { $variablesSectionRequested } from "~/builder/shared/nano-states";
import { $variableValuesByInstanceSelector } from "~/shared/nano-states";
import { $dataSources } from "~/shared/sync/data-stores";
import {
@@ -463,12 +464,25 @@ const VariablesList = ({ isOpen }: { isOpen: boolean }) => {
const label = "Variables";
export const VariablesSection = () => {
const sectionRequested = useStore($variablesSectionRequested);
const triggerRef = useRef<HTMLButtonElement>(null);
const variableToFocus = useStore($variableToFocus);
const variableToOpen = useStore($variableToOpen);
const availableVariables = useStore($availableVariables);
const selectedInstance = useStore($selectedInstance);
const selectedScopeId = selectedInstance?.id ?? ROOT_INSTANCE_ID;
const [isOpen, setIsOpen] = useOpenState(label);
useEffect(() => {
if (sectionRequested === false) {
return;
}
if (isOpen === false) {
setIsOpen(true);
return;
}
triggerRef.current?.scrollIntoView({ block: "nearest" });
$variablesSectionRequested.set(false);
}, [isOpen, sectionRequested, setIsOpen]);
useEffect(() => {
if (
variableToOpen !== undefined &&
@@ -514,6 +528,7 @@ export const VariablesSection = () => {
onOpenChange={setIsOpen}
trigger={
<SectionTitle
ref={triggerRef}
suffix={
<Flex align="center">
<VariablePopoverTrigger>
@@ -1,11 +1,13 @@
import { atom, computed } from "nanostores";
import {
$isPreviewMode,
$isDesignMode,
$selectedInstanceRenderState,
} from "~/shared/nano-states/misc";
import { $canvasIframeState } from "~/shared/nano-states/canvas";
import type { SidebarPanelName } from "~/builder/sidebar-left/types";
import { $settings, getSetting } from "./client-settings";
import type { BuilderView } from "~/shared/router-utils/path-utils";
export const $isShareDialogOpen = atom<boolean>(false);
@@ -79,6 +81,17 @@ export const $clampingRect = computed(
);
export const $activeInspectorPanel = atom<"style" | "settings">("style");
export const $variablesSectionRequested = atom(false);
export const openBuilderView = (view: BuilderView) => {
if ($isPreviewMode.get()) {
return;
}
$activeInspectorPanel.set("settings");
$variablesSectionRequested.set(
view === "settings/variables" && $isDesignMode.get()
);
};
export const $dataLoadingState = atom<"idle" | "loading" | "loaded">("idle");
@@ -130,7 +130,7 @@ test("convert legacy instances to lexical", async () => {
);
});
test("convert element instances to lexical", async () => {
test("convert ws:element instances to Lexical", async () => {
const refs: Refs = new Map();
const editor = createHeadlessEditor({
nodes: [LinkNode],
@@ -211,7 +211,7 @@ test("keeps explicit line break instances while editing", async () => {
]);
});
test("convert lexical to element instances updates", async () => {
test("convert Lexical to ws:element instance updates", async () => {
const refs: Refs = new Map();
let nextId = 0;
const createId = () => `generated-${++nextId}`;
@@ -38,7 +38,9 @@ import { DocumentSourceDiagnosticsError } from "@webstudio-is/content-engine/com
import * as assetUploader from "@webstudio-is/asset-uploader/server";
import * as apiRuntime from "./api-runtime.server";
import * as issueReportService from "./github-issue-report.server";
import { apiRouter, __testing__ } from "./api-router.server";
import { apiRouter } from "./api-router.server";
import { buildRouter } from "./build-router.server";
import { assertPublishDomains } from "./publish-validation.server";
import * as assetQueryPreview from "./asset-query-preview.server";
import * as formSimulation from "./simulate-form.server";
import * as db from "~/shared/db";
@@ -57,7 +59,6 @@ const servicesDir = new URL(".", import.meta.url);
const server = createTestServer();
import { assertContentOrBuildTransactions } from "./api-content-permissions.server";
const { assertApiPublishDomains } = __testing__;
const createContext = (
allowAdditionalPermissions: boolean,
@@ -1375,19 +1376,18 @@ describe("api router permits", () => {
const project = { domain: "project.wstd.dev" };
expect(() =>
assertApiPublishDomains({
auth: { type: "user", permits: ["edit"] },
assertPublishDomains({
auth: { type: "user" },
domains: ["custom.example.com"],
project,
})
).not.toThrow();
expect(() =>
assertApiPublishDomains({
assertPublishDomains({
auth: {
type: "token",
token: createToken({ relation: "editors", canPublish: false }),
permits: ["view", "edit", "api"],
},
domains: ["project.wstd.dev"],
project,
@@ -1395,11 +1395,10 @@ describe("api router permits", () => {
).toThrow("Authorization token does not have publish permission");
expect(() =>
assertApiPublishDomains({
assertPublishDomains({
auth: {
type: "token",
token: createToken({ relation: "editors", canPublish: true }),
permits: ["view", "edit", "api"],
},
domains: ["custom.example.com"],
project,
@@ -1407,11 +1406,10 @@ describe("api router permits", () => {
).not.toThrow();
expect(() =>
assertApiPublishDomains({
assertPublishDomains({
auth: {
type: "token",
token: createToken({ relation: "builders", canPublish: false }),
permits: ["view", "edit", "build", "api"],
},
domains: ["project.wstd.dev"],
project,
@@ -1419,11 +1417,10 @@ describe("api router permits", () => {
).not.toThrow();
expect(() =>
assertApiPublishDomains({
assertPublishDomains({
auth: {
type: "token",
token: createToken({ relation: "builders", canPublish: false }),
permits: ["view", "edit", "build", "api"],
},
domains: ["custom.example.com"],
project,
@@ -1431,14 +1428,13 @@ describe("api router permits", () => {
).toThrow("Authorization token does not have publish permission");
expect(() =>
assertApiPublishDomains({
assertPublishDomains({
auth: {
type: "token",
token: createToken({
relation: "administrators",
canPublish: true,
}),
permits: ["view", "edit", "build", "admin", "api"],
},
domains: ["custom.example.com"],
project,
@@ -1522,6 +1518,201 @@ describe("api router permits", () => {
}
);
test("lets an admin share link validate in Builder with API access disabled", async () => {
vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(
createToken({
relation: "administrators",
canPublish: true,
canUseApi: false,
})
);
vi.spyOn(projectApi, "loadById").mockResolvedValue({
domain: "project.wstd.dev",
domainsVirtual: [
{ domain: "custom.example.com", status: "ACTIVE", verified: true },
],
} as never);
vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue(
createEditableContentBuild()
);
vi.spyOn(assetUploader, "loadAssetDataByProject").mockResolvedValue({
assets: [],
assetFolders: [],
});
vi.spyOn(db, "loadProjectBundleByProjectId").mockResolvedValue(
createPublishedProjectBundleFixture()
);
const context = createContext(true);
const input = {
projectId: "project-1",
target: "staging" as const,
domains: ["custom.example.com"],
};
const browserContext = {
...context,
apiClient: { ...context.apiClient, type: "browser" as const },
};
const cliContext = {
...context,
apiClient: { ...context.apiClient, type: "cli" as const },
};
await expect(
createCaller(cliContext).publish.validate(input)
).rejects.toMatchObject({
code: "FORBIDDEN",
cause: { webstudioCode: "API_ACCESS_DISABLED" },
});
await expect(
buildRouter.createCaller(browserContext).validatePublish(input)
).resolves.toMatchObject({
valid: true,
domains: input.domains,
diagnostics: { mdxOmissions: [], mdxErrors: [] },
cssValid: true,
});
});
test.each(["viewers", "builders", "owner"] as const)(
"validates a custom domain in Builder for %s without API access",
async (role) => {
const projectId = `validation-project-${role}`;
const context =
role === "owner"
? createContext(false, {
type: "user",
userId: "owner-1",
sessionCreatedAt: 0,
isLoggedInToBuilder: async () => true,
})
: createContext(false);
server.use(
postgrestDb.get("Project", ({ request }) => {
const { searchParams } = new URL(request.url);
if (searchParams.get("id") !== `eq.${projectId}`) {
return json([]);
}
if (searchParams.has("userId")) {
return json(
searchParams.get("userId") === "eq.owner-1"
? [{ id: projectId }]
: []
);
}
return json([
{
id: projectId,
userId: "owner-1",
domain: "project.wstd.dev",
domainsVirtual: [
{
domain: "custom.example.com",
status: "ACTIVE",
verified: true,
},
],
latestStaticBuild: [],
},
]);
}),
postgrestDb.get("AuthorizationToken", ({ request }) => {
const { searchParams } = new URL(request.url);
const relations = searchParams
.get("relation")
?.slice(4, -1)
.split(",");
return json(
searchParams.get("projectId") === `eq.${projectId}` &&
relations?.includes(role)
? [{ token: "secret-token" }]
: []
);
}),
postgrestDb.get("User", () => json({ id: "owner-1" })),
postgrestDb.get("Asset", () => json([])),
postgrestDb.get("AssetFolder", () => json([]))
);
vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue({
...createEditableContentBuild(),
projectId,
});
const caller = buildRouter.createCaller({
...context,
apiClient: { ...context.apiClient, type: "browser" },
});
const input = {
projectId,
target: "staging" as const,
domains: ["custom.example.com"],
};
await expect(caller.validatePublish(input)).resolves.toMatchObject({
valid: true,
domains: input.domains,
diagnostics: { mdxOmissions: [], mdxErrors: [] },
});
await expect(
caller.validatePublish({ ...input, domains: ["unknown.example.com"] })
).rejects.toMatchObject({ code: "BAD_REQUEST" });
}
);
test.each([
{ scenario: "cli", type: "cli", tokenProjectId: "validation-project-cli" },
{ scenario: "missing-grant", type: "browser", tokenProjectId: undefined },
{
scenario: "cross-project",
type: "browser",
tokenProjectId: "another-project",
},
] as const)(
"denies Builder validation before reading a project ($scenario)",
async ({ scenario, type, tokenProjectId }) => {
const projectId = `validation-project-${scenario}`;
const authToken = `validation-token-${scenario}`;
const projectFilters: (string | null)[] = [];
server.use(
postgrestDb.get("AuthorizationToken", ({ request }) => {
const { searchParams } = new URL(request.url);
const projectFilter = searchParams.get("projectId");
projectFilters.push(projectFilter);
return json(
tokenProjectId !== undefined &&
searchParams.get("token") === `eq.${authToken}` &&
(projectFilter === null ||
projectFilter === `eq.${tokenProjectId}`)
? [{ token: authToken }]
: []
);
})
);
const loadProject = vi.spyOn(projectApi, "loadById").mockResolvedValue({
domain: "project.wstd.dev",
domainsVirtual: [],
} as never);
const context = createContext(true, {
type: "token",
authToken,
ownerId: "user-1",
});
const caller = buildRouter.createCaller({
...context,
apiClient: { ...context.apiClient, type },
});
await expect(
caller.validatePublish({
projectId,
target: "staging",
domains: ["project.wstd.dev"],
})
).rejects.toMatchObject({ code: "FORBIDDEN" });
expect(projectFilters).toEqual(type === "cli" ? [] : [`eq.${projectId}`]);
expect(loadProject).not.toHaveBeenCalled();
}
);
test("warns before publishing when generated CSS cannot build", async () => {
vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(
@@ -1707,7 +1898,7 @@ describe("api router permits", () => {
target: "production",
domains: ["custom.example.com"],
})
).rejects.toThrow("Authorization token does not have publish permission");
).rejects.toMatchObject({ code: "FORBIDDEN" });
expect(loadBundle).not.toHaveBeenCalled();
});
+11 -136
View File
@@ -13,14 +13,11 @@ import {
setMarketplaceApprovalStatus,
} from "@webstudio-is/project/index.server";
import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";
import { hasCssSyntaxError } from "@webstudio-is/css-data";
import { parseGeneratedStyleDeclaration } from "@webstudio-is/project-build/persistence";
import { singlePlayerVersionMismatchError } from "@webstudio-is/project/build-patch-core.server";
import {
createProjectDomain,
deleteProjectDomain,
getDefaultPublishDomains,
getVerifiedPublishDomains,
getProjectPublishJob,
getProjectPublishLog,
listProjectDomains,
@@ -35,8 +32,6 @@ import {
import { PrePublishAuditError } from "@webstudio-is/project-build/runtime";
import {
getBuilderRuntimeOperationInputSchema,
getBuildIntegrityIssues,
formatBuildIntegrityError,
paginateOutput,
paginatedOutputInputSchema,
} from "@webstudio-is/project-build/runtime";
@@ -70,8 +65,6 @@ import {
} from "./api-permits.server";
import { componentMetas } from "~/shared/component-metas.server";
import {
generateCss,
getStyleDeclKey,
templates as templateSchema,
type Asset,
type AssetFolder,
@@ -110,35 +103,11 @@ import { createAssetClient } from "../shared/asset-client";
import { previewProjectAssetQuery } from "./asset-query-preview.server";
import { simulateFormSubmission } from "./simulate-form.server";
import { publishConfiguredIssueReport } from "./github-issue-report.server";
import { loadContentDatabasePublishDiagnostics } from "./content-database-publish-diagnostics.server";
const assertApiPublishDomains = ({
auth,
domains,
project,
}: {
auth: Awaited<ReturnType<typeof assertApiProjectPermit>>;
domains: string[];
project: { domain: string };
}) => {
if (auth.type === "user") {
return;
}
const { token } = auth;
if (token.canPublish === true) {
return;
}
if (
token.relation === "builders" &&
domains.length > 0 &&
domains.every((domain) => domain === project.domain)
) {
return;
}
throw new AuthorizationError(
"Authorization token does not have publish permission"
);
};
import {
assertPublishDomains,
publishValidationInput,
validatePublish,
} from "./publish-validation.server";
const projectIdInput = z.object({ projectId: z.string() });
@@ -611,47 +580,6 @@ const loadRuntimeAssetData = async (ctx: AppContext, projectId: string) => {
});
};
const canPublishBuildCss = async (build: CompactBuild, assets: Asset[]) => {
const usedComponents = new Set(
build.instances.map((instance) => instance.component)
);
const { cssText } = generateCss({
assets: new Map(assets.map((asset) => [asset.id, asset])),
instances: new Map(
build.instances.map((instance) => [instance.id, instance])
),
props: new Map(build.props.map((prop) => [prop.id, prop])),
breakpoints: new Map(
build.breakpoints.map((breakpoint) => [breakpoint.id, breakpoint])
),
styles: new Map(
build.styles
.filter(
(style) => parseGeneratedStyleDeclaration(style).errors.length === 0
)
.map((style) => [getStyleDeclKey(style), style])
),
styleSources: new Map(
build.styleSources.map((source) => [source.id, source])
),
styleSourceSelections: new Map(
build.styleSourceSelections.map((selection) => [
selection.instanceId,
selection,
])
),
componentMetas: new Map(
[...componentMetas].filter(([name]) => usedComponents.has(name))
),
assetBaseUrl: "",
atomic:
build.projectSettings?.compiler?.atomicStyles ??
build.pages?.compiler?.atomicStyles ??
true,
});
return hasCssSyntaxError(cssText) === false;
};
const createServerContentBlockApplication = ({
ctx,
projectId,
@@ -1188,59 +1116,10 @@ export const apiRouter = router({
}),
publish: router({
validate: projectQuery(
projectIdInput.extend({
target: z.enum(["staging", "production"]),
domains: z.array(z.string()).optional(),
}),
"edit",
async ({ auth, ctx, input }) => {
const project = await loadById(input.projectId, ctx);
const domains =
input.domains ?? getDefaultPublishDomains(project, input.target);
assertApiPublishDomains({ auth, domains, project });
if (domains.length === 0) {
throwApiError(
"BAD_REQUEST",
"Select at least one domain to publish."
);
}
const verifiedDomains = getVerifiedPublishDomains(project, domains);
const invalidDomains = domains.filter(
(domain) => verifiedDomains.includes(domain) === false
);
if (invalidDomains.length > 0) {
throwApiError(
"BAD_REQUEST",
`Publish domains must belong to this project and be active and verified: ${invalidDomains.join(", ")}`
);
}
const build = await loadDevBuildByProjectId(ctx, input.projectId);
const issues = getBuildIntegrityIssues(build);
if (issues[0] !== undefined) {
throwApiError(
"BAD_REQUEST",
formatBuildIntegrityError(issues[0], "Cannot publish"),
{ issues }
);
}
const diagnostics = await loadContentDatabasePublishDiagnostics(
input.projectId,
ctx,
{ build }
);
const { assets } = await loadRuntimeAssetData(ctx, input.projectId);
const cssValid = await canPublishBuildCss(build, assets);
return {
valid: true,
target: input.target,
domains,
diagnostics,
cssValid,
};
},
{ command: "validate-publish", client: "validatePublish" }
),
validate: projectQuery(publishValidationInput, "edit", validatePublish, {
command: "validate-publish",
client: "validatePublish",
}),
list: projectQuery(
paginatedProjectInput,
@@ -1297,7 +1176,7 @@ export const apiRouter = router({
const project = await loadById(input.projectId, ctx);
const domains =
input.domains ?? getDefaultPublishDomains(project, input.target);
assertApiPublishDomains({ auth, domains, project });
assertPublishDomains({ auth, domains, project });
const result = await publishProject(
{ project, domains, target: input.target },
ctx
@@ -1371,7 +1250,7 @@ export const apiRouter = router({
const project = await loadById(input.projectId, ctx);
const domains =
input.domains ?? getDefaultPublishDomains(project, input.target);
assertApiPublishDomains({ auth, domains, project });
assertPublishDomains({ auth, domains, project });
await unpublishProjectDomains(
{ projectId: input.projectId, domains },
ctx
@@ -1439,7 +1318,3 @@ export const apiRouter = router({
),
}),
});
export const __testing__ = {
assertApiPublishDomains,
};
@@ -1,4 +1,5 @@
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import {
AuthorizationError,
authorizeProject,
@@ -51,6 +52,10 @@ import {
} from "./api-build.server";
import { assertApiProjectPermit } from "./api-permits.server";
import { loadContentDatabasePublishDiagnostics } from "./content-database-publish-diagnostics.server";
import {
publishValidationInput,
validatePublish,
} from "./publish-validation.server";
const projectBundleInput = z.object({
projectId: z.string(),
@@ -308,6 +313,24 @@ export const buildRouter = router({
);
}),
validatePublish: procedure
.input(publishValidationInput)
.query(async ({ ctx, input }) => {
if (
ctx.apiClient.type !== "browser" ||
(await authorizeProject.hasProjectPermit(
{ projectId: input.projectId, permit: "view" },
ctx
)) === false
) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You don't have access to this project",
});
}
return await validatePublish({ ctx, input });
}),
contentDatabasePublishDiagnostics: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ ctx, input }) => {
@@ -0,0 +1,157 @@
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import type { db as authDb } from "@webstudio-is/authorization-token/index.server";
import { loadById } from "@webstudio-is/project/index.server";
import type { CompactBuild } from "@webstudio-is/project-build";
import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";
import {
formatBuildIntegrityError,
getBuildIntegrityIssues,
} from "@webstudio-is/project-build/runtime";
import { parseGeneratedStyleDeclaration } from "@webstudio-is/project-build/persistence";
import {
getDefaultPublishDomains,
getVerifiedPublishDomains,
} from "@webstudio-is/domain/index.server";
import { loadAssetDataByProject } from "@webstudio-is/asset-uploader/server";
import { hasCssSyntaxError } from "@webstudio-is/css-data";
import { generateCss, getStyleDeclKey, type Asset } from "@webstudio-is/sdk";
import { componentMetas } from "~/shared/component-metas.server";
import { throwApiError } from "./api-errors.server";
import { loadContentDatabasePublishDiagnostics } from "./content-database-publish-diagnostics.server";
type PublishAuthorization =
| { type: "user" }
| { type: "token"; token: Awaited<ReturnType<typeof authDb.getTokenInfo>> };
export const publishValidationInput = z.object({
projectId: z.string(),
target: z.enum(["staging", "production"]),
domains: z.array(z.string()).optional(),
});
export const assertPublishDomains = ({
auth,
domains,
project,
}: {
auth: PublishAuthorization;
domains: string[];
project: { domain: string };
}) => {
if (auth.type === "user") {
return;
}
const { token } = auth;
if (token.canPublish === true) {
return;
}
if (
token.relation === "builders" &&
domains.length > 0 &&
domains.every((domain) => domain === project.domain)
) {
return;
}
throw new TRPCError({
code: "FORBIDDEN",
message: "Authorization token does not have publish permission",
});
};
const canPublishBuildCss = async (build: CompactBuild, assets: Asset[]) => {
const usedComponents = new Set(
build.instances.map((instance) => instance.component)
);
const { cssText } = generateCss({
assets: new Map(assets.map((asset) => [asset.id, asset])),
instances: new Map(
build.instances.map((instance) => [instance.id, instance])
),
props: new Map(build.props.map((prop) => [prop.id, prop])),
breakpoints: new Map(
build.breakpoints.map((breakpoint) => [breakpoint.id, breakpoint])
),
styles: new Map(
build.styles
.filter(
(style) => parseGeneratedStyleDeclaration(style).errors.length === 0
)
.map((style) => [getStyleDeclKey(style), style])
),
styleSources: new Map(
build.styleSources.map((source) => [source.id, source])
),
styleSourceSelections: new Map(
build.styleSourceSelections.map((selection) => [
selection.instanceId,
selection,
])
),
componentMetas: new Map(
[...componentMetas].filter(([name]) => usedComponents.has(name))
),
assetBaseUrl: "",
atomic:
build.projectSettings?.compiler?.atomicStyles ??
build.pages?.compiler?.atomicStyles ??
true,
});
return hasCssSyntaxError(cssText) === false;
};
export const validatePublish = async ({
auth,
ctx,
input,
}: {
auth?: PublishAuthorization;
ctx: AppContext;
input: z.infer<typeof publishValidationInput>;
}) => {
const project = await loadById(input.projectId, ctx);
const domains =
input.domains ?? getDefaultPublishDomains(project, input.target);
if (auth !== undefined) {
assertPublishDomains({ auth, domains, project });
}
if (domains.length === 0) {
throwApiError("BAD_REQUEST", "Select at least one domain to publish.");
}
const verifiedDomains = getVerifiedPublishDomains(project, domains);
const invalidDomains = domains.filter(
(domain) => verifiedDomains.includes(domain) === false
);
if (invalidDomains.length > 0) {
throwApiError(
"BAD_REQUEST",
`Publish domains must belong to this project and be active and verified: ${invalidDomains.join(", ")}`
);
}
const build = await loadDevBuildByProjectId(ctx, input.projectId);
const issues = getBuildIntegrityIssues(build);
if (issues[0] !== undefined) {
throwApiError(
"BAD_REQUEST",
formatBuildIntegrityError(issues[0], "Cannot publish"),
{ issues }
);
}
const diagnostics = await loadContentDatabasePublishDiagnostics(
input.projectId,
ctx,
{ build }
);
const { assets } = await loadAssetDataByProject(input.projectId, ctx, {
skipPermissionsCheck: true,
});
const cssValid = await canPublishBuildCss(build, assets);
return {
valid: true,
target: input.target,
domains,
diagnostics,
cssValid,
};
};
+18 -6
View File
@@ -1,6 +1,8 @@
import {
getAllPages,
isPageTemplate,
ROOT_INSTANCE_ID,
getPageById,
type Instances,
type Pages,
} from "@webstudio-is/sdk";
@@ -11,11 +13,13 @@ import {
$canOpenPageTemplates,
} from "../nano-states";
import { builderUrl } from "../router-utils";
import type { BuilderView } from "../router-utils/path-utils";
import { $instances, $pages, $project } from "../sync/data-stores";
import { canResolveInstanceSelector } from "./selection";
export const getInstanceLink = (
instanceSelector: InstanceSelector | undefined
instanceSelector: InstanceSelector | undefined,
{ pageId, view }: { pageId?: string; view?: BuilderView } = {}
) => {
const pages = $pages.get();
const project = $project.get();
@@ -24,6 +28,7 @@ export const getInstanceLink = (
}
const selection = getDeepLinkedInstanceSelection({
instanceSelector,
pageId,
pages,
instances: $instances.get(),
canOpenPageTemplates: $canOpenPageTemplates.get(),
@@ -38,6 +43,7 @@ export const getInstanceLink = (
origin: window.location.origin,
authToken: $authToken.get(),
mode: mode === "design" ? undefined : mode,
view,
safemode:
new URLSearchParams(window.location.search).get("safemode") === "true",
});
@@ -48,11 +54,13 @@ export const getInstanceSelectorFromUrl = (searchParams: URLSearchParams) =>
export const getDeepLinkedInstanceSelection = ({
instanceSelector,
pageId,
canOpenPageTemplates,
pages,
instances,
}: {
instanceSelector: InstanceSelector | undefined;
pageId?: string;
canOpenPageTemplates: boolean;
pages: Pages;
instances: Instances;
@@ -62,18 +70,22 @@ export const getDeepLinkedInstanceSelection = ({
}
const instanceId = instanceSelector[0];
const isGlobalRoot =
instanceSelector.length === 1 && instanceId === ROOT_INSTANCE_ID;
if (
instanceId === undefined ||
instances.has(instanceId) === false ||
(!isGlobalRoot && instances.has(instanceId) === false) ||
canResolveInstanceSelector(instanceSelector, instances) === false
) {
return;
}
const rootInstanceId = instanceSelector.at(-1);
const page = getAllPages(pages).find(
(page) => page.rootInstanceId === rootInstanceId
);
const page =
isGlobalRoot && pageId !== undefined
? (getPageById(pages, pageId) ?? pages.pageTemplates?.get(pageId))
: getAllPages(pages).find(
(page) => page.rootInstanceId === instanceSelector.at(-1)
);
if (
page === undefined ||
(isPageTemplate(page) && canOpenPageTemplates === false)
@@ -5,16 +5,25 @@ import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { expect, test } from "vitest";
import type { Project } from "@webstudio-is/project";
import { createDefaultPages } from "@webstudio-is/project-build";
import { renderData, ws } from "@webstudio-is/template";
import {
$authToken,
$builderMode,
$isPreviewMode,
$pageNavigation,
$selectedInstanceSelector,
$selectedPageHash,
$selectedPageId,
requestPageNavigation,
selectInstance,
selectPage,
} from "~/shared/nano-states";
import { $pages, $project } from "~/shared/sync/data-stores";
import {
$activeInspectorPanel,
$variablesSectionRequested,
openBuilderView,
} from "~/builder/shared/nano-states";
import { $instances, $pages, $project } from "~/shared/sync/data-stores";
import { PreviewNavigationObserver, useSyncPageUrl } from "./use-switch-page";
(
@@ -29,20 +38,26 @@ const withRouter = async (
commits: Array<() => void>;
router: ReturnType<typeof createBrowserRouter>;
}) => Promise<void>,
mode: "design" | "preview" = "preview"
mode: "design" | "preview" = "preview",
initialPath = mode === "preview" ? "/?mode=preview" : "/"
) => {
const savedUrl = window.location.href;
const savedState = history.state;
const saved = [
const stores = [
$pages,
$instances,
$project,
$authToken,
$builderMode,
$pageNavigation,
$selectedPageHash,
$selectedPageId,
].map((store) => store.get());
history.replaceState({}, "", mode === "preview" ? "/?mode=preview" : "/");
$activeInspectorPanel,
$variablesSectionRequested,
];
const saved = stores.map((store) => store.get());
const savedSelection = $selectedInstanceSelector.get();
history.replaceState({}, "", initialPath);
const pages = createDefaultPages({
homePageId: "home",
rootInstanceId: "home-root",
@@ -57,15 +72,27 @@ const withRouter = async (
});
pages.folders.get(pages.rootFolderId)!.children.push("other");
$pages.set(pages);
$instances.set(
renderData(
<>
<ws.element ws:tag="body" ws:id="home-root" />
<ws.element ws:tag="body" ws:id="other-root">
<ws.element ws:tag="section" ws:id="other-section" />
</ws.element>
</>
).instances
);
$project.set({ id: "090e6e14-ae50-4b2e-bd22-71733cec05bb" } as Project);
$authToken.set(undefined);
$selectedPageId.set("home");
$builderMode.set(mode);
$activeInspectorPanel.set("style");
$variablesSectionRequested.set(false);
$pageNavigation.set(undefined);
const commits: Array<() => void> = [];
let blocked = false;
const App = () => {
useSyncPageUrl({ isDataLoaded: true });
useSyncPageUrl({ isDataLoaded: true, onView: openBuilderView });
const preview = useStore($isPreviewMode);
return preview && <PreviewNavigationObserver />;
};
@@ -113,19 +140,72 @@ const withRouter = async (
router.dispose();
container.remove();
history.replaceState(savedState, "", savedUrl);
const stores = [
$pages,
$project,
$authToken,
$builderMode,
$pageNavigation,
$selectedPageHash,
$selectedPageId,
];
stores.forEach((store, index) => store.set(saved[index] as never));
selectInstance(savedSelection);
}
};
test("a Settings URL keeps the view when its page path becomes a page ID", async () => {
const historyLength = history.length;
await withRouter(
async () => {
const params = new URLSearchParams(window.location.search);
expect(params.get("view")).toBe("settings");
expect(params.get("pageId")).toBe("other");
expect($selectedInstanceSelector.get()).toEqual([
"other-section",
"other-root",
]);
expect($activeInspectorPanel.get()).toBe("settings");
expect($variablesSectionRequested.get()).toBe(false);
expect(history.length).toBe(historyLength);
},
"design",
"/?pageId=%2Fother&instance=other-section%2Cother-root&view=settings"
);
});
test("a page-level Settings URL keeps its implicit page root", async () => {
await withRouter(
async () => {
expect($selectedInstanceSelector.get()).toEqual(["other-root"]);
expect($activeInspectorPanel.get()).toBe("settings");
expect(new URLSearchParams(window.location.search).has("instance")).toBe(
false
);
},
"design",
"/?pageId=other&view=settings"
);
});
test("a Settings Variables URL opens the requested page and Global root on load and Back", async () => {
const deepLink = "/?pageId=other&instance=%3Aroot&view=settings%2Fvariables";
await withRouter(
async ({ back }) => {
expect($selectedPageId.get()).toBe("other");
expect($selectedInstanceSelector.get()).toEqual([":root"]);
expect($activeInspectorPanel.get()).toBe("settings");
expect($variablesSectionRequested.get()).toBe(true);
expect(window.location.pathname + window.location.search).toBe(deepLink);
await act(async () => {
$activeInspectorPanel.set("style");
$variablesSectionRequested.set(false);
selectPage("home");
});
await expect.poll(() => window.location.search).toBe("");
await back();
expect($selectedPageId.get()).toBe("other");
expect($selectedInstanceSelector.get()).toEqual([":root"]);
expect($activeInspectorPanel.get()).toBe("settings");
expect($variablesSectionRequested.get()).toBe(true);
},
"design",
deepLink
);
});
test("repeated same-URL requests get distinct acknowledgements without adding a Back entry", async () => {
await withRouter(async ({ request, back }) => {
await request();
@@ -17,6 +17,10 @@ import {
setBuilderMode,
} from "~/shared/nano-states";
import { builderPath } from "~/shared/router-utils";
import {
getBuilderView,
type BuilderView,
} from "~/shared/router-utils/path-utils";
import { $selectedPage } from "../nano-states";
import { selectPage } from "../nano-states";
import { findPageByIdOrPath, isPageTemplate } from "@webstudio-is/sdk";
@@ -54,7 +58,7 @@ export const __testing__ = {
shouldNavigateToPageState,
};
const setPageStateFromUrl = () => {
const setPageStateFromUrl = (onView?: (view: BuilderView) => void) => {
const searchParams = new URLSearchParams(window.location.search);
const pages = $pages.get();
if (pages === undefined) {
@@ -88,8 +92,10 @@ const setPageStateFromUrl = () => {
},
});
const requestedInstanceSelector = getInstanceSelectorFromUrl(searchParams);
const view = getBuilderView(searchParams);
const instanceSelection = getDeepLinkedInstanceSelection({
instanceSelector: requestedInstanceSelector,
pageId: view === "settings/variables" ? pageId : undefined,
canOpenPageTemplates: $canOpenPageTemplates.get(),
pages,
instances: $instances.get(),
@@ -97,9 +103,12 @@ const setPageStateFromUrl = () => {
if (instanceSelection !== undefined) {
$selectedPageId.set(instanceSelection.pageId);
selectInstance(instanceSelection.instanceSelector);
return true;
} else {
selectPage(pageId);
}
if (view !== undefined) {
onView?.(view);
}
selectPage(pageId);
return true;
};
@@ -148,24 +157,42 @@ const useSyncPageStateToUrl = (
const searchParamsPageHash = searchParams.get("pageHash") ?? "";
const searchParamsInstanceSelector =
getInstanceSelectorFromUrl(searchParams);
const view = getBuilderView(searchParams);
const isCanonicalPageId = searchParamsPageId === page.id;
const matchesPage =
isCanonicalPageId ||
(view !== undefined &&
findPageByIdOrPath(searchParamsPageId, pages)?.id === page.id);
const keepView =
view !== undefined &&
matchesPage &&
(searchParamsInstanceSelector === undefined
? selectedInstanceSelector?.[0] === page.rootInstanceId
: areInstanceSelectorsEqual(
searchParamsInstanceSelector,
selectedInstanceSelector
));
const searchParamsModeRaw = searchParams.get("mode");
const searchParamsMode = isBuilderMode(searchParamsModeRaw)
? searchParamsModeRaw
: undefined;
const builderModeParam = builderMode === "design" ? undefined : builderMode;
const searchParamsSafemode = searchParams.get("safemode");
const keepRootSelector =
keepView && searchParamsInstanceSelector !== undefined;
const instanceSelector =
selectedInstanceSelector === undefined ||
selectedInstanceSelector[0] === page.rootInstanceId ||
(!keepRootSelector &&
selectedInstanceSelector[0] === page.rootInstanceId) ||
canResolveInstanceSelector(selectedInstanceSelector, $instances.get()) ===
false
? undefined
: selectedInstanceSelector;
const isSamePageState =
searchParamsPageId === page.id &&
const sameHashAndMode =
searchParamsPageHash === pageHash.hash &&
searchParamsMode === builderModeParam;
const isSamePageState = isCanonicalPageId && sameHashAndMode;
const request = $pageNavigation.get();
const committedKey = request?.location?.key ?? pending.current?.key;
@@ -241,8 +268,9 @@ const useSyncPageStateToUrl = (
pageHash: pageHash.hash === "" ? undefined : pageHash.hash,
mode: builderModeParam,
safemode: searchParamsSafemode === "true",
view: keepView ? view : undefined,
}),
{ replace: isSamePageState }
{ replace: matchesPage && sameHashAndMode }
);
}, [
builderMode,
@@ -273,23 +301,29 @@ export const PreviewNavigationObserver = () => {
return null;
};
export const useSyncPageUrl = ({ isDataLoaded }: { isDataLoaded: boolean }) => {
export const useSyncPageUrl = ({
isDataLoaded,
onView,
}: {
isDataLoaded: boolean;
onView?: (view: BuilderView) => void;
}) => {
const [isUrlStateInitialized, setIsUrlStateInitialized] = useState(false);
const page = useSyncPageStateToUrl(isUrlStateInitialized);
const canOpenPageTemplate = useStore($canOpenPageTemplates);
// Apply initial URL state only after all synchronized data has loaded.
useEffect(() => {
if (isDataLoaded && !isUrlStateInitialized && setPageStateFromUrl()) {
if (isDataLoaded && !isUrlStateInitialized && setPageStateFromUrl(onView)) {
setIsUrlStateInitialized(true);
}
}, [isDataLoaded, isUrlStateInitialized]);
}, [isDataLoaded, isUrlStateInitialized, onView]);
useEffect(() => {
window.addEventListener("popstate", setPageStateFromUrl, true);
return () =>
window.removeEventListener("popstate", setPageStateFromUrl, true);
}, []);
const onPopstate = () => setPageStateFromUrl(onView);
window.addEventListener("popstate", onPopstate, true);
return () => window.removeEventListener("popstate", onPopstate, true);
}, [onView]);
useEffect(() => {
const pages = $pages.get();
@@ -4,6 +4,7 @@ import {
builderUrl,
restAssetsUploadPath,
areBuilderDataUrlsEqual,
getBuilderView,
} from "./path-utils";
test("includes an instance deep link in builder paths", () => {
@@ -49,6 +50,7 @@ test("instance navigation preserves Builder data but access changes do not", ()
builderPath({
instanceSelector: ["second", "body"],
authToken: "share-token",
view: "settings",
}),
current
);
@@ -56,3 +58,15 @@ test("instance navigation preserves Builder data but access changes do not", ()
next.searchParams.set("authToken", "other-token");
expect(areBuilderDataUrlsEqual(current, next)).toBe(false);
});
test("round-trips supported Builder views and ignores unknown section paths", () => {
const url = new URL(
builderPath({ view: "settings/variables" }),
"https://wstd.dev"
);
expect(getBuilderView(url.searchParams)).toBe("settings/variables");
url.searchParams.set("view", "settings");
expect(getBuilderView(url.searchParams)).toBe("settings");
url.searchParams.set("view", "settings/unknown");
expect(getBuilderView(url.searchParams)).toBeUndefined();
});
@@ -14,6 +14,15 @@ const searchParams = (params: Record<string, string | undefined | null>) => {
return asString === "" ? "" : `?${asString}`;
};
export type BuilderView = "settings" | "settings/variables";
export const getBuilderView = (searchParams: URLSearchParams) => {
const view = searchParams.get("view");
if (view === "settings" || view === "settings/variables") {
return view;
}
};
export type BuilderLinkParams = {
pageId?: string;
instanceSelector?: readonly string[];
@@ -21,6 +30,7 @@ export type BuilderLinkParams = {
pageHash?: string;
mode?: BuilderMode;
safemode?: boolean;
view?: BuilderView;
};
export const builderPath = ({
@@ -30,6 +40,7 @@ export const builderPath = ({
pageHash,
mode,
safemode = false,
view,
}: BuilderLinkParams = {}) => {
return `/${searchParams({
pageId,
@@ -38,6 +49,7 @@ export const builderPath = ({
pageHash,
mode,
safemode: safemode ? "true" : undefined,
view,
})}`;
};
@@ -184,6 +196,7 @@ export const areBuilderDataUrlsEqual = (currentUrl: URL, nextUrl: URL) => {
"instanceId",
"mode",
"pageHash",
"view",
]) {
current.searchParams.delete(param);
next.searchParams.delete(param);
+1 -1
View File
@@ -46,7 +46,7 @@ The recipient needs access to the project. If you opened the Builder through a
share link, the copied URL keeps that share link’s access token.
You can also copy the browser URL, which tracks the selected page and instance.
Webstudio also uses these links for actions such as **Show element** in pre-publish
Webstudio also uses these links for actions such as **Show instance** in pre-publish
findings. If the instance was removed before the link is opened, the Builder
still opens the requested page.
@@ -19,11 +19,10 @@ that could make the generated site fail or behave unexpectedly.
Diagnostics, and the server may reject the publish.
- **Warnings** appear immediately but do not prevent publishing.
On paid plans, when a finding identifies a component, choose **Show element** to
select the affected instance. Free plans show a
short error or warning without full details or element navigation. Fix the
problem, then publish again. Draft pages are excluded because they are not part
of the generated site.
On paid plans, choose **Show instance** to select the affected instance and open
**Settings**. For a missing Resource used by a variable, this also opens
**Variables** at the variable’s scope. Free plans show a short error or warning.
Fix the problem, then publish again. Draft pages are excluded from the generated site.
## Publish details
+5 -5
View File
@@ -257,7 +257,7 @@ For an editable MDX article, use the resource to select the Content Block's sour
### Content Block completion checklist
For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.
For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value instance; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.
### Complete article editability is required
@@ -272,7 +272,7 @@ Before handoff:
**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.
Keep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.
Keep intended editable values separate from display formatting. For reading time, use three inline sibling text instances: static `— `, one instance bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The bound instance must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.
If an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.
@@ -435,15 +435,15 @@ terms, agents can:
- Read and update marketplace product metadata.
- List, create, update, delete, and replace redirects.
- List, create, update, and delete responsive breakpoints.
- List and inspect page elements.
- List and inspect instances on a page.
- Insert registered components.
- Insert styled JSX fragments.
- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.
- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete instances.
- Fill grid cells.
- List and update text children.
- Update plain text and expression text.
- Update structured rich text.
- Add, update, delete, and bind element props.
- Add, update, delete, and bind instance props.
- Bind props to expressions, resources, actions, and runtime system values.
- Read, add, update, delete, and replace local styles.
- Update selected style-source styles.
+7 -7
View File
@@ -180,12 +180,12 @@ const taskRecipeUseCases = {
],
folders: ["List folders", "Create folder", "Update folder", "Delete folder"],
elements: [
"List element instances",
"Inspect one element instance",
"List instances",
"Inspect one instance",
"Insert authored JSX or one component template",
"Move elements",
"Clone element subtree",
"Delete element subtree",
"Move instances",
"Clone an instance subtree",
"Delete an instance subtree",
],
text: ["List text/expression children", "Update text child"],
props: [
@@ -473,8 +473,8 @@ const readFirstUseCases = [
"List breakpoints",
"List page templates",
"List folders",
"List element instances",
"Inspect one element instance",
"List instances",
"Inspect one instance",
"List text/expression children",
"Read styles",
"List data variables",
+5 -5
View File
@@ -2,15 +2,15 @@
// Edit markdown files in src/docs instead.
export const cliDocs = {
"api-use-cases":
'# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nest Line truncated
'# 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 instances.\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 nes Line truncated
"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## Publish and wait\n\nUse `webstudio publish deploy --target production --json --wait` to wait for\nthis publish and read its available diagnostics before the CLI exits. Without\n`--wait`, publish returns as soon as the job is accepted. Waiting stops after\n360 checks at five-second intervals, plus the time spent on API requests. It\ndoes not stop the remote publish or save its logs. A successful publish still\nsucceeds if its logs are unavailable.\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[] }.\nAn Editor link with API access can patch text and editable props inside a\nContent Block. The server checks the complete batch before saving it. Pages,\nassets, component structure, and design changes still require Builder access.\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 reus Line truncated
'# 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## Publish and wait\n\nUse `webstudio publish deploy --target production --json --wait` to wait for\nthis publish and read its available diagnostics before the CLI exits. Without\n`--wait`, publish returns as soon as the job is accepted. Waiting stops after\n360 checks at five-second intervals, plus the time spent on API requests. It\ndoes not stop the remote publish or save its logs. A successful publish still\nsucceeds if its logs are unavailable.\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, instance, 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[] }.\nAn Editor link with API access can patch text and editable props inside a\nContent Block. The server checks the complete batch before saving it. Pages,\nassets, component structure, and design changes still require Builder access.\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: component instances and children, including text/expression children\n- props: instance props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and Line truncated
"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 m Line truncated
'# 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 m Line truncated
"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### Style source transfer\n\nUse `copy-design-token` with `tokenId` to get a transfer payload. Pass that payload as `data` to `paste-design-token` in the target project. Set `instanceId` to attach the new token to an instance; without it, paste creates the token without attaching it. Each paste creates the next numbered copy. Image and font assets transfer when both projects use the same Webstudio origin.\n\nThe same commands transfer all three style source types. Call `copy-design-token` with `styleSourceId` and `sourceType` set to `token`, `tag`, or `local`. The older `tokenId` input still copies a Token. Pass the returned `data` to `paste-design-token`; the payload identifies its source type. A Tag style merges into the matching global tag. A Local style merges into the Local source of the supplied `instanceId`, creating that source if needed. Pasted declarations replace matching properties, states, and breakpoints; other styles remain.\n\n### Native Form actions\n\nA native Form (`ResourceForm`) selects Resources through a data source. Create\nthe Resource with `scopeInstanceId` on the Form or an ancestor and\n`exposeAsDataSource:true`; use the returned `dataSourceId` in the Form\'s `action`\nJSON array with `update-props`. Scope it to the Form when the request needs\n`formData`. Do not bind a resource prop or set `exposeAsDataSource:false` for a\nnative Form action. The selected Resource rLine truncated
'# 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### Style source transfer\n\nUse `copy-design-token` with `tokenId` to get a transfer payload. Pass that payload as `data` to `paste-design-token` in the target project. Set `instanceId` to attach the new token to an instance; without it, paste creates the token without attaching it. Each paste creates the next numbered copy. Image and font assets transfer when both projects use the same Webstudio origin.\n\nThe same commands transfer all three style source types. Call `copy-design-token` with `styleSourceId` and `sourceType` set to `token`, `tag`, or `local`. The older `tokenId` input still copies a Token. Pass the returned `data` to `paste-design-token`; the payload identifies its source type. A Tag style merges into the matching global tag. A Local style merges into the Local source of the supplied `instanceId`, creating that source if needed. Pasted declarations replace matching properties, states, and breakpoints; other styles remain.\n\n### Native Form actions\n\nA native Form (`ResourceForm`) selects Resources through a data source. Create\nthe Resource with `scopeInstanceId` on the Form or an ancestor and\n`exposeAsDataSource:true`; use the returned `dataSourceId` in the Form\'s `action`\nJSON array with `update-props`. Scope it to the Form when the request needs\n`formData`. Do not bind a resource prop or set `exposeAsDataSource:false` for a\nnative Form action. The selected Resource rLine truncated
"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-refe Line truncated
'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-refe Line truncated
"mcp-vision":
'# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.\n- Session previews download missing project assets into `.webstudio/assets`. If `PREVIEW_ASSET_DOWNLOAD_FAILED` occurs, restore network and project asset access, then retry `preview.start`.\n- When launcher metadata is available, dependency installation reuses a supported npm or pnpm launcher. Without launcher metadata, it defaults to npm.\n- When npm is selected, dependency installation honors `npm_config_cache`. If it is unset, preview uses the writable `.webstudio/preview/.npm-cache` directory instead of the user\'s default npm cache.\n- For npm cache permission errors, unset `npm_config_cache` to use the preview-local cache, then retry. No cache deletion is required.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, the error includes the selected package-manager path and sanitized diagnostics. Check that path and the network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n\n## Visual Verification Rule\n\nAsk the user whether they want visual verification before starting it, unless the user explicitly requested screenshots, visual verification, or a rendered audit. Never start `preview.start`, `screenshot`, `screenshot.diff`, `vision.install-ocr`, or a rendered audit automatically. If the user does not opt in, use focused non-visual assertions and report that vision was not run. After the user opts in, use `preview.start` and `screenshot({ path })` so vision can inspect the current MCP session and verify that generated project files are current. Iterative preview is the default: it keeps one generated-site server and browser alive, regenerates changed files, and performs an ordinary page reload without Vite HMR. Use `mode: "production"` only for release-like verification; rendered audit selects it automatically. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\nAn authenticated project share URL is used with `webstudio init --link`; it is\nnot a generated-site preview URL. Project screenshots and rendered audits use\nthe generated local preview owned by the current CLI/MCP process. Do not pass a\nBuilder/share URL to `screenshot`, even without query parameters. Use `path`\nafter starting preview, or use `baseUrl` only for an intentional generated site\nthat is already running. Path captures verify the generated-site root marker\nand fail instead of returning a screenshot of Builder chrome.\n\n## Vision Verification Loop\n\n- Ask the user whether they want visual verification unless they explicitly requested it. Stop before calling preview, capture, comparison, OCR, or rendered-audit tools until the user opts in.\n- Make focused page/content/style changes with semantic MCP tools.\n- Call preview.start once to keep the iterative generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- Read `preview.status.stale` before relying on generated output. When present, `renderedProjectVersion` identifies the last project version materialized into the preview; a stale preview refreshes automatically on the next managed screenshot or `preview.start` call.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate the current session in place, wait for its exact project version, and normally reload the route. The server and browser remain alive. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running generated site without starting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baLine truncated
} as const;
+8 -8
View File
@@ -100,7 +100,7 @@ MCP lets agents work on one configured Webstudio project. Agents can:
- Update page metadata, SEO fields, auth settings, and marketplace metadata.
- Insert components and styled JSX sections.
- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.
- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.
- Move, copy, wrap, unwrap, convert, rename, retag, and delete instances.
- Update text, rich text, props, bindings, and actions.
- Create and update local styles, design tokens, style sources, and CSS variables.
- Create static data variables and JSON variables.
@@ -406,13 +406,13 @@ Commands:
- MCP tool: delete-folder {"folderId":"<folderId>"}
## List element instances
## List instances
Commands:
- MCP tool: list-instances {"pagePath":"/","maxDepth":3}
## Inspect one element instance
## Inspect one instance
Commands:
@@ -457,7 +457,7 @@ Notes:
- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.
- Put reusable insertable options inside exactly one direct `ws:block-template` child. A missing or second template container makes the Content Block invalid. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.
- Before implementation, inventory every editor-owned field and its intended control and write destination, whether or not the block uses MDX. Check that templates contain the required styling, but do not treat containment or a successful text edit as proof that the whole block is editable. Test every field through Content mode, inspect its saved project data or source file, reload, and restore the original value. Report passed, failed, or not tested for each field; missing or read-only required controls are unfinished requirements.
- Use controls that match the content: a calendar for dates and an image picker for image replacement. Keep fixed punctuation and units out of directly bound value elements. Preserve stored types and wording: when reading time is already a complete string such as `4 min read`, bind that string directly rather than assuming it is a number.
- 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 instances. Preserve stored types and wording: when reading time is already a complete string such as `4 min read`, bind that string directly rather than assuming it is a number.
- For MDX-backed blocks, containment alone is not enough: the MDX body is editable through its source mapping, but the designed shell needs writable document-frontmatter bindings. Follow the binding recipe below rather than binding editable article fields to query results.
## Store Content Block content in MDX
@@ -514,7 +514,7 @@ Notes:
- Create writable bindings explicitly; the default is read-only. Merely moving a heading or Link inside the Content Block does not make its query-bound text editable.
- The MDX body uses its source mapping. Static designed content outside that body remains protected unless its text or supported props bind to writable frontmatter fields. Do not apply these generic instance tools to MDX-generated instances.
- Use direct static paths. Property access is already safe. Fallbacks and formatted expressions, such as `document.frontmatter.title ?? "Untitled"`, remain read-only.
- Keep every intended editable value in its own text element with a single direct read-write binding. For reading time, use three inline siblings: static `— `, the bound reading-time value, and static ` min read`. Preserve whitespace and the stored field type. Do not combine them into a template literal or concatenate strings, and do not put literal siblings inside the value element itself. Keep fixed wording protected in the designed shell.
- Keep every intended editable value in its own text instance 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 bound instance. Keep fixed wording protected in the designed shell.
- Prefer component formatting controls, such as Date Time formatting with a directly bound date prop, over transforming the expression. Do not silently sacrifice editability for formatting or a fallback; explain unsupported cases and ask before making an intended editable field read-only.
- A direct writable binding such as `document.frontmatter.author.name` can edit a shared author loaded through `../authors/acme.md#frontmatter`. The edit saves to the author file and affects every article using it; preserve the article's `$ref` marker.
- Before handoff, inventory every article-owned field, including header text, author details, dates, reading time, categories, hero and inline image sources, alternative text, captions, links, and custom-component content. For each field, inspect its binding and source, edit it through the Content-mode UI, verify the saved MDX or referenced file, reload, and restore the test value. Record passed, failed, or not tested for each field. A correct preview, a successful MCP write, and one representative text edit do not prove the whole article is editable. Do not claim completion while required fields fail or remain untested.
@@ -538,7 +538,7 @@ Notes:
- If the picker is missing or disabled, inspect the source mode, document scope, loaded reference, and permissions before claiming a product limitation.
- Verify through Content mode with an approved temporary replacement. Check the saved `$ref`, unchanged unrelated MDX and original shared Asset, reload persistence, and restoration. If that test is not authorized, report it as not tested, not passed.
## Move elements
## Move instances
Commands:
@@ -550,13 +550,13 @@ Notes:
- 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.
- Moves in one `moves` array are applied sequentially in array order.
## Clone element subtree
## Clone an instance subtree
Commands:
- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}
## Delete element subtree
## Delete an instance subtree
Commands:
+4 -4
View File
@@ -61,7 +61,7 @@ searches asset metadata, not asset binaries or document contents.
For a short end-consumer summary of what MCP can do, see
`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same
project, page, element, style, data, asset, publish, domain, and visual
project, page, instance, style, data, asset, publish, domain, and visual
verification capabilities without internal command names.
### Top-Level Commands
@@ -125,8 +125,8 @@ Supported namespaces:
- pages: redirects, page records, and folders
- projectSettings: project-wide metadata and compiler settings
- instances: element instances and children, including text/expression children
- props: element props, bindings, page references, resource bindings
- instances: component instances and children, including text/expression children
- props: instance props, bindings, page references, resource bindings
- styles: CSS declarations keyed by style declaration key
- styleSources: local style sources and reusable design tokens
- styleSourceSelections: instance-to-style-source connections
@@ -258,7 +258,7 @@ Update page title metadata:
}
]
Update a text child on an element:
Update a text child on an instance:
[
{
+2 -2
View File
@@ -100,7 +100,7 @@ For an editable MDX article, use the resource to select the Content Block's sour
### Content Block completion checklist
For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.
For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value instance; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.
### Complete article editability is required
@@ -115,7 +115,7 @@ Before handoff:
**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.
Keep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.
Keep intended editable values separate from display formatting. For reading time, use three inline sibling text instances: static `— `, one instance bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The bound instance must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.
Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.
+5 -5
View File
@@ -230,7 +230,7 @@ For an editable MDX article, use the resource to select the Content Block's sour
### Content Block completion checklist
For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.
For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value instance; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.
### Complete article editability is required
@@ -245,7 +245,7 @@ Before handoff:
**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.
Keep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.
Keep intended editable values separate from display formatting. For reading time, use three inline sibling text instances: static `— `, one instance bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The bound instance must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.
If an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.
@@ -408,15 +408,15 @@ terms, agents can:
- Read and update marketplace product metadata.
- List, create, update, delete, and replace redirects.
- List, create, update, and delete responsive breakpoints.
- List and inspect page elements.
- List and inspect instances on a page.
- Insert registered components.
- Insert styled JSX fragments.
- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.
- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete instances.
- Fill grid cells.
- List and update text children.
- Update plain text and expression text.
- Update structured rich text.
- Add, update, delete, and bind element props.
- Add, update, delete, and bind instance props.
- Bind props to expressions, resources, actions, and runtime system values.
- Read, add, update, delete, and replace local styles.
- Update selected style-source styles.
@@ -37,7 +37,7 @@ For an editable MDX article, use the resource to select the Content Block's sour
### Content Block completion checklist
For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.
For every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value instance; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.
### Complete article editability is required
@@ -52,7 +52,7 @@ Before handoff:
**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.
Keep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.
Keep intended editable values separate from display formatting. For reading time, use three inline sibling text instances: static `— `, one instance bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The bound instance must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.
Run it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.
+1 -1
View File
@@ -2617,7 +2617,7 @@ describe("project session mcp adapter", () => {
input: { instanceId: "body" },
})
).rejects.toThrow(
"list-instances input.instanceId is not supported. Expected one of: rootInstanceId, maxDepth. Did you mean rootInstanceId? Use rootInstanceId to list a subtree, or inspect-instance to inspect one element."
"list-instances input.instanceId is not supported. Expected one of: rootInstanceId, maxDepth. Did you mean rootInstanceId? Use rootInstanceId to list a subtree, or inspect-instance to inspect one instance."
);
expect(executeOperation).not.toHaveBeenCalled();
+5 -5
View File
@@ -1069,7 +1069,7 @@ const getUnsupportedInputFieldHint = ({
return " Use get-page/get-page-by-path for page metadata, list-instances to inspect page root contents, and inspect-instance for props, styles, children, bindings, or sources.";
}
if (command === "list-instances" && field === "instanceId") {
return " Use rootInstanceId to list a subtree, or inspect-instance to inspect one element.";
return " Use rootInstanceId to list a subtree, or inspect-instance to inspect one instance.";
}
return "";
};
@@ -4572,7 +4572,7 @@ const capabilityAreas = [
},
{
area: "content",
goal: "Inspect and edit element instances, text, props, bindings, and page content.",
goal: "Inspect and edit instances, text, props, bindings, and page content.",
tools: [
"list-instances",
"inspect-instance",
@@ -5627,7 +5627,7 @@ const animationComponentGuidanceByComponent = new Map<string, string>([
'Each animation needs keyframes; timing is optional and defaults to {}. In keyframes[].styles, use CSS property names with raw CSS strings such as transform:"translateX(-75%)"; update-props parses them into Webstudio style data. Timing can use rangeStart/rangeEnd, fill, easing, duration, delay, and iterations. Duration makes Range End unnecessary because duration defines when the animation ends.',
'Use fill:"backwards" for in animations from animation styles to canvas styles, and fill:"forwards" for out animations from canvas styles to animation styles.',
"Direct child animations expose --index and --total to support staggered formulas such as calc(var(--index) * 20%).",
"For polished pages, design the element's normal canvas styles as the final state, then set the Animation Group keyframes to the starting or ending animated state.",
"For polished pages, design the instance's normal canvas styles as the final state, then set the Animation Group keyframes to the starting or ending animated state.",
].join(" "),
],
[
@@ -7198,7 +7198,7 @@ const metaGoalGuides = [
"Do not call meta.index after this guide. If an exact mutation schema is still needed, make at most one meta.get-more-tools call listing all immediately required authoring tools rather than rediscovering them one at a time.",
"Never place credentials, service-role keys, refresh tokens, private session values, or authenticated response bodies in project data, command output, screenshots, agent instructions, or error reports. Ask the user to configure secrets in the provider/server environment.",
"Keep all four auth states in the editable component structure even when bindings select only one at runtime. Give each state a visible label using the exact terms signed-out, loading, signed-in, and failed-auth so authors can inspect and verify every state. Use page basic auth only when the user asks for Webstudio's fixed login/password gate; it is not Supabase or Firebase authentication.",
"Use focused resources and variables for public client configuration and session-shaped data. Keep authorization enforcement and privileged provider calls server-side; a hidden Builder element is not an authorization boundary.",
"Use focused resources and variables for public client configuration and session-shaped data. Keep authorization enforcement and privileged provider calls server-side; a hidden Builder instance is not an authorization boundary.",
"When fixture/session data must feed a resource, create the page and scoped fixture variables there. Use create-page's returned rootInstanceId directly instead of listing instances to rediscover it. Call list-variables after creation only when a resource expression actually needs the returned encoded name. Do not repeat list-variables when the fixture variable is not referenced, as in the expression-free state gallery, and do not guess or reference variables before they exist.",
"Create resources only after their scope and referenced variables exist. When reusing the discovered /api/auth/session convention, pass recipe.createResourceInput directly as the entire create-resource tool input, unchanged except for its account root id placeholder. Do not wrap it in another resource object. Keep every request field nested under resource. resource.url is the HTTP request target, not a provider call or session-state expression. Use literal wrappers only for fixed header, search-parameter, and body text.",
"Keep the server-mediated session resource as provider-convention evidence, but use only non-secret scoped fixture variables to drive local auth-state visibility. Do not bind that server-only resource into local preview rendering: its endpoint is intentionally absent locally and can recurse through the generated route.",
@@ -7271,7 +7271,7 @@ const metaGoalGuides = [
"Before the first mutation, call inspect-design-context exactly once instead of calling list-pages, list-breakpoints, list-design-tokens, list-assets, or list-variables separately. Use one list-instances call only when needed to inspect a representative existing page pattern. Do not call get-styles: the bounded design context and optional focused instance result provide the reusable design-system evidence needed here without risking an oversized style dump. Reuse exact existing values, breakpoint ids, and patterns; do not create a parallel design system from approximate screenshot colors or spacing.",
"Call create-page exactly once and use its returned rootInstanceId as the insertion parent. Insert the complete semantic page in one fragment when practical, and use the insertion result's instanceIds for follow-up token attachments. Do not call list-instances after the first mutation to rediscover ids already returned by mutations.",
"After insertion, call attach-design-token at least once with an exact existing style source id returned by inspect-design-context. Attach it where the shared typography, color, or other token is intended. Reusing only the token's current raw value creates a disconnected local copy.",
"Create semantic editable structure with insert-fragment-verified using only lowercase HTML elements and literal text. Do not include inline styles or ws:style in the fragment; apply fixed CSS with update-styles after insertion. Do not improvise component names, expression syntax, or object-valued style expressions. Use assets for real imagery and text or controls for real content; do not flatten the design into one image or absolute-position every element.",
"Create semantic editable structure with insert-fragment-verified using only lowercase HTML elements and literal text. Do not include inline styles or ws:style in the fragment; apply fixed CSS with update-styles after insertion. Do not improvise component names, expression syntax, or object-valued style expressions. Use assets for real imagery and text or controls for real content; do not flatten the design into one image or absolute-position every instance.",
"Implement responsive behavior inside the project's actual breakpoint ranges.",
'Represent literal CSS values as {"type":"keyword","value":"..."}, including lengths such as "48px" and colors such as "#fff". Do not invent value types such as "length"; use {"type":"unit","value":48,"unit":"px"} only when numeric structure is specifically needed.',
"Each update-styles updates item is flat: include instanceId, property, value, and optional breakpoint directly on every item. Do not group properties under styles or declarations.",
+2 -2
View File
@@ -878,7 +878,7 @@ export const auditRules = {
"unused-design-token": rule(
"styles",
"info",
"The design token is not assigned to any element.",
"The design token is not assigned to any instance.",
"Apply the token or remove it."
),
"unused-css-variable": rule(
@@ -890,7 +890,7 @@ export const auditRules = {
"unused-local-style-source": rule(
"styles",
"info",
"The local style source has declarations but no element assignment.",
"The local style source has declarations but is not assigned to any instance.",
"Assign the style source or remove it."
),
"unused-breakpoint": rule(
@@ -82,7 +82,7 @@ const getItemRootInstanceId = (fragment: WebstudioFragment) => {
) {
return throwBuilderRuntimeError(
"BAD_REQUEST",
"Collection itemFragment must contain exactly one root instance. Wrap repeated sibling elements in one lowercase HTML element or registered component."
"Collection itemFragment must contain exactly one root instance. Wrap repeated sibling instances in one lowercase HTML element or registered component."
);
}
const instances = new Map(
@@ -485,6 +485,13 @@ test("blocks publishing when required audit input is unavailable", () => {
test("includes existing resource integrity checks in the audit pipeline", () => {
const { instances, props } = renderData(<Body ws:id="body"></Body>);
props.set("resource-prop", {
id: "resource-prop",
instanceId: "body",
name: "data",
type: "resource",
value: "missing-prop-resource",
});
const findings = runPrePublishAudit({
pages: createPages(marketEdgePage),
instances,
@@ -514,9 +521,21 @@ test("includes existing resource integrity checks in the audit pipeline", () =>
'resource variable "Products" (resource-variable) references missing resource "missing-resource".',
location: {
dataSourceId: "resource-variable",
instanceId: "body",
resourceId: "missing-resource",
},
},
{
ruleId: "resource-integrity",
severity: "error",
message:
'prop "data" (resource-prop) references missing resource "missing-prop-resource".',
location: {
propId: "resource-prop",
resourceId: "missing-prop-resource",
instanceId: "body",
},
},
]);
});
@@ -119,37 +119,48 @@ const checkBuildIntegrity: PrePublishAuditCheck = ({
resources: resources.values(),
instances: instances.values(),
assets: assets.values(),
}).map((issue) => ({
ruleId:
issue.type === "missingResource"
? "resource-integrity"
: issue.type === "slotInContentBlockTemplates"
? "content-block-template-integrity"
: "content-block-source-integrity",
severity: "error",
message: formatBuildIntegrityIssue(issue),
location: {
...(issue.type === "missingResource"
? {
...(issue.source === "dataSource"
? { dataSourceId: issue.dataSourceId }
: { propId: issue.propId }),
resourceId: issue.resourceId,
}
: issue.type === "slotInContentBlockTemplates"
? { instanceId: issue.instanceId }
: {
instanceId: issue.blockInstanceId,
...(issue.type === "duplicateContentBlockSource"
? { propId: issue.propIds[0] }
}).map((issue) => {
const instanceId =
issue.type !== "missingResource"
? undefined
: issue.source === "dataSource"
? dataSources.get(issue.dataSourceId)?.scopeInstanceId
: props.get(issue.propId)?.instanceId;
return {
ruleId:
issue.type === "missingResource"
? "resource-integrity"
: issue.type === "slotInContentBlockTemplates"
? "content-block-template-integrity"
: "content-block-source-integrity",
severity: "error",
message: formatBuildIntegrityIssue(issue),
location: {
...(issue.type === "missingResource"
? {
...(issue.source === "dataSource"
? { dataSourceId: issue.dataSourceId }
: { propId: issue.propId }),
...(issue.type === "missingContentBlockSourceAsset" ||
issue.type === "incompatibleContentBlockSourceAsset"
? { assetId: issue.assetId }
resourceId: issue.resourceId,
...(instanceId !== undefined && instances.has(instanceId)
? { instanceId }
: {}),
}),
},
}));
}
: issue.type === "slotInContentBlockTemplates"
? { instanceId: issue.instanceId }
: {
instanceId: issue.blockInstanceId,
...(issue.type === "duplicateContentBlockSource"
? { propId: issue.propIds[0] }
: { propId: issue.propId }),
...(issue.type === "missingContentBlockSourceAsset" ||
issue.type === "incompatibleContentBlockSourceAsset"
? { assetId: issue.assetId }
: {}),
}),
},
};
});
const checkJsonPropValues: PrePublishAuditCheck = ({ props, instances }) =>
[...props.values()]
+2 -2
View File
@@ -552,7 +552,7 @@ export const analyzeProject = (
declarationCount: token.declarationCount,
usageCount: token.usageCount,
...(input.query === undefined
? { message: "Design token has no element assignments." }
? { message: "Design token is not used by any instances." }
: {}),
});
}
@@ -635,7 +635,7 @@ export const analyzeProject = (
styleSourceId: styleSource.id,
declarationCount,
message:
"Local style source has declarations but is not assigned to any element.",
"Local style source has declarations but is not assigned to any instance.",
});
}
@@ -299,13 +299,13 @@ const curatedPublicApiOperationDocumentation = [
{
command: "list-instances",
description:
"List element instances in the build tree, including parent id and index when known",
"List instances in the build tree, including parent id and index when known",
examples: ["webstudio list-instances --path / --max-depth 2 --json"],
},
{
command: "inspect-instance",
description:
"Show one element with its classes and custom attributes by default. Include styles, children, bindings, sources, and ancestors as needed",
"Show one instance with its classes and custom attributes by default. Include styles, children, bindings, sources, and ancestors as needed",
requiredOptions: ["instance", "json"],
examples: [
"webstudio inspect-instance --instance instance-id --include props,styles,children,ancestors --json",
@@ -387,14 +387,14 @@ const curatedPublicApiOperationDocumentation = [
},
{
command: "move-instance",
description: "Move element instances to another parent or position",
description: "Move instances to another parent or position",
examples: [
'MCP tool: move-instance {"moves":[{"instanceId":"instance-id","parentInstanceId":"parent-id","insertIndex":0}]}',
],
},
{
command: "clone-instance",
description: "Clone an element instance subtree",
description: "Clone an instance subtree",
requiredOptions: ["source", "json"],
examples: [
"webstudio clone-instance --source instance-id --parent parent-id --json",
@@ -402,28 +402,28 @@ const curatedPublicApiOperationDocumentation = [
},
{
command: "delete-instance",
description: "Delete element instance subtrees",
description: "Delete instance subtrees",
requiredOptions: ["instance", "json"],
examples: ["webstudio delete-instance --instance instance-id --json"],
},
{
command: "update-props",
description:
'Create or update direct element prop values; match value to type, for example textarea placeholder uses { "name": "placeholder", "type": "string", "value": "..." }. Use this for fixed strings, numbers, booleans, JSON, assets, and pages. Parameters are internal scoped runtime values, not a public authoring surface. Editor tokens are limited to content-mode props',
'Create or update direct instance prop values; match value to type, for example textarea placeholder uses { "name": "placeholder", "type": "string", "value": "..." }. Use this for fixed strings, numbers, booleans, JSON, assets, and pages. Parameters are internal scoped runtime values, not a public authoring surface. Editor tokens are limited to content-mode props',
requiredOptions: ["input", "json"],
examples: ["webstudio update-props --input props.json --json"],
},
{
command: "delete-props",
description:
"Delete element props by instance and prop name; editor tokens are limited to content-mode props",
"Delete props by instance and prop name; editor tokens are limited to content-mode props",
requiredOptions: ["input", "json"],
examples: ["webstudio delete-props --input props.json --json"],
},
{
command: "bind-props",
description:
"Bind element props to dynamic expressions, resources, actions, or existing scoped runtime context such as system. Do not create parameter records, and do not use bindings for fixed string values; use update-props instead",
"Bind instance props to dynamic expressions, resources, actions, or existing scoped runtime context such as system. Do not create parameter records, and do not use bindings for fixed string values; use update-props instead",
requiredOptions: ["input", "json"],
examples: ["webstudio bind-props --input bindings.json --json"],
},
@@ -435,7 +435,7 @@ const curatedPublicApiOperationDocumentation = [
{
command: "update-text",
description:
'Update a text or expression child on an element instance; mode must be "text" or "expression" when provided, never "replace"; editor tokens are limited to content-mode text',
'Update a text or expression child on an instance; mode must be "text" or "expression" when provided, never "replace"; editor tokens are limited to content-mode text',
requiredOptions: ["instance", "child-index", "text", "json"],
examples: [
'webstudio update-text --instance instance-id --child-index 0 --text "Launch faster" --mode text --json',
@@ -445,7 +445,7 @@ const curatedPublicApiOperationDocumentation = [
{
command: "set-text-content",
description:
'Replace all text content on an element instance with operation "set", or remove it with operation "reset"',
'Replace all text content on an instance with operation "set", or remove it with operation "reset"',
examples: [
'MCP tool: set-text-content {"operation":"set","instanceId":"instance-id","text":"Launch faster","mode":"text"}',
'MCP tool: set-text-content {"operation":"reset","instanceId":"instance-id"}',
@@ -556,7 +556,7 @@ const curatedPublicApiOperationDocumentation = [
},
{
command: "attach-design-token",
description: "Attach a reusable style token to element instances",
description: "Attach a reusable style token to instances",
requiredOptions: ["design-token", "input", "json"],
examples: [
"webstudio attach-design-token --design-token token-id --input instances.json --json",
@@ -564,7 +564,7 @@ const curatedPublicApiOperationDocumentation = [
},
{
command: "detach-design-token",
description: "Detach a reusable style token from element instances",
description: "Detach a reusable style token from instances",
requiredOptions: ["design-token", "input", "json"],
examples: [
"webstudio detach-design-token --design-token token-id --input instances.json --json",
@@ -615,7 +615,7 @@ const curatedPublicApiOperationDocumentation = [
{
command: "create-variable",
description:
"Create a data variable scoped to an element instance. Use string, number, boolean, string[], or json values.",
"Create a data variable scoped to an instance. Use string, number, boolean, string[], or json values.",
requiredOptions: ["scope-instance", "name", "value-type", "value", "json"],
examples: [
'webstudio create-variable --scope-instance body-id --name title --value-type string --value "Hello" --json',