Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions src/ExpressionSplitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,17 @@ export interface ExpressionCode {

export type ExpressionChunk = ExpressionCode | ExpressionText;

const OPEN_BRACKET = /(?<escape>\\|)(?<brackets>\{\{)/;
const CLOSE_BRACKET = /(?<escape>\\|)(?<brackets>\}\})/;
const OPEN_BRACKET = /(?<brackets>\{\{)/;
const CLOSE_BRACKET = /(?<brackets>\}\})/;

export const escapeCode = (text: string): string => {
return text.replace('\\}}', '}}');
};

const normalizeBackslashes = (text: string): string => {
return text.replace(/\\\\/g, '\\');
};

export const splitExpression = (expression: string): ExpressionChunk[] => {
const chunks: ExpressionChunk[] = [];
let searchingFor: 'open' | 'close' = 'open';
Expand Down Expand Up @@ -51,16 +55,21 @@ export const splitExpression = (expression: string): ExpressionChunk[] => {
}
break;
}
if (res.groups.escape) {
buffer += expr.slice(0, res.index + 3);
index += res.index + 3;

const beforeMatch = expr.slice(0, res.index);
const backslashCount = beforeMatch.match(/\\*$/)?.[0]?.length ?? 0;
const isEscaped = backslashCount % 2 === 1;

if (isEscaped) {
buffer += expr.slice(0, res.index + '{{'.length);
index += res.index + '{{'.length;
} else {
buffer += expr.slice(0, res.index);

if (searchingFor === 'open') {
chunks.push({
type: 'text',
text: buffer,
text: normalizeBackslashes(buffer),
});
searchingFor = 'close';
activeRegex = CLOSE_BRACKET;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,30 @@ describe('tmpl Expression Parser', () => {
]);
});

test('Escaped closinging bracket', () => {
test('Escaped closing bracket', () => {
expect(splitExpression('test {{ code.test("\\}}") }}')).toEqual([
{ type: 'text', text: 'test ' },
{ type: 'code', text: ' code.test("}}") ', hasClosingBrackets: true },
]);
});

test('Escaped backslashes before double opening curly braces', () => {
const expr =
'C:\\\\Users\\\\Administrator\\\\Desktop\\\\abc\\\\{{ $json.files[0].fileName }}';
const result = splitExpression(expr);

expect(result).toEqual([
{
type: 'text',
text: 'C:\\Users\\Administrator\\Desktop\\abc\\',
},
{
type: 'code',
text: ' $json.files[0].fileName ',
hasClosingBrackets: true,
},
]);
});
});

describe('Compatible joining', () => {
Expand Down
Loading