Branchwell

Skillfarm / website · skillfarm.ai / src / lib / zip.ts

Raw 2.5 KB on 154cbccf923a68550a73e85d66bba0b0fb8f1943
1// Minimal store-only (no compression) ZIP writer, enough for small text bundles.
2const CRC_TABLE = (() => {
3 const t = new Uint32Array(256);
4 for (let n = 0; n < 256; n++) {
5 let c = n;
6 for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
7 t[n] = c >>> 0;
8 }
9 return t;
10})();
11
12function crc32(data: Uint8Array): number {
13 let c = 0xffffffff;
14 for (let i = 0; i < data.length; i++) c = CRC_TABLE[(c ^ data[i]) & 0xff] ^ (c >>> 8);
15 return (c ^ 0xffffffff) >>> 0;
16}
17
18export function makeZip(files: { path: string; data: Uint8Array }[]): Uint8Array {
19 const enc = new TextEncoder();
20 const chunks: Uint8Array[] = [];
21 const central: Uint8Array[] = [];
22 let offset = 0;
23 for (const f of files) {
24 const name = enc.encode(f.path);
25 const crc = crc32(f.data);
26 const local = new DataView(new ArrayBuffer(30));
27 local.setUint32(0, 0x04034b50, true);
28 local.setUint16(4, 20, true);
29 local.setUint16(6, 0x0800, true); // UTF-8 names
30 local.setUint16(8, 0, true); // stored
31 local.setUint16(10, 0, true);
32 local.setUint16(12, 0x21, true); // 1980-01-01
33 local.setUint32(14, crc, true);
34 local.setUint32(18, f.data.length, true);
35 local.setUint32(22, f.data.length, true);
36 local.setUint16(26, name.length, true);
37 local.setUint16(28, 0, true);
38 chunks.push(new Uint8Array(local.buffer), name, f.data);
39
40 const cd = new DataView(new ArrayBuffer(46));
41 cd.setUint32(0, 0x02014b50, true);
42 cd.setUint16(4, 20, true);
43 cd.setUint16(6, 20, true);
44 cd.setUint16(8, 0x0800, true);
45 cd.setUint16(10, 0, true);
46 cd.setUint16(12, 0, true);
47 cd.setUint16(14, 0x21, true);
48 cd.setUint32(16, crc, true);
49 cd.setUint32(20, f.data.length, true);
50 cd.setUint32(24, f.data.length, true);
51 cd.setUint16(28, name.length, true);
52 cd.setUint32(38, 0o100644 << 16, true);
53 cd.setUint32(42, offset, true);
54 central.push(new Uint8Array(cd.buffer), name);
55 offset += 30 + name.length + f.data.length;
56 }
57 const cdSize = central.reduce((n, c) => n + c.length, 0);
58 const end = new DataView(new ArrayBuffer(22));
59 end.setUint32(0, 0x06054b50, true);
60 end.setUint16(8, files.length, true);
61 end.setUint16(10, files.length, true);
62 end.setUint32(12, cdSize, true);
63 end.setUint32(16, offset, true);
64 const all = [...chunks, ...central, new Uint8Array(end.buffer)];
65 const out = new Uint8Array(all.reduce((n, c) => n + c.length, 0));
66 let p = 0;
67 for (const c of all) {
68 out.set(c, p);
69 p += c.length;
70 }
71 return out;
72}