Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix pretty-printing strings with \u2028 or \u2029 #1056

Merged
merged 2 commits into from
Feb 6, 2022
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
14 changes: 10 additions & 4 deletions lib/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3086,19 +3086,25 @@ function getPossibleRaw(node:
}
}

function jsSafeStringify(str: string) {
return JSON.stringify(str).replace(/[\u2028\u2029]/g, function (m) {
return "\\u" + m.charCodeAt(0).toString(16);
});
}

function nodeStr(str: string, options: any) {
isString.assert(str);
switch (options.quote) {
case "auto": {
const double = JSON.stringify(str);
const single = swapQuotes(JSON.stringify(swapQuotes(str)));
const double = jsSafeStringify(str);
const single = swapQuotes(jsSafeStringify(swapQuotes(str)));
return double.length > single.length ? single : double;
}
case "single":
return swapQuotes(JSON.stringify(swapQuotes(str)));
return swapQuotes(jsSafeStringify(swapQuotes(str)));
case "double":
default:
return JSON.stringify(str);
return jsSafeStringify(str);
}
}

Expand Down
16 changes: 16 additions & 0 deletions test/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,22 @@ describe("printer", function () {
);
});

it("pretty-prints U+2028 and U+2029 as Unicode escapes", function () {
const ast = parse('"\\u2028";');
const printer = new Printer();
assert.strictEqual(
printer.printGenerically(ast).code,
'"\\u2028";',
);

const ast2 = parse('"\\u2029";');
const printer2 = new Printer();
assert.strictEqual(
printer2.printGenerically(ast2).code,
'"\\u2029";',
);
});

it("should print block comments at head of class once", function () {
// Given.
const ast = parse(
Expand Down