Skip to content

Commit

Permalink
fix: unescape backslashes on the way into the parser (#52)
Browse files Browse the repository at this point in the history
We already account for escape sequences added to the AST _later on_
(i.e. something like stylelint, postcss, etc has mutated it).

However, we do not unescape sequences on the way into the parser.

For example:

```ts
css`
  .foo {
    content: "\\abc";
  }
`;
```

This is already escaped, once for JS, once for the resulting CSS.

When we parse this, we extract the CSS _and keep the double-escape_.
This of course means the resulting CSS file internally has one too many
escapes.

To account for this, we now unescape CSS on the way in (i.e. replace
double escapes with single).
  • Loading branch information
43081j authored Dec 12, 2023
1 parent 7619a25 commit 59beb40
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,9 @@ export const parse: Parser<Root | Document> = (
}
}

const deindentedStyleText = deindentedLines.join('\n');
const deindentedStyleText = deindentedLines
.join('\n')
.replace(/\\\\/g, '\\');
let root: Root;

try {
Expand Down
16 changes: 15 additions & 1 deletion src/test/stringify_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ describe('stringify', () => {
);
});

it('should escape backslashes', () => {
it('should escape backslashes from mutated ast', () => {
const {ast} = createTestAst(`
css\`.foo { color: hotpink; }\`;
`);
Expand All @@ -382,4 +382,18 @@ describe('stringify', () => {
`
);
});

it('should escape backslashes from input', () => {
const {ast} = createTestAst(`
css\`.foo { content: "\\\\eee"; }\`;
`);

const output = ast.toString(syntax);
assert.equal(
output,
`
css\`.foo { content: "\\\\eee"; }\`;
`
);
});
});

0 comments on commit 59beb40

Please sign in to comment.