Skip to content
Closed
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
6 changes: 6 additions & 0 deletions packages/typescript/src/api/node/wtf8.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,12 @@ export function encodeWtf8(text: string): Uint8Array {
}

export class Wtf8Decoder extends TextDecoder {
constructor(label: string | undefined = "utf-8", options?: ConstructorParameters<typeof TextDecoder>[1]) {
// U+FEFF inside a payload is data. TextDecoder otherwise drops it at the
// start of each decoded segment, including the segment after a lone surrogate.
super(label, { ignoreBOM: true, ...options });
}

override decode(input?: DecodeInput, options?: DecodeOptions): string {
if (input == null) {
return super.decode(undefined, options);
Expand Down
2 changes: 1 addition & 1 deletion packages/typescript/src/wasm/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ type Frame = RequestFrame | CallFrame;

const encoder = new TextEncoder();
const decoder = new TextDecoder();
const fileContentDecoder = new Wtf8Decoder("utf-8", { ignoreBOM: true });
const fileContentDecoder = new Wtf8Decoder();

/**
* API transport backed by an in-process TypeScript WebAssembly reactor.
Expand Down
28 changes: 28 additions & 0 deletions packages/typescript/test/wtf8.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,34 @@ describe("Wtf8Decoder", { concurrency }, () => {
[0xD83E, 0xDD80, 0xD7FF, 0xD800, 0xD801, 0xDC00, 0xD83E, 0xDD80],
);
});

test("preserves U+FEFF at the start of a decoded segment", () => {
const decoder = new Wtf8Decoder();
const cases: readonly [string, string, readonly number[]][] = [
["leading", "\uFEFFx", [0xFEFF, 0x78]],
["only", "\uFEFF", [0xFEFF]],
["after a lone surrogate", "\uD800\uFEFF", [0xD800, 0xFEFF]],
["middle", "a\uFEFFb", [0x61, 0xFEFF, 0x62]],
["trailing", "x\uFEFF", [0x78, 0xFEFF]],
["template text", "\uFEFFtail", [0xFEFF, 0x74, 0x61, 0x69, 0x6C]],
];

for (const [name, text, expected] of cases) {
assert.deepStrictEqual(
Array.from(decoder.decode(encodeWtf8(text)), c => c.codePointAt(0)),
expected,
name,
);
}
});

test("explicit ignoreBOM: false still opts out", () => {
const decoder = new Wtf8Decoder("utf-8", { ignoreBOM: false });
assert.deepStrictEqual(
Array.from(decoder.decode(encodeWtf8("\uFEFFx")), c => c.codePointAt(0)),
[0x78],
);
});
});

describe("Msgpack strings", { concurrency }, () => {
Expand Down