Open History to see the last commit
1import { decodeFilePreviewText } from "@t3tools/shared/filePreview";
2import { afterEach, describe, expect, it, vi } from "vite-plus/test";
3
4const NodeTextDecoder = globalThis.TextDecoder;
5
6class HermesTextDecoder extends NodeTextDecoder {
7 constructor(label = "utf-8", options?: TextDecoderOptions) {
8 if (!/^utf-(8|16le|16be)$/i.test(label)) throw new RangeError(`Unsupported encoding: ${label}`);
9 super(label, options);
10 }
11}
12
13afterEach(() => {
14 vi.unstubAllGlobals();
15 vi.resetModules();
16});
17
18describe("text decoder polyfill", () => {
19 it("lets a runtime without GB18030 preview a GBK source file", async () => {
20 vi.stubGlobal("TextDecoder", HermesTextDecoder);
21 const gbk = new Uint8Array([
22 0x2f, 0x2f, 0x20, 0xd6, 0xd0, 0xce, 0xc4, 0xd7, 0xa2, 0xca, 0xcd, 0x0a, 0x69, 0x6e, 0x74,
23 0x20, 0x61, 0x20, 0x3d, 0x20, 0x31, 0x3b, 0x0a,
24 ]);
25 expect(() => decodeFilePreviewText(gbk)).toThrow("UTF-8");
26
27 await import("./text-decoder-polyfill");
28
29 expect(decodeFilePreviewText(gbk).text).toBe("// 中文注释\nint a = 1;\n");
30 expect(new TextDecoder()).toBeInstanceOf(HermesTextDecoder);
31 });
32});