Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

fix: harden MCP mutations and validation (#6402)

Oleg Isonen0d448313ab19
diff --git a/apps/builder/app/builder/features/pages/page-utils.test.ts b/apps/builder/app/builder/features/pages/page-utils.test.ts
index a2b2468fb5..096fc18658 100644
--- a/apps/builder/app/builder/features/pages/page-utils.test.ts
+++ b/apps/builder/app/builder/features/pages/page-utils.test.ts
@@ -267,48 +267,28 @@ test("page root scope should provide page system variable value", () => {
expect($pageRootScope.get()).toEqual({
aliases: new Map([["$ws$dataSource$systemId", "system"]]),
scope: {
- $ws$dataSource$systemId: {
- origin: "https://undefined.wstd.work",
- params: {},
- pathname: "/",
- search: {},
- },
+ $ws$dataSource$systemId: initialSystem,
},
variableValues: new Map([
- [
- "systemId",
- {
- params: {},
- pathname: "/",
- search: {},
- origin: "https://undefined.wstd.work",
- },
- ],
+ [SYSTEM_VARIABLE_ID, initialSystem],
+ ["systemId", initialSystem],
]),
});
- updateCurrentSystem({
+ const updatedSystem = {
+ ...initialSystem,
params: { slug: "my-post" },
+ };
+ updateCurrentSystem({
+ params: updatedSystem.params,
});
expect($pageRootScope.get()).toEqual({
aliases: new Map([["$ws$dataSource$systemId", "system"]]),
scope: {
- $ws$dataSource$systemId: {
- params: { slug: "my-post" },
- pathname: "/",
- search: {},
- origin: "https://undefined.wstd.work",
- },
+ $ws$dataSource$systemId: updatedSystem,
},
variableValues: new Map([
- [
- "systemId",
- {
- params: { slug: "my-post" },
- pathname: "/",
- search: {},
- origin: "https://undefined.wstd.work",
- },
- ],
+ [SYSTEM_VARIABLE_ID, updatedSystem],
+ ["systemId", updatedSystem],
]),
});
});
diff --git a/apps/builder/app/builder/features/pages/page-utils.ts b/apps/builder/app/builder/features/pages/page-utils.ts
index 51769b1afb..b217a3ada9 100644
--- a/apps/builder/app/builder/features/pages/page-utils.ts
+++ b/apps/builder/app/builder/features/pages/page-utils.ts
@@ -35,7 +35,8 @@ export const $pageRootScope = computed(
variableValuesByInstanceSelector.get(
getInstanceKey([page.rootInstanceId, ROOT_INSTANCE_ID])
) ?? new Map<string, unknown>();
- for (const [dataSourceId, value] of values) {
+ const visibleDataSourceIdByName = new Map<string, string>();
+ for (const dataSourceId of values.keys()) {
let dataSource = dataSources.get(dataSourceId);
if (dataSourceId === SYSTEM_VARIABLE_ID) {
dataSource = systemParameter;
@@ -43,6 +44,17 @@ export const $pageRootScope = computed(
if (dataSource === undefined) {
continue;
}
+ visibleDataSourceIdByName.set(dataSource.name, dataSourceId);
+ }
+ for (const dataSourceId of visibleDataSourceIdByName.values()) {
+ const value = values.get(dataSourceId);
+ const dataSource =
+ dataSourceId === SYSTEM_VARIABLE_ID
+ ? systemParameter
+ : dataSources.get(dataSourceId);
+ if (dataSource === undefined) {
+ continue;
+ }
const name = encodeDataSourceVariable(dataSourceId);
scope[name] = value;
aliases.set(name, dataSource.name);
diff --git a/apps/builder/app/canvas/elements.test.tsx b/apps/builder/app/canvas/elements.test.tsx
new file mode 100644
index 0000000000..d666cf33dc
--- /dev/null
+++ b/apps/builder/app/canvas/elements.test.tsx
@@ -0,0 +1,44 @@
+import { forwardRef } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { expect, test } from "vitest";
+import type { Instance } from "@webstudio-is/sdk";
+import type { Components } from "@webstudio-is/react-sdk";
+import {
+ createInstanceChildrenElements,
+ type WebstudioComponentProps,
+} from "./elements";
+
+test("renders expression and instance siblings in order", () => {
+ const instances = new Map<string, Instance>([
+ [
+ "child",
+ {
+ id: "child",
+ type: "instance",
+ component: "Box",
+ children: [],
+ },
+ ],
+ ]);
+ const Component = forwardRef<HTMLElement, WebstudioComponentProps>(
+ ({ instance }, _ref) => <span>{instance.id}</span>
+ );
+ const children = createInstanceChildrenElements({
+ instances,
+ instanceSelector: ["parent"],
+ children: [
+ {
+ type: "expression",
+ value: '"Hello " + $ws$dataSource$name',
+ },
+ { type: "id", value: "child" },
+ ],
+ Component,
+ components: new Map() as Components,
+ variableValues: new Map([["name", "world"]]),
+ });
+
+ expect(renderToStaticMarkup(<>{children}</>)).toBe(
+ "Hello world<span>child</span>"
+ );
+});
diff --git a/apps/builder/app/canvas/elements.tsx b/apps/builder/app/canvas/elements.tsx
index 437955a8a0..c32723d903 100644
--- a/apps/builder/app/canvas/elements.tsx
+++ b/apps/builder/app/canvas/elements.tsx
@@ -7,7 +7,11 @@ import {
} from "react";
import type { Instance, Instances } from "@webstudio-is/sdk";
import type { Components } from "@webstudio-is/react-sdk";
-import type { InstanceSelector } from "@webstudio-is/project-build/runtime";
+import { renderText as renderTextValue } from "@webstudio-is/react-sdk/runtime";
+import {
+ computeExpression,
+ type InstanceSelector,
+} from "@webstudio-is/project-build/runtime";
export type WebstudioComponentProps = {
instance: Instance;
@@ -63,6 +67,7 @@ export const createInstanceChildrenElements = ({
children,
Component,
components,
+ variableValues = new Map(),
}: {
instances: Instances;
instanceSelector: InstanceSelector;
@@ -71,13 +76,15 @@ export const createInstanceChildrenElements = ({
WebstudioComponentProps & RefAttributes<HTMLElement>
>;
components: Components;
+ variableValues?: ReadonlyMap<string, unknown>;
}) => {
const elements = children.map((child) => {
if (child.type === "text") {
return renderText(child.value);
}
if (child.type === "expression") {
- return;
+ const value = computeExpression(child.value, variableValues);
+ return renderText(String(renderTextValue(value)));
}
if (child.type === "id") {
return createInstanceElement({
diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
index b674cfa1cb..f4ac10fc49 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -56,10 +56,12 @@ import {
getIndexedInstanceId,
$registeredComponentMetas,
$variableValuesByInstanceSelector,
+ $unscopedVariableValues,
$isDesignMode,
$selectedInstanceRenderState,
$selectedPageHash,
} from "~/shared/nano-states";
+import { getInstanceVariableValues } from "~/shared/instance-utils/variable-values";
import { $project, $props } from "~/shared/sync/data-stores";
import { $textEditingInstanceSelector } from "~/shared/nano-states";
import { $instances } from "~/shared/sync/data-stores";
@@ -696,6 +698,9 @@ const WebstudioComponentCanvasInner = forwardRef<
const { [showAttribute]: show = true, ...instanceProps } =
useInstanceProps(instanceSelector);
+ const hasExpressionChildren = instance.children.some(
+ (child) => child.type === "expression"
+ );
const children =
getTextContent(instanceProps) ??
@@ -705,6 +710,13 @@ const WebstudioComponentCanvasInner = forwardRef<
children: instance.children,
Component: WebstudioComponentCanvas,
components,
+ variableValues: hasExpressionChildren
+ ? getInstanceVariableValues(
+ $variableValuesByInstanceSelector.get(),
+ instanceSelector,
+ $unscopedVariableValues.get()
+ )
+ : undefined,
});
/**
* Prevents edited element from having a size of 0 on the first render.
@@ -767,6 +779,16 @@ const WebstudioComponentCanvasInner = forwardRef<
children: instance.children,
Component: WebstudioComponentCanvas,
components,
+ variableValues: hasExpressionChildren
+ ? getInstanceVariableValues(
+ $variableValuesByInstanceSelector.get(),
+ [
+ getIndexedInstanceId(instance.id, key),
+ ...instanceSelector,
+ ],
+ $unscopedVariableValues.get()
+ )
+ : undefined,
})}
</Fragment>
));
@@ -998,6 +1020,9 @@ const WebstudioComponentPreviewInner = forwardRef<
const { isSafeMode } = useContext(ReactSdkContext);
const { [showAttribute]: show = true, ...instanceProps } =
useInstanceProps(instanceSelector);
+ const hasExpressionChildren = instance.children.some(
+ (child) => child.type === "expression"
+ );
const props: {
[componentAttribute]: string;
[idAttribute]: string;
@@ -1033,6 +1058,16 @@ const WebstudioComponentPreviewInner = forwardRef<
children: instance.children,
Component: WebstudioComponentPreview,
components,
+ variableValues: hasExpressionChildren
+ ? getInstanceVariableValues(
+ $variableValuesByInstanceSelector.get(),
+ [
+ getIndexedInstanceId(instance.id, key),
+ ...instanceSelector,
+ ],
+ $unscopedVariableValues.get()
+ )
+ : undefined,
})}
</Fragment>
));
@@ -1090,6 +1125,13 @@ const WebstudioComponentPreviewInner = forwardRef<
children: instance.children,
Component: WebstudioComponentPreview,
components,
+ variableValues: hasExpressionChildren
+ ? getInstanceVariableValues(
+ $variableValuesByInstanceSelector.get(),
+ instanceSelector,
+ $unscopedVariableValues.get()
+ )
+ : undefined,
})}
</Component>
);
diff --git a/apps/builder/app/shared/content-block-source-utils.test.ts b/apps/builder/app/shared/content-block-source-utils.test.ts
index f2fd3e61b8..efc80c2654 100644
--- a/apps/builder/app/shared/content-block-source-utils.test.ts
+++ b/apps/builder/app/shared/content-block-source-utils.test.ts
@@ -1,7 +1,6 @@
import { describe, expect, test } from "vitest";
import { ROOT_INSTANCE_ID, type Instances } from "@webstudio-is/sdk";
import {
- getContentBlockOccurrenceVariableValues,
isRepeatedContentBlockOccurrence,
parseContentBlockRenderScope,
resolveContentBlockOccurrenceAssetId,
@@ -18,18 +17,11 @@ describe("Content Block occurrence source", () => {
expect(parseContentBlockRenderScope('["block",1]')).toBeUndefined();
});
- test("resolves the same direct and root-qualified variable scopes", () => {
+ test("resolves a root-qualified variable scope", () => {
const values = new Map([["asset", "article"]]);
- const direct = new Map([[JSON.stringify(selector), values]]);
const rootQualified = new Map([
[JSON.stringify([...selector, ROOT_INSTANCE_ID]), values],
]);
- expect(
- getContentBlockOccurrenceVariableValues({
- instanceSelector: selector,
- variableValuesByRenderScope: direct,
- })
- ).toBe(values);
expect(
resolveContentBlockOccurrenceAssetId({
source: { type: "expression", value: "asset" },
diff --git a/apps/builder/app/shared/content-block-source-utils.ts b/apps/builder/app/shared/content-block-source-utils.ts
index a853fb41cb..eee3fbb62f 100644
--- a/apps/builder/app/shared/content-block-source-utils.ts
+++ b/apps/builder/app/shared/content-block-source-utils.ts
@@ -5,11 +5,7 @@ import {
type Instances,
} from "@webstudio-is/sdk";
import type { InstanceSelector } from "@webstudio-is/project-build/runtime";
-
-type VariableValuesByRenderScope = ReadonlyMap<
- string,
- ReadonlyMap<string, unknown>
->;
+import { getInstanceVariableValues } from "./instance-utils/variable-values";
export const parseContentBlockRenderScope = (renderScope: string) => {
try {
@@ -26,18 +22,6 @@ export const parseContentBlockRenderScope = (renderScope: string) => {
}
};
-export const getContentBlockOccurrenceVariableValues = ({
- instanceSelector,
- variableValuesByRenderScope,
-}: {
- instanceSelector: InstanceSelector;
- variableValuesByRenderScope: VariableValuesByRenderScope;
-}) =>
- variableValuesByRenderScope.get(JSON.stringify(instanceSelector)) ??
- variableValuesByRenderScope.get(
- JSON.stringify([...instanceSelector, ROOT_INSTANCE_ID])
- );
-
export const resolveContentBlockOccurrenceAssetId = ({
source,
instanceSelector,
@@ -45,14 +29,17 @@ export const resolveContentBlockOccurrenceAssetId = ({
}: {
source: ContentBlockSource;
instanceSelector: InstanceSelector;
- variableValuesByRenderScope: VariableValuesByRenderScope;
+ variableValuesByRenderScope: ReadonlyMap<
+ string,
+ ReadonlyMap<string, unknown>
+ >;
}) =>
resolveContentBlockSourceAssetId({
source,
- values: getContentBlockOccurrenceVariableValues({
- instanceSelector,
+ values: getInstanceVariableValues(
variableValuesByRenderScope,
- }),
+ instanceSelector
+ ),
});
export const isRepeatedContentBlockOccurrence = ({
diff --git a/apps/builder/app/shared/instance-utils/variable-values.test.ts b/apps/builder/app/shared/instance-utils/variable-values.test.ts
new file mode 100644
index 0000000000..9ffc350e63
--- /dev/null
+++ b/apps/builder/app/shared/instance-utils/variable-values.test.ts
@@ -0,0 +1,40 @@
+import { expect, test } from "vitest";
+import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";
+import { getInstanceVariableValues } from "./variable-values";
+
+test("merges fallback values with a root-qualified canvas scope", () => {
+ const directValues = new Map([["direct", "value"]]);
+ expect(
+ getInstanceVariableValues(
+ new Map([[JSON.stringify(["box", "body"]), directValues]]),
+ ["box", "body"]
+ )
+ ).toBe(directValues);
+
+ const valuesByInstanceSelector = new Map([
+ [
+ JSON.stringify(["box", "body", ROOT_INSTANCE_ID]),
+ new Map([
+ ["overridden", "scoped"],
+ ["scoped", "value"],
+ ]),
+ ],
+ ]);
+
+ expect(
+ getInstanceVariableValues(
+ valuesByInstanceSelector,
+ ["box", "body"],
+ new Map([
+ ["unscoped", "value"],
+ ["overridden", "unscoped"],
+ ])
+ )
+ ).toEqual(
+ new Map([
+ ["unscoped", "value"],
+ ["overridden", "scoped"],
+ ["scoped", "value"],
+ ])
+ );
+});
diff --git a/apps/builder/app/shared/instance-utils/variable-values.ts b/apps/builder/app/shared/instance-utils/variable-values.ts
new file mode 100644
index 0000000000..1cab3739d4
--- /dev/null
+++ b/apps/builder/app/shared/instance-utils/variable-values.ts
@@ -0,0 +1,22 @@
+import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";
+import type { InstanceSelector } from "@webstudio-is/project-build/runtime";
+
+export const getInstanceVariableValues = (
+ valuesByInstanceSelector: ReadonlyMap<string, ReadonlyMap<string, unknown>>,
+ instanceSelector: InstanceSelector,
+ fallbackValues?: ReadonlyMap<string, unknown>
+) => {
+ const scopedValues =
+ valuesByInstanceSelector.get(JSON.stringify(instanceSelector)) ??
+ valuesByInstanceSelector.get(
+ JSON.stringify(
+ instanceSelector.at(-1) === ROOT_INSTANCE_ID
+ ? instanceSelector
+ : [...instanceSelector, ROOT_INSTANCE_ID]
+ )
+ );
+ if (fallbackValues === undefined || scopedValues === undefined) {
+ return scopedValues ?? fallbackValues;
+ }
+ return new Map([...fallbackValues, ...scopedValues]);
+};
diff --git a/apps/builder/app/shared/nano-states/props.test.tsx b/apps/builder/app/shared/nano-states/props.test.tsx
index 40b3618211..2437109169 100644
--- a/apps/builder/app/shared/nano-states/props.test.tsx
+++ b/apps/builder/app/shared/nano-states/props.test.tsx
@@ -924,6 +924,41 @@ test("compute instance text content bound to expression", () => {
cleanStores($propValuesByInstanceSelector);
});
+test("does not collapse mixed expression and element children into text", () => {
+ $instances.set(
+ toMap([
+ {
+ id: "body",
+ type: "instance",
+ component: "Body",
+ children: [{ type: "id", value: "mixed" }],
+ },
+ {
+ id: "mixed",
+ type: "instance",
+ component: "Box",
+ children: [
+ { type: "expression", value: '"Hello"' },
+ { type: "id", value: "sibling" },
+ ],
+ },
+ {
+ id: "sibling",
+ type: "instance",
+ component: "Text",
+ children: [{ type: "text", value: "world" }],
+ },
+ ])
+ );
+ selectPageRoot("body");
+
+ expect(
+ $propValuesByInstanceSelector.get().get(getInstanceKey(["mixed", "body"]))
+ ).toEqual(new Map());
+
+ cleanStores($propValuesByInstanceSelector);
+});
+
test("use page system values in props", () => {
const systemParameter = new Parameter("system");
const data = renderData(
@@ -1141,6 +1176,41 @@ test("compute item values for collection", () => {
).toEqual("orange");
});
+test("keeps explicitly referenced outer collection items in nested scope", () => {
+ const outerItem = new Parameter("item");
+ const innerItem = new Parameter("item");
+ const data = renderData(
+ <Body ws:id="bodyId">
+ <ws.collection ws:id="outerId" data={["outer"]} item={outerItem}>
+ <ws.collection ws:id="innerId" data={["inner"]} item={innerItem}>
+ <Box ws:id="boxId" />
+ </ws.collection>
+ </ws.collection>
+ </Body>
+ );
+ $instances.set(data.instances);
+ $dataSources.set(data.dataSources);
+ $props.set(data.props);
+ const [outerItemId, innerItemId] = data.dataSources.keys();
+ selectPageRoot("bodyId");
+
+ const values = $variableValuesByInstanceSelector
+ .get()
+ .get(
+ getInstanceKey([
+ "boxId",
+ "innerId[0]",
+ "innerId",
+ "outerId[0]",
+ "outerId",
+ "bodyId",
+ ROOT_INSTANCE_ID,
+ ])
+ );
+ expect(values?.get(outerItemId)).toBe("outer");
+ expect(values?.get(innerItemId)).toBe("inner");
+});
+
test("compute item values for collection with object data", () => {
const dataVariable = new Variable("dataVariable", {
first: "apple",
@@ -1482,7 +1552,7 @@ test("provide global system variable value", () => {
);
});
-test("mask variables with the same name in nested scope", () => {
+test("keeps shadowed variables addressable by id in nested scope", () => {
const bodyVariable = new Variable("myVariable", "body");
const boxVariable = new Variable("myVariable", "box");
const data = renderData(
@@ -1513,6 +1583,7 @@ test("mask variables with the same name in nested scope", () => {
getInstanceKey(["boxId", "bodyId", ROOT_INSTANCE_ID]),
new Map<string, unknown>([
[SYSTEM_VARIABLE_ID, initialSystem],
+ [bodyVariableId, "body"],
[boxVariableId, "box"],
]),
],
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index 9a08a4c749..edf170006b 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -208,7 +208,7 @@ const $resourceVariableValues = computed(
* values of all variables without computing scope specifics like collections
* simplified version of variable values by instance selector
*/
-const $unscopedVariableValues = computed(
+export const $unscopedVariableValues = computed(
[
$dataSources,
$dataSourceVariables,
@@ -404,7 +404,7 @@ export const $propValuesByInstanceSelector = computed(
if (child.type === "text" && instance.children.length === 1) {
propValues.set(textContentAttribute, child.value);
}
- if (child.type === "expression") {
+ if (child.type === "expression" && instance.children.length === 1) {
const value = computeExpression(child.value, variableValues);
if (value !== undefined) {
propValues.set(textContentAttribute, value);
@@ -489,11 +489,9 @@ export const $variableValuesByInstanceSelector = computed(
const collectVariables = (
instanceSelector: InstanceSelector,
- parentVariableValues = new Map<string, unknown>(),
- parentVariableNames = new Map<DataSource["name"], DataSource["id"]>()
+ parentVariableValues = new Map<string, unknown>()
) => {
const [instanceId] = instanceSelector;
- const variableNames = new Map(parentVariableNames);
const variableValues = new Map<string, unknown>(parentVariableValues);
variableValuesByInstanceSelector.set(
getInstanceKey(instanceSelector),
@@ -502,15 +500,10 @@ export const $variableValuesByInstanceSelector = computed(
const variables = variablesByInstanceId.get(instanceId);
// set global system value
if (instanceId === ROOT_INSTANCE_ID) {
- variableNames.set("system", SYSTEM_VARIABLE_ID);
variableValues.set(SYSTEM_VARIABLE_ID, system);
}
if (variables) {
for (const variable of variables) {
- // delete previous variable with the same name
- // because it is masked and no longer available
- variableValues.delete(variableNames.get(variable.name) ?? "");
- variableNames.set(variable.name, variable.id);
if (variable.type === "variable") {
const value = dataSourceVariables.get(variable.id);
variableValues.set(variable.id, value ?? variable.value.value);
@@ -538,18 +531,16 @@ export const $variableValuesByInstanceSelector = computed(
}
}
}
- return { variableValues, variableNames };
+ return variableValues;
};
const traverseInstances = (
instanceSelector: InstanceSelector,
- parentVariableValues = new Map<string, unknown>(),
- parentVariableNames = new Map<DataSource["name"], DataSource["id"]>()
+ parentVariableValues = new Map<string, unknown>()
) => {
- let { variableValues, variableNames } = collectVariables(
+ let variableValues = collectVariables(
instanceSelector,
- parentVariableValues,
- parentVariableNames
+ parentVariableValues
);
const [instanceId] = instanceSelector;
@@ -631,26 +622,17 @@ export const $variableValuesByInstanceSelector = computed(
if (instance.component === portalComponent) {
// allow accessing global variables in slots
variableValues = globalVariableValues;
- variableNames = globalVariableNames;
}
for (const child of instance.children) {
if (child.type === "id") {
- traverseInstances(
- [child.value, ...instanceSelector],
- variableValues,
- variableNames
- );
+ traverseInstances([child.value, ...instanceSelector], variableValues);
}
}
};
- const {
- variableValues: globalVariableValues,
- variableNames: globalVariableNames,
- } = collectVariables([ROOT_INSTANCE_ID]);
+ const globalVariableValues = collectVariables([ROOT_INSTANCE_ID]);
traverseInstances(
[page.rootInstanceId, ROOT_INSTANCE_ID],
- globalVariableValues,
- globalVariableNames
+ globalVariableValues
);
return variableValuesByInstanceSelector;
}
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.ts
index bf57b1988d..1ebce9aa48 100644
--- a/packages/cli/src/commands/mcp.test.ts
+++ b/packages/cli/src/commands/mcp.test.ts
@@ -1196,6 +1196,57 @@ test("adapts MCP upload assets input to public API upload input", () => {
expect(input).toHaveProperty("readAssetData", expect.any(Function));
});
+test("validates font metadata before uploading", () => {
+ expect(() =>
+ getMcpOperationInput("upload-asset", {
+ asset: {
+ name: "variable.woff2",
+ type: "font",
+ format: "woff2",
+ meta: { family: "Inter", style: "normal", weight: 400 },
+ },
+ })
+ ).not.toThrow();
+
+ let error: unknown;
+ try {
+ getMcpOperationInput("upload-assets", {
+ assets: [
+ {
+ name: "variable.woff2",
+ type: "font",
+ format: "woff2",
+ meta: {
+ family: "Inter",
+ style: "normal",
+ weight: "100 900",
+ subset: "latin",
+ },
+ },
+ ],
+ });
+ } catch (caught) {
+ error = caught;
+ }
+
+ expect(createMcpSingleOpCallErrorPayload({ error, elapsedMs: 1 })).toEqual({
+ ok: false,
+ error: {
+ code: "INVALID_INPUT",
+ message: expect.stringContaining("Asset operation input is invalid."),
+ issues: expect.arrayContaining([
+ expect.objectContaining({
+ path: ["assets", "0", "meta", "weight"],
+ }),
+ expect.objectContaining({
+ path: ["assets", "0", "meta", "subset"],
+ }),
+ ]),
+ },
+ meta: { elapsedMs: 1 },
+ });
+});
+
test("rejects every Markdown and MDX upload filename/format mismatch", () => {
let error: unknown;
try {
diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.ts
index 4acb363667..52ceaff935 100644
--- a/packages/cli/src/commands/mcp.ts
+++ b/packages/cli/src/commands/mcp.ts
@@ -30,6 +30,8 @@ import packageJson from "../../package.json" with { type: "json" };
import type { ProjectSessionSnapshot } from "@webstudio-is/project-build/project-session";
import {
formatValidationErrorMessage,
+ getZodValidationIssues,
+ prefixValidationIssuePaths,
type SemanticValidationIssue,
} from "@webstudio-is/project-build/runtime";
import {
@@ -44,6 +46,7 @@ import {
import { contentEngineLimits } from "@webstudio-is/content-engine/limits";
import { assetQueryRequest } from "@webstudio-is/content-engine";
import { assetType, getFileExtension } from "@webstudio-is/sdk";
+import { fontMetaUpdate } from "@webstudio-is/fonts";
import { resolveApiConnection } from "../api-connection";
import {
getCliErrorIssues,
@@ -217,7 +220,7 @@ const getTextAssetFormat = (value: string): "md" | "mdx" | undefined => {
return extension === "md" || extension === "mdx" ? extension : undefined;
};
-const getTextAssetDescriptorIssues = ({
+const getAssetDescriptorIssues = ({
assets,
pathPrefix,
}: {
@@ -320,6 +323,17 @@ const getTextAssetDescriptorIssues = ({
})
);
}
+ if (asset.type === "font" && isPlainRecord(asset.meta)) {
+ const fontMetaResult = fontMetaUpdate.safeParse(asset.meta);
+ if (fontMetaResult.success === false) {
+ issues.push(
+ ...prefixValidationIssuePaths(
+ getZodValidationIssues(fontMetaResult.error),
+ [...assetPath, "meta"]
+ )
+ );
+ }
+ }
const name = typeof asset.name === "string" ? asset.name : "";
const filenameFormat = getFileExtension(name)?.toLowerCase();
const declaredFormat =
@@ -366,7 +380,7 @@ const assertTextAssetDescriptorFormats = ({
assets: unknown[];
pathPrefix: string[];
}) => {
- const issues = getTextAssetDescriptorIssues({ assets, pathPrefix });
+ const issues = getAssetDescriptorIssues({ assets, pathPrefix });
if (issues.length > 0) {
throw Object.assign(
new Error("Markdown and MDX Asset descriptors are invalid."),
@@ -428,7 +442,7 @@ const getMcpUploadAssetInput = (input: unknown) => {
message: "assetsDir must be a string.",
}),
]),
- ...getTextAssetDescriptorIssues({
+ ...getAssetDescriptorIssues({
assets: [input.asset],
pathPrefix: ["asset"],
}),
@@ -485,7 +499,7 @@ const getMcpUploadAssetsInput = (input: unknown) => {
message: "assetsDir must be a string.",
}),
]),
- ...getTextAssetDescriptorIssues({ assets, pathPrefix: ["assets"] }),
+ ...getAssetDescriptorIssues({ assets, pathPrefix: ["assets"] }),
]);
if (assets.every(hasAssetName) === false) {
throw new Error("Unreachable invalid Asset descriptors");
diff --git a/packages/expression/src/expression.test.ts b/packages/expression/src/expression.test.ts
index 6e9682f2b4..3d3a2bbc82 100644
--- a/packages/expression/src/expression.test.ts
+++ b/packages/expression/src/expression.test.ts
@@ -545,6 +545,7 @@ describe("expression value kinds", () => {
["{}", "object"],
['"text"', "string"],
["`text`", "string"],
+ ['"text" + value', "string"],
['"text" /* trailing comment */', "string"],
["value +", "unknown"],
['"text" trailing', "unknown"],
diff --git a/packages/expression/src/index.ts b/packages/expression/src/index.ts
index e1615778a2..d6592cd2d1 100644
--- a/packages/expression/src/index.ts
+++ b/packages/expression/src/index.ts
@@ -235,6 +235,16 @@ const getExpressionNodeValueKind = (
if (node.type === "TemplateLiteral") {
return "string";
}
+ if (node.type === "BinaryExpression" && node.operator === "+") {
+ const leftKind =
+ node.left.type === "PrivateIdentifier"
+ ? "unknown"
+ : getExpressionNodeValueKind(node.left, variableValues);
+ const rightKind = getExpressionNodeValueKind(node.right, variableValues);
+ if (leftKind === "string" || rightKind === "string") {
+ return "string";
+ }
+ }
if (
node.type === "ChainExpression" ||
node.type === "ParenthesizedExpression"
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index 0f8ba9b206..7e202b7ddc 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -5225,6 +5225,7 @@ export const runtimeOperationContractData = [
required: ["include", "category", "thumbnailAssetId"],
},
},
+ additionalProperties: false,
required: [],
},
},
@@ -66846,6 +66847,8 @@ export const runtimeOperationContractData = [
},
name: {
type: "string",
+ description:
+ 'Prop name. A bound "style" prop must evaluate to an object such as { color: themeColor }, never a CSS declaration string.',
},
binding: {
oneOf: [
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index a16782a2dc..f6b895450f 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -8060,14 +8060,11 @@ describe("project session mcp adapter", () => {
listedTools.tools.find(({ name }) => name === "list-pages")
).not.toHaveProperty("_meta");
expect(
- listedTools.tools.find(({ name }) => name === "delete-instance")
- ).not.toHaveProperty("description");
- expect(
- listedTools.tools.find(({ name }) => name === "meta.guide")?.description
- ).toBeTypeOf("string");
- expect(
- listedTools.tools.find(({ name }) => name === "list-pages")?.description
- ).toBeTypeOf("string");
+ listedTools.tools.filter(
+ ({ description }) =>
+ typeof description !== "string" || description.trim() === ""
+ )
+ ).toEqual([]);
expect(
JSON.stringify(
listedTools.tools.find(({ name }) => name === "list-pages")
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 5a8406c223..5cd575b16e 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -7426,11 +7426,6 @@ const sdkDetailedInputToolNames = new Set([
"workflow.next",
]);
-const sdkDescribedToolNames = new Set([
- ...sdkDetailedInputToolNames,
- ...metaGoalGuides.flatMap(({ tools }) => tools),
-]);
-
const getSdkToolAnnotations = (tool: ProjectSessionMcpTool) => {
const readOnly = isReadOnlyProjectSessionMcpTool(tool);
const annotations: NonNullable<SdkTool["annotations"]> = {
@@ -7443,18 +7438,11 @@ const getSdkToolAnnotations = (tool: ProjectSessionMcpTool) => {
return Object.keys(annotations).length === 0 ? undefined : annotations;
};
-// Keep output contracts, complete input guidance, and Webstudio operation
-// metadata for local validation, generated documentation, and focused
-// discovery. The startup instructions and described discovery tools route
-// models to meta.guide, which returns descriptions for the relevant operation
-// set. Do not resend descriptions for every operation in every MCP handshake.
const toSdkTool = (tool: ProjectSessionMcpTool): SdkTool => {
const annotations = getSdkToolAnnotations(tool);
return {
name: tool.name,
- ...(sdkDescribedToolNames.has(tool.name)
- ? { description: tool.description }
- : {}),
+ description: tool.description,
inputSchema: getSdkInputSchema(
tool.inputSchema,
sdkDetailedInputToolNames.has(tool.name)
diff --git a/packages/project-build/src/runtime/asset-resources.test.ts b/packages/project-build/src/runtime/asset-resources.test.ts
index 7235ac0ade..5a9580f609 100644
--- a/packages/project-build/src/runtime/asset-resources.test.ts
+++ b/packages/project-build/src/runtime/asset-resources.test.ts
@@ -1,10 +1,75 @@
import { describe, expect, test } from "vitest";
+import { createDefaultPages } from "@webstudio-is/project-build";
+import {
+ createDefaultStructuredAssetQueryResourceConfiguration,
+ createStructuredAssetQueryResourceBody,
+} from "@webstudio-is/sdk";
import {
assetsResourceCreateInput,
assetsResourceUpdateInput,
+ createAssetsResource,
getAssetsResource,
+ updateAssetsResource,
} from "./asset-resources";
+const filterQuery = (value: string) => ({
+ where: {
+ all: [{ field: ["folderId"], operator: "eq" as const, value }],
+ },
+});
+
+const createState = (includeFolderVariable = false) => ({
+ pages: createDefaultPages({ rootInstanceId: "body" }),
+ instances: new Map(),
+ props: new Map(),
+ dataSources: new Map([
+ [
+ "posts-data",
+ {
+ id: "posts-data",
+ type: "resource" as const,
+ name: "posts",
+ resourceId: "posts",
+ scopeInstanceId: ":root",
+ },
+ ],
+ ...(includeFolderVariable
+ ? ([
+ [
+ "folder-id",
+ {
+ id: "folder-id",
+ type: "variable" as const,
+ name: "folderId",
+ value: { type: "string" as const, value: "folder" },
+ scopeInstanceId: ":root",
+ },
+ ],
+ ] as const)
+ : []),
+ ]),
+ resources: new Map([
+ [
+ "posts",
+ {
+ id: "posts",
+ name: "Posts",
+ control: "system" as const,
+ method: "post" as const,
+ url: '"/$resources/assets"',
+ headers: [],
+ body: createStructuredAssetQueryResourceBody(
+ createDefaultStructuredAssetQueryResourceConfiguration()
+ ),
+ },
+ ],
+ ]),
+ breakpoints: new Map(),
+ styleSources: new Map(),
+ styleSourceSelections: new Map(),
+ styles: new Map(),
+});
+
describe("Assets resource mutation input", () => {
test("returns the exact stored query decoding error", () => {
expect(
@@ -139,6 +204,49 @@ describe("Assets resource mutation input", () => {
}
);
+ test("rejects filter expressions that reference unavailable variables", () => {
+ expect(() =>
+ createAssetsResource(
+ createState(),
+ assetsResourceCreateInput.parse({
+ name: "Posts",
+ scopeInstanceId: ":root",
+ query: filterQuery("folderId"),
+ }),
+ { createId: () => "unused" }
+ )
+ ).toThrow('unavailable variable "folderId"');
+ });
+
+ test("accepts filter expressions that reference scoped variables", () => {
+ expect(() =>
+ createAssetsResource(
+ createState(true),
+ assetsResourceCreateInput.parse({
+ name: "Posts",
+ scopeInstanceId: ":root",
+ query: filterQuery("folderId"),
+ }),
+ { createId: () => "unused" }
+ )
+ ).not.toThrow();
+ });
+
+ test("rejects unavailable filter variables when updating", () => {
+ expect(() =>
+ updateAssetsResource(
+ createState(),
+ assetsResourceUpdateInput.parse({
+ resourceId: "posts",
+ values: {
+ query: filterQuery("folderId"),
+ },
+ }),
+ { createId: () => "unused" }
+ )
+ ).toThrow('unavailable variable "folderId"');
+ });
+
test("keeps omitted query update fields absent for patch merging", () => {
expect(
assetsResourceUpdateInput.parse({
diff --git a/packages/project-build/src/runtime/asset-resources.ts b/packages/project-build/src/runtime/asset-resources.ts
index 7b7b7989cd..7778048806 100644
--- a/packages/project-build/src/runtime/asset-resources.ts
+++ b/packages/project-build/src/runtime/asset-resources.ts
@@ -3,13 +3,16 @@ import {
assetQueryResourceConfigurationPatchInput,
createDefaultStructuredAssetQueryResourceConfiguration,
createStructuredAssetQueryResourceBody,
+ decodeDataVariableId,
isAssetsResource,
parseStructuredAssetQueryResourceBodyResult,
+ ROOT_INSTANCE_ID,
SYSTEM_VARIABLE_ID,
type AssetQueryWhereExpression,
type Resource,
type StructuredAssetQueryWhereBinding,
} from "@webstudio-is/sdk";
+import { getExpressionIdentifiers } from "@webstudio-is/expression";
import { mapQueryWhere } from "@webstudio-is/query-builder/runtime";
import { assetsResourceUrl } from "@webstudio-is/sdk/runtime";
import { z } from "zod";
@@ -18,6 +21,7 @@ import type { BuilderRuntimeContext } from "./context";
import {
createResource,
normalizeResourceExpressionInput,
+ bindExpressionToInstanceScope,
optionalResourceScopeInstanceIdInput,
resourceScopeInstanceIdInput,
unsetExpressionVariables,
@@ -62,6 +66,47 @@ const normalizeWhere = (
value: normalizeResourceExpressionInput(condition.value),
}));
+const assertQueryExpressionsInScope = ({
+ state,
+ scopeInstanceId,
+ query,
+}: {
+ state: Pick<BuilderState, "instances" | "dataSources">;
+ scopeInstanceId: string;
+ query: z.output<typeof assetQueryResourceConfigurationInput>;
+}) => {
+ if (state.instances === undefined || state.dataSources === undefined) {
+ return;
+ }
+ const expressions = [query.limit, query.offset];
+ mapQueryWhere(query.where, (condition) => {
+ if (typeof condition.value === "string") {
+ expressions.push(condition.value);
+ }
+ return condition;
+ });
+ for (const expression of expressions) {
+ if (typeof expression !== "string") {
+ continue;
+ }
+ const boundExpression = bindExpressionToInstanceScope({
+ expression,
+ instanceId: scopeInstanceId,
+ instances: state.instances,
+ dataSources: state.dataSources,
+ });
+ const unknownIdentifier = [
+ ...getExpressionIdentifiers(boundExpression),
+ ].find((identifier) => decodeDataVariableId(identifier) === undefined);
+ if (unknownIdentifier !== undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ `Asset query expression references unavailable variable ${JSON.stringify(unknownIdentifier)}. Use a scoped variable name for dynamic data or a literal such as ${JSON.stringify(JSON.stringify(unknownIdentifier))}.`
+ );
+ }
+ }
+};
+
const createAssetResourceBody = (
configuration: z.output<typeof assetQueryResourceConfigurationInput>
) =>
@@ -180,9 +225,8 @@ const createStoredAssetsResource = ({
query,
}: {
name: string;
- query?: z.output<typeof assetQueryResourceConfigurationInput>;
+ query: z.output<typeof assetQueryResourceConfigurationInput>;
}) => {
- const configuration = assetQueryResourceConfigurationInput.parse(query ?? {});
return {
name,
control: "system" as const,
@@ -195,7 +239,7 @@ const createStoredAssetsResource = ({
value: { type: "literal" as const, value: "application/json" },
},
],
- body: createAssetResourceBody(configuration),
+ body: createAssetResourceBody(query),
};
};
@@ -205,10 +249,16 @@ export const createAssetsResource = (
context: BuilderRuntimeContext
) => {
const { name, scopeInstanceId, dataSourceName, query } = input;
+ const configuration = assetQueryResourceConfigurationInput.parse(query ?? {});
+ assertQueryExpressionsInScope({
+ state,
+ scopeInstanceId,
+ query: configuration,
+ });
return createResource(
state,
{
- resource: createStoredAssetsResource({ name, query }),
+ resource: createStoredAssetsResource({ name, query: configuration }),
scopeInstanceId,
dataSourceName: dataSourceName ?? name,
exposeAsDataSource: true,
@@ -233,26 +283,39 @@ export const updateAssetsResource = (
const storedConfiguration = parsedConfiguration.success
? parsedConfiguration.value
: undefined;
- if (storedConfiguration === undefined && queryUpdate === undefined) {
- return throwBuilderRuntimeError(
- "BAD_REQUEST",
- `${
- parsedConfiguration.success === false
- ? parsedConfiguration.message
- : "Stored Assets query configuration could not be decoded."
- } Replace or remove the query to repair it.`
- );
+ let query: z.output<typeof assetQueryResourceConfigurationInput>;
+ if (queryUpdate === undefined) {
+ if (storedConfiguration === undefined) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ `${
+ parsedConfiguration.success === false
+ ? parsedConfiguration.message
+ : "Stored Assets query configuration could not be decoded."
+ } Replace or remove the query to repair it.`
+ );
+ }
+ query = storedConfiguration;
+ } else if (queryUpdate === null) {
+ query = createDefaultStructuredAssetQueryResourceConfiguration();
+ } else {
+ query = assetQueryResourceConfigurationInput.parse({
+ ...storedConfiguration,
+ ...queryUpdate,
+ });
}
- const currentQuery = storedConfiguration;
- const query =
- queryUpdate === undefined
- ? currentQuery
- : queryUpdate === null
- ? createDefaultStructuredAssetQueryResourceConfiguration()
- : assetQueryResourceConfigurationInput.parse({
- ...currentQuery,
- ...queryUpdate,
- });
+ const currentDataSource = Array.from(state.dataSources?.values() ?? []).find(
+ (dataSource) =>
+ dataSource.type === "resource" && dataSource.resourceId === resource.id
+ );
+ assertQueryExpressionsInScope({
+ state,
+ scopeInstanceId:
+ input.scopeInstanceId ??
+ currentDataSource?.scopeInstanceId ??
+ ROOT_INSTANCE_ID,
+ query,
+ });
return updateResource(
state,
{
diff --git a/packages/project-build/src/runtime/binding-verification.acceptance.test.ts b/packages/project-build/src/runtime/binding-verification.acceptance.test.ts
index b2762e3e3f..18528b3593 100644
--- a/packages/project-build/src/runtime/binding-verification.acceptance.test.ts
+++ b/packages/project-build/src/runtime/binding-verification.acceptance.test.ts
@@ -39,6 +39,86 @@ const applyMutation = (
};
describe("dynamic binding verification acceptance", () => {
+ test("binds data source assignments in actions", () => {
+ const state = createBindingVerificationFixture();
+ const context = createContext();
+
+ const nextState = applyMutation(
+ state,
+ "instances.bindProps",
+ {
+ bindings: [
+ {
+ instanceId: "checkout",
+ name: "onSubmit",
+ binding: {
+ type: "action",
+ value: [
+ {
+ type: "execute",
+ args: ["nextValue"],
+ code: "featuredProduct = nextValue",
+ },
+ ],
+ },
+ },
+ ],
+ },
+ context
+ );
+
+ expect(
+ [...nextState.props!.values()].find(
+ (prop) => prop.instanceId === "checkout" && prop.name === "onSubmit"
+ )
+ ).toMatchObject({
+ type: "action",
+ value: [
+ {
+ code: `${encodeDataVariableId("featured-product")} = nextValue`,
+ },
+ ],
+ });
+ });
+
+ test("warns about unresolved action assignment targets", () => {
+ const result = executeBuilderRuntimeOperation({
+ id: "instances.bindProps",
+ state: createBindingVerificationFixture(),
+ input: {
+ bindings: [
+ {
+ instanceId: "checkout",
+ name: "onSubmit",
+ binding: {
+ type: "action",
+ value: [
+ {
+ type: "execute",
+ args: ["nextValue"],
+ code: "featuerdProduct = nextValue",
+ },
+ ],
+ },
+ },
+ ],
+ },
+ context: createContext(),
+ });
+
+ expect(result).toMatchObject({
+ kind: "mutation",
+ result: {
+ warnings: [
+ expect.objectContaining({
+ path: ["bindings", "0", "binding", "value", "0", "code"],
+ message: '"featuerdProduct" is not defined in the scope',
+ }),
+ ],
+ },
+ });
+ });
+
test("checks realistic text, prop, action, parameter, resource, and metadata bindings", () => {
const state = createBindingVerificationFixture();
const result = verifyBindings(state, { limit: 200 });
diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.ts
index 2bb037679a..88fec78438 100644
--- a/packages/project-build/src/runtime/components.test.ts
+++ b/packages/project-build/src/runtime/components.test.ts
@@ -254,6 +254,58 @@ test("assigns a unique name when inserting into a Templates list", async () => {
);
});
+test("replaces only the child at an explicit insert index", async () => {
+ const parent: Instance = {
+ type: "instance",
+ id: "parent",
+ component: "Box",
+ children: [
+ { type: "id", value: "first" },
+ { type: "id", value: "second" },
+ ],
+ };
+ const state = createState(parent);
+ state.instances.set("first", {
+ type: "instance",
+ id: "first",
+ component: "Box",
+ children: [],
+ });
+ state.instances.set("second", {
+ type: "instance",
+ id: "second",
+ component: "Text",
+ children: [{ type: "text", value: "Keep me" }],
+ });
+ const fragment = await parseWebstudioJsxFragment("<Box />");
+
+ const mutation = insertFragment(
+ state,
+ {
+ parentInstanceId: parent.id,
+ fragment,
+ mode: "replace",
+ insertIndex: 0,
+ },
+ { createId: createIdFactory() }
+ );
+
+ expect(mutation.result.removedInstanceIds).toEqual(["first"]);
+ expect(
+ mutation.payload
+ .find(({ namespace }) => namespace === "instances")
+ ?.patches.filter(
+ ({ op, path }) =>
+ op === "remove" && path[0] === "parent" && path[1] === "children"
+ )
+ ).toEqual([{ op: "remove", path: ["parent", "children", 0] }]);
+ expect(
+ mutation.payload
+ .flatMap(({ patches }) => patches)
+ .some(({ op, path }) => op === "remove" && path.includes("second"))
+ ).toBe(false);
+});
+
test("uses the public collision-safe component identifier as the template name", async () => {
const parent: Instance = {
type: "instance",
diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.ts
index cb2cb68175..b6b3348322 100644
--- a/packages/project-build/src/runtime/components.ts
+++ b/packages/project-build/src/runtime/components.ts
@@ -789,7 +789,7 @@ const createInsertFragmentMutation = <
const parentChildren = parent.children ?? [];
const insertIndex =
mode === "replace"
- ? 0
+ ? (explicitInsertIndex ?? 0)
: mode === "prepend"
? 0
: (explicitInsertIndex ?? parentChildren.length);
@@ -799,6 +799,20 @@ const createInsertFragmentMutation = <
"Insert index is outside parent children"
);
}
+ if (
+ mode === "replace" &&
+ explicitInsertIndex !== undefined &&
+ insertIndex === parentChildren.length
+ ) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Replace index is outside parent children"
+ );
+ }
+ const replacedChildren =
+ mode === "replace" && explicitInsertIndex !== undefined
+ ? parentChildren.slice(insertIndex, insertIndex + 1)
+ : parentChildren;
const { newInstanceIds, newDataSourceIds, didMergeBreakpointsDueToLimit } =
insertWebstudioFragmentCopy({
@@ -859,7 +873,7 @@ const createInsertFragmentMutation = <
parent,
replacedInstanceIds:
mode === "replace"
- ? parentChildren.flatMap((child) =>
+ ? replacedChildren.flatMap((child) =>
child.type === "id" ? [child.value] : []
)
: [],
@@ -869,7 +883,7 @@ const createInsertFragmentMutation = <
const requiredTemplateNameConfirmation =
mode === "replace" && parent.component === blockTemplateComponent
? getBlockTemplateNameConfirmation({
- changes: parentChildren.flatMap((child, index) => {
+ changes: replacedChildren.flatMap((child, index) => {
if (child.type !== "id") {
return [];
}
@@ -898,7 +912,13 @@ const createInsertFragmentMutation = <
...parent,
children:
mode === "replace"
- ? insertedChildren
+ ? explicitInsertIndex === undefined
+ ? insertedChildren
+ : [
+ ...parentChildren.slice(0, insertIndex),
+ ...insertedChildren,
+ ...parentChildren.slice(insertIndex + 1),
+ ]
: [
...parentChildren.slice(0, insertIndex),
...insertedChildren,
@@ -1002,6 +1022,10 @@ const createInsertFragmentMutation = <
styleSources: mutationState.styleSources.values(),
styleSourceSelections: mutationState.styleSourceSelections.values(),
styles: mutationState.styles.values(),
+ replaceIndex:
+ mode === "replace" && explicitInsertIndex !== undefined
+ ? insertIndex
+ : undefined,
});
const insertPayload = createFragmentInsertPayload({
before: mutationState,
diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsx
index c1d1c0bb6d..b0012d1c87 100644
--- a/packages/project-build/src/runtime/data.test.tsx
+++ b/packages/project-build/src/runtime/data.test.tsx
@@ -24,6 +24,7 @@ import { createDefaultPages } from "@webstudio-is/project-build";
import {
computeExpression,
computeExpressionWithinScope,
+ bindExpressionToInstanceScope,
createDataVariable,
dataVariableCreateInput,
createDataVariableCreatePayload,
@@ -1510,6 +1511,31 @@ test("prevent rebinding with nested collection item", () => {
]);
});
+test("binds an explicitly referenced shadowed collection item", () => {
+ const outerItem = new Parameter("item");
+ const innerItem = new Parameter("item");
+ const data = renderData(
+ <Body ws:id="bodyId">
+ <ws.collection ws:id="outerId" data={[]} item={outerItem}>
+ <ws.collection ws:id="innerId" data={[]} item={innerItem}>
+ <Box ws:id="boxId" />
+ </ws.collection>
+ </ws.collection>
+ </Body>
+ );
+ const [outerItemId] = data.dataSources.keys();
+ const expression = encodeDataVariableId(outerItemId);
+
+ expect(
+ bindExpressionToInstanceScope({
+ expression,
+ instanceId: "boxId",
+ instances: data.instances,
+ dataSources: data.dataSources,
+ })
+ ).toBe(expression);
+});
+
test("delete variable and unset it in expressions", () => {
const bodyVariable = new Variable("bodyVariable", "one value of body");
const data = renderData(
@@ -3439,7 +3465,7 @@ describe("resource patch helpers", () => {
});
});
- test("preserves explicit write-resource exposure during unrelated updates", () => {
+ test("preserves explicit write-resource exposure during a full update", () => {
const state = createResourceState();
state.instances.set("body", {
type: "instance",
@@ -3460,7 +3486,15 @@ describe("resource patch helpers", () => {
state,
{
resourceId: "resource",
- values: { name: "Renamed" },
+ values: {
+ name: resource.name,
+ control: resource.control,
+ method: "post",
+ url: resource.url,
+ searchParams: resource.searchParams,
+ headers: resource.headers,
+ body: resource.body,
+ },
},
{ createId: () => "unused-id" }
);
diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.ts
index aacb4b1eac..96c07c77e6 100644
--- a/packages/project-build/src/runtime/data.ts
+++ b/packages/project-build/src/runtime/data.ts
@@ -569,7 +569,7 @@ const getDataSourcesByScopeInstanceId = (dataSources: DataSources) => {
return dataSourcesByScopeInstanceId;
};
-const findMaskedVariablesByInstanceId = ({
+const findVariablesByInstanceId = ({
startingInstanceId,
parentInstanceById,
instances,
@@ -589,8 +589,11 @@ const findMaskedVariablesByInstanceId = ({
currentId = parentInstanceById.get(currentId);
}
instanceIdsPath.push(ROOT_INSTANCE_ID);
- const maskedVariables = new Map<DataSource["name"], DataSource["id"]>();
- maskedVariables.set("system", SYSTEM_VARIABLE_ID);
+ const maskedIdByName = new Map<DataSource["name"], DataSource["id"]>();
+ const availableDataSourceIds = new Set<DataSource["id"]>([
+ SYSTEM_VARIABLE_ID,
+ ]);
+ maskedIdByName.set("system", SYSTEM_VARIABLE_ID);
for (const instanceId of instanceIdsPath.reverse()) {
const instance = instances.get(instanceId);
const scopedDataSources = dataSourcesByScopeInstanceId.get(instanceId);
@@ -605,10 +608,11 @@ const findMaskedVariablesByInstanceId = ({
) {
continue;
}
- maskedVariables.set(dataSource.name, dataSource.id);
+ maskedIdByName.set(dataSource.name, dataSource.id);
+ availableDataSourceIds.add(dataSource.id);
}
}
- return maskedVariables;
+ return { maskedIdByName, availableDataSourceIds };
};
export const findAvailableVariables = ({
@@ -620,7 +624,7 @@ export const findAvailableVariables = ({
instances: Instances;
dataSources: DataSources;
}) => {
- const maskedVariables = findMaskedVariablesByInstanceId({
+ const { maskedIdByName } = findVariablesByInstanceId({
startingInstanceId,
parentInstanceById: getParentInstanceById(instances),
instances,
@@ -628,7 +632,7 @@ export const findAvailableVariables = ({
dataSourcesByScopeInstanceId: getDataSourcesByScopeInstanceId(dataSources),
});
const availableVariables: DataSource[] = [];
- for (const dataSourceId of maskedVariables.values()) {
+ for (const dataSourceId of maskedIdByName.values()) {
const dataSource = dataSources.get(dataSourceId);
if (dataSource) {
availableVariables.push(dataSource);
@@ -645,23 +649,27 @@ export const bindExpressionToInstanceScope = ({
instanceId,
instances,
dataSources,
+ excludeVariableNames = [],
}: {
expression: string;
instanceId: Instance["id"];
instances: Instances;
dataSources: DataSources;
+ excludeVariableNames?: Iterable<string>;
}) => {
- const maskedIdByName = findMaskedVariablesByInstanceId({
+ const { maskedIdByName, availableDataSourceIds } = findVariablesByInstanceId({
startingInstanceId: instanceId,
parentInstanceById: getParentInstanceById(instances),
instances,
dataSources,
});
+ for (const name of excludeVariableNames) {
+ maskedIdByName.delete(name);
+ }
const boundExpression = restoreExpressionVariables({
expression,
maskedIdByName,
});
- const availableDataSourceIds = new Set(maskedIdByName.values());
for (const identifier of getExpressionIdentifiers(boundExpression)) {
const dataSourceId = decodeDataVariableId(identifier);
if (
@@ -1024,7 +1032,7 @@ export const rebindTreeVariablesMutable = ({
dataSources,
resources,
update: (expression, instanceId, args) => {
- const maskedVariables = findMaskedVariablesByInstanceId({
+ const { maskedIdByName: maskedVariables } = findVariablesByInstanceId({
startingInstanceId: instanceId,
parentInstanceById,
instances,
@@ -1090,7 +1098,7 @@ export const deleteVariableMutable = (
const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();
unsetNameById.set(dataSource.id, dataSource.name);
const startingInstanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;
- const maskedIdByName = findMaskedVariablesByInstanceId({
+ const { maskedIdByName } = findVariablesByInstanceId({
startingInstanceId,
parentInstanceById: getParentInstanceById(data.instances),
instances: data.instances,
@@ -2728,7 +2736,7 @@ export const updateResource = (
const scopeInstanceId = input.scopeInstanceId ?? dataSource?.scopeInstanceId;
const exposeAsDataSource =
input.exposeAsDataSource ??
- (values.method !== undefined && nextResource.method !== "get"
+ (resource.method !== nextResource.method && nextResource.method !== "get"
? false
: dataSource !== undefined ||
(nextResource.method === "get" && scopeInstanceId !== undefined));
diff --git a/packages/project-build/src/runtime/expression-scope.ts b/packages/project-build/src/runtime/expression-scope.ts
index ef7a6ee0f1..eb81a96c99 100644
--- a/packages/project-build/src/runtime/expression-scope.ts
+++ b/packages/project-build/src/runtime/expression-scope.ts
@@ -5,7 +5,8 @@ import { getExpressionWarnings } from "./expression-validation";
export const bindExpressionInput = (
state: Pick<BuilderState, "instances" | "dataSources">,
instanceId: string,
- expression: string
+ expression: string,
+ excludeVariableNames?: Iterable<string>
) => {
if (state.instances === undefined || state.dataSources === undefined) {
return expression;
@@ -15,6 +16,7 @@ export const bindExpressionInput = (
instanceId,
instances: state.instances,
dataSources: state.dataSources,
+ excludeVariableNames,
});
};
diff --git a/packages/project-build/src/runtime/instance-duplicate.test.ts b/packages/project-build/src/runtime/instance-duplicate.test.ts
index 36278a4571..f9249be1bf 100644
--- a/packages/project-build/src/runtime/instance-duplicate.test.ts
+++ b/packages/project-build/src/runtime/instance-duplicate.test.ts
@@ -104,6 +104,25 @@ test("duplicates an instance after itself", () => {
]);
});
+test("duplicates an instance into another parent", () => {
+ const data = createData();
+ data.instances.set("target", createInstance("target"));
+ const ids = ["source-copy", "child-copy"];
+
+ const newRootInstanceId = duplicateInstanceAfterItselfMutable({
+ data,
+ sourceInstanceId: "source",
+ parentInstanceId: "target",
+ projectId: "project-id",
+ createId: () => ids.shift() ?? "missing",
+ });
+
+ expect(newRootInstanceId).toBe("source-copy");
+ expect(data.instances.get("target")?.children).toEqual([
+ { type: "id", value: "source-copy" },
+ ]);
+});
+
test("preserves legacy HtmlEmbed code when duplicating an instance", () => {
const data = createData();
data.instances.set("source", {
diff --git a/packages/project-build/src/runtime/instance-duplicate.ts b/packages/project-build/src/runtime/instance-duplicate.ts
index 3656209572..be6f23c7e5 100644
--- a/packages/project-build/src/runtime/instance-duplicate.ts
+++ b/packages/project-build/src/runtime/instance-duplicate.ts
@@ -102,7 +102,8 @@ export const duplicateInstanceAfterItselfMutable = ({
sourceInstanceId
);
if (indexWithinChildren === -1) {
- return;
+ parentInstance.children.push({ type: "id", value: newRootInstanceId });
+ return newRootInstanceId;
}
parentInstance.children.splice(indexWithinChildren + 1, 0, {
type: "id",
diff --git a/packages/project-build/src/runtime/instances.ts b/packages/project-build/src/runtime/instances.ts
index 9084754bc5..fe2ff32bef 100644
--- a/packages/project-build/src/runtime/instances.ts
+++ b/packages/project-build/src/runtime/instances.ts
@@ -1261,6 +1261,7 @@ export const createInstanceAppendPayload = ({
styleSources,
styleSourceSelections,
styles,
+ replaceIndex,
}: {
parent: Instance;
instances: Instances;
@@ -1272,12 +1273,17 @@ export const createInstanceAppendPayload = ({
styleSources: Iterable<StyleSource>;
styleSourceSelections: Iterable<StyleSourceSelection>;
styles: Iterable<StyleDecl>;
+ replaceIndex?: number;
}) => {
const parentChildren = parent.children ?? [];
+ const replacedChildren =
+ mode === "replace" && replaceIndex !== undefined
+ ? parentChildren.slice(replaceIndex, replaceIndex + 1)
+ : parentChildren;
const replacedInstanceIds =
mode === "replace"
? new Set(
- parentChildren.flatMap((child) =>
+ replacedChildren.flatMap((child) =>
child.type === "id"
? collectInstanceIds(instances, child.value)
: []
@@ -1308,9 +1314,9 @@ export const createInstanceAppendPayload = ({
patches: [
...(mode === "replace"
? sortChildRemovalPatches(
- parentChildren.map((_child, index) => ({
+ replacedChildren.map((_child, index) => ({
op: "remove" as const,
- path: [parent.id, "children", index] as [
+ path: [parent.id, "children", (replaceIndex ?? 0) + index] as [
string,
"children",
number,
diff --git a/packages/project-build/src/runtime/pages.test.ts b/packages/project-build/src/runtime/pages.test.ts
index 99dfad8191..aa90a24cce 100644
--- a/packages/project-build/src/runtime/pages.test.ts
+++ b/packages/project-build/src/runtime/pages.test.ts
@@ -68,6 +68,7 @@ import {
pageTemplateSettingsInput,
pageTextContentSettingsInput,
pageSettingsDefaultValues,
+ pageSettingsUpdateInput,
reparentOrphans,
reparentOrphansMutable,
savePagePathInHistory,
@@ -2180,6 +2181,15 @@ describe("updatePage", () => {
});
describe("updatePageMarketplace", () => {
+ test("rejects update-page fields that page settings does not accept", () => {
+ expect(
+ pageSettingsUpdateInput.safeParse({
+ pageId: "page",
+ values: { meta: { description: '"Description"' } },
+ }).success
+ ).toBe(false);
+ });
+
test("updates settings, marketplace, and home page in one mutation", () => {
const pages = createPages();
const result = updatePageSettings(
diff --git a/packages/project-build/src/runtime/pages.ts b/packages/project-build/src/runtime/pages.ts
index 6cc5134185..d9ab12a5f4 100644
--- a/packages/project-build/src/runtime/pages.ts
+++ b/packages/project-build/src/runtime/pages.ts
@@ -1268,7 +1268,8 @@ export const pageSettingsUpdateInput = z.object({
thumbnailAssetId: z.string(),
}),
})
- .partial(),
+ .partial()
+ .strict(),
});
export const pageSavePathInHistoryInput = z.object({
diff --git a/packages/project-build/src/runtime/props.test.ts b/packages/project-build/src/runtime/props.test.ts
index 78d6ec9e07..c151fddec7 100644
--- a/packages/project-build/src/runtime/props.test.ts
+++ b/packages/project-build/src/runtime/props.test.ts
@@ -278,6 +278,34 @@ describe("prop input creators", () => {
).toThrow();
});
+ test("rejects definitely non-object expressions bound to the style prop", () => {
+ for (const value of [
+ '"color: " + themeColor',
+ "42",
+ "true",
+ "null",
+ "[]",
+ ]) {
+ expect(() =>
+ propBindingInput.parse({
+ instanceId: "instance-id",
+ name: "style",
+ binding: { type: "expression", value },
+ })
+ ).toThrow("must evaluate to an object");
+ }
+ expect(() =>
+ propBindingInput.parse({
+ instanceId: "instance-id",
+ name: "style",
+ binding: {
+ type: "expression",
+ value: "{ color: themeColor }",
+ },
+ })
+ ).not.toThrow();
+ });
+
test("reports malformed prop update batch items by index", () => {
const result = propUpdatesInput.safeParse({
updates: [
diff --git a/packages/project-build/src/runtime/props.ts b/packages/project-build/src/runtime/props.ts
index 9ae1583dc2..c7382cc5b8 100644
--- a/packages/project-build/src/runtime/props.ts
+++ b/packages/project-build/src/runtime/props.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { parseCssValue } from "@webstudio-is/css-data";
+import { getExpressionValueKind } from "@webstudio-is/expression";
import {
blockComponent,
contentBlockSourceProp,
@@ -307,7 +308,11 @@ export const propBindingInput = z
.object({
propId: runtimeGeneratedIdInput,
instanceId: z.string(),
- name: z.string(),
+ name: z
+ .string()
+ .describe(
+ 'Prop name. A bound "style" prop must evaluate to an object such as { color: themeColor }, never a CSS declaration string.'
+ ),
binding: z.discriminatedUnion("type", [
...dataPropBindingInput.options,
actionPropBindingInput,
@@ -324,6 +329,20 @@ export const propBindingInput = z
}),
["binding", "value"]
);
+ if (
+ value.name === "style" &&
+ value.binding.type === "expression" &&
+ !["object", "unknown"].includes(
+ getExpressionValueKind({ expression: value.binding.value })
+ )
+ ) {
+ context.addIssue({
+ code: "custom",
+ path: ["binding", "value"],
+ message:
+ 'A bound "style" prop must evaluate to an object keyed by style properties, for example { color: themeColor }.',
+ });
+ }
});
export const propUpdatesInput = z.object({
diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.ts
index a6dfee4cc1..bd64d563fe 100644
--- a/packages/project-build/src/runtime/registry.ts
+++ b/packages/project-build/src/runtime/registry.ts
@@ -1567,21 +1567,39 @@ export const builderRuntimeOperations = [
props.bindProps(
state,
{
- bindings: input.bindings.map((binding) =>
- binding.binding.type === "expression"
- ? {
- ...binding,
- binding: {
- ...binding.binding,
- value: bindExpressionInput(
+ bindings: input.bindings.map((binding) => {
+ if (binding.binding.type === "expression") {
+ return {
+ ...binding,
+ binding: {
+ ...binding.binding,
+ value: bindExpressionInput(
+ state,
+ binding.instanceId,
+ binding.binding.value
+ ),
+ },
+ };
+ }
+ if (binding.binding.type === "action") {
+ return {
+ ...binding,
+ binding: {
+ ...binding.binding,
+ value: binding.binding.value.map((action) => ({
+ ...action,
+ code: bindExpressionInput(
state,
binding.instanceId,
- binding.binding.value
+ action.code,
+ action.args
),
- },
- }
- : binding
- ),
+ })),
+ },
+ };
+ }
+ return binding;
+ }),
},
context
),
diff --git a/packages/sdk/src/resource-loader.test.ts b/packages/sdk/src/resource-loader.test.ts
index 2c60423ff9..accf4bf887 100644
--- a/packages/sdk/src/resource-loader.test.ts
+++ b/packages/sdk/src/resource-loader.test.ts
@@ -232,6 +232,52 @@ describe("loadResource", () => {
});
});
+ test("logs the response body when a resource request fails", async () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ mockFetch.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ code: "INVALID_REQUEST",
+ issues: [{ path: ["query", "where"] }],
+ }),
+ { status: 400 }
+ )
+ );
+
+ await loadResource(mockFetch, {
+ name: "resource",
+ url: "https://example.com/resource",
+ searchParams: [],
+ method: "get",
+ headers: [],
+ });
+
+ expect(error).toHaveBeenCalledWith(
+ expect.stringContaining('"code": "INVALID_REQUEST"')
+ );
+ expect(error).toHaveBeenCalledWith(
+ expect.stringContaining('"path": [\n "query",\n "where"')
+ );
+ });
+
+ test("bounds resource error diagnostics", async () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ mockFetch.mockResolvedValue(
+ new Response("x".repeat(3000), { status: 500 })
+ );
+
+ await loadResource(mockFetch, {
+ name: "resource",
+ url: "https://example.com/resource",
+ searchParams: [],
+ method: "get",
+ headers: [],
+ });
+
+ expect(error).toHaveBeenCalledWith(expect.stringContaining("…truncated"));
+ expect(error.mock.calls[0]?.[0]).not.toContain("x".repeat(2001));
+ });
+
test("exposes Assets query results as an ID-keyed resource value", async () => {
mockFetch.mockResolvedValue(
new Response(
diff --git a/packages/sdk/src/resource-loader.ts b/packages/sdk/src/resource-loader.ts
index 6b25909f47..e4363fc79b 100644
--- a/packages/sdk/src/resource-loader.ts
+++ b/packages/sdk/src/resource-loader.ts
@@ -3,6 +3,32 @@ import type { ResourceRequest } from "./schema/resources";
import { serializeValue } from "./to-string";
const LOCAL_RESOURCE_PREFIX = "$resources";
+const RESOURCE_ERROR_DETAIL_LIMIT = 2000;
+
+const formatResourceErrorDetail = (data: unknown) => {
+ let detail = "";
+ if (typeof data === "string") {
+ detail = data;
+ } else if (
+ typeof data === "object" &&
+ data !== null &&
+ Array.isArray(data) === false
+ ) {
+ const record = data as Record<string, unknown>;
+ const structuredDetail: Record<string, unknown> = {};
+ for (const key of ["code", "message", "issues"]) {
+ if (record[key] !== undefined) {
+ structuredDetail[key] = record[key];
+ }
+ }
+ if (Object.keys(structuredDetail).length > 0) {
+ detail = JSON.stringify(structuredDetail, undefined, 2);
+ }
+ }
+ return detail.length > RESOURCE_ERROR_DETAIL_LIMIT
+ ? `${detail.slice(0, RESOURCE_ERROR_DETAIL_LIMIT)}\n…truncated`
+ : detail;
+};
/**
* Prevents fetch cycles by prefixing local resources.
@@ -294,7 +320,10 @@ export const loadResource = async (
}
if (!response.ok) {
- console.error(`Failed to load resource request: ${response.status}`);
+ const detail = formatResourceErrorDetail(data);
+ console.error(
+ `Failed to load resource request: ${response.status}${detail === "" ? "" : `\n${detail}`}`
+ );
}
const result = {