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.

feat: support objects and member expressions (#2576)

Bogdan Chadkind04beb762071
diff --git a/apps/builder/app/builder/features/settings-panel/variables.tsx b/apps/builder/app/builder/features/settings-panel/variables.tsx
index 1afbd48b49..5dbbb08657 100644
--- a/apps/builder/app/builder/features/settings-panel/variables.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variables.tsx
@@ -46,7 +46,8 @@ const parseVariableValue = (code: string) => {
const result: { value?: unknown; error?: string } = {};
const ids = new Set<string>();
try {
- validateExpression(code, {
+ code = validateExpression(code, {
+ optional: true,
transformIdentifier: (id) => {
ids.add(id);
return id;
@@ -58,7 +59,8 @@ const parseVariableValue = (code: string) => {
}
if (ids.size === 0) {
try {
- result.value = eval(code);
+ // wrap with parentheses to treat {} as object instead of block
+ result.value = eval(`(${code})`);
} catch (error) {
result.error = `Parse Error: ${(error as Error).message}`;
}
@@ -85,10 +87,7 @@ const saveVariable = (
}
const [instanceId] = instanceSelector;
serverSyncStore.createTransaction([dataSourcesStore], (dataSources) => {
- let variableValue: VariableDataSource["value"] = {
- type: "string",
- value: "",
- };
+ let variableValue: VariableDataSource["value"] = { type: "json", value };
if (typeof value === "string") {
variableValue = { type: "string", value };
}
diff --git a/packages/react-sdk/package.json b/packages/react-sdk/package.json
index 1795fc5d34..e4b2557a07 100644
--- a/packages/react-sdk/package.json
+++ b/packages/react-sdk/package.json
@@ -35,6 +35,7 @@
},
"dependencies": {
"@jsep-plugin/assignment": "^1.2.1",
+ "@jsep-plugin/object": "^1.2.1",
"@webstudio-is/css-engine": "workspace:*",
"@webstudio-is/fonts": "workspace:*",
"@webstudio-is/image": "workspace:*",
diff --git a/packages/react-sdk/src/expression.test.ts b/packages/react-sdk/src/expression.test.ts
index c3a0be72df..b8435b4131 100644
--- a/packages/react-sdk/src/expression.test.ts
+++ b/packages/react-sdk/src/expression.test.ts
@@ -14,6 +14,32 @@ test("allow literals and array expressions", () => {
).toEqual(`["", '', 0, true, false, null, undefined]`);
});
+test("allow object literals", () => {
+ const ids: string[] = [];
+ expect(
+ validateExpression(
+ `{param1: "", "param2": 0, ["param3"]: false, [a]: b }`,
+ {
+ transformIdentifier: (id) => {
+ ids.push(id);
+ return id;
+ },
+ }
+ )
+ ).toEqual(`{param1: "", "param2": 0, ["param3"]: false, [a]: b}`);
+ expect(ids).toEqual(["a", "b"]);
+});
+
+test("expand shorthand properties in objects", () => {
+ expect(validateExpression(`{a}`)).toEqual(`{a: a}`);
+});
+
+test("supports array of objects", () => {
+ expect(
+ validateExpression(`[{name: 'John'}, {name: 'Dave'}, {name: 'Oliver'}]`)
+ ).toEqual(`[{name: 'John'}, {name: 'Dave'}, {name: 'Oliver'}]`);
+});
+
test("allow unary and binary expressions", () => {
expect(validateExpression(`[-1, 1 + 1]`)).toEqual(`[-1, 1 + 1]`);
});
@@ -25,10 +51,49 @@ test("optionally allow assignment expressions", () => {
expect(validateExpression(`a = 2`, { effectful: true })).toEqual(`a = 2`);
});
-test("forbid member expressions", () => {
- expect(() => {
- validateExpression("var1 + obj.param");
- }).toThrowError(/Cannot access "param" of "obj"/);
+test("allow member expressions", () => {
+ const ids: string[] = [];
+ expect(
+ validateExpression("a.b.c", {
+ transformIdentifier: (id) => {
+ ids.push(id);
+ return id;
+ },
+ })
+ ).toEqual("a.b.c");
+ expect(ids).toEqual(["a"]);
+});
+
+test("allow indexed member expressions", () => {
+ const ids: string[] = [];
+ expect(
+ validateExpression(`a["b"][1]`, {
+ transformIdentifier: (id) => {
+ ids.push(id);
+ return id;
+ },
+ })
+ ).toEqual(`a["b"][1]`);
+ expect(ids).toEqual(["a"]);
+});
+
+test("allow indexed member expressions with identifiers", () => {
+ const ids: string[] = [];
+ expect(
+ validateExpression(`a[b]`, {
+ transformIdentifier: (id) => {
+ ids.push(id);
+ return id;
+ },
+ })
+ ).toEqual(`a[b]`);
+ expect(ids).toEqual(["a", "b"]);
+});
+
+test("optionally transpile all member expressions into optional chaining", () => {
+ expect(validateExpression(`a.b["c"][1]`, { optional: true })).toEqual(
+ `a?.b?.["c"]?.[1]`
+ );
});
test("forbid this expressions", () => {
diff --git a/packages/react-sdk/src/expression.ts b/packages/react-sdk/src/expression.ts
index 3f1f28fba4..a00ef2b2d9 100644
--- a/packages/react-sdk/src/expression.ts
+++ b/packages/react-sdk/src/expression.ts
@@ -1,112 +1,86 @@
import jsep from "jsep";
import jsepAssignment from "@jsep-plugin/assignment";
+import jsepObject from "@jsep-plugin/object";
import type {
UpdateExpression,
AssignmentExpression,
} from "@jsep-plugin/assignment";
+import type { ObjectExpression, Property } from "@jsep-plugin/object";
import type { DataSources, Props, Scope } from "@webstudio-is/sdk";
jsep.plugins.register(jsepAssignment);
+jsep.plugins.register(jsepObject);
type TransformIdentifier = (id: string, assignee: boolean) => string;
-type Node = jsep.CoreExpression | UpdateExpression | AssignmentExpression;
+type Node =
+ | jsep.CoreExpression
+ | UpdateExpression
+ | AssignmentExpression
+ | ObjectExpression
+ | Property;
const generateCode = (
node: Node,
failOnForbidden: boolean,
- effectful: boolean,
- transformIdentifier: TransformIdentifier
+ options: {
+ effectful: boolean;
+ optional: boolean;
+ transformIdentifier: TransformIdentifier;
+ }
): string => {
if (node.type === "Identifier") {
- return transformIdentifier(node.name, false);
+ return options.transformIdentifier(node.name, false);
}
if (node.type === "MemberExpression") {
- if (failOnForbidden) {
- const object = generateCode(
- node.object as Node,
- false,
- effectful,
- transformIdentifier
- );
- const property = generateCode(
- node.property as Node,
- false,
- effectful,
- transformIdentifier
- );
- throw Error(`Cannot access "${property}" of "${object}"`);
+ const object = generateCode(node.object as Node, failOnForbidden, options);
+ const property = node.property as Node;
+ let propertyString: string;
+ // prevent transforming identifiers from member expressions like "b" in "a.b"
+ if (property.type === "Identifier" && node.computed === false) {
+ propertyString = property.name;
+ } else {
+ propertyString = generateCode(property, failOnForbidden, options);
+ }
+ if (node.computed) {
+ if (options.optional) {
+ return `${object}?.[${propertyString}]`;
+ } else {
+ return `${object}[${propertyString}]`;
+ }
+ }
+ if (options.optional) {
+ return `${object}?.${propertyString}`;
+ } else {
+ return `${object}.${propertyString}`;
}
- const object = generateCode(
- node.object as Node,
- failOnForbidden,
- effectful,
- transformIdentifier
- );
- const property = generateCode(
- node.property as Node,
- failOnForbidden,
- effectful,
- transformIdentifier
- );
- return `${object}.${property}`;
}
if (node.type === "Literal") {
return node.raw;
}
if (node.type === "UnaryExpression") {
- const arg = generateCode(
- node.argument as Node,
- failOnForbidden,
- effectful,
- transformIdentifier
- );
+ const arg = generateCode(node.argument as Node, failOnForbidden, options);
return `${node.operator}${arg}`;
}
if (node.type === "BinaryExpression") {
- const left = generateCode(
- node.left as Node,
- failOnForbidden,
- effectful,
- transformIdentifier
- );
- const right = generateCode(
- node.right as Node,
- failOnForbidden,
- effectful,
- transformIdentifier
- );
+ const left = generateCode(node.left as Node, failOnForbidden, options);
+ const right = generateCode(node.right as Node, failOnForbidden, options);
return `${left} ${node.operator} ${right}`;
}
if (node.type === "ArrayExpression") {
const elements = node.elements.map((element) =>
- generateCode(
- element as Node,
- failOnForbidden,
- effectful,
- transformIdentifier
- )
+ generateCode(element as Node, failOnForbidden, options)
);
return `[${elements.join(", ")}]`;
}
if (node.type === "CallExpression") {
if (failOnForbidden) {
- const callee = generateCode(
- node.callee as Node,
- false,
- effectful,
- transformIdentifier
- );
+ const callee = generateCode(node.callee as Node, false, options);
throw Error(`Cannot call "${callee}"`);
}
- const callee = generateCode(
- node.callee as Node,
- failOnForbidden,
- effectful,
- transformIdentifier
- );
+ const callee = generateCode(node.callee as Node, failOnForbidden, options);
const args = node.arguments.map((arg) =>
- generateCode(arg as Node, failOnForbidden, effectful, transformIdentifier)
+ generateCode(arg as Node, failOnForbidden, options)
);
return `${callee}(${args.join(", ")})`;
}
@@ -126,39 +100,70 @@ const generateCode = (
if (node.operator !== "=") {
throw Error(`Only "=" assignment operator is supported`);
}
- if (effectful === false) {
+ if (options.effectful === false) {
throw Error(`Cannot use assignment in this expression`);
}
- const left = generateCode(
- node.left as Node,
- failOnForbidden,
- effectful,
+ const left = generateCode(node.left as Node, failOnForbidden, {
+ ...options,
// override and mark all identifiers inside of left expression as assignee
- (id) => transformIdentifier(id, true)
- );
- const right = generateCode(
- node.right as Node,
- failOnForbidden,
- effectful,
- transformIdentifier
- );
+ transformIdentifier: (id) => options.transformIdentifier(id, true),
+ });
+ const right = generateCode(node.right as Node, failOnForbidden, options);
return `${left} ${node.operator} ${right}`;
}
if (node.type === "UpdateExpression") {
throw Error(`"${node.operator}" operator is not supported`);
}
+ if (node.type === "ObjectExpression") {
+ const properties = node.properties.map((property) =>
+ generateCode(property, failOnForbidden, options)
+ );
+ return `{${properties.join(", ")}}`;
+ }
+ if (node.type === "Property") {
+ const key = node.key as Node;
+ let keyString: string;
+ if (key.type === "Identifier" && node.computed === false) {
+ keyString = key.name;
+ } else {
+ keyString = generateCode(key, failOnForbidden, options);
+ }
+ const value = generateCode(node.value as Node, failOnForbidden, options);
+ if (node.computed) {
+ return `[${keyString}]: ${value}`;
+ }
+ return `${keyString}: ${value}`;
+ }
node satisfies never;
return "";
};
export const validateExpression = (
code: string,
- options?: { effectful?: boolean; transformIdentifier?: TransformIdentifier }
+ options?: {
+ /**
+ * Enable assignment operator for actions
+ */
+ effectful?: boolean;
+ /**
+ * Add optional chaining to access nested properties safely
+ * and without checks even when not exist
+ */
+ optional?: boolean;
+ transformIdentifier?: TransformIdentifier;
+ }
) => {
- const { effectful = false, transformIdentifier = (id: string) => id } =
- options ?? {};
+ const {
+ effectful = false,
+ optional = false,
+ transformIdentifier = (id: string) => id,
+ } = options ?? {};
const expression = jsep(code) as Node;
- return generateCode(expression, true, effectful, transformIdentifier);
+ return generateCode(expression, true, {
+ effectful,
+ optional,
+ transformIdentifier,
+ });
};
const computeExpressionDependencies = (
@@ -297,6 +302,7 @@ export const generateDataSources = ({
const name = scope.getName(prop.id, prop.name);
output.set(prop.id, name);
const code = validateExpression(dataSource.code, {
+ optional: true,
transformIdentifier: (identifier) => {
const depId = decodeDataSourceVariable(identifier);
const dep = depId ? dataSources.get(depId) : undefined;
@@ -321,6 +327,7 @@ export const generateDataSources = ({
for (const value of prop.value) {
args = value.args;
newCode += validateExpression(value.code, {
+ optional: true,
effectful: true,
transformIdentifier: (identifier, assignee) => {
if (args?.includes(identifier)) {
diff --git a/packages/sdk/src/schema/data-sources.ts b/packages/sdk/src/schema/data-sources.ts
index 8409a52d52..09d4d654ac 100644
--- a/packages/sdk/src/schema/data-sources.ts
+++ b/packages/sdk/src/schema/data-sources.ts
@@ -20,6 +20,10 @@ export const DataSourceVariableValue = z.union([
type: z.literal("string[]"),
value: z.array(z.string()),
}),
+ z.object({
+ type: z.literal("json"),
+ value: z.unknown(),
+ }),
]);
export const DataSource = z.union([
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 335ffe308c..9052ef8cbf 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1562,6 +1562,9 @@ importers:
'@jsep-plugin/assignment':
specifier: ^1.2.1
version: 1.2.1([email protected])
+ '@jsep-plugin/object':
+ specifier: ^1.2.1
+ version: 1.2.1([email protected])
'@webstudio-is/css-engine':
specifier: workspace:*
version: link:../css-engine
@@ -4491,6 +4494,15 @@ packages:
jsep: 1.3.8
dev: false
+ resolution: {integrity: sha512-6YoZP80h2QFCuxyqj+OvoqEnTu2r5cSRpgpvGauWlvnevFP/F/dibpvXDpnHeqwT2FIzzvg47YOe3QD/UT8vJw==}
+ engines: {node: '>= 10.16.0'}
+ peerDependencies:
+ jsep: ^0.4.0||^1.0.0
+ dependencies:
+ jsep: 1.3.8
+ dev: false
+
resolution: {integrity: sha512-Lg3PnLp0QXpxwLIAuuJboLeRaIhrgJjeuh797QADg3xz8wGLugQOS5DpsE8A6i6Adgzf+bacllkKZG3J0tGfDw==}
dev: true