-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathnpm-retry.mjs
More file actions
59 lines (49 loc) · 1.52 KB
/
Copy pathnpm-retry.mjs
File metadata and controls
59 lines (49 loc) · 1.52 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
import { spawnSync } from "node:child_process";
import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
const DEFAULT_ATTEMPTS = 3;
const DEFAULT_BACKOFF_MS = 20_000;
function runNpm(args) {
const command = process.platform === "win32" ? "npm.cmd" : "npm";
const result = spawnSync(command, args, {
shell: process.platform === "win32",
stdio: "inherit",
});
if (result.error) {
console.error(`Failed to start npm: ${result.error.message}`);
return 1;
}
return result.status ?? 1;
}
function wait(delayMs) {
return new Promise((resolve) => setTimeout(resolve, delayMs));
}
export async function runWithRetry(
args,
{ attempts = DEFAULT_ATTEMPTS, backoffMs = DEFAULT_BACKOFF_MS, run = runNpm, sleep = wait } = {},
) {
let exitCode = 1;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
exitCode = await run(args);
if (exitCode === 0) {
return 0;
}
if (attempt < attempts) {
const delayMs = attempt * backoffMs;
console.warn(
`npm failed with exit code ${exitCode}; retrying in ${delayMs / 1000}s (${attempt + 1}/${attempts})`,
);
await sleep(delayMs);
}
}
return exitCode;
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
const args = process.argv.slice(2);
if (args.length === 0) {
console.error("Usage: node scripts/npm-retry.mjs <npm arguments...>");
process.exitCode = 2;
} else {
process.exitCode = await runWithRetry(args);
}
}