diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index e78aa22422..2fe8acedf7 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -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(() => {
diff --git a/apps/builder/app/builder/features/publish/diagnostics.test.tsx b/apps/builder/app/builder/features/publish/diagnostics.test.tsx
index d7a4a929ab..f40746fc65 100644
--- a/apps/builder/app/builder/features/publish/diagnostics.test.tsx
+++ b/apps/builder/app/builder/features/publish/diagnostics.test.tsx
@@ -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: ,
+ link: ,
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: Show element,
- reportText: "Invalid element",
+ title: "Invalid instance",
+ link: Show instance,
+ reportText: "Invalid instance",
},
],
{ open: true, initialTab: "errors", onOpenChange }
);
- const link =
- document.body.querySelector('a[href="#element"]');
+ const link = document.body.querySelector(
+ '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: Show element,
- reportText: "Invalid element",
+ title: "Invalid instance",
+ link: Show instance,
+ reportText: "Invalid instance",
},
],
{ open: true, initialTab: "errors", onOpenChange }
);
- const link =
- document.body.querySelector('a[href="#element"]');
+ const link = document.body.querySelector(
+ 'a[href="#instance"]'
+ );
expect(link).not.toBeNull();
act(() => {
link?.dispatchEvent(
diff --git a/apps/builder/app/builder/features/publish/diagnostics.tsx b/apps/builder/app/builder/features/publish/diagnostics.tsx
index a8f201c981..1ec74332ed 100644
--- a/apps/builder/app/builder/features/publish/diagnostics.tsx
+++ b/apps/builder/app/builder/features/publish/diagnostics.tsx
@@ -113,9 +113,9 @@ const FindingList = ({
{findings.map((finding, index) => (
- {finding.source !== "publish" && (
+ {finding.source === "build" && (
- {finding.source === "build" ? "Build" : "Audit"}
+ Build
)}
{finding.source === "publish" ? (
diff --git a/apps/builder/app/builder/features/publish/publish-click.render.test.tsx b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx
index dac32c429e..8a4e15b437 100644
--- a/apps/builder/app/builder/features/publish/publish-click.render.test.tsx
+++ b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx
@@ -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;
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;
@@ -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(
'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(
+
+
+
+
+ Heading in button
+
+
+
+ );
+ 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(
+ 'input[name="domainToPublish[]"]'
+ );
+ if (domain?.checked === false) {
+ await act(async () =>
+ document.body.querySelector('[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")
+ );
+ expect(document.body.textContent).toContain("1 error · 1 warning");
+
+ const seeIssues = Array.from(
+ document.body.querySelectorAll("button")
+ ).find((button) => button.textContent?.trim() === "See issues");
+ await act(async () => seeIssues?.click());
+
+ const link = Array.from(
+ document.body.querySelectorAll("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('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();
+ 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(
+ 'input[name="domainToPublish[]"]'
+ );
+ if (domain?.checked === false) {
+ await act(async () =>
+ document.body.querySelector('[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(
+ '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([
diff --git a/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx b/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx
index 7988e37b90..55b50db683 100644
--- a/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx
+++ b/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx
@@ -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) => {
diff --git a/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx b/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx
index 4d361b7812..23de35864b 100644
--- a/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx
+++ b/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx
@@ -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": () => ({
diff --git a/apps/builder/app/builder/features/publish/publish-session.render.test.tsx b/apps/builder/app/builder/features/publish/publish-session.render.test.tsx
index cb10e5f84e..adf265ad19 100644
--- a/apps/builder/app/builder/features/publish/publish-session.render.test.tsx
+++ b/apps/builder/app/builder/features/publish/publish-session.render.test.tsx
@@ -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();
diff --git a/apps/builder/app/builder/features/publish/publish-validation.tsx b/apps/builder/app/builder/features/publish/publish-validation.tsx
index 9a9ce35402..95fc821116 100644
--- a/apps/builder/app/builder/features/publish/publish-validation.tsx
+++ b/apps/builder/app/builder/features/publish/publish-validation.tsx
@@ -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>;
}) => {
- const target = getPrePublishInstanceTarget(
- instanceId,
- pageId,
- instanceSelector
- );
- if (target === undefined) {
- return null;
- }
return (
- {children}
+ Show instance
);
};
@@ -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 : (
-
- Show element
-
+ target === undefined ? undefined : (
+
),
- 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 : (
-
- Open Content Block
-
- ),
- })
+ (finding) => {
+ const target = getPrePublishInstanceTarget(
+ { instanceId: finding.relatedInstanceId },
+ "settings"
+ );
+ return {
+ ...finding,
+ link:
+ target === undefined ? undefined : (
+
+ ),
+ };
+ }
);
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)}
-
- Webstudio MCP
-
- {message.slice(mcpUrlIndex + mcpUrl.length)}
- >
- );
+ const details = hideDetails ? undefined : mcpUrlIndex === -1 ? (
+ message
+ ) : (
+ <>
+ {message.slice(0, mcpUrlIndex)}
+
+ Webstudio MCP
+
+ {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}`,
},
]);
};
diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.test.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.test.tsx
index 4065e693d3..9cde0994e2 100644
--- a/apps/builder/app/builder/features/settings-panel/variables-section.test.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variables-section.test.tsx
@@ -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(
+
+
+
+ )
+ );
+ const trigger = container.querySelector(
+ '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" }));
diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsx
index 7288369edd..6a602d6ace 100644
--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx
@@ -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(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={
diff --git a/apps/builder/app/builder/shared/nano-states.ts b/apps/builder/app/builder/shared/nano-states.ts
index d1a9f42e68..6f0d51f0ed 100644
--- a/apps/builder/app/builder/shared/nano-states.ts
+++ b/apps/builder/app/builder/shared/nano-states.ts
@@ -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(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");
diff --git a/apps/builder/app/canvas/features/text-editor/interop.test.tsx b/apps/builder/app/canvas/features/text-editor/interop.test.tsx
index fd4b15254d..d632e47715 100644
--- a/apps/builder/app/canvas/features/text-editor/interop.test.tsx
+++ b/apps/builder/app/canvas/features/text-editor/interop.test.tsx
@@ -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}`;
diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.ts
index 3dce746732..23aabbaad6 100644
--- a/apps/builder/app/services/api-router.server.test.ts
+++ b/apps/builder/app/services/api-router.server.test.ts
@@ -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();
});
diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.ts
index c93d01069e..d3f5cb9a98 100644
--- a/apps/builder/app/services/api-router.server.ts
+++ b/apps/builder/app/services/api-router.server.ts
@@ -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>;
- 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,
-};
diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.ts
index 62eff5ba73..f324d3ff2b 100644
--- a/apps/builder/app/services/build-router.server.ts
+++ b/apps/builder/app/services/build-router.server.ts
@@ -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 }) => {
diff --git a/apps/builder/app/services/publish-validation.server.ts b/apps/builder/app/services/publish-validation.server.ts
new file mode 100644
index 0000000000..a9c42bd3a0
--- /dev/null
+++ b/apps/builder/app/services/publish-validation.server.ts
@@ -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> };
+
+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;
+}) => {
+ 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,
+ };
+};
diff --git a/apps/builder/app/shared/instance-utils/link.ts b/apps/builder/app/shared/instance-utils/link.ts
index 23c40b0fa9..96a2d7a596 100644
--- a/apps/builder/app/shared/instance-utils/link.ts
+++ b/apps/builder/app/shared/instance-utils/link.ts
@@ -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)
diff --git a/apps/builder/app/shared/pages/use-switch-page-history.browser.test.tsx b/apps/builder/app/shared/pages/use-switch-page-history.browser.test.tsx
index 9917be62f1..a97f5adb33 100644
--- a/apps/builder/app/shared/pages/use-switch-page-history.browser.test.tsx
+++ b/apps/builder/app/shared/pages/use-switch-page-history.browser.test.tsx
@@ -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;
}) => Promise,
- 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(
+ <>
+
+
+
+
+ >
+ ).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 && ;
};
@@ -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();
diff --git a/apps/builder/app/shared/pages/use-switch-page.ts b/apps/builder/app/shared/pages/use-switch-page.ts
index 14ad52d962..b0fb893917 100644
--- a/apps/builder/app/shared/pages/use-switch-page.ts
+++ b/apps/builder/app/shared/pages/use-switch-page.ts
@@ -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();
diff --git a/apps/builder/app/shared/router-utils/path-utils.test.ts b/apps/builder/app/shared/router-utils/path-utils.test.ts
index 45227ba823..0d23abcd26 100644
--- a/apps/builder/app/shared/router-utils/path-utils.test.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.test.ts
@@ -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();
+});
diff --git a/apps/builder/app/shared/router-utils/path-utils.ts b/apps/builder/app/shared/router-utils/path-utils.ts
index b2c17ba678..0ee2792fa4 100644
--- a/apps/builder/app/shared/router-utils/path-utils.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.ts
@@ -14,6 +14,15 @@ const searchParams = (params: Record) => {
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);
diff --git a/docs/university/foundations/navigator.md b/docs/university/foundations/navigator.md
index eb8d850d11..2166f58e5e 100644
--- a/docs/university/foundations/navigator.md
+++ b/docs/university/foundations/navigator.md
@@ -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.
diff --git a/docs/university/foundations/publishing-and-custom-domains.md b/docs/university/foundations/publishing-and-custom-domains.md
index 35f738582b..facc3fb9de 100644
--- a/docs/university/foundations/publishing-and-custom-domains.md
+++ b/docs/university/foundations/publishing-and-custom-domains.md
@@ -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
diff --git a/docs/university/mcp.md b/docs/university/mcp.md
index 18add97c95..762c2a472b 100644
--- a/docs/university/mcp.md
+++ b/docs/university/mcp.md
@@ -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.
diff --git a/packages/cli/src/commands/man.ts b/packages/cli/src/commands/man.ts
index 3ee28822ae..8a18656eac 100644
--- a/packages/cli/src/commands/man.ts
+++ b/packages/cli/src/commands/man.ts
@@ -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",
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 56850f95bb..c470e1da5f 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -2,15 +2,15 @@
// Edit markdown files in src/docs instead.
export const cliDocs = {
"api-use-cases":
- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link --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 \n- MCP tool: import {"to":""}\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 `. 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 \'\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call \'\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Enter this workflow only when the user explicitly requests visual verification or opts in after being asked. Do not start preview, screenshots, diffs, OCR, or rendered audits automatically after a mutation.\n- `preview.status` reports whether generated output is `stale`. When no preview is running, `url`, `pid`, and `mode` are omitted. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- MCP preview and path-based screenshot tools select an available loopback port and return the preview URL. Do not pass `host` or `port`.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- After opt-in, use this so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Calling `preview.start` after a committed mutation restarts a stale iterative server so external browsers and HTTP clients receive the newly generated project.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- When launcher metadata is available, Preview reuses a supported npm or pnpm launcher. Without launcher metadata, it uses npm when available and otherwise falls back to pnpm.\n- Unless `npm_config_cache` is already configured, npm uses the writable `.webstudio/preview/.npm-cache` directory.\n- For npm cache permission errors, unset `npm_config_cache` to use the preview-local cache, then retry. No cache deletion is required.\n- If dependency installation fails, check the reported package-manager path and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":""}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"\\"Pricing\\"","meta":{"description":"\\"Plans for teams\\""}}\n\nNotes:\n\n- `name` and `path` are plain values. Page `title` and metadata text fields contain expression source; quote fixed text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- CLI flags such as `--title` treat values as fixed text. Add `--expressions` to `webstudio create-page` when passing expression source through these flags; quote any fixed text in the same call as a JavaScript string expression.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"","values":{"title":"\\"Pricing\\"","meta":{"description":"\\"Plans\\"","status":200}}}\n- MCP tool: update-page {"pageId":"","values":{"meta":{"auth":{"method":"basic","login":"","password":""}}}}\n\nNotes:\n\n- For fixed page `title` and metadata text, quote the text as a JavaScript string literal inside the JSON string.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`. An unquoted word is a variable reference.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n- For `webstudio update-page`, add `--expressions` when page title or metadata flags contain expression source. Without it, those flags are fixed text.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"hello@example.com","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"","author":"Acme Studio","email":"hello@example.com","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"\\"Landing\\""}\n\nCLI `create-page-template` and `update-page-template` use fixed text flags by default. Add `--expressions` when passing expression source through title or metadata flags.\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":""}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":""}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"","targetTemplateId":"","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":""}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":""}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"","fragment":"
Product OS
"}\n- MCP tool: insert-component {"parentInstanceId":"","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"","component":"ResourceForm"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- Use lowercase HTML JSX such as `