Skip to content

Commit

Permalink
fix: template literal escaping
Browse files Browse the repository at this point in the history
  • Loading branch information
j4k0xb committed Jan 1, 2024
1 parent fdf2137 commit 38f0165
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import templateLiterals from '../transforms/template-literals';

const expectJS = testTransform(templateLiterals);

test('escape quotes', () =>
test('escape sequences', () =>
expectJS(
`"'".concat(foo, "' \\"").concat(bar, "\\"");`,
).toMatchInlineSnapshot(`\`'\${foo}' "\${bar}"\`;`));
`"'".concat(foo, "' \\"").concat(bar, "\\"").concat("$\\0\\b\\f\\n\\r\\t\\v");`,
).toMatchInlineSnapshot(`\`'\${foo}' "\${bar}"\\$\\0\\b\\f\n\\r\\t\\v\`;`));

test('expressions', () =>
expectJS(`
Expand Down
19 changes: 13 additions & 6 deletions packages/webcrack/src/transpile/transforms/template-literals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,19 @@ import { Transform, constMemberExpression } from '../../ast-utils';
// TODO: option ignoreToPrimitiveHint (uses `+` instead of concat)

function escape(str: string) {
return str
.replace(/\\/g, '\\\\')
.replace(/`/g, '\\`')
.replace(/\$/g, '\\$')
.replace(/\t/g, '\\t')
.replace(/\r/g, '\\r');
return (
str
.replaceAll('\\', '\\\\')
.replaceAll('`', '\\`')
.replaceAll('$', '\\$')
.replaceAll('\0', '\\0')
.replaceAll('\b', '\\b')
.replaceAll('\f', '\\f')
// .replaceAll('\n', '\\n') // not escaped because multiline strings are preferred
.replaceAll('\r', '\\r')
.replaceAll('\t', '\\t')
.replaceAll('\v', '\\v')
);
}

function push(template: t.TemplateLiteral, value: t.Expression) {
Expand Down

0 comments on commit 38f0165

Please sign in to comment.