-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathfiles.ts
More file actions
185 lines (154 loc) · 5.98 KB
/
files.ts
File metadata and controls
185 lines (154 loc) · 5.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/*
* This file is part of Edgehog.
*
* Copyright 2026 SECO Mind Srl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
import { compress } from "lz4js";
const BLOCK_SIZE = 512;
// Computes a SHA-256 digest of binary data
// Returns the digest in the format "sha256:<hex>".
const computeDigest = async (data: Uint8Array): Promise<string> => {
const hashBuffer = await crypto.subtle.digest(
"SHA-256",
data.buffer as ArrayBuffer,
);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return `sha256:${hashHex}`;
};
const formatFileSize = (bytes: number): string => {
if (bytes === 0) return "0 B";
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024)
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
};
// Returns the path to use as the tar entry name.
// Uses webkitRelativePath (set by folder selection) when available,
// falling back to the file name for individually selected files.
const getTarEntryPath = (file: File): string =>
file.webkitRelativePath || file.name;
const writeTarDirectoryEntry = (
dirPath: string,
chunks: Uint8Array[],
): void => {
const header = new Uint8Array(BLOCK_SIZE);
const encoder = new TextEncoder();
header.set(encoder.encode(dirPath).slice(0, 100), 0);
header.set(encoder.encode("0000755\0"), 100); // rwxr-xr-x
header.set(encoder.encode("0000000\0"), 108);
header.set(encoder.encode("0000000\0"), 116);
header.set(encoder.encode("00000000000\0"), 124); // size 0
const mtime = Math.floor(Date.now() / 1000)
.toString(8)
.padStart(11, "0");
header.set(encoder.encode(mtime + "\0"), 136);
header.set(encoder.encode(" "), 148); // placeholder checksum
header[156] = 0x35; // ASCII '5' = directory
header.set(encoder.encode("ustar\0"), 257);
header.set(encoder.encode("00"), 263);
let checksum = 0;
for (let i = 0; i < BLOCK_SIZE; i++) checksum += header[i];
header.set(
encoder.encode(checksum.toString(8).padStart(6, "0") + "\0 "),
148,
);
chunks.push(header);
};
// Creates a tar archive from an array of files.
// Returns a Uint8Array containing the raw tar data (uncompressed).
const createTarArchive = async (files: File[]): Promise<Uint8Array> => {
const chunks: Uint8Array[] = [];
const directories = new Set<string>();
for (const file of files) {
const entryPath = getTarEntryPath(file);
const parts = entryPath.split("/");
for (let i = 1; i < parts.length; i++) {
directories.add(parts.slice(0, i).join("/") + "/");
}
}
for (const dirPath of [...directories].sort()) {
writeTarDirectoryEntry(dirPath, chunks);
}
for (const file of files) {
const fileData = new Uint8Array(await file.arrayBuffer());
const fileName = getTarEntryPath(file);
// Build the 512-byte tar header
const header = new Uint8Array(BLOCK_SIZE);
const encoder = new TextEncoder();
// File name (offset 0, 100 bytes)
const nameBytes = encoder.encode(fileName);
header.set(nameBytes.slice(0, 100), 0);
// File size in octal (offset 124, 12 bytes)
const sizeOctal = fileData.length.toString(8).padStart(11, "0");
header.set(encoder.encode(sizeOctal + "\0"), 124);
// Modification time in octal (offset 136, 12 bytes)
const mtime = Math.floor((file.lastModified || Date.now()) / 1000)
.toString(8)
.padStart(11, "0");
header.set(encoder.encode(mtime + "\0"), 136);
// Initialize checksum field with spaces (offset 148, 8 bytes)
header.set(encoder.encode(" "), 148);
// Type flag (offset 156, 1 byte) - '0' = regular file
header[156] = 0x30; // ASCII '0'
// USTAR indicator (offset 257, 6 bytes)
header.set(encoder.encode("ustar\0"), 257);
// USTAR version (offset 263, 2 bytes)
header.set(encoder.encode("00"), 263);
// Compute checksum: sum of all bytes in the header treated as unsigned
let checksum = 0;
for (let i = 0; i < BLOCK_SIZE; i++) {
checksum += header[i];
}
const checksumStr = checksum.toString(8).padStart(6, "0") + "\0 ";
header.set(encoder.encode(checksumStr), 148);
chunks.push(header);
chunks.push(fileData);
// Pad file data to a multiple of 512 bytes
const remainder = fileData.length % BLOCK_SIZE;
if (remainder > 0) {
chunks.push(new Uint8Array(BLOCK_SIZE - remainder));
}
}
// End-of-archive marker: two 512-byte blocks of zeros
chunks.push(new Uint8Array(BLOCK_SIZE * 2));
// Concatenate all chunks
const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
const tarData = new Uint8Array(totalLength);
let offset = 0;
for (const chunk of chunks) {
tarData.set(chunk, offset);
offset += chunk.length;
}
return tarData;
};
// Creates an LZ4 compressed tar archive from multiple files.
// Returns a Blob of the compressed archive.
const createTarGzArchive = async (files: File[]): Promise<Blob> => {
const tarData = await createTarArchive(files);
// Run compression on a later tick so callers can await it asynchronously.
const lz4Data = await new Promise<Uint8Array>((resolve) => {
setTimeout(() => resolve(compress(tarData)), 0);
});
return new Blob([lz4Data.buffer as ArrayBuffer], {
type: "application/x-lz4",
});
};
export { computeDigest, createTarArchive, createTarGzArchive, formatFileSize };