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: Fix expression method completions (#5765)

Oleg Isonend88f0067c2c3
diff --git a/apps/builder/app/builder/shared/expression-editor.test.ts b/apps/builder/app/builder/shared/expression-editor.test.ts
index 063e7407d6..dbf8e733a1 100644
--- a/apps/builder/app/builder/shared/expression-editor.test.ts
+++ b/apps/builder/app/builder/shared/expression-editor.test.ts
@@ -1,5 +1,79 @@
import { describe, test, expect } from "vitest";
-import { generateCompletionOptions } from "./expression-editor";
+import { CompletionContext } from "@codemirror/autocomplete";
+import { EditorState } from "@codemirror/state";
+import { javascript } from "@codemirror/lang-javascript";
+import { allowedArrayMethods, allowedStringMethods } from "@webstudio-is/sdk";
+import {
+ completionPath,
+ generateCompletionOptions,
+ getCompletionTarget,
+ getCompletionReplacement,
+} from "./expression-editor";
+
+type CompletionReplacement = ReturnType<typeof getCompletionReplacement>;
+
+const applyReplacement = (
+ value: string,
+ { text, from, to }: CompletionReplacement
+) => {
+ return `${value.slice(0, from)}${text}${value.slice(to)}`;
+};
+
+const expectMethodOptions = ({
+ options,
+ methods,
+ detail,
+}: {
+ options: ReturnType<typeof generateCompletionOptions>;
+ methods: ReadonlySet<string>;
+ detail: string;
+}) => {
+ for (const method of methods) {
+ expect(options).toContainEqual({
+ label: method,
+ displayLabel: `${method}()`,
+ detail,
+ type: "method",
+ insertText: `${method}()`,
+ });
+ }
+};
+
+const expectMethodsInsertAsCalls = ({
+ methods,
+ objectName,
+}: {
+ methods: ReadonlySet<string>;
+ objectName: string;
+}) => {
+ const memberPrefix = `${objectName}.`;
+
+ for (const method of methods) {
+ const value = `${memberPrefix}${method.slice(0, 3)}`;
+ const result = applyReplacement(
+ value,
+ getCompletionReplacement({
+ label: method,
+ insertText: `${method}()`,
+ type: "method",
+ pathLength: 1,
+ from: memberPrefix.length,
+ to: value.length,
+ })
+ );
+
+ expect(result).toEqual(`${memberPrefix}${method}()`);
+ expect(result).not.toContain(`["${method}()"]`);
+ }
+};
+
+const getCompletionPath = (value: string) => {
+ const state = EditorState.create({
+ doc: value,
+ extensions: [javascript({})],
+ });
+ return completionPath(new CompletionContext(state, value.length, true));
+};
describe("generateCompletionOptions", () => {
describe("object properties", () => {
@@ -64,7 +138,11 @@ describe("generateCompletionOptions", () => {
expect(labels).toContain("1");
expect(labels).toContain("2");
expect(labels).toContain("length");
- expect(labels).toContain("slice()");
+ expectMethodOptions({
+ options,
+ methods: allowedArrayMethods,
+ detail: "array method",
+ });
// Check specific values
const lengthOption = options.find((o) => o.label === "length");
@@ -89,6 +167,52 @@ describe("generateCompletionOptions", () => {
type: "property",
});
});
+
+ test("returns array methods after string method calls returning arrays", () => {
+ const path = getCompletionPath("Test.split(2).");
+ expect(path).toEqual({
+ path: [],
+ name: "",
+ expression: "Test.split(2)",
+ });
+
+ const target = getCompletionTarget({
+ ...path!,
+ scope: { Test: "Test" },
+ });
+ const options = generateCompletionOptions({
+ target,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ expectMethodOptions({
+ options,
+ methods: allowedArrayMethods,
+ detail: "array method",
+ });
+ });
+
+ test("filters array methods after string method calls returning arrays", () => {
+ const path = getCompletionPath("Test.split(2).toS");
+ expect(path).toEqual({
+ path: [],
+ name: "toS",
+ expression: "Test.split(2)",
+ });
+
+ const target = getCompletionTarget({
+ ...path!,
+ scope: { Test: "Test" },
+ });
+ const labels = generateCompletionOptions({
+ target,
+ pathName: path!.name,
+ pathLength: 1,
+ }).map((option) => option.label);
+
+ expect(labels).toEqual(["toString"]);
+ });
});
describe("string methods", () => {
@@ -100,10 +224,11 @@ describe("generateCompletionOptions", () => {
pathLength: 1,
});
- const methodLabels = options.map((o) => o.label);
- expect(methodLabels).toContain("toUpperCase()");
- expect(methodLabels).toContain("toLowerCase()");
- expect(methodLabels).toContain("replace()");
+ expectMethodOptions({
+ options,
+ methods: allowedStringMethods,
+ detail: "string method",
+ });
});
test("filters string methods by pathName", () => {
@@ -116,8 +241,74 @@ describe("generateCompletionOptions", () => {
// Should include both toUpperCase and toLocaleUpperCase
const labels = options.map((o) => o.label);
- expect(labels).toContain("toUpperCase()");
- expect(labels).toContain("toLocaleUpperCase()");
+ expect(labels).toContain("toUpperCase");
+ expect(labels).toContain("toLocaleUpperCase");
+ });
+
+ test("returns string methods after array method calls returning strings", () => {
+ const path = getCompletionPath("items.join().");
+ expect(path).toEqual({
+ path: [],
+ name: "",
+ expression: "items.join()",
+ });
+
+ const target = getCompletionTarget({
+ ...path!,
+ scope: { items: ["T", "e", "s", "t"] },
+ });
+ const options = generateCompletionOptions({
+ target,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ expectMethodOptions({
+ options,
+ methods: allowedStringMethods,
+ detail: "string method",
+ });
+ });
+
+ test("returns string methods after string-only calls on unknown receivers", () => {
+ const path = getCompletionPath(`Test.replace("e", "a").`);
+ expect(path).toEqual({
+ path: [],
+ name: "",
+ expression: `Test.replace("e", "a")`,
+ });
+
+ const target = getCompletionTarget({
+ ...path!,
+ scope: {},
+ });
+ const options = generateCompletionOptions({
+ target,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ expectMethodOptions({
+ options,
+ methods: allowedStringMethods,
+ detail: "string method",
+ });
+ });
+
+ test("does not infer conflicting return kinds for unknown receivers", () => {
+ const path = getCompletionPath("value.slice().");
+ expect(path).toEqual({
+ path: [],
+ name: "",
+ expression: "value.slice()",
+ });
+
+ expect(
+ getCompletionTarget({
+ ...path!,
+ scope: {},
+ })
+ ).toEqual(undefined);
});
test("does not return string methods for non-string targets", () => {
@@ -134,6 +325,87 @@ describe("generateCompletionOptions", () => {
});
});
+ describe("method completion insertion", () => {
+ test("inserts all supported string methods as method calls", () => {
+ expectMethodsInsertAsCalls({
+ methods: allowedStringMethods,
+ objectName: "Test",
+ });
+ });
+
+ test("inserts all supported array methods as method calls", () => {
+ expectMethodsInsertAsCalls({
+ methods: allowedArrayMethods,
+ objectName: "items",
+ });
+ });
+
+ test("keeps non-identifier properties as computed members", () => {
+ const value = "Test.";
+
+ expect(
+ applyReplacement(
+ value,
+ getCompletionReplacement({
+ label: "prop with spaces",
+ pathLength: 1,
+ from: value.length,
+ to: value.length,
+ })
+ )
+ ).toEqual(`Test["prop with spaces"]`);
+ });
+
+ test("keeps numeric properties as computed members", () => {
+ const value = "items.";
+
+ expect(
+ applyReplacement(
+ value,
+ getCompletionReplacement({
+ label: "0",
+ pathLength: 1,
+ from: value.length,
+ to: value.length,
+ })
+ )
+ ).toEqual("items[0]");
+ });
+ });
+
+ describe("completion replacement ranges", () => {
+ test("replaces only the typed identifier for identifier properties", () => {
+ const value = "Test.na";
+
+ expect(
+ applyReplacement(
+ value,
+ getCompletionReplacement({
+ label: "name",
+ pathLength: 1,
+ from: "Test.".length,
+ to: value.length,
+ })
+ )
+ ).toEqual("Test.name");
+ });
+
+ test("does not rewrite top-level non-identifier variables as computed members", () => {
+ expect(
+ getCompletionReplacement({
+ label: "$ws$dataSource$example",
+ pathLength: 0,
+ from: 0,
+ to: 0,
+ })
+ ).toEqual({
+ text: "$ws$dataSource$example",
+ from: 0,
+ to: 0,
+ });
+ });
+ });
+
describe("pathLength === 0 (top-level variables)", () => {
test("does not include methods for top-level variables", () => {
const target = "hello";
@@ -216,7 +488,9 @@ describe("generateCompletionOptions", () => {
// Empty array has length and all array methods
const labels = options.map((o) => o.label);
expect(labels).toContain("length");
- expect(labels).toContain("slice()");
+ for (const method of allowedArrayMethods) {
+ expect(labels).toContain(method);
+ }
const lengthOption = options.find((o) => o.label === "length");
expect(lengthOption).toEqual({
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index fdb84a0b51..013c4865c8 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -32,6 +32,7 @@ import {
lintExpression,
allowedStringMethods,
allowedArrayMethods,
+ getExpressionValueKind,
} from "@webstudio-is/sdk";
import {
EditorContent,
@@ -103,11 +104,50 @@ const VariablesData = Facet.define<{
const Identifier = /^[\p{L}$][\p{L}\p{N}$]*$/u;
+type ExpressionCompletionOption = {
+ label: string;
+ displayLabel?: string;
+ detail: string;
+ type?: "method" | "property";
+ insertText?: string;
+};
+
+type CompletionPath =
+ | { path: string[]; name: string; expression?: undefined }
+ | { path: []; name: string; expression: string };
+
+const createMethodCompletionOptions = ({
+ methods,
+ pathName,
+ detail,
+}: {
+ methods: ReadonlySet<string>;
+ pathName: string;
+ detail: string;
+}): Array<ExpressionCompletionOption> => {
+ const query = pathName.toLowerCase();
+ const options: Array<ExpressionCompletionOption> = [];
+
+ for (const method of methods) {
+ if (method.toLowerCase().includes(query)) {
+ options.push({
+ label: method,
+ displayLabel: `${method}()`,
+ detail,
+ type: "method",
+ insertText: `${method}()`,
+ });
+ }
+ }
+
+ return options;
+};
+
const pathFor = (
read: (node: SyntaxNode) => string,
member: SyntaxNode,
name: string
-) => {
+): CompletionPath | undefined => {
const path: string[] = [];
// traverse from current node to the root variable
for (;;) {
@@ -152,12 +192,22 @@ const pathFor = (
/// it will return `{path: [], name: "x"}`. When not in a property or
/// name, it will return undefined if `context.explicit` is false, and
/// `{path: [], name: ""}` otherwise.
-const completionPath = (
+export const completionPath = (
context: CompletionContext
-): { path: string[]; name: string } | undefined => {
+): CompletionPath | undefined => {
const read = (node: SyntaxNode) =>
context.state.doc.sliceString(node.from, node.to);
const inner = syntaxTree(context.state).resolveInner(context.pos, -1);
+ const pathForMemberExpression = (member: SyntaxNode, name: string) => {
+ const path = pathFor(read, member, name);
+ if (path) {
+ return path;
+ }
+ const object = member.firstChild;
+ if (object) {
+ return { path: [] as [], name, expression: read(object) };
+ }
+ };
// suggest global variable name when user start completion explicitly
if (inner.name === "Script") {
if (context.explicit) {
@@ -171,18 +221,49 @@ const completionPath = (
}
// suggest property name when enter `object.`
if (inner.name === "." && inner.parent?.name === "MemberExpression") {
- return pathFor(read, inner.parent, "");
+ return pathForMemberExpression(inner.parent, "");
}
// complete property when enter "object.prope"
if (
inner.name === "PropertyName" &&
inner.parent?.name === "MemberExpression"
) {
- return pathFor(read, inner.parent, read(inner));
+ return pathForMemberExpression(inner.parent, read(inner));
}
return;
};
+export const getCompletionTarget = ({
+ expression,
+ path,
+ scope,
+}: CompletionPath & {
+ scope: Scope;
+}) => {
+ if (expression) {
+ const valueKind = getExpressionValueKind({
+ expression,
+ variableValues: scope,
+ });
+ if (valueKind === "array") {
+ return [];
+ }
+ if (valueKind === "string") {
+ return "";
+ }
+ return;
+ }
+
+ let target: unknown = scope;
+ for (const step of path) {
+ target = (target as Record<string, unknown> | undefined)?.[step];
+ if (target == null) {
+ return;
+ }
+ }
+ return target;
+};
+
/**
* Generate completion options for object properties and array/string methods.
* Exported for testing.
@@ -195,8 +276,8 @@ export const generateCompletionOptions = ({
target: unknown;
pathName: string;
pathLength: number;
-}): Array<{ label: string; detail: string; type?: string }> => {
- const options: Array<{ label: string; detail: string; type?: string }> = [];
+}): Array<ExpressionCompletionOption> => {
+ const options: Array<ExpressionCompletionOption> = [];
// Add object properties
if (typeof target === "object" && target !== null) {
@@ -214,15 +295,13 @@ export const generateCompletionOptions = ({
const isArray = Array.isArray(target);
if (isString) {
- for (const method of allowedStringMethods) {
- if (method.toLowerCase().includes(pathName.toLowerCase())) {
- options.push({
- label: `${method}()`,
- detail: "string method",
- type: "method",
- });
- }
- }
+ options.push(
+ ...createMethodCompletionOptions({
+ methods: allowedStringMethods,
+ pathName,
+ detail: "string method",
+ })
+ );
}
if (isArray) {
@@ -235,21 +314,59 @@ export const generateCompletionOptions = ({
});
}
- for (const method of allowedArrayMethods) {
- if (method.toLowerCase().includes(pathName.toLowerCase())) {
- options.push({
- label: `${method}()`,
- detail: "array method",
- type: "method",
- });
- }
- }
+ options.push(
+ ...createMethodCompletionOptions({
+ methods: allowedArrayMethods,
+ pathName,
+ detail: "array method",
+ })
+ );
}
}
return options;
};
+export const getCompletionReplacement = ({
+ label,
+ insertText,
+ type,
+ pathLength,
+ from,
+ to,
+}: {
+ label: string;
+ insertText?: string;
+ type?: ExpressionCompletionOption["type"];
+ pathLength: number;
+ from: number;
+ to: number;
+}) => {
+ if (type === "method") {
+ const textToInsert =
+ insertText ?? (label.endsWith("()") ? label : `${label}()`);
+ return { text: textToInsert, from, to };
+ }
+
+ const textToInsert = insertText ?? label;
+
+ // complete valid js identifier or top level variable without quotes
+ if (Identifier.test(textToInsert) || pathLength === 0) {
+ return { text: textToInsert, from, to };
+ }
+
+ return {
+ // `param with spaces` -> ["param with spaces"]
+ // `0` -> [0]
+ text: `[${/^\d+$/.test(textToInsert) ? textToInsert : JSON.stringify(textToInsert)}]`,
+ // remove dot when autocomplete computed member expression
+ // variable.
+ // variable["name"]
+ from: from - 1,
+ to,
+ };
+};
+
// Defines a completion source that completes from the given scope
// object (for example `globalThis`). Will enter properties
// of the object when completing properties on a directly-named path.
@@ -259,20 +376,16 @@ const scopeCompletionSource: CompletionSource = (context) => {
if (path === undefined) {
return null;
}
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- let target: any = scope;
- for (const step of path.path) {
- target = target?.[step];
- if (target == null) {
- return null;
- }
+ const target = getCompletionTarget({ ...path, scope });
+ if (target === undefined) {
+ return null;
}
// Generate base completion options using exported function
const baseOptions = generateCompletionOptions({
target,
pathName: path.name,
- pathLength: path.path.length,
+ pathLength: path.expression ? 1 : path.path.length,
});
// Convert to CodeMirror Completion format with apply functions
@@ -280,35 +393,27 @@ const scopeCompletionSource: CompletionSource = (context) => {
const name = option.label;
return {
label: name,
- displayLabel: decodeDataVariableName(name),
+ displayLabel: option.displayLabel ?? decodeDataVariableName(name),
detail: option.detail,
type: option.type,
apply: (view, completion, from, to) => {
- const textToInsert = name;
- // complete valid js identifier or top level variable without quotes
- if (Identifier.test(textToInsert) || path.path.length === 0) {
- // complete with dot
- view.dispatch({
- ...insertCompletionText(view.state, textToInsert, from, to),
- annotations: pickedCompletion.of(completion),
- });
- } else {
- // complete with computed member expression
- view.dispatch({
- ...insertCompletionText(
- view.state,
- // `param with spaces` -> ["param with spaces"]
- // `0` -> [0]
- `[${/^\d+$/.test(textToInsert) ? textToInsert : JSON.stringify(textToInsert)}]`,
- // remove dot when autocomplete computed member expression
- // variable.
- // variable["name"]
- from - 1,
- to
- ),
- annotations: pickedCompletion.of(completion),
- });
- }
+ const replacement = getCompletionReplacement({
+ label: name,
+ insertText: option.insertText,
+ type: option.type,
+ pathLength: path.expression ? 1 : path.path.length,
+ from,
+ to,
+ });
+ view.dispatch({
+ ...insertCompletionText(
+ view.state,
+ replacement.text,
+ replacement.from,
+ replacement.to
+ ),
+ annotations: pickedCompletion.of(completion),
+ });
},
};
});
@@ -442,6 +547,7 @@ const expressionLinter = linter((view) => {
return lintExpression({
expression: view.state.doc.toString(),
availableVariables: new Set(Object.keys(scope)),
+ variableValues: scope,
});
});
diff --git a/packages/sdk/src/expression.test.ts b/packages/sdk/src/expression.test.ts
index 8a2836f28e..111762fda6 100644
--- a/packages/sdk/src/expression.test.ts
+++ b/packages/sdk/src/expression.test.ts
@@ -11,6 +11,8 @@ import {
parseObjectExpression,
generateObjectExpression,
SYSTEM_VARIABLE_ID,
+ allowedArrayMethods,
+ allowedStringMethods,
} from "./expression";
describe("lint expression", () => {
@@ -230,6 +232,7 @@ describe("lint expression", () => {
"endsWith",
"includes",
"startsWith",
+ "toString",
"toUpperCase",
"toLocaleLowerCase",
"toLocaleUpperCase",
@@ -242,7 +245,7 @@ describe("lint expression", () => {
).toEqual([]);
});
- test.each(["at", "includes", "join", "slice"])(
+ test.each(["at", "includes", "join", "slice", "toString"])(
"allow safe array method: %s",
(method) => {
expect(
@@ -254,6 +257,94 @@ describe("lint expression", () => {
}
);
+ test("allow supported methods on known native-compatible receivers", () => {
+ expect(
+ lintExpression({
+ expression: `title.split("").toString()`,
+ availableVariables: new Set(["title"]),
+ variableValues: new Map([["title", "Test"]]),
+ })
+ ).toEqual([]);
+ expect(
+ lintExpression({
+ expression: `arr.join("").split("").toString()`,
+ availableVariables: new Set(["arr"]),
+ variableValues: new Map([["arr", ["T", "e", "s", "t"]]]),
+ })
+ ).toEqual([]);
+ expect(
+ lintExpression({
+ expression: `count.toString() + flag.toString() + object.toString()`,
+ availableVariables: new Set(["count", "flag", "object"]),
+ variableValues: new Map<string, unknown>([
+ ["count", 2],
+ ["flag", true],
+ ["object", {}],
+ ]),
+ })
+ ).toEqual([]);
+ expect(
+ lintExpression({
+ expression: `title.replace("e", "a").toLowerCase()`,
+ availableVariables: new Set(["title"]),
+ })
+ ).toEqual([]);
+ expect(
+ lintExpression({
+ expression: `arr.join("").toLowerCase()`,
+ availableVariables: new Set(["arr"]),
+ })
+ ).toEqual([]);
+ });
+
+ test("forbid supported method names on known native-incompatible receivers", () => {
+ expect(
+ lintExpression({
+ expression: `arr.split()`,
+ availableVariables: new Set(["arr"]),
+ variableValues: new Map([["arr", []]]),
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"split" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `title.join()`,
+ availableVariables: new Set(["title"]),
+ variableValues: new Map([["title", "Test"]]),
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"join" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `[1, 2, 3].toLowerCase()`,
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"toLowerCase" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `"Test".join()`,
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"join" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `title.split("").toLowerCase()`,
+ availableVariables: new Set(["title"]),
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"toLowerCase" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `arr.join("").join()`,
+ availableVariables: new Set(["arr"]),
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([`"join" function is not supported`]);
+ expect(
+ lintExpression({
+ expression: `null.toString() + undefined.toString()`,
+ }).map((diagnostic) => diagnostic.message)
+ ).toEqual([
+ `"toString" function is not supported`,
+ `"undefined" is not defined in the scope`,
+ `"toString" function is not supported`,
+ ]);
+ });
+
test("allow chained string methods", () => {
expect(
lintExpression({
@@ -331,6 +422,14 @@ describe("get expression identifiers", () => {
});
describe("transpile expression", () => {
+ const expectTranspiledExpressionToMatchNative = (expression: string) => {
+ const nativeResult = new Function(`return (${expression})`)();
+ const transpiledResult = new Function(
+ `return (${transpileExpression({ expression, executable: true })})`
+ )();
+ expect(transpiledResult).toEqual(nativeResult);
+ };
+
test("preserve spaces and parentheses", () => {
expect(
transpileExpression({ expression: " 1 + (2 + 3) ", executable: true })
@@ -434,6 +533,48 @@ describe("transpile expression", () => {
).toEqual("data?.title?.split?.('-')");
});
+ test("preserve native behavior for all supported string methods", () => {
+ const expressionsByMethod = {
+ at: `"Hello".at(1)`,
+ endsWith: `"Hello".endsWith("lo")`,
+ includes: `"Hello".includes("ell")`,
+ replace: `"Hello".replace("l", "x")`,
+ slice: `"Hello".slice(1, 4)`,
+ split: `"Hello".split("l")`,
+ startsWith: `"Hello".startsWith("He")`,
+ toLocaleLowerCase: `"Hello".toLocaleLowerCase()`,
+ toLocaleUpperCase: `"Hello".toLocaleUpperCase()`,
+ toLowerCase: `"Hello".toLowerCase()`,
+ toString: `"Hello".toString()`,
+ toUpperCase: `"Hello".toUpperCase()`,
+ };
+
+ expect(new Set(Object.keys(expressionsByMethod))).toEqual(
+ allowedStringMethods
+ );
+ for (const expression of Object.values(expressionsByMethod)) {
+ expectTranspiledExpressionToMatchNative(expression);
+ }
+ expectTranspiledExpressionToMatchNative(`"Test".split(2).toString()`);
+ });
+
+ test("preserve native behavior for all supported array methods", () => {
+ const expressionsByMethod = {
+ at: `["a", "b", "c"].at(1)`,
+ includes: `["a", "b", "c"].includes("b")`,
+ join: `["a", "b", "c"].join("-")`,
+ slice: `["a", "b", "c"].slice(1, 3)`,
+ toString: `["a", "b", "c"].toString()`,
+ };
+
+ expect(new Set(Object.keys(expressionsByMethod))).toEqual(
+ allowedArrayMethods
+ );
+ for (const expression of Object.values(expressionsByMethod)) {
+ expectTranspiledExpressionToMatchNative(expression);
+ }
+ });
+
test("transpile chained string methods with optional chaining", () => {
expect(
transpileExpression({
diff --git a/packages/sdk/src/expression.ts b/packages/sdk/src/expression.ts
index 18364b93a4..90f6048d41 100644
--- a/packages/sdk/src/expression.ts
+++ b/packages/sdk/src/expression.ts
@@ -29,30 +29,216 @@ type ExpressionVisitor = {
[K in Expression["type"]]: (node: Extract<Expression, { type: K }>) => void;
};
-export const allowedStringMethods = new Set([
- "toLowerCase",
- "replace",
- "split",
- "slice",
- "at",
- "endsWith",
- "includes",
- "startsWith",
- "toUpperCase",
- "toLocaleLowerCase",
- "toLocaleUpperCase",
+export type VariableValues =
+ | ReadonlyMap<Identifier["name"], unknown>
+ | Readonly<Record<Identifier["name"], unknown>>;
+
+export type ExpressionValueKind =
+ | "array"
+ | "bigint"
+ | "boolean"
+ | "nullish"
+ | "number"
+ | "object"
+ | "string"
+ | "unknown";
+
+const stringMethodReturnKindByName = new Map<string, ExpressionValueKind>([
+ ["toLowerCase", "string"],
+ ["replace", "string"],
+ ["split", "array"],
+ ["slice", "string"],
+ ["at", "unknown"],
+ ["endsWith", "boolean"],
+ ["includes", "boolean"],
+ ["startsWith", "boolean"],
+ ["toString", "string"],
+ ["toUpperCase", "string"],
+ ["toLocaleLowerCase", "string"],
+ ["toLocaleUpperCase", "string"],
+]);
+
+const arrayMethodReturnKindByName = new Map<string, ExpressionValueKind>([
+ ["at", "unknown"],
+ ["includes", "boolean"],
+ ["join", "string"],
+ ["slice", "array"],
+ ["toString", "string"],
]);
-export const allowedArrayMethods = new Set(["at", "includes", "join", "slice"]);
+export const allowedStringMethods = new Set(
+ stringMethodReturnKindByName.keys()
+);
+
+export const allowedArrayMethods = new Set(arrayMethodReturnKindByName.keys());
+
+const getVariableValue = (
+ variableValues: undefined | VariableValues,
+ name: Identifier["name"]
+) => {
+ if (variableValues === undefined) {
+ return;
+ }
+ const maybeMap = variableValues as Partial<ReadonlyMap<string, unknown>>;
+ if (
+ typeof maybeMap.has === "function" &&
+ typeof maybeMap.get === "function"
+ ) {
+ if (maybeMap.has(name)) {
+ return { value: maybeMap.get(name) };
+ }
+ return;
+ }
+ const record = variableValues as Readonly<Record<string, unknown>>;
+ if (Object.hasOwn(record, name)) {
+ return { value: record[name] };
+ }
+};
+
+const getValueKind = (value: unknown): ExpressionValueKind => {
+ if (Array.isArray(value)) {
+ return "array";
+ }
+ if (value === undefined || value === null) {
+ return "nullish";
+ }
+ switch (typeof value) {
+ case "bigint":
+ return "bigint";
+ case "boolean":
+ return "boolean";
+ case "number":
+ return "number";
+ case "string":
+ return "string";
+ case "object":
+ return "object";
+ default:
+ return "unknown";
+ }
+};
+
+const getMethodReturnKind = (
+ receiverKind: ExpressionValueKind,
+ methodName: string
+): ExpressionValueKind => {
+ if (receiverKind === "array") {
+ return arrayMethodReturnKindByName.get(methodName) ?? "unknown";
+ }
+ if (receiverKind === "string") {
+ return stringMethodReturnKindByName.get(methodName) ?? "unknown";
+ }
+ if (receiverKind === "unknown") {
+ const stringReturnKind = stringMethodReturnKindByName.get(methodName);
+ const arrayReturnKind = arrayMethodReturnKindByName.get(methodName);
+ if (stringReturnKind && arrayReturnKind === undefined) {
+ return stringReturnKind;
+ }
+ if (arrayReturnKind && stringReturnKind === undefined) {
+ return arrayReturnKind;
+ }
+ if (stringReturnKind === arrayReturnKind) {
+ return stringReturnKind ?? "unknown";
+ }
+ return "unknown";
+ }
+ return methodName === "toString" ? "string" : "unknown";
+};
+
+const isMethodSupported = (
+ receiverKind: ExpressionValueKind,
+ methodName: string
+) => {
+ if (receiverKind === "unknown") {
+ return (
+ allowedStringMethods.has(methodName) ||
+ allowedArrayMethods.has(methodName)
+ );
+ }
+ if (receiverKind === "string") {
+ return stringMethodReturnKindByName.has(methodName);
+ }
+ if (receiverKind === "array") {
+ return arrayMethodReturnKindByName.has(methodName);
+ }
+ if (receiverKind === "nullish") {
+ return false;
+ }
+ return methodName === "toString";
+};
+
+const getExpressionNodeValueKind = (
+ node: Expression,
+ variableValues: undefined | VariableValues
+): ExpressionValueKind => {
+ if (node.type === "Identifier") {
+ if (node.name === "undefined") {
+ return "nullish";
+ }
+ const variable = getVariableValue(variableValues, node.name);
+ return variable ? getValueKind(variable.value) : "unknown";
+ }
+ if (node.type === "Literal") {
+ return getValueKind(node.value);
+ }
+ if (node.type === "ArrayExpression") {
+ return "array";
+ }
+ if (node.type === "ObjectExpression") {
+ return "object";
+ }
+ if (node.type === "TemplateLiteral") {
+ return "string";
+ }
+ if (
+ node.type === "ChainExpression" ||
+ node.type === "ParenthesizedExpression"
+ ) {
+ return getExpressionNodeValueKind(node.expression, variableValues);
+ }
+ if (
+ node.type === "CallExpression" &&
+ node.callee.type === "MemberExpression" &&
+ node.callee.object.type !== "Super" &&
+ node.callee.property.type === "Identifier"
+ ) {
+ const receiverKind = getExpressionNodeValueKind(
+ node.callee.object,
+ variableValues
+ );
+ const methodName = node.callee.property.name;
+ if (isMethodSupported(receiverKind, methodName)) {
+ return getMethodReturnKind(receiverKind, methodName);
+ }
+ }
+ return "unknown";
+};
+
+export const getExpressionValueKind = ({
+ expression,
+ variableValues,
+}: {
+ expression: string;
+ variableValues?: VariableValues;
+}): ExpressionValueKind => {
+ try {
+ const node = parseExpressionAt(expression, 0, { ecmaVersion: "latest" });
+ return getExpressionNodeValueKind(node, variableValues);
+ } catch {
+ return "unknown";
+ }
+};
export const lintExpression = ({
expression,
availableVariables = new Set(),
allowAssignment = false,
+ variableValues,
}: {
expression: string;
availableVariables?: Set<Identifier["name"]>;
allowAssignment?: boolean;
+ variableValues?: VariableValues;
}): Diagnostic[] => {
const diagnostics: Diagnostic[] = [];
const addMessage = (
@@ -134,10 +320,14 @@ export const lintExpression = ({
if (node.callee.type === "MemberExpression") {
if (node.callee.property.type === "Identifier") {
const methodName = node.callee.property.name;
- if (
- allowedStringMethods.has(methodName) ||
- allowedArrayMethods.has(methodName)
- ) {
+ const receiverKind =
+ node.callee.object.type === "Super"
+ ? "unknown"
+ : getExpressionNodeValueKind(
+ node.callee.object,
+ variableValues
+ );
+ if (isMethodSupported(receiverKind, methodName)) {
return;
}
calleeName = methodName;