-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbuild.ts
98 lines (76 loc) · 2.59 KB
/
build.ts
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
// File taken from https://deno.land/x/[email protected]/scripts/build.ts
// Copyright 2020-present the denosaurs team. All rights reserved. MIT license.
import { encode } from "https://deno.land/[email protected]/encoding/base64.ts";
import { compress } from "https://deno.land/x/[email protected]/mod.ts";
import * as Terser from "https://esm.sh/[email protected]";
const name = "ammonia_wasm";
const encoder = new TextEncoder();
async function requires(...executables: string[]) {
const where = Deno.build.os === "windows" ? "where" : "which";
for (const executable of executables) {
const process = Deno.run({
cmd: [where, executable],
stderr: "null",
stdin: "null",
stdout: "null",
});
if (!(await process.status()).success) {
err(`Could not find required build tool ${executable}`);
}
}
}
async function run(msg: string, cmd: string[]) {
log(msg);
const process = Deno.run({ cmd });
if (!(await process.status()).success) {
err(`${msg} failed`);
}
}
function log(text: string): void {
console.log(`[log] ${text}`);
}
function err(text: string): never {
console.log(`[err] ${text}`);
return Deno.exit(1);
}
await requires("rustup", "rustc", "cargo", "wasm-pack");
if (!(await Deno.stat("Cargo.toml")).isFile) {
err(`the build script should be executed in the "${name}" root`);
}
await run(
"building using wasm-pack",
["wasm-pack", "build", "--target", "web", "--release"],
);
await Deno.remove("pkg/.gitignore");
await Deno.remove("pkg/package.json");
await Deno.remove("pkg/README.md");
const wasm = await Deno.readFile(`pkg/${name}_bg.wasm`);
const compressed = compress(wasm);
log(
`compressed wasm using lz4, size reduction: ${wasm.length -
compressed.length} bytes`,
);
const encoded = encode(compressed);
log(
`encoded wasm using base64, size increase: ${encoded.length -
compressed.length} bytes`,
);
log("inlining wasm in js");
const source = `import * as lz4 from "https://deno.land/x/[email protected]/mod.ts";
export const source = lz4.decompress(Uint8Array.from(atob("${encoded}"), c => c.charCodeAt(0)));`;
log("minifying js");
const output = await Terser.minify(`${source}`, {
mangle: { module: true },
output: {
preamble: "//deno-fmt-ignore-file",
},
});
const reduction = new Blob([(`${source}`)]).size -
new Blob([output.code!]).size;
log(`minified js, size reduction: ${reduction} bytes`);
log(`writing output to file ("wasm.js")`);
await Deno.writeFile("wasm.js", encoder.encode(output.code));
const outputFile = await Deno.stat("wasm.js");
log(
`output file ("wasm.js"), final size is: ${outputFile.size} bytes`,
);