Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// oxlint-disable no-control-regex
import { describe, expect, it } from 'vitest';

import { escapeNonCharacterUnicode } from '../escape-unicode';

describe('escapeNonCharacterUnicode', () => {
it('should escape non-characters in the BMP', () => {
expect(escapeNonCharacterUnicode('\uFDD0\uFFFE\uFFFF')).toBe(
'\\ufdd0\\ufffe\\uffff',
);
});

it('should escape non-characters outside the BMP as surrogate pairs', () => {
expect(escapeNonCharacterUnicode('\u{1FFFF}\u{10FFFE}')).toBe(
'\\ud83f\\udfff\\udbff\\udffe',
);
});

it('should produce output that round-trips to the original string', () => {
const original = 'a\uFFFF\u{1FFFE}\u{10FFFF}b';
const escaped = escapeNonCharacterUnicode(JSON.stringify(original));

expect(escaped).toMatch(/^[\x00-\x7F]*$/);
expect(JSON.parse(escaped)).toBe(original);
});

it('should not change other characters', () => {
const text = 'const s = "h\u00e9llo \u{1F44B} \uFFFD";';
expect(escapeNonCharacterUnicode(text)).toBe(text);
});
});
12 changes: 10 additions & 2 deletions packages/wxt/src/internal/builtin-modules/escape-unicode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,18 @@ function escapeUnicodePlugin(wxt: Wxt): Plugin {
*
* - https://github.com/rolldown/rolldown/issues/8805#issuecomment-4103480096
* - https://github.com/rolldown/rolldown/issues/8805#issuecomment-5134001768
*
* Each UTF-16 code unit is escaped separately, so characters outside the BMP
* become a surrogate pair (`\ud83f\udfff`). That form is valid in strings,
* template literals, and regular expressions with or without the `u` flag.
*/
function escapeNonCharacterUnicode(text: string): string {
export function escapeNonCharacterUnicode(text: string): string {
return text.replace(
/[\uFDD0-\uFDEF\uFFFE\uFFFF]|[\u{1FFFE}\u{1FFFF}\u{2FFFE}\u{2FFFF}\u{3FFFE}\u{3FFFF}\u{4FFFE}\u{4FFFF}\u{5FFFE}\u{5FFFF}\u{6FFFE}\u{6FFFF}\u{7FFFE}\u{7FFFF}\u{8FFFE}\u{8FFFF}\u{9FFFE}\u{9FFFF}\u{AFFFE}\u{AFFFF}\u{BFFFE}\u{BFFFF}\u{CFFFE}\u{CFFFF}\u{DFFFE}\u{DFFFF}\u{EFFFE}\u{EFFFF}\u{FFFFE}\u{FFFFF}\u{10FFFE}\u{10FFFF}]/gu,
(m) => '\\u' + m.codePointAt(0)!.toString(16),
(m) =>
Array.from(
{ length: m.length },
(_, i) => '\\u' + m.charCodeAt(i).toString(16).padStart(4, '0'),
).join(''),
);
}
Loading