Skip to content

The open alternative to Salesforce, designed for AI.

refactor(shared): resolve workflow variables without handlebars (#25852)

Félix Malfaitaedb53bca398
diff --git a/packages/twenty-shared/package.json b/packages/twenty-shared/package.json
index e7b89723527..284c7ca429e 100644
--- a/packages/twenty-shared/package.json
+++ b/packages/twenty-shared/package.json
@@ -23,7 +23,6 @@
"@swc/jest": "^0.2.39",
"@types/addressparser": "^1.0.3",
"@types/babel__preset-env": "^7",
- "@types/handlebars": "^4.1.0",
"@types/jest": "^30.0.0",
"@types/lodash.camelcase": "^4.3.7",
"@types/lodash.escaperegexp": "^4.1.9",
@@ -50,7 +49,6 @@
"ai": "7.0.93",
"class-validator": "^0.14.0",
"expr-eval-fork": "3.0.3",
- "handlebars": "^4.7.9",
"libphonenumber-js": "^1.10.26",
"lodash.camelcase": "^4.3.0",
"lodash.escaperegexp": "^4.1.2",
diff --git a/packages/twenty-shared/src/utils/__tests__/evalFromContext.test.ts b/packages/twenty-shared/src/utils/__tests__/evalFromContext.test.ts
new file mode 100644
index 00000000000..ea4219ea310
--- /dev/null
+++ b/packages/twenty-shared/src/utils/__tests__/evalFromContext.test.ts
@@ -0,0 +1,166 @@
+import { evalFromContext } from '../evalFromContext';
+
+describe('evalFromContext', () => {
+ const context = {
+ user: { name: 'John Doe', age: 30 },
+ step: {
+ 'key with space': 'spaced',
+ 'key.with.dots': 'dotted',
+ '0': 'zero',
+ },
+ list: ['a', { x: 'x1' }],
+ nullValue: null,
+ nested: { child: null },
+ date: new Date('2020-01-02T03:04:05.000Z'),
+ notANumber: NaN,
+ fn: () => 1,
+ text: 'hi',
+ };
+
+ it('should resolve a dotted path', () => {
+ expect(evalFromContext('{{user.name}}', context)).toBe('John Doe');
+ });
+
+ it('should preserve primitive types rather than stringifying them', () => {
+ expect(evalFromContext('{{user.age}}', context)).toBe(30);
+ expect(evalFromContext('{{nullValue}}', context)).toBeNull();
+ });
+
+ it('should return undefined for a path that does not resolve', () => {
+ expect(evalFromContext('{{user.email}}', context)).toBeUndefined();
+ expect(evalFromContext('{{missing.deep.path}}', context)).toBeUndefined();
+ });
+
+ it('should resolve segment literals containing spaces or dots', () => {
+ expect(evalFromContext('{{step.[key with space]}}', context)).toBe(
+ 'spaced',
+ );
+ expect(evalFromContext('{{step.[key.with.dots]}}', context)).toBe('dotted');
+ });
+
+ // A path ending in a number or a keyword read it as a value rather than a
+ // key, so it never resolved; mid-path the same segment is an ordinary key
+ it('should reject a trailing bare number but index through it mid-path', () => {
+ expect(evalFromContext('{{list.[0]}}', context)).toBe('a');
+ expect(evalFromContext('{{list.[1].x}}', context)).toBe('x1');
+ expect(evalFromContext('{{list.0}}', context)).toBeUndefined();
+ expect(evalFromContext('{{list.1.x}}', context)).toBe('x1');
+ expect(evalFromContext('{{list.0.length}}', context)).toBe(1);
+ });
+
+ // Handlebars compiled each hop as `x != null ? x.key : x`, so walking through
+ // a null yields that null rather than undefined
+ it('should short-circuit to the nullish container it walks through', () => {
+ expect(evalFromContext('{{nested.child.whatever}}', context)).toBeNull();
+ });
+
+ it('should deny prototype access', () => {
+ expect(evalFromContext('{{text.toString}}', context)).toBeUndefined();
+ expect(evalFromContext('{{text.constructor}}', context)).toBeUndefined();
+ expect(evalFromContext('{{user.__proto__}}', context)).toBeUndefined();
+ expect(evalFromContext('{{user.hasOwnProperty}}', context)).toBeUndefined();
+ });
+
+ it('should still read own properties that live on built-ins', () => {
+ expect(evalFromContext('{{text.length}}', context)).toBe(2);
+ expect(evalFromContext('{{list.length}}', context)).toBe(2);
+ });
+
+ // The value is JSON round-tripped, which is what the Handlebars `json` helper
+ // plus JSON.parse did, so these coercions are part of the contract
+ it('should JSON round-trip the resolved value', () => {
+ expect(evalFromContext('{{date}}', context)).toBe(
+ '2020-01-02T03:04:05.000Z',
+ );
+ expect(evalFromContext('{{notANumber}}', context)).toBeNull();
+ expect(evalFromContext('{{fn}}', context)).toBeUndefined();
+ });
+
+ it('should resolve the whole context for self references', () => {
+ expect(evalFromContext('{{this}}', context)).toEqual(
+ JSON.parse(JSON.stringify(context)),
+ );
+ expect(evalFromContext('{{.}}', context)).toEqual(
+ JSON.parse(JSON.stringify(context)),
+ );
+ });
+
+ it('should ignore extra params, which were Handlebars helper arguments', () => {
+ expect(evalFromContext('{{user.name ignored}}', context)).toBe('John Doe');
+ expect(evalFromContext('{{step.[key with space] ignored}}', context)).toBe(
+ 'spaced',
+ );
+ });
+
+ it('should return undefined for an empty or malformed expression', () => {
+ expect(evalFromContext('{{}}', context)).toBeUndefined();
+ expect(evalFromContext('{{ }}', context)).toBeUndefined();
+ expect(evalFromContext('{{step.[unclosed}}', context)).toBeUndefined();
+ expect(evalFromContext('not a token', context)).toBeUndefined();
+ });
+
+ // `@root.` was a data lookup in Handlebars and compiled to a different guard
+ // from a bare path, so these two families are pinned separately
+ describe('context-prefixed paths', () => {
+ const prefixContext = {
+ zero: 0,
+ emptyString: '',
+ truthy: 'hi',
+ obj: { p: 1 },
+ };
+
+ it('should resolve a path rooted at the context', () => {
+ expect(evalFromContext('{{@root.obj.p}}', prefixContext)).toBe(1);
+ expect(evalFromContext('{{./obj.p}}', prefixContext)).toBe(1);
+ expect(evalFromContext('{{this.obj.p}}', prefixContext)).toBe(1);
+ });
+
+ // The guard is a plain truthiness test, so NaN short-circuits like any other
+ // falsy value and JSON round-trips to null
+ it('should short-circuit an @root path on NaN', () => {
+ expect(
+ evalFromContext('{{@root.notANumber.missing}}', { notANumber: NaN }),
+ ).toBeNull();
+ });
+
+ it('should short-circuit an @root path on a falsy value', () => {
+ expect(evalFromContext('{{@root.zero.missing}}', prefixContext)).toBe(0);
+ expect(
+ evalFromContext('{{@root.emptyString.missing}}', prefixContext),
+ ).toBe('');
+ expect(
+ evalFromContext('{{@root.truthy.missing}}', prefixContext),
+ ).toBeUndefined();
+ });
+
+ it('should short-circuit a bare path only on a nullish value', () => {
+ expect(
+ evalFromContext('{{zero.missing}}', prefixContext),
+ ).toBeUndefined();
+ expect(
+ evalFromContext('{{this.zero.missing}}', prefixContext),
+ ).toBeUndefined();
+ });
+ });
+
+ // A keyword read as a value rather than a key, which Handlebars only did
+ // where a value was expected: the whole expression, or the last segment of a
+ // path. Anywhere else it is an ordinary key, so `obj.true.length` resolves
+ it('should not resolve a trailing bare keyword segment', () => {
+ const keywordContext = { obj: { true: 'T', null: 'N' }, null: { x: 1 } };
+
+ expect(evalFromContext('{{obj.true}}', keywordContext)).toBeUndefined();
+ expect(evalFromContext('{{obj.null}}', keywordContext)).toBeUndefined();
+ expect(evalFromContext('{{obj.[true]}}', keywordContext)).toBe('T');
+ expect(evalFromContext('{{obj.[null]}}', keywordContext)).toBe('N');
+ expect(evalFromContext('{{obj.true.length}}', keywordContext)).toBe(1);
+ expect(evalFromContext('{{null.x}}', keywordContext)).toBe(1);
+ expect(evalFromContext('{{@root.null.x}}', keywordContext)).toBe(1);
+ });
+
+ it('should support literals, as Handlebars path expressions did', () => {
+ expect(evalFromContext('{{true}}', context)).toBe(true);
+ expect(evalFromContext('{{null}}', context)).toBeNull();
+ expect(evalFromContext('{{42}}', context)).toBe(42);
+ });
+});
diff --git a/packages/twenty-shared/src/utils/evalFromContext.ts b/packages/twenty-shared/src/utils/evalFromContext.ts
index 9759022eb2d..60c4ad4cdae 100644
--- a/packages/twenty-shared/src/utils/evalFromContext.ts
+++ b/packages/twenty-shared/src/utils/evalFromContext.ts
@@ -1,24 +1,278 @@
-import Handlebars from 'handlebars';
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { isDefined } from '@/utils/validation/isDefined';
+
+// Resolves a single `{{ path }}` token against a context object.
+//
+// This replaces a Handlebars `{{{ json <path> }}}` compile whose only purpose
+// was to read a value out of the context: Handlebars is CommonJS, so bundlers
+// cannot tree-shake it, and it reached every browser consumer of this package
+// through the utils barrel for what is a property lookup.
+//
+// The quirks below are Handlebars' own and are reproduced deliberately, because
+// workflows already in flight were authored against them:
+// - a bare numeric path segment never resolves (`arr.0`), only `arr.[0]` does
+// - only own properties resolve, so prototype access is denied
+// - extra space-separated params are ignored (they were helper params)
+// - the value is JSON round-tripped, so Dates become ISO strings, NaN and
+// Infinity become null, and functions or circular values become undefined
+const TOKEN_PATTERN = /^\{\{([^{}]*)\}\}$/;
+const NUMBER_LITERAL_PATTERN = /^-?\d+(\.\d+)?$/;
+const WHOLE_CONTEXT_PATHS = ['.', 'this', '@root'];
+const CONTEXT_PREFIXES = ['./', 'this.', '@root.'];
+const KEYWORD_LITERALS = ['true', 'false', 'null', 'undefined'];
+
+type PathSegment = { value: string; isLiteralSegment: boolean };
+
+// Reads the first space-separated token, treating `[...]` as atomic so that
+// `{{step.[key with space] extra}}` still yields `step.[key with space]`
+const readFirstParam = (expression: string): string | undefined => {
+ let param = '';
+
+ for (let index = 0; index < expression.length; ++index) {
+ const character = expression[index];
+
+ if (character === '[') {
+ const closingIndex = expression.indexOf(']', index + 1);
+
+ if (closingIndex === -1) {
+ return undefined;
+ }
+
+ param += expression.slice(index, closingIndex + 1);
+ index = closingIndex;
+ continue;
+ }
+
+ if (/\s/.test(character)) {
+ break;
+ }
+
+ param += character;
+ }
+
+ return param;
+};
+
+const parsePathSegments = (path: string): PathSegment[] | undefined => {
+ const segments: PathSegment[] = [];
+ let current = '';
+ let hasCurrent = false;
+ let justClosedLiteralSegment = false;
+
+ for (let index = 0; index < path.length; ++index) {
+ const character = path[index];
+
+ if (character === '[') {
+ if (hasCurrent) {
+ return undefined;
+ }
+
+ const closingIndex = path.indexOf(']', index + 1);
+
+ if (closingIndex === -1) {
+ return undefined;
+ }
+
+ segments.push({
+ value: path.slice(index + 1, closingIndex),
+ isLiteralSegment: true,
+ });
+ index = closingIndex;
+ justClosedLiteralSegment = true;
+ continue;
+ }
+
+ if (character === '.') {
+ if (hasCurrent) {
+ segments.push({ value: current, isLiteralSegment: false });
+ current = '';
+ hasCurrent = false;
+ continue;
+ }
+
+ if (justClosedLiteralSegment) {
+ justClosedLiteralSegment = false;
+ continue;
+ }
+
+ // An empty segment: a leading dot is not a path at all, while a repeated
+ // dot mid-path truncates it, both matching how Handlebars parsed these
+ if (segments.length === 0) {
+ return undefined;
+ }
+
+ return segments;
+ }
+
+ // Anything other than a separator straight after `[...]`, such as `[a]b`
+ if (justClosedLiteralSegment) {
+ return undefined;
+ }
+
+ current += character;
+ hasCurrent = true;
+ }
+
+ if (hasCurrent) {
+ segments.push({ value: current, isLiteralSegment: false });
+ }
+
+ return segments;
+};
+
+const readOwnProperty = (target: unknown, key: string): unknown => {
+ if (!Object.prototype.hasOwnProperty.call(target, key)) {
+ return undefined;
+ }
+
+ return (target as Record<string, unknown>)[key];
+};
+
+const toJsonValue = (value: unknown): unknown => {
+ try {
+ const serialized = JSON.stringify(value);
+
+ if (serialized === undefined) {
+ return undefined;
+ }
+
+ return JSON.parse(serialized);
+ } catch {
+ return undefined;
+ }
+};
export const evalFromContext = (
input: string,
context: Record<string, unknown>,
) => {
- try {
- Handlebars.registerHelper('json', (input: string) => JSON.stringify(input));
+ const tokenMatch = input.match(TOKEN_PATTERN);
- const inputWithHelper = input
- .replace('{{', '{{{ json ')
- .replace('}}', ' }}}');
+ if (tokenMatch === null) {
+ return undefined;
+ }
- const inferredInput = Handlebars.compile(inputWithHelper)(context, {
- helpers: {
- json: (input: string) => JSON.stringify(input),
- },
- });
+ const expression = tokenMatch[1].trim();
- return JSON.parse(inferredInput);
- } catch {
+ if (!isNonEmptyString(expression)) {
return undefined;
}
+
+ const param = readFirstParam(expression);
+
+ if (!isNonEmptyString(param)) {
+ return undefined;
+ }
+
+ if (WHOLE_CONTEXT_PATHS.includes(param)) {
+ return toJsonValue(context);
+ }
+
+ // Stripped before the `@` guard below, so `@root.foo` stays a path rooted at
+ // the context rather than being rejected as an unsupported data variable
+ const contextPrefix = CONTEXT_PREFIXES.find((prefix) =>
+ param.startsWith(prefix),
+ );
+ const normalizedPath =
+ contextPrefix === undefined ? param : param.slice(contextPrefix.length);
+
+ // `this..foo` truncated at the repeated dot in Handlebars, leaving the context
+ if (contextPrefix !== undefined && normalizedPath.startsWith('.')) {
+ return toJsonValue(context);
+ }
+
+ if (contextPrefix === undefined) {
+ if (param.startsWith('@')) {
+ return undefined;
+ }
+
+ if (param === 'true') {
+ return true;
+ }
+
+ if (param === 'false') {
+ return false;
+ }
+
+ if (param === 'null') {
+ return null;
+ }
+
+ if (param === 'undefined') {
+ return undefined;
+ }
+
+ if (NUMBER_LITERAL_PATTERN.test(param)) {
+ return Number(param);
+ }
+
+ if (
+ (param.startsWith('"') && param.endsWith('"') && param.length > 1) ||
+ (param.startsWith("'") && param.endsWith("'") && param.length > 1)
+ ) {
+ return param.slice(1, -1);
+ }
+ }
+
+ if (param.includes('../')) {
+ return undefined;
+ }
+
+ const segments = parsePathSegments(normalizedPath);
+
+ if (segments === undefined) {
+ return undefined;
+ }
+
+ if (segments.length === 0) {
+ return toJsonValue(context);
+ }
+
+ // A number or a keyword read as a value rather than a key, so a path ending in
+ // one never resolved. Mid-path they are ordinary keys: `arr.0` is undefined
+ // but `arr.0.length` is not, and `[0]` works in either position
+ const lastSegment = segments[segments.length - 1];
+
+ if (
+ !lastSegment.isLiteralSegment &&
+ (NUMBER_LITERAL_PATTERN.test(lastSegment.value) ||
+ KEYWORD_LITERALS.includes(lastSegment.value))
+ ) {
+ return undefined;
+ }
+
+ // A leading `[]` collapsed the whole path to the context in Handlebars, but
+ // only for a bare path: under `@root.` it stayed an ordinary empty-string key
+ if (
+ contextPrefix !== '@root.' &&
+ segments[0].isLiteralSegment &&
+ segments[0].value === ''
+ ) {
+ return toJsonValue(context);
+ }
+
+ // Handlebars guarded each hop, but with a different test depending on how the
+ // path started: `x != null ? x.key : x` for a bare or `this.` path, and a
+ // plain truthiness check for an `@root.` data lookup, so walking through 0 or
+ // '' yields that value there rather than undefined
+ const shortCircuitsOnFalsy = contextPrefix === '@root.';
+
+ let resolved: unknown = context;
+
+ for (const segment of segments) {
+ // Mirrors the compiled guard exactly rather than enumerating falsy values,
+ // which would miss NaN and anything else JavaScript counts as falsy
+ const shortCircuits = shortCircuitsOnFalsy
+ ? !resolved
+ : !isDefined(resolved);
+
+ if (shortCircuits) {
+ return toJsonValue(resolved);
+ }
+
+ resolved = readOwnProperty(resolved, segment.value);
+ }
+
+ return toJsonValue(resolved);
};
diff --git a/packages/twenty-shared/src/utils/variable-resolver.ts b/packages/twenty-shared/src/utils/variable-resolver.ts
index c0e7b9a804f..03b7b0d3d59 100644
--- a/packages/twenty-shared/src/utils/variable-resolver.ts
+++ b/packages/twenty-shared/src/utils/variable-resolver.ts
@@ -64,10 +64,12 @@ const resolveObject = (
);
};
+// Returns the resolved value itself when the whole string is one variable, so
+// `{{step.amount}}` keeps its type instead of being stringified
const resolveString = (
input: string,
context: Record<string, unknown>,
-): string => {
+): unknown => {
const matchedTokens = input.match(VARIABLE_PATTERN);
if (!matchedTokens || matchedTokens.length === 0) {
@@ -85,6 +87,6 @@ const resolveString = (
return JSON.stringify(processedToken);
}
- return processedToken;
+ return String(processedToken);
});
};
diff --git a/yarn.lock b/yarn.lock
index 64bd5514c2d..145d964ce5e 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -20584,15 +20584,6 @@ __metadata:
languageName: node
linkType: hard
-"@types/handlebars@npm:^4.1.0":
- version: 4.1.0
- resolution: "@types/handlebars@npm:4.1.0"
- dependencies:
- handlebars: "npm:*"
- checksum: 10c0/50e85efb4a9306c8b2278dd1570714e9021f201ef317a259ce2d63406057e6575f3066b862bed3d192828d1cc32b80d3a0d2e18d0cd9cda98ec5f1f69038e342
- languageName: node
- linkType: hard
-
"@types/har-format@npm:^1.2.16":
version: 1.2.16
resolution: "@types/har-format@npm:1.2.16"
@@ -33086,7 +33077,7 @@ __metadata:
languageName: node
linkType: hard
-"handlebars@npm:*, handlebars@npm:4.7.9, handlebars@npm:^4.7.7, handlebars@npm:^4.7.9":
+"handlebars@npm:4.7.9, handlebars@npm:^4.7.7":
version: 4.7.9
resolution: "handlebars@npm:4.7.9"
dependencies:
@@ -50353,7 +50344,6 @@ __metadata:
"@swc/jest": "npm:^0.2.39"
"@types/addressparser": "npm:^1.0.3"
"@types/babel__preset-env": "npm:^7"
- "@types/handlebars": "npm:^4.1.0"
"@types/jest": "npm:^30.0.0"
"@types/lodash.camelcase": "npm:^4.3.7"
"@types/lodash.escaperegexp": "npm:^4.1.9"
@@ -50366,7 +50356,6 @@ __metadata:
class-validator: "npm:^0.14.0"
expr-eval-fork: "npm:3.0.3"
glob: "npm:^11.1.0"
- handlebars: "npm:^4.7.9"
jest: "npm:29.7.0"
jest-environment-jsdom: "npm:30.0.0-beta.3"
libphonenumber-js: "npm:^1.10.26"