Skip to content
Source
Sign inSign up
samwillis/hackernews-realtime
Open History to see the last commit

bootstrap.mjs

158 lines4.9 KB

1import { execFileSync } from "node:child_process";
2import {
3 access,
4 cp,
5 mkdir,
6 mkdtemp,
7 readFile,
8 readdir,
9 rename,
10 rm,
11 writeFile,
12} from "node:fs/promises";
13import { createHash } from "node:crypto";
14import { tmpdir } from "node:os";
15import { resolve } from "node:path";
16​
17const root = resolve(import.meta.dirname, "..");
18const lockPath = resolve(root, "neon-toolchain.lock.json");
19const lock = JSON.parse(await readFile(lockPath, "utf8"));
20if (process.versions.node !== lock.node)
21 throw new Error(
22 `Use Node ${lock.node} to reproduce the Neon package artifacts`,
23 );
24const run = (command, args, cwd, capture = false) =>
25 execFileSync(command, args, {
26 cwd,
27 stdio: capture ? "pipe" : "inherit",
28 encoding: "utf8",
29 env: { ...process.env, HUSKY: "0" },
30 });
31const source = resolve(
32 process.env.NEON_PKGS_DIR || resolve(root, ".local/toolchains/neon-pkgs"),
33);
34await mkdir(resolve(root, ".local/toolchains"), { recursive: true });
35try {
36 await access(resolve(source, ".git"));
37} catch {
38 if (process.env.NEON_PKGS_DIR)
39 throw new Error("NEON_PKGS_DIR does not exist");
40 run(
41 "git",
42 ["clone", "--filter=blob:none", "--no-checkout", lock.repository, source],
43 root,
44 );
46if (!process.env.NEON_PKGS_DIR) {
47 run("git", ["fetch", "origin", lock.commit], source);
48 run("git", ["checkout", "--detach", lock.commit], source);
50if (
51 run("git", ["rev-parse", "HEAD"], source, true).trim() !== lock.commit ||
52 run("git", ["status", "--porcelain"], source, true).trim()
53) {
54 throw new Error("Neon checkout must be clean and match the pinned commit");
56run(
57 "npx",
58 ["--yes", lock.packageManager, "install", "--frozen-lockfile"],
59 source,
60);
61const filters = [...lock.packages.map((name) => `@neon/${name}...`), "neon..."];
62run(
63 "npx",
64 [
65 "--yes",
66 lock.packageManager,
67 ...filters.flatMap((value) => ["--filter", value]),
68 "build",
69 ],
70 source,
71);
72const destination = resolve(root, ".sdk");
73await mkdir(destination, { recursive: true });
74async function normalizeDistribution(directory) {
75 for (const entry of await readdir(directory, { withFileTypes: true })) {
76 const path = resolve(directory, entry.name);
77 if (entry.isDirectory()) await normalizeDistribution(path);
78 else if (entry.name.endsWith(".map")) await rm(path);
79 else if (/\.(js|ts)$/.test(entry.name)) {
80 const content = await readFile(path, "utf8");
81 await writeFile(
82 path,
83 content.replace(/^\/\/[@#] sourceMappingURL=.*\r?\n?/gm, ""),
84 );
85 }
86 }
88for (const name of lock.packages) {
89 const packageDir = resolve(source, "packages", name);
90 const metadata = JSON.parse(
91 await readFile(resolve(packageDir, "package.json"), "utf8"),
92 );
93 delete metadata.scripts;
94 delete metadata.devDependencies;
95 for (const section of ["dependencies", "peerDependencies"]) {
96 for (const [dependency, version] of Object.entries(
97 metadata[section] || {},
98 )) {
99 if (!version.startsWith("workspace:")) continue;
100 const sibling = dependency.replace("@neon/", "");
101 if (!lock.packages.includes(sibling))
102 throw new Error(`Missing runtime closure: ${dependency}`);
103 metadata[section][dependency] = JSON.parse(
104 await readFile(
105 resolve(source, "packages", sibling, "package.json"),
106 "utf8",
107 ),
108 ).version;
109 }
110 }
111 const temporary = await mkdtemp(resolve(tmpdir(), "hn-sdk-"));
112 try {
113 await writeFile(
114 resolve(temporary, "package.json"),
115 JSON.stringify(metadata, null, 2) + "\n",
116 );
117 for (const file of metadata.files) {
118 if (file !== "package.json")
119 await cp(resolve(packageDir, file), resolve(temporary, file), {
120 recursive: true,
121 });
122 }
123 // The prerelease declaration bundler emits nondeterministic mapping names.
124 // Source maps are optional debugging artifacts; exclude them, retaining
125 // identical runtime JavaScript and type declarations in reproducible packs.
126 await normalizeDistribution(temporary);
127 const [{ filename }] = JSON.parse(
128 run(
129 "npm",
130 [
131 "pack",
132 "--ignore-scripts",
133 "--json",
134 "--pack-destination",
135 destination,
136 ],
137 temporary,
138 true,
139 ),
140 );
141 const target = `neon-${name}.tgz`;
142 await rename(resolve(destination, filename), resolve(destination, target));
143 const integrity =
144 "sha512-" +
145 createHash("sha512")
146 .update(await readFile(resolve(destination, target)))
147 .digest("base64");
148 if (process.argv.includes("--update-integrity"))
149 lock.integrities[target] = integrity;
150 else if (lock.integrities[target] !== integrity)
151 throw new Error(`Package integrity mismatch: ${target}`);
152 console.log(`Verified ${target}`);
153 } finally {
154 await rm(temporary, { recursive: true, force: true });
155 }
157if (process.argv.includes("--update-integrity"))
158 await writeFile(lockPath, JSON.stringify(lock, null, 2) + "\n");