Skip to content

Commit db0afa9

Browse files
chuckjazmhevery
authored andcommitted
fix(compiler-cli): emit correct css string escape sequences (#22776)
Works around an issue with TypeScript 2.6 and 2.7 that causes the tranformer emit to emit incorrect escapes for css string literals. Fixes: #22774 PR Close #22776
1 parent 5298b2b commit db0afa9

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

packages/compiler-cli/src/transformers/node_emitter.ts

+16-1
Original file line numberDiff line numberDiff line change
@@ -55,13 +55,28 @@ export class TypeScriptNodeEmitter {
5555
// NodeEmitterVisitor
5656
type RecordedNode<T extends ts.Node = ts.Node> = (T & { __recorded: any; }) | null;
5757

58+
function escapeLiteral(value: string): string {
59+
return value.replace(/(\"|\\)/g, '\\$1').replace(/(\n)|(\r)/g, function(v, n, r) {
60+
return n ? '\\n' : '\\r';
61+
});
62+
}
63+
5864
function createLiteral(value: any) {
5965
if (value === null) {
6066
return ts.createNull();
6167
} else if (value === undefined) {
6268
return ts.createIdentifier('undefined');
6369
} else {
64-
return ts.createLiteral(value);
70+
const result = ts.createLiteral(value);
71+
if (ts.isStringLiteral(result) && result.text.indexOf('\\') >= 0) {
72+
// Hack to avoid problems cause indirectly by:
73+
// https://github.com/Microsoft/TypeScript/issues/20192
74+
// This avoids the string escaping normally performed for a string relying on that
75+
// TypeScript just emits the text raw for a numeric literal.
76+
(result as any).kind = ts.SyntaxKind.NumericLiteral;
77+
result.text = `"${escapeLiteral(result.text)}"`;
78+
}
79+
return result;
6580
}
6681
}
6782

packages/compiler-cli/test/transformers/node_emitter_spec.ts

+8
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,14 @@ describe('TypeScriptNodeEmitter', () => {
176176
]).toStmt())
177177
.replace(/\s+/gm, ''))
178178
.toEqual(`({someKey:1,a:"a","b":"b","*":"star"});`);
179+
180+
// Regressions #22774
181+
expect(emitStmt(o.literal('\\0025BC').toStmt())).toEqual('"\\\\0025BC";');
182+
expect(emitStmt(o.literal('"some value"').toStmt())).toEqual('"\\"some value\\"";');
183+
expect(emitStmt(o.literal('"some \\0025BC value"').toStmt()))
184+
.toEqual('"\\"some \\\\0025BC value\\"";');
185+
expect(emitStmt(o.literal('\n \\0025BC \n ').toStmt())).toEqual('"\\n \\\\0025BC \\n ";');
186+
expect(emitStmt(o.literal('\r \\0025BC \r ').toStmt())).toEqual('"\\r \\\\0025BC \\r ";');
179187
});
180188

181189
it('should support blank literals', () => {

0 commit comments

Comments
 (0)