From a5506a9fe2be2b30d9fb9bfbb66a527b7cfd566a Mon Sep 17 00:00:00 2001 From: Jordan Pittman Date: Mon, 17 Jun 2024 11:33:14 -0400 Subject: [PATCH] Only re-apply string escaping when necessary (#295) * Simplify test * Only apply escaping when necessary --- src/index.ts | 23 +++++++++++++++++++++-- tests/format.test.js | 11 +++-------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/index.ts b/src/index.ts index c4608ac9..25f76bce 100644 --- a/src/index.ts +++ b/src/index.ts @@ -467,18 +467,37 @@ function sortStringLiteral( }) let didChange = result !== node.value node.value = result + + // A string literal was escaped if: + // - There are backslashes in the raw value; AND + // - The raw value is not the same as the value (excluding the surrounding quotes) + let wasEscaped = false + + if (node.extra) { + // JavaScript (StringLiteral) + wasEscaped = + node.extra?.rawValue.includes('\\') && + node.extra?.raw.slice(1, -1) !== node.value + } else { + // TypeScript (Literal) + wasEscaped = + node.value.includes('\\') && node.raw.slice(1, -1) !== node.value + } + + let escaped = wasEscaped ? result.replace(/\\/g, '\\\\') : result + if (node.extra) { // JavaScript (StringLiteral) let raw = node.extra.raw node.extra = { ...node.extra, rawValue: result, - raw: raw[0] + result.replace(/\\/g, '\\\\') + raw.slice(-1), + raw: raw[0] + escaped + raw.slice(-1), } } else { // TypeScript (Literal) let raw = node.raw - node.raw = raw[0] + result.replace(/\\/g, '\\\\') + raw.slice(-1) + node.raw = raw[0] + escaped + raw.slice(-1) } return didChange } diff --git a/tests/format.test.js b/tests/format.test.js index 76c41e28..bf51f87d 100644 --- a/tests/format.test.js +++ b/tests/format.test.js @@ -94,15 +94,10 @@ let javascript = [ ';
', ';
', ], - [ - `;
`, - `;
`, - ], - [ - `;
`, - `;
`, - ], + t`;
`, + t`;
`, + t`;
`, [ `;
`,