Skip to content

Commit

Permalink
fix: Handle backslashes before opening curly braces (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
ivov authored Jan 2, 2025
1 parent 30da791 commit 7390e48
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
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

0 comments on commit 7390e48

Please sign in to comment.