Repository navigation
Expand file tree
/
Copy pathbuild.mjs
More file actions
334 lines (302 loc) · 12.5 KB
/
Copy pathbuild.mjs
File metadata and controls
334 lines (302 loc) · 12.5 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Build pipeline for Zodiac Chronobox. Plain Node + esbuild, no other dependencies.
//
// node build.mjs production build into out/ (reproducible)
// node build.mjs --dev watch + rebuild into out/, serve on PORT (default 3130)
//
// Production options: --sourcemap adds linked sourcemaps (off by default).
//
// The build hash:
// One hash names the whole build. The page shows its first 8 characters in
// the footer, so the page must contain the hash, so the hash cannot cover
// the final index.html. It is defined like this:
// sha256 over the sorted lines "<path> <sha256>\n" of every file in out/
// except build.json, where index.html is hashed with the placeholder
// __BUILD_HASH__ in the place where the hash goes.
// To check a deployed copy: put the placeholder back into index.html and
// compute the same thing, or build the same commit and compare.
// build.json lists the final sha256 of every file, index.html included.
import * as esbuild from "esbuild";
import { createHash } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
import fs from "node:fs/promises";
import { watch as fsWatch } from "node:fs";
import http from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = path.dirname(fileURLToPath(import.meta.url));
const SRC = path.join(ROOT, "src");
const STATIC = path.join(ROOT, "static");
const args = new Set(process.argv.slice(2));
const DEV = args.has("--dev");
/** A short tag of the film's content, in both of its sizes. It goes into the film's address, so that a new film is never taken from a cache. */
function filmTag() {
const files = ["chronobox-film.mp4", "chronobox-film-1440.mp4"].map((name) => path.join(STATIC, name)).filter((file) => existsSync(file));
if (files.length === 0) return "none";
const hash = createHash("sha256");
for (const file of files) hash.update(readFileSync(file));
return hash.digest("hex").slice(0, 10);
}
// The dev server writes to its own folder, so a production build never mixes with it.
const OUT = path.join(ROOT, DEV ? "out-dev" : "out");
const SOURCEMAP = DEV || args.has("--sourcemap");
const pkg = JSON.parse(await fs.readFile(path.join(ROOT, "package.json"), "utf8"));
// The page talks to nobody but the token index of third-party services, and only after they are switched on.
const PROD_CONNECT = "connect-src https://eth.blockscout.com https://eth-sepolia.blockscout.com";
const DEV_CONNECT = `${PROD_CONNECT} 'self' http://127.0.0.1:8545 http://localhost:8545 http://127.0.0.1:8546`;
const HASH_PLACEHOLDER = "__BUILD_HASH__";
/** Shared esbuild options for app code. */
function appOptions() {
return {
absWorkingDir: ROOT,
bundle: true,
format: "esm",
target: "es2022",
platform: "browser",
jsx: "automatic",
jsxImportSource: "preact",
charset: "utf8",
minify: !DEV,
sourcemap: SOURCEMAP ? "linked" : false,
sourcesContent: DEV,
define: {
__DEV__: JSON.stringify(DEV),
__FILM__: JSON.stringify(filmTag()),
},
loader: {
".svg": "file",
".png": "file",
".woff2": "file",
".woff": "file",
},
assetNames: "assets/[name]-[hash]",
logLevel: "warning",
};
}
const sha256 = (data) => createHash("sha256").update(data).digest("hex");
async function clean() {
await fs.rm(OUT, { recursive: true, force: true });
await fs.mkdir(OUT, { recursive: true });
}
async function copyStatic() {
if (!existsSync(STATIC)) return;
await fs.cp(STATIC, OUT, { recursive: true });
}
/** Fill src/index.html: hashed asset names, dev CSP and dev wallet script. */
async function writeIndex({ js, css }) {
let html = await fs.readFile(path.join(SRC, "index.html"), "utf8");
const replace = (from, to) => {
if (!html.includes(from)) throw new Error(`src/index.html: expected to find ${from}`);
html = html.replace(from, to);
};
replace('href="./assets/app.css"', `href="./${css}"`);
replace('src="./assets/app.js"', `src="./${js}"`);
if (!html.includes(HASH_PLACEHOLDER)) throw new Error(`src/index.html: expected to find ${HASH_PLACEHOLDER}`);
if (DEV) {
html = html.replace(HASH_PLACEHOLDER, "dev");
replace(PROD_CONNECT, DEV_CONNECT);
// Classic script without defer: runs before the module app script.
replace(
`<script type="module" src="./${js}"></script>`,
`<script src="./dev-wallet.js"></script>\n <script type="module" src="./${js}"></script>`,
);
}
assertNoInline(html);
await fs.writeFile(path.join(OUT, "index.html"), html);
}
function assertNoInline(html) {
for (const m of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
if (!/\bsrc=/.test(m[1]) || m[2].trim() !== "") throw new Error("index.html: inline script not allowed");
}
if (/<style\b/i.test(html) || /\sstyle=/i.test(html)) throw new Error("index.html: inline style not allowed");
if (/\son[a-z]+=/i.test(html)) throw new Error("index.html: inline event handler not allowed");
}
async function listFiles(dir, base = dir) {
const out = [];
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) out.push(...(await listFiles(full, base)));
else out.push(path.relative(base, full).split(path.sep).join("/"));
}
return out.sort();
}
// ---------------------------------------------------------------------------
// Production
async function buildProd() {
await clean();
await copyStatic();
const stripDevCss = {
name: "strip-dev-css",
setup(build) {
build.onResolve({ filter: /devbar\.css$/ }, () => ({ path: "devbar.css", namespace: "strip-dev" }));
build.onLoad({ filter: /.*/, namespace: "strip-dev" }, () => ({ contents: "", loader: "css" }));
},
};
const result = await esbuild.build({
...appOptions(),
entryPoints: [{ in: "src/main.tsx", out: "app" }],
outdir: OUT,
entryNames: "assets/[name]-[hash]",
plugins: [stripDevCss],
metafile: true,
write: true,
});
const outputs = Object.keys(result.metafile.outputs).map((p) => path.relative(OUT, path.join(ROOT, p)).split(path.sep).join("/"));
const js = outputs.find((p) => /^assets\/app-[^/]+\.js$/.test(p));
const css = outputs.find((p) => /^assets\/app-[^/]+\.css$/.test(p));
if (!js) throw new Error("build: no app JS output");
if (!css) throw new Error("build: no app CSS output (src/main.tsx must import ./styles.css)");
await writeIndex({ js, css });
// The build hash (see the header comment). index.html still has the placeholder here.
const files = {};
for (const p of await listFiles(OUT)) files[p] = sha256(await fs.readFile(path.join(OUT, p)));
const buildHash = sha256(Object.keys(files).sort().map((p) => `${p} ${files[p]}\n`).join(""));
const indexPath = path.join(OUT, "index.html");
await fs.writeFile(indexPath, (await fs.readFile(indexPath, "utf8")).replace(HASH_PLACEHOLDER, buildHash));
// build.json: the final hash of every file except itself.
const all = {};
for (const p of await listFiles(OUT)) all[p] = sha256(await fs.readFile(path.join(OUT, p)));
const manifest = { version: pkg.version, buildHash, files: all };
await fs.writeFile(path.join(OUT, "build.json"), JSON.stringify(manifest, null, 2) + "\n");
// Guard: dev-only tools must never reach production.
for (const p of await listFiles(OUT)) {
const text = await fs.readFile(path.join(OUT, p), "latin1");
if (text.includes("dev-wallet") || text.includes("devbar")) throw new Error(`build: dev-only code found in out/${p}`);
}
// Report.
const rows = [];
for (const p of await listFiles(OUT)) {
const buf = await fs.readFile(path.join(OUT, p));
rows.push([p, String(buf.length), sha256(buf)]);
}
const w0 = Math.max(...rows.map((r) => r[0].length));
const w1 = Math.max(...rows.map((r) => r[1].length));
for (const [p, size, hash] of rows) console.log(`${p.padEnd(w0)} ${size.padStart(w1)} ${hash}`);
console.log(`\nversion ${pkg.version}\nbuild hash ${buildHash}`);
}
// ---------------------------------------------------------------------------
// Dev
const MIME = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".map": "application/json; charset=utf-8",
".webmanifest": "application/manifest+json",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".mp4": "video/mp4",
".ico": "image/x-icon",
".woff2": "font/woff2",
".woff": "font/woff",
".txt": "text/plain; charset=utf-8",
};
function listen(server, port) {
return new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(port, "127.0.0.1", () => {
server.off("error", reject);
resolve();
});
});
}
function serve(req, res) {
const send = (status, body, type = "text/plain; charset=utf-8") => {
res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
res.end(req.method === "HEAD" ? undefined : body);
};
if (req.method !== "GET" && req.method !== "HEAD") return send(405, "Method not allowed\n");
let pathname;
try {
pathname = decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname);
} catch {
return send(400, "Bad request\n");
}
if (pathname.endsWith("/")) pathname += "index.html";
// The states that `npm run scenarios` put on the fork, for #/states. Not a file of the build.
if (pathname === "/scenarios.json") {
return fs.readFile(path.join(ROOT, ".scenarios", "scenarios.json")).then(
(body) => send(200, body, "application/json; charset=utf-8"),
() => send(404, "No scenarios yet: run npm run scenarios\n"),
);
}
// The dev server also serves the files in brand/.
const base = pathname.startsWith("/brand/") ? ROOT : OUT;
const file = path.join(base, path.normalize(pathname));
if (file !== base && !file.startsWith(base + path.sep)) return send(403, "Forbidden\n");
fs.readFile(file)
.then((body) => send(200, body, MIME[path.extname(file).toLowerCase()] ?? "application/octet-stream"))
.catch(async () => {
// SPA fallback only for navigations without a file extension.
if (path.extname(pathname) === "") {
try {
return send(200, await fs.readFile(path.join(OUT, "index.html")), MIME[".html"]);
} catch {}
}
send(404, "Not found\n");
});
}
async function dev() {
const port = Number(process.env.PORT ?? 3130);
const server = http.createServer(serve);
try {
await listen(server, port);
} catch (err) {
if (err.code === "EADDRINUSE") console.error(`Port ${port} is already in use. Stop the other process or set PORT.`);
else console.error(err);
process.exit(1);
}
await clean();
await copyStatic();
const assets = { js: "assets/app.js", css: "assets/app.css" };
await writeIndex(assets);
const log = (label) => ({
name: "log",
setup(build) {
build.onEnd((r) => {
const t = new Date().toLocaleTimeString();
if (r.errors.length) console.log(`[${t}] ${label}: build failed (${r.errors.length} errors)`);
else console.log(`[${t}] ${label}: built`);
});
},
});
const appCtx = await esbuild.context({
...appOptions(),
entryPoints: [{ in: "src/main.tsx", out: "app" }],
outdir: path.join(OUT, "assets"),
plugins: [log("app")],
});
// Classic script (IIFE) so it runs before the module app script and keeps its globals private.
const walletCtx = await esbuild.context({
...appOptions(),
format: "iife",
entryPoints: [{ in: "src/dev-wallet.ts", out: "dev-wallet" }],
outdir: OUT,
plugins: [log("dev-wallet")],
});
await Promise.all([appCtx.watch(), walletCtx.watch()]);
const rerun = (what, fn) => () =>
fn().then(
() => console.log(`[${new Date().toLocaleTimeString()}] ${what} updated`),
(e) => console.error(`${what}: ${e.message}`),
);
if (existsSync(STATIC)) fsWatch(STATIC, { recursive: true }, rerun("static", copyStatic));
fsWatch(path.join(SRC, "index.html"), rerun("index.html", () => writeIndex(assets)));
console.log(`Dev server: http://localhost:${port}/ (anvil wallet: ?account=0|1|2, scenarios: #/states)`);
const stop = async () => {
await Promise.all([appCtx.dispose(), walletCtx.dispose()]);
server.close();
process.exit(0);
};
process.on("SIGINT", stop);
process.on("SIGTERM", stop);
}
try {
if (DEV) await dev();
else await buildProd();
} catch (err) {
console.error(err instanceof Error ? err.message : err);
process.exit(1);
}