-
Notifications
You must be signed in to change notification settings - Fork 16
/
before.js
53 lines (51 loc) · 2.28 KB
/
before.js
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
import console, { originalConsole } from "../modules/console.js";
console.info("Initialization done.");
import jsonModule from "../modules/jsonModule.js";
import testLatency from "../modules/testLatency.js";
import mkdtmp from "../modules/mkdtmp.js";
import fs from "node:fs";
import path from "node:path";
const packageLockFile = "package-lock.json";
const registries = [
"https://registry.npmjs.org/",
"https://mirrors.cloud.tencent.com/npm/",
"https://registry.npmmirror.com/",
];
const targetPath = "index.json";
const latency = await testLatency(registries.map((base) => `${base}${targetPath}`));
const targetRegistry = latency.sort(([, a], [, b]) => a - b)[0][0].replace(targetPath, "");
const otherRegistries = registries.filter((registry) => registry !== targetRegistry);
console.info("targetRegistry:", targetRegistry);
console.info("otherRegistries:", otherRegistries);
console.info("Start to backup", packageLockFile);
const tmpdir = await mkdtmp({
subDir: process.env.RANDOM_UUID,
});
const backupedPackageLockFile = path.join(tmpdir, packageLockFile);
await fs.promises.cp(packageLockFile, backupedPackageLockFile, { force: true, preserveTimestamps: true });
console.info("backup:", backupedPackageLockFile);
console.info("Start to read", packageLockFile);
const packageLockFileContent = await jsonModule.readFile(packageLockFile);
console.info("Start to modified resolved path for packages");
const modifiedCount = {};
for (const key of Object.keys(packageLockFileContent.packages)) {
if (typeof packageLockFileContent.packages[key].resolved === "string") {
let url = packageLockFileContent.packages[key].resolved;
for (const registry of otherRegistries) {
if (url.startsWith(registry)) {
url = url.replace(registry, targetRegistry);
if (typeof modifiedCount[registry] !== "number") {
modifiedCount[registry] = 0;
}
modifiedCount[registry]++;
break;
}
}
packageLockFileContent.packages[key].resolved = url;
}
}
console.info("modifiedCount:", modifiedCount);
console.info("Start to write back", packageLockFile);
await jsonModule.writeFile(packageLockFile, packageLockFileContent);
console.info("Done.");
originalConsole.info("=".repeat(120));