Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

binaryPreview.worker.test.ts

340 lines12.6 KB

1import JSZip from "jszip";
2import { expect, it, vi } from "vite-plus/test";
3​
4import {
5 ARCHIVE_ENTRY_MAX_BYTES,
6 compareArchiveRows,
7 formatArchiveModifiedDate,
8 type BinaryWorkerRequest,
9 type BinaryWorkerResult,
10} from "./binaryPreviewProtocol";
11​
12async function startWorker() {
13 const worker = new EventTarget();
14 let receive = (_result: BinaryWorkerResult) => {};
15 vi.stubGlobal(
16 "self",
17 Object.assign(worker, { postMessage: (result: BinaryWorkerResult) => receive(result) }),
18 );
19 vi.resetModules();
20 await import("./binaryPreview.worker");
21 return (input: BinaryWorkerRequest) =>
22 new Promise<BinaryWorkerResult>((resolve) => {
23 receive = resolve;
24 worker.dispatchEvent(new MessageEvent("message", { data: input }));
25 });
27​
28it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])(
29 "only copies previewable TAR payloads with a %i-byte entry",
30 async (size) => {
31 const encode = (value: string) => new TextEncoder().encode(value);
32 const large = new Uint8Array(size).fill(97);
33 const entries = [
34 { path: "before.txt", bytes: encode("before") },
35 { path: "large.txt", bytes: large },
36 { path: "empty.txt", bytes: new Uint8Array() },
37 { path: "large-link.txt", bytes: new Uint8Array(), link: "large.txt" },
38 { path: "after.txt", bytes: encode("after") },
39 ];
40 const contents = (entry: (typeof entries)[number]) => (entry.link ? large : entry.bytes);
41 const bytes = new Uint8Array(
42 entries.reduce(
43 (length, entry) => length + 512 + Math.ceil(entry.bytes.length / 512) * 512,
44 1024,
45 ),
46 );
47 let offset = 0;
48 for (const entry of entries) {
49 const write = (position: number, value: string) =>
50 bytes.set(encode(value), offset + position);
51 write(0, entry.path);
52 write(124, entry.bytes.length.toString(8).padStart(11, "0") + "\0");
53 write(136, "00000000000\0");
54 bytes.fill(32, offset + 148, offset + 156);
55 write(156, entry.link ? "1" : "0");
56 if (entry.link) write(157, entry.link);
57 write(
58 148,
59 bytes
60 .subarray(offset, offset + 512)
61 .reduce((sum, byte) => sum + byte, 0)
62 .toString(8)
63 .padStart(6, "0") + "\0 ",
64 );
65 bytes.set(entry.bytes, offset + 512);
66 offset += 512 + Math.ceil(entry.bytes.length / 512) * 512;
67 }
68​
69 try {
70 const request = await startWorker();
71 using copies = vi.spyOn(Uint8Array.prototype, "slice");
72 expect(
73 await request({ type: "open", kind: "archive", name: "mixed.tar", bytes: bytes.buffer }),
74 ).toEqual({
75 type: "archive",
76 entries: entries.map((entry) => ({
77 path: entry.path,
78 size: contents(entry).length,
79 directory: false,
80 modified: "1970-01-01T00:00:00.000Z",
81 })),
82 });
83 const copiedBytes = copies.mock.results.reduce(
84 (total, result) => total + (result.type === "return" ? result.value.byteLength : 0),
85 0,
86 );
87 expect(copiedBytes).toBe(11 + (size <= ARCHIVE_ENTRY_MAX_BYTES ? size : 0));
88 for (const entry of entries) {
89 const result = await request({ type: "entry", path: entry.path });
90 const expected = contents(entry);
91 if (expected.length > ARCHIVE_ENTRY_MAX_BYTES) {
92 expect(result).toEqual({
93 type: "error",
94 code: "archive-entry-too-large",
95 message: "archive-entry-too-large",
96 });
97 } else {
98 if (result.type !== "entry") throw new Error("Expected entry");
99 expect(result.path).toBe(entry.path);
100 expect(result.bytes.length).toBe(expected.length);
101 expect(result.bytes.every((byte, index) => byte === expected[index])).toBe(true);
102 }
103 }
104 expect(await request({ type: "entry", path: "missing.txt" })).toEqual({
105 type: "error",
106 code: "archive-entry-unavailable",
107 message: "archive-entry-unavailable",
108 });
109 } finally {
110 vi.unstubAllGlobals();
111 }
112 },
113);
114​
115it.each([
116 { timeZone: "Asia/Tokyo", tarEvening: "11/26/2026", tarNight: "11/25/2026" },
117 { timeZone: "America/Chicago", tarEvening: "11/25/2026", tarNight: "11/24/2026" },
118 { timeZone: "America/Nuuk", tarEvening: "11/25/2026", tarNight: "11/24/2026" },
119])(
120 "formats archived ZIP dates and local TAR instants in $timeZone",
121 async ({ timeZone, tarEvening, tarNight }) => {
122 const zip = new JSZip();
123 // JSZip writes the UTC parts of these dates as the entries' DOS wall-clock fields.
124 zip.file("evening.txt", "a", { date: new Date(Date.UTC(2026, 10, 25, 20, 0)) });
125 zip.file("night.txt", "b", { date: new Date(Date.UTC(2026, 10, 25, 1, 30)) });
126 zip.file("dst-midnight.txt", "c", { date: new Date(Date.UTC(2026, 2, 28, 23, 30)) });
127 const bytes = await zip.generateAsync({ type: "arraybuffer" });
128 const previous = process.env.TZ;
129 process.env.TZ = timeZone;
130 try {
131 const request = await startWorker();
132 const result = await request({ type: "open", kind: "archive", name: "times.zip", bytes });
133 if (result.type !== "archive") throw new Error("Expected archive");
134 expect(result.entries.map(({ modified }) => modified)).toEqual([
135 "2026-11-25T20:00:00.000",
136 "2026-11-25T01:30:00.000",
137 "2026-03-28T23:30:00.000",
138 ]);
139 expect(
140 result.entries.map(({ modified }) => formatArchiveModifiedDate(modified, "en-US")),
141 ).toEqual(["11/25/2026", "11/25/2026", "3/28/2026"]);
142 expect([
143 formatArchiveModifiedDate("2026-11-25T20:00:00.000Z", "en-US"),
144 formatArchiveModifiedDate("2026-11-25T01:30:00.000Z", "en-US"),
145 formatArchiveModifiedDate(null, "en-US"),
146 ]).toEqual([tarEvening, tarNight, "-"]);
147 } finally {
148 if (previous === undefined) delete process.env.TZ;
149 else process.env.TZ = previous;
150 vi.unstubAllGlobals();
151 }
152 },
153);
154​
155it("sorts archive folders first, then numbered names in natural order", () => {
156 const rows = ["page10.txt", "vol10", "page2.txt", "vol2", "page1.txt", "vol1"].map((path) => ({
157 path,
158 directory: path.startsWith("vol"),
159 }));
160 expect(rows.sort(compareArchiveRows).map(({ path }) => path)).toEqual([
161 "vol1",
162 "vol2",
163 "vol10",
164 "page1.txt",
165 "page2.txt",
166 "page10.txt",
167 ]);
168});
169​
170it("formats singular and plural byte labels for SQLite BLOB cells", async () => {
171 const { default: initSqlJs } = await import("sql.js");
172 const SQL = await initSqlJs();
173 const db = new SQL.Database();
174 db.run(
175 "CREATE TABLE blobs(empty BLOB, one BLOB, four BLOB); INSERT INTO blobs VALUES (X'', X'FF', X'DEADBEEF');",
176 );
177 const bytes = db.export().slice().buffer;
178 db.close();
179​
180 try {
181 const request = await startWorker();
182 await request({ type: "open", kind: "sqlite", name: "blobs.sqlite", bytes });
183 expect(await request({ type: "rows", table: "blobs", page: 0 })).toEqual({
184 type: "rows",
185 table: "blobs",
186 page: 0,
187 columns: ["empty", "one", "four"],
188 rows: [["[blob: 0 bytes]", "[blob: 1 byte]", "[blob: 4 bytes]"]],
189 });
190 } finally {
191 vi.unstubAllGlobals();
192 }
193});
194​
195it("reads GNU base-256 TAR modification dates, including ones before 1970", async () => {
196 const encode = (value: string) => new TextEncoder().encode(value);
197 const entries = [
198 { path: "before-epoch.txt", mtime: new Uint8Array(12).fill(0xff) },
199 { path: "far-future.txt", mtime: Uint8Array.of(0x80, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0) },
200 { path: "out-of-range.txt", mtime: Uint8Array.of(0x80, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0) },
201 ];
202 const bytes = new Uint8Array(entries.length * 512 + 1024);
203 entries.forEach((entry, index) => {
204 const offset = index * 512;
205 bytes.set(encode(entry.path), offset);
206 bytes.set(encode("00000000000\0"), offset + 124);
207 bytes.set(entry.mtime, offset + 136);
208 bytes.fill(32, offset + 148, offset + 156);
209 bytes.set(encode("0"), offset + 156);
210 const sum = bytes.subarray(offset, offset + 512).reduce((acc, byte) => acc + byte, 0);
211 bytes.set(encode(sum.toString(8).padStart(6, "0") + "\0 "), offset + 148);
212 });
213​
214 try {
215 const request = await startWorker();
216 const result = await request({
217 type: "open",
218 kind: "archive",
219 name: "gnu.tar",
220 bytes: bytes.buffer,
221 });
222 if (result.type !== "archive") throw new Error(`Expected archive, got ${result.type}`);
223 expect(result.entries.map(({ modified }) => modified)).toEqual([
224 "1969-12-31T23:59:59.000Z",
225 "2242-03-16T12:56:32.000Z",
226 null,
227 ]);
228 } finally {
229 vi.unstubAllGlobals();
230 }
231});
232​
233it("reads GNU base-256 TAR entry sizes", async () => {
234 const encode = (value: string) => new TextEncoder().encode(value);
235 const bytes = new Uint8Array(2048);
236 bytes.set(encode("hello.txt"), 0);
237 bytes.set(Uint8Array.of(0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3), 124);
238 bytes.set(encode("00000000000\0"), 136);
239 bytes.fill(32, 148, 156);
240 bytes.set(encode("0"), 156);
241 bytes.set(Uint8Array.of(0x68, 0x69, 0x0a), 512);
242 const sum = bytes.subarray(0, 512).reduce((acc, byte) => acc + byte, 0);
243 bytes.set(encode(sum.toString(8).padStart(6, "0") + "\0 "), 148);
244​
245 try {
246 const request = await startWorker();
247 expect(
248 await request({ type: "open", kind: "archive", name: "sample.tar", bytes: bytes.buffer }),
249 ).toEqual({
250 type: "archive",
251 entries: [
252 { path: "hello.txt", size: 3, directory: false, modified: "1970-01-01T00:00:00.000Z" },
253 ],
254 });
255 const result = await request({ type: "entry", path: "hello.txt" });
256 if (result.type !== "entry") throw new Error(`Expected entry, got ${result.type}`);
257 expect([...result.bytes]).toEqual([0x68, 0x69, 0x0a]);
258 } finally {
259 vi.unstubAllGlobals();
260 }
261});
262​
263it("keeps TAR member names that differ only by a leading U+FEFF distinct", async () => {
264 const encode = (value: string) => new TextEncoder().encode(value);
265 const entries = [
266 { type: "0", path: "\uFEFFreport.txt", contents: "ONE" },
267 { type: "0", path: "report.txt", contents: "TWO" },
268 { type: "L", path: "././@LongLink", contents: "\uFEFFnotes.txt\0" },
269 { type: "0", path: "notes.txt", contents: "THREE" },
270 ];
271 const bytes = new Uint8Array(entries.length * 1024 + 1024);
272 entries.forEach((entry, index) => {
273 const offset = index * 1024;
274 const contents = encode(entry.contents);
275 bytes.set(encode(entry.path), offset);
276 bytes.set(encode(contents.length.toString(8).padStart(11, "0") + "\0"), offset + 124);
277 bytes.set(encode("00000000000\0"), offset + 136);
278 bytes.fill(32, offset + 148, offset + 156);
279 bytes.set(encode(entry.type), offset + 156);
280 const sum = bytes.subarray(offset, offset + 512).reduce((acc, byte) => acc + byte, 0);
281 bytes.set(encode(sum.toString(8).padStart(6, "0") + "\0 "), offset + 148);
282 bytes.set(contents, offset + 512);
283 });
284​
285 try {
286 const request = await startWorker();
287 const result = await request({
288 type: "open",
289 kind: "archive",
290 name: "test.tar",
291 bytes: bytes.buffer,
292 });
293 if (result.type !== "archive") throw new Error(`Expected archive, got ${result.type}`);
294 expect(result.entries.map(({ path }) => path)).toEqual([
295 "\uFEFFreport.txt",
296 "report.txt",
297 "\uFEFFnotes.txt",
298 ]);
299 const decoded = [];
300 for (const { path } of result.entries) {
301 const entry = await request({ type: "entry", path });
302 decoded.push(entry.type === "entry" ? new TextDecoder().decode(entry.bytes) : entry.type);
303 }
304 expect(decoded).toEqual(["ONE", "TWO", "THREE"]);
305 } finally {
306 vi.unstubAllGlobals();
307 }
308});
309​
310it("opens a plain TAR whose first member name starts with 0x1F", async () => {
311 const encode = (value: string) => new TextEncoder().encode(value);
312 const path = "\x1fhello.txt";
313 const contents = encode("hi\n");
314 const bytes = new Uint8Array(512 * 2 + 1024);
315 bytes.set(encode(path), 0);
316 bytes.set(encode("000644 \0"), 100);
317 bytes.set(encode(contents.length.toString(8).padStart(11, "0") + "\0"), 124);
318 bytes.set(encode("00000000000\0"), 136);
319 bytes.fill(32, 148, 156);
320 bytes.set(encode("0"), 156);
321 bytes.set(encode("ustar\x0000"), 257);
322 const sum = bytes.subarray(0, 512).reduce((acc, byte) => acc + byte, 0);
323 bytes.set(encode(sum.toString(8).padStart(6, "0") + "\0 "), 148);
324 bytes.set(contents, 512);
325​
326 try {
327 const request = await startWorker();
328 expect(
329 await request({ type: "open", kind: "archive", name: "sample.tar", bytes: bytes.buffer }),
330 ).toEqual({
331 type: "archive",
332 entries: [{ path, size: 3, directory: false, modified: "1970-01-01T00:00:00.000Z" }],
333 });
334 const entry = await request({ type: "entry", path });
335 if (entry.type !== "entry") throw new Error(`Expected entry, got ${entry.type}`);
336 expect([...entry.bytes]).toEqual([0x68, 0x69, 0x0a]);
337 } finally {
338 vi.unstubAllGlobals();
339 }
340});