-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathminimize.mjs
More file actions
74 lines (64 loc) · 1.9 KB
/
Copy pathminimize.mjs
File metadata and controls
74 lines (64 loc) · 1.9 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
// Minimizes in place
if (process.argv.length !== 4) {
console.error("Usage: node minimize.js <wasm-file> <output>");
process.exit(1);
}
const path = process.argv[2];
const outputPath = process.argv[3];
import fs from 'fs';
const wasmBuffer = fs.readFileSync(path);
class BufferView {
constructor(buffer) {
this.buffer = buffer;
this.offset = 0;
this.size = buffer.length;
}
readVu32() {
let value = 0;
let shift = 0;
let byte;
do {
byte = this.buffer[this.offset++];
value |= (byte & 0x7F) << shift;
shift += 7;
} while (byte & 0x80);
return value;
}
writeVu32(value) {
do {
let byte = value & 0x7F;
value >>>= 7;
if (value !== 0) {
byte |= 0x80;
}
this.buffer[this.offset++] = byte;
} while (value !== 0);
}
writeBuffer(srcBuffer) {
srcBuffer.copy(this.buffer, this.offset);
this.offset += srcBuffer.length;
}
readBuffer(length) {
const outBuffer = this.buffer.slice(this.offset, this.offset + length);
this.offset += length;
return outBuffer;
}
}
const input = new BufferView(wasmBuffer);
// We're cutting down bytes, size will get shorter
const output = new BufferView(Buffer.alloc(wasmBuffer.length + 128));
output.writeBuffer(input.readBuffer(8)); // Magic + version
// Delete useless section
while (input.offset < input.size) {
const sectionId = input.readVu32();
const sectionSize = input.readVu32();
const sectionBytes = input.readBuffer(sectionSize);
if (sectionId === 0) { // Custom section
continue;
}
// Otherwise copy it over
output.writeVu32(sectionId);
output.writeVu32(sectionSize);
output.writeBuffer(sectionBytes);
}
fs.writeFileSync(outputPath, output.buffer.slice(0, output.offset));