返回 CodeWhale
install.js
根目录 / npm / codewhale / scripts / install.js
1 function assertSupportedNode() {
2 const version = process.versions && process.versions.node ? process.versions.node : "unknown";
3 const major = Number.parseInt(String(version).split(".")[0], 10);
4 if (Number.isNaN(major) || major < 22) {
5 process.stderr.write(
6 "codewhale: Node.js 22 or newer is required for npm installation. " +
7 `Current Node.js version is ${version}. ` +
8 "Please upgrade Node.js and rerun `npm install -g codewhale`.\n",
9 );
10 process.exit(1);
11 }
12 }
13
14 assertSupportedNode();
15
16 const fs = require("fs");
17 const https = require("https");
18 const http = require("http");
19 const net = require("net");
20 const tls = require("tls");
21 const crypto = require("crypto");
22 const { URL } = require("url");
23 const { mkdir, chmod, stat, rename, readFile, unlink, writeFile } = fs.promises;
24 const { createWriteStream } = fs;
25 const path = require("path");
26 const os = require("os");
27
28 const {
29 CHECKSUM_MANIFEST,
30 assertCnbMirrorSupportedPlatform,
31 checksumManifestUrl,
32 cnbReleaseBaseUrl,
33 detectBinaryNames,
34 explicitReleaseBase,
35 firstPartyReleaseSources,
36 githubReleaseBaseUrl,
37 openHarmonyDirections,
38 redactUrl,
39 releaseAssetUrl,
40 releaseAssetUrlFromBase,
41 releaseBinaryDirectory,
42 shouldRaceFirstPartyMirrors,
43 usesCnbMirror,
44 validateReleaseUrl,
45 } = require("./artifacts");
46 const { preflightGlibc, detectHostGlibc, detectBinaryRequiredGlibc, _internal: glibc } = require("./preflight-glibc");
47 const compiledHosts = require("./compiled-hosts");
48 const pkg = require("../package.json");
49
50 const DEFAULT_TIMEOUT_MS = 300_000; // 5 minutes per attempt
51 const DEFAULT_STALL_MS = 30_000; // abort if no bytes for 30s
52 const OPTIONAL_TIMEOUT_MS = 15_000; // fail fast during optional npm postinstall
53 const OPTIONAL_STALL_MS = 5_000; // avoid long hangs when install can recover on first run
54 const MANIFEST_TIMEOUT_MS = 15_000; // small checksum probes must not wait on a binary budget
55 const MANIFEST_STALL_MS = 5_000;
56 const MAX_ATTEMPTS = 5;
57 const OPTIONAL_MAX_ATTEMPTS = 1; // runtime keeps the full retry budget on first launch
58 const BASE_BACKOFF_MS = 1_000;
59
60 const RETRYABLE_NET_CODES = new Set([
61 "ECONNRESET",
62 "ECONNREFUSED",
63 "EDOWNLOADTIMEOUT",
64 "ETIMEDOUT",
65 "EAI_AGAIN",
66 "ENOTFOUND",
67 "ENETUNREACH",
68 "EHOSTUNREACH",
69 "EPIPE",
70 "ECONNABORTED",
71 ]);
72
73 class NonRetryableError extends Error {
74 constructor(message) {
75 super(message);
76 this.name = "NonRetryableError";
77 this.nonRetryable = true;
78 }
79 }
80
81 class HttpStatusError extends Error {
82 constructor(status, url) {
83 super(`Request failed with status ${status}: ${redactUrl(url)}`);
84 this.name = "HttpStatusError";
85 this.status = status;
86 }
87 }
88
89 class DownloadTimeoutError extends Error {
90 constructor(message) {
91 super(message);
92 this.name = "DownloadTimeoutError";
93 this.code = "EDOWNLOADTIMEOUT";
94 }
95 }
96
97 function abortError(message) {
98 const err = new Error(message || "The operation was aborted");
99 err.name = "AbortError";
100 err.code = "ABORT_ERR";
101 err.nonRetryable = true;
102 return err;
103 }
104
105 function isAbortError(err) {
106 return Boolean(err) && (err.name === "AbortError" || err.code === "ABORT_ERR");
107 }
108
109 // Binary-version precedence must match run.js and verify-release-assets.js so
110 // install-time asset resolution agrees with runtime and release verification.
111 // `codewhaleBinaryVersion` lets a packaging-only npm release target a specific
112 // CodeWhale binary; legacy env vars and `deepseekBinaryVersion` stay supported
113 // for backward compatibility (#3769). `pkgObj`/`env` are injectable for tests.
114 function resolvePackageVersion(pkgObj = pkg, env = process.env) {
115 const configuredVersion =
116 env.CODEWHALE_VERSION ||
117 env.DEEPSEEK_TUI_VERSION ||
118 env.DEEPSEEK_VERSION ||
119 pkgObj.codewhaleBinaryVersion ||
120 pkgObj.deepseekBinaryVersion ||
121 pkgObj.version;
122 return String(configuredVersion).trim();
123 }
124
125 function resolveRepo(env = process.env) {
126 return (
127 env.CODEWHALE_GITHUB_REPO ||
128 env.DEEPSEEK_TUI_GITHUB_REPO ||
129 env.DEEPSEEK_GITHUB_REPO ||
130 "codewhale-hq/CodeWhale"
131 );
132 }
133
134 function isOptionalInstall(argv = process.argv.slice(2), env = process.env) {
135 return (
136 argv.includes("--optional") ||
137 env.CODEWHALE_OPTIONAL_INSTALL === "1" ||
138 env.DEEPSEEK_TUI_OPTIONAL_INSTALL === "1" ||
139 env.DEEPSEEK_OPTIONAL_INSTALL === "1"
140 );
141 }
142
143 function shouldForceDownload(env = process.env) {
144 return (
145 env.CODEWHALE_FORCE_DOWNLOAD === "1" ||
146 env.DEEPSEEK_TUI_FORCE_DOWNLOAD === "1" ||
147 env.DEEPSEEK_FORCE_DOWNLOAD === "1"
148 );
149 }
150
151 function shouldDisableInstall(env = process.env) {
152 return (
153 env.CODEWHALE_DISABLE_INSTALL === "1" ||
154 env.DEEPSEEK_TUI_DISABLE_INSTALL === "1" ||
155 env.DEEPSEEK_DISABLE_INSTALL === "1"
156 );
157 }
158
159 function isInstallContext(context) {
160 return context === "install";
161 }
162
163 function isPnpmUserAgent(env = process.env) {
164 return String(env.npm_config_user_agent || "").toLowerCase().includes("pnpm/");
165 }
166
167 function shouldSkipOptionalPostinstall(
168 context,
169 argv = process.argv.slice(2),
170 env = process.env,
171 ) {
172 return isInstallContext(context) && isOptionalInstall(argv, env) && isPnpmUserAgent(env);
173 }
174
175 // Optional install only relaxes npm postinstall behavior. Runtime downloads
176 // keep the normal retry/timeout budget so first-run recovery stays resilient.
177 function defaultTimeoutMs(context = "runtime", env = process.env) {
178 return isInstallContext(context) && isOptionalInstall(undefined, env)
179 ? OPTIONAL_TIMEOUT_MS
180 : DEFAULT_TIMEOUT_MS;
181 }
182
183 function defaultStallMs(context = "runtime", env = process.env) {
184 return isInstallContext(context) && isOptionalInstall(undefined, env)
185 ? OPTIONAL_STALL_MS
186 : DEFAULT_STALL_MS;
187 }
188
189 function maxAttempts(context = "runtime", env = process.env) {
190 return isInstallContext(context) && isOptionalInstall(undefined, env)
191 ? OPTIONAL_MAX_ATTEMPTS
192 : MAX_ATTEMPTS;
193 }
194
195 function binaryPaths() {
196 const { codewhale, codew } = detectBinaryNames();
197 const releaseDir = releaseBinaryDirectory();
198 return {
199 codewhale: {
200 asset: codewhale,
201 target: path.join(releaseDir, process.platform === "win32" ? "codewhale.exe" : "codewhale"),
202 },
203 codew: {
204 asset: codew,
205 target: path.join(releaseDir, process.platform === "win32" ? "codew.exe" : "codew"),
206 },
207 };
208 } // single binary — no tui asset (v0.9.5+)
209
210 // ────────────────────────────────────────────────────────────────────────────
211 // Logging / progress
212 // ────────────────────────────────────────────────────────────────────────────
213
214 function isQuietInstall(env = process.env) {
215 if (
216 env.CODEWHALE_QUIET_INSTALL === "1" ||
217 env.DEEPSEEK_TUI_QUIET_INSTALL === "1"
218 ) {
219 return true;
220 }
221 const level = (env.npm_config_loglevel || "").toLowerCase();
222 return level === "silent" || level === "error";
223 }
224
225 function logInfo(message) {
226 if (isQuietInstall()) {
227 return;
228 }
229 process.stderr.write(`codewhale: ${message}\n`);
230 }
231
232 function installFailureHint(error) {
233 const message = error && error.message ? String(error.message) : "";
234 const code = error && error.code ? String(error.code) : "";
235 const releaseBase =
236 process.env.CODEWHALE_RELEASE_BASE_URL ||
237 process.env.DEEPSEEK_TUI_RELEASE_BASE_URL ||
238 process.env.DEEPSEEK_RELEASE_BASE_URL;
239 const networkMarkers = [
240 "github.com",
241 "ENOTFOUND",
242 "EAI_AGAIN",
243 "ETIMEDOUT",
244 "ECONNRESET",
245 "ENETUNREACH",
246 "EHOSTUNREACH",
247 "EDOWNLOADTIMEOUT",
248 ];
249 const looksLikeNetworkDownloadFailure = networkMarkers.some(
250 (marker) => message.includes(marker) || code === marker,
251 );
252 if (!looksLikeNetworkDownloadFailure) {
253 return "";
254 }
255
256 if (releaseBase) {
257 return [
258 "codewhale install hint:",
259 ` CODEWHALE_RELEASE_BASE_URL resolves to ${redactUrl(releaseBase)}`,
260 " Verify that this directory contains codewhale-artifacts-sha256.txt",
261 " plus the codewhale/codew binary assets for your platform (single binary).",
262 ].join("\n");
263 }
264
265 return [
266 "codewhale install hint:",
267 " The npm package downloads prebuilt binaries from GitHub Releases.",
268 " On Linux x64 it also probes the CNB first-party checksum manifest and uses",
269 " the first source whose HTTP response and manifest validate.",
270 " If both are unavailable, mirror the release assets and set:",
271 " CODEWHALE_RELEASE_BASE_URL=https://<mirror>/<release-asset-directory>/",
272 " or CODEWHALE_USE_CNB_MIRROR=1 on Linux x64.",
273 " The directory must contain codewhale-artifacts-sha256.txt and the platform binaries.",
274 " See https://github.com/codewhale-hq/CodeWhale/blob/main/docs/INSTALL.md#npm-binary-download-times-out",
275 ].join("\n");
276 }
277
278 function envInt(name, fallback, env = process.env) {
279 const raw = env[name];
280 if (!raw) {
281 return fallback;
282 }
283 const parsed = Number.parseInt(String(raw).trim(), 10);
284 if (!Number.isFinite(parsed) || parsed <= 0) {
285 return fallback;
286 }
287 return parsed;
288 }
289
290 function downloadTimeoutMs(context = "runtime", env = process.env) {
291 return envInt(
292 "CODEWHALE_DOWNLOAD_TIMEOUT_MS",
293 envInt(
294 "DEEPSEEK_TUI_DOWNLOAD_TIMEOUT_MS",
295 envInt("DEEPSEEK_DOWNLOAD_TIMEOUT_MS", defaultTimeoutMs(context, env), env),
296 env,
297 ),
298 env,
299 );
300 }
301
302 function downloadStallMs(context = "runtime", env = process.env) {
303 return envInt(
304 "CODEWHALE_DOWNLOAD_STALL_MS",
305 envInt(
306 "DEEPSEEK_TUI_DOWNLOAD_STALL_MS",
307 envInt("DEEPSEEK_DOWNLOAD_STALL_MS", defaultStallMs(context, env), env),
308 env,
309 ),
310 env,
311 );
312 }
313
314 function formatMb(bytes) {
315 return (bytes / (1024 * 1024)).toFixed(0);
316 }
317
318 function createProgressReporter(assetName, totalBytes) {
319 if (isQuietInstall()) {
320 return { onChunk: () => {}, finish: () => {} };
321 }
322 const isTty = !!process.stderr.isTTY;
323 const interactive = isTty;
324 const tickBytes = interactive ? 1 * 1024 * 1024 : 5 * 1024 * 1024;
325 const tickMs = 2_000;
326
327 let received = 0;
328 let lastBytesPrinted = 0;
329 let lastTimePrinted = 0;
330 let everPrinted = false;
331
332 const render = (final) => {
333 if (totalBytes && totalBytes > 0) {
334 const pct = Math.min(100, Math.round((received / totalBytes) * 100));
335 const line = `codewhale: downloading ${assetName}: ${formatMb(received)} / ${formatMb(totalBytes)} MB (${pct}%)`;
336 if (interactive) {
337 process.stderr.write(`${line}\r`);
338 } else {
339 process.stderr.write(`${line}\n`);
340 }
341 } else {
342 const line = `codewhale: downloading ${assetName}: ${formatMb(received)} MB downloaded`;
343 if (interactive) {
344 process.stderr.write(`${line}\r`);
345 } else {
346 process.stderr.write(`${line}\n`);
347 }
348 }
349 everPrinted = true;
350 lastBytesPrinted = received;
351 lastTimePrinted = Date.now();
352 };
353
354 return {
355 onChunk(chunkLen) {
356 received += chunkLen;
357 const now = Date.now();
358 if (
359 received - lastBytesPrinted >= tickBytes ||
360 (interactive && now - lastTimePrinted >= tickMs)
361 ) {
362 render(false);
363 }
364 },
365 finish() {
366 // Final line — always render once.
367 render(true);
368 if (interactive && everPrinted) {
369 // Move past the carriage-return line and emit a "done" footer.
370 process.stderr.write("\n");
371 }
372 process.stderr.write(`codewhale: ${assetName} ... done.\n`);
373 },
374 };
375 }
376
377 // ────────────────────────────────────────────────────────────────────────────
378 // Proxy support (HTTPS_PROXY / HTTP_PROXY / NO_PROXY) — pure Node, CONNECT
379 // tunnel + TLS upgrade for HTTPS targets.
380 // ────────────────────────────────────────────────────────────────────────────
381
382 function getProxyUrl(targetUrl) {
383 const isHttps = targetUrl.protocol === "https:";
384 const candidates = isHttps
385 ? ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"]
386 : ["HTTP_PROXY", "http_proxy"];
387 for (const name of candidates) {
388 const raw = process.env[name];
389 if (raw && String(raw).trim() !== "") {
390 return String(raw).trim();
391 }
392 }
393 return null;
394 }
395
396 function shouldBypassProxy(host) {
397 const raw = process.env.NO_PROXY || process.env.no_proxy;
398 if (!raw) {
399 return false;
400 }
401 const lower = String(host).toLowerCase();
402 for (const part of String(raw).split(",")) {
403 const entry = part.trim().toLowerCase();
404 if (!entry) {
405 continue;
406 }
407 if (entry === "*") {
408 return true;
409 }
410 // Strip leading dot and any explicit port.
411 const stripped = entry.replace(/^\./, "").replace(/:.*$/, "");
412 if (!stripped) {
413 continue;
414 }
415 if (lower === stripped || lower.endsWith(`.${stripped}`)) {
416 return true;
417 }
418 }
419 return false;
420 }
421
422 function parseProxy(proxyStr) {
423 // Accept "http://user:pass@host:port" and bare "host:port".
424 const normalized = /^[a-z][a-z0-9+\-.]*:\/\//i.test(proxyStr)
425 ? proxyStr
426 : `http://${proxyStr}`;
427 const u = new URL(normalized);
428 const port = u.port
429 ? Number.parseInt(u.port, 10)
430 : u.protocol === "https:"
431 ? 443
432 : 80;
433 let auth = null;
434 if (u.username) {
435 const user = decodeURIComponent(u.username);
436 const pass = u.password ? decodeURIComponent(u.password) : "";
437 auth = Buffer.from(`${user}:${pass}`).toString("base64");
438 }
439 return {
440 protocol: u.protocol,
441 host: u.hostname,
442 port,
443 auth,
444 raw: proxyStr,
445 };
446 }
447
448 function connectThroughProxy(proxy, targetHost, targetPort, timeoutMs) {
449 return new Promise((resolve, reject) => {
450 const socket = net.connect({ host: proxy.host, port: proxy.port });
451 let settled = false;
452 const fail = (err) => {
453 if (settled) return;
454 settled = true;
455 try {
456 socket.destroy();
457 } catch {
458 // ignore
459 }
460 reject(err);
461 };
462
463 const timer = timeoutMs > 0
464 ? setTimeout(() => fail(new DownloadTimeoutError(
465 `proxy CONNECT to ${proxy.host}:${proxy.port} timed out after ${timeoutMs} ms`,
466 )), timeoutMs)
467 : null;
468
469 socket.once("error", (err) => {
470 if (timer) clearTimeout(timer);
471 // Surface proxy host so the user can fix it.
472 const wrapped = new Error(
473 `proxy connection failed (${proxy.host}:${proxy.port}): ${err.message}`,
474 );
475 wrapped.code = err.code;
476 fail(wrapped);
477 });
478
479 socket.once("connect", () => {
480 const lines = [
481 `CONNECT ${targetHost}:${targetPort} HTTP/1.1`,
482 `Host: ${targetHost}:${targetPort}`,
483 "User-Agent: codewhale-installer",
484 "Proxy-Connection: keep-alive",
485 ];
486 if (proxy.auth) {
487 lines.push(`Proxy-Authorization: Basic ${proxy.auth}`);
488 }
489 const req = `${lines.join("\r\n")}\r\n\r\n`;
490
491 let buf = Buffer.alloc(0);
492 const onData = (chunk) => {
493 buf = Buffer.concat([buf, chunk]);
494 const idx = buf.indexOf("\r\n\r\n");
495 if (idx === -1) {
496 if (buf.length > 16 * 1024) {
497 socket.removeListener("data", onData);
498 fail(new Error(
499 `proxy ${proxy.host}:${proxy.port} returned an oversized response header`,
500 ));
501 }
502 return;
503 }
504 socket.removeListener("data", onData);
505 const head = buf.slice(0, idx).toString("utf8");
506 const firstLine = head.split(/\r?\n/, 1)[0] || "";
507 const m = firstLine.match(/^HTTP\/\d\.\d\s+(\d{3})/);
508 if (!m) {
509 fail(new Error(`proxy ${proxy.host}:${proxy.port} returned invalid CONNECT reply: ${firstLine}`));
510 return;
511 }
512 const code = Number.parseInt(m[1], 10);
513 if (code !== 200) {
514 fail(new Error(
515 `proxy ${proxy.host}:${proxy.port} refused CONNECT to ${targetHost}:${targetPort}: HTTP ${code}`,
516 ));
517 return;
518 }
519 if (timer) clearTimeout(timer);
520 if (settled) return;
521 settled = true;
522 // Any bytes past the header belong to the tunneled stream — but in
523 // practice CONNECT 200 has no body; if it did, we'd lose those bytes
524 // here. Keep it simple: trust well-behaved proxies.
525 resolve(socket);
526 };
527 socket.on("data", onData);
528 socket.write(req, "utf8");
529 });
530 });
531 }
532
533 // ────────────────────────────────────────────────────────────────────────────
534 // HTTP request with timeout, stall detection, and proxy support.
535 // ────────────────────────────────────────────────────────────────────────────
536
537 function httpRequest(rawUrl, opts = {}) {
538 const context =
539 opts.context === undefined || opts.context === null ? "runtime" : opts.context;
540 const totalTimeoutMs =
541 opts.totalTimeoutMs === undefined || opts.totalTimeoutMs === null
542 ? downloadTimeoutMs(context)
543 : opts.totalTimeoutMs;
544 const stallMs =
545 opts.stallMs === undefined || opts.stallMs === null
546 ? downloadStallMs(context)
547 : opts.stallMs;
548
549 return new Promise((resolve, reject) => {
550 let url;
551 try {
552 url = new URL(rawUrl);
553 } catch (err) {
554 reject(new NonRetryableError(`Invalid URL: ${redactUrl(rawUrl)} (${err.message})`));
555 return;
556 }
557 if (url.protocol !== "https:" && url.protocol !== "http:") {
558 reject(new NonRetryableError(`Unsupported protocol: ${url.protocol}`));
559 return;
560 }
561
562 const proxyStr = !shouldBypassProxy(url.hostname) ? getProxyUrl(url) : null;
563 const isHttps = url.protocol === "https:";
564 const port = url.port
565 ? Number.parseInt(url.port, 10)
566 : isHttps
567 ? 443
568 : 80;
569
570 let totalTimer = null;
571 let stallTimer = null;
572 let settled = false;
573 let handedOff = false;
574 let req = null;
575 let res = null;
576 const signal = opts.signal;
577 let onAbort = null;
578
579 const cleanup = () => {
580 if (totalTimer) {
581 clearTimeout(totalTimer);
582 totalTimer = null;
583 }
584 if (stallTimer) {
585 clearTimeout(stallTimer);
586 stallTimer = null;
587 }
588 if (signal && onAbort) {
589 signal.removeEventListener("abort", onAbort);
590 onAbort = null;
591 }
592 };
593
594 const fail = (err) => {
595 if (settled) {
596 // The stall, total, and abort budgets outlive the handoff: once the
597 // caller owns the body, end it with the error so the caller's own
598 // `error` handler rejects instead of waiting on a silent socket.
599 if (handedOff) {
600 cleanup();
601 try {
602 if (res && !res.destroyed) res.destroy(err);
603 } catch {
604 // ignore
605 }
606 }
607 return;
608 }
609 settled = true;
610 cleanup();
611 try {
612 if (req && !req.destroyed) req.destroy();
613 } catch {
614 // ignore
615 }
616 try {
617 if (res && !res.destroyed) res.destroy();
618 } catch {
619 // ignore
620 }
621 reject(err);
622 };
623
624 // Hand the live response stream to the caller. The timers stay armed
625 // until the body ends or closes (see `fail`).
626 const handOff = (response) => {
627 settled = true;
628 handedOff = true;
629 response.on("close", () => cleanup());
630 resolve({ redirect: null, response });
631 };
632
633 if (signal) {
634 if (signal.aborted) {
635 reject(abortError());
636 return;
637 }
638 onAbort = function () {
639 fail(abortError());
640 };
641 signal.addEventListener("abort", onAbort);
642 }
643
644 if (totalTimeoutMs > 0) {
645 totalTimer = setTimeout(() => {
646 fail(new DownloadTimeoutError(
647 `download exceeded total timeout of ${totalTimeoutMs} ms ` +
648 `(set CODEWHALE_DOWNLOAD_TIMEOUT_MS to raise it; current stall budget is ${stallMs} ms)`,
649 ));
650 }, totalTimeoutMs);
651 }
652
653 const armStallTimer = () => {
654 if (stallMs <= 0) return;
655 if (stallTimer) clearTimeout(stallTimer);
656 stallTimer = setTimeout(() => {
657 // A body the caller has paused (a slow disk pushing back through
658 // `pipe`) is not a stalled network. The total budget still bounds it.
659 if (handedOff && res && res.readableFlowing === false) {
660 armStallTimer();
661 return;
662 }
663 fail(new DownloadTimeoutError(
664 `download stalled — no bytes received for ${stallMs} ms ` +
665 `(set CODEWHALE_DOWNLOAD_STALL_MS to raise it; total budget is ${totalTimeoutMs} ms)`,
666 ));
667 }, stallMs);
668 };
669
670 const launch = (socket) => {
671 const reqOptions = {
672 method: "GET",
673 host: url.hostname,
674 port,
675 path: `${url.pathname}${url.search || ""}`,
676 headers: {
677 Host: url.host,
678 "User-Agent": "codewhale-installer",
679 Accept: "*/*",
680 Connection: "close",
681 },
682 };
683 if (socket) {
684 reqOptions.createConnection = () => socket;
685 if (isHttps) {
686 // Wrap raw TCP socket from CONNECT in TLS.
687 const tlsSocket = tls.connect({
688 socket,
689 servername: url.hostname,
690 ALPNProtocols: ["http/1.1"],
691 });
692 tlsSocket.once("error", (err) => fail(err));
693 reqOptions.createConnection = () => tlsSocket;
694 }
695 }
696 const client = isHttps ? https : http;
697 try {
698 req = client.request(reqOptions, (response) => {
699 res = response;
700 response.pause();
701 armStallTimer();
702 response.on("data", () => {
703 armStallTimer();
704 });
705 response.on("end", () => {
706 cleanup();
707 });
708 response.on("error", (err) => fail(err));
709
710 const status = response.statusCode || 0;
711 if (status >= 300 && status < 400 && response.headers.location) {
712 cleanup();
713 settled = true;
714 response.resume();
715 resolve({ redirect: response.headers.location, response: null });
716 return;
717 }
718 if (status < 200 || status >= 300) {
719 const err = new HttpStatusError(status, rawUrl);
720 // 4xx: non-retryable; 5xx: retryable.
721 if (status >= 400 && status < 500) {
722 err.nonRetryable = true;
723 }
724 fail(err);
725 return;
726 }
727 if (settled) return;
728 handOff(response);
729 });
730 req.once("error", (err) => fail(err));
731 req.once("socket", (s) => {
732 // Belt-and-suspenders: surface socket-level errors quickly.
733 s.once("error", (err) => fail(err));
734 });
735 req.end();
736 } catch (err) {
737 fail(err);
738 }
739 };
740
741 if (proxyStr) {
742 let proxy;
743 try {
744 proxy = parseProxy(proxyStr);
745 } catch (err) {
746 fail(new NonRetryableError(
747 `Invalid proxy URL "${proxyStr}": ${err.message}`,
748 ));
749 return;
750 }
751 if (!isHttps) {
752 // Plain HTTP through proxy — send absolute URI, no CONNECT.
753 const client = http;
754 try {
755 req = client.request(
756 {
757 host: proxy.host,
758 port: proxy.port,
759 method: "GET",
760 path: rawUrl,
761 headers: {
762 Host: url.host,
763 "User-Agent": "codewhale-installer",
764 Accept: "*/*",
765 Connection: "close",
766 ...(proxy.auth ? { "Proxy-Authorization": `Basic ${proxy.auth}` } : {}),
767 },
768 },
769 (response) => {
770 res = response;
771 response.pause();
772 armStallTimer();
773 response.on("data", () => armStallTimer());
774 response.on("end", () => cleanup());
775 response.on("error", (err) => fail(err));
776 const status = response.statusCode || 0;
777 if (status >= 300 && status < 400 && response.headers.location) {
778 cleanup();
779 settled = true;
780 response.resume();
781 resolve({ redirect: response.headers.location, response: null });
782 return;
783 }
784 if (status < 200 || status >= 300) {
785 const err = new HttpStatusError(status, rawUrl);
786 if (status >= 400 && status < 500) err.nonRetryable = true;
787 fail(err);
788 return;
789 }
790 if (settled) return;
791 handOff(response);
792 },
793 );
794 req.once("error", (err) => fail(err));
795 req.end();
796 } catch (err) {
797 fail(err);
798 }
799 return;
800 }
801
802 // HTTPS through proxy: CONNECT tunnel + TLS upgrade.
803 connectThroughProxy(proxy, url.hostname, port, Math.max(stallMs, 5_000))
804 .then((tcpSocket) => {
805 if (settled) {
806 try { tcpSocket.destroy(); } catch { /* ignore */ }
807 return;
808 }
809 const tlsSocket = tls.connect({
810 socket: tcpSocket,
811 servername: url.hostname,
812 ALPNProtocols: ["http/1.1"],
813 });
814 tlsSocket.once("error", (err) => fail(err));
815 tlsSocket.once("secureConnect", () => {
816 if (settled) {
817 try { tlsSocket.destroy(); } catch { /* ignore */ }
818 return;
819 }
820 const reqOptions = {
821 method: "GET",
822 createConnection: () => tlsSocket,
823 path: `${url.pathname}${url.search || ""}`,
824 headers: {
825 Host: url.host,
826 "User-Agent": "codewhale-installer",
827 Accept: "*/*",
828 Connection: "close",
829 },
830 };
831 try {
832 req = https.request(reqOptions, (response) => {
833 res = response;
834 response.pause();
835 armStallTimer();
836 response.on("data", () => armStallTimer());
837 response.on("end", () => cleanup());
838 response.on("error", (err) => fail(err));
839 const status = response.statusCode || 0;
840 if (status >= 300 && status < 400 && response.headers.location) {
841 cleanup();
842 settled = true;
843 response.resume();
844 resolve({ redirect: response.headers.location, response: null });
845 return;
846 }
847 if (status < 200 || status >= 300) {
848 const err = new HttpStatusError(status, rawUrl);
849 if (status >= 400 && status < 500) err.nonRetryable = true;
850 fail(err);
851 return;
852 }
853 if (settled) return;
854 handOff(response);
855 });
856 req.once("error", (err) => fail(err));
857 req.end();
858 } catch (err) {
859 fail(err);
860 }
861 });
862 })
863 .catch((err) => fail(err));
864 return;
865 }
866
867 // No proxy — direct connection.
868 launch(null);
869 });
870 }
871
872 // ────────────────────────────────────────────────────────────────────────────
873 // Retry wrapper
874 // ────────────────────────────────────────────────────────────────────────────
875
876 function isRetryable(err) {
877 if (!err) return false;
878 if (isAbortError(err)) return false;
879 if (err.nonRetryable) return false;
880 if (err.retryable === true) return true;
881 if (err instanceof NonRetryableError) return false;
882 if (err instanceof DownloadTimeoutError) return true;
883 // withRetry() rethrows a plain Error while preserving name/status, so wrapped
884 // HTTP 5xx failures still classify as retryable during optional postinstall.
885 if (
886 (err instanceof HttpStatusError || err.name === "HttpStatusError") &&
887 typeof err.status === "number"
888 ) {
889 return err.status >= 500;
890 }
891 if (err.code && RETRYABLE_NET_CODES.has(err.code)) return true;
892 // Network-flavored messages we may see without a code.
893 const msg = String(err.message || "").toLowerCase();
894 if (msg.includes("network") && msg.includes("unreachable")) return true;
895 if (msg.includes("socket hang up")) return true;
896 if (msg.includes("aborted")) return true;
897 return false;
898 }
899
900 function backoffDelay(attempt) {
901 // attempt is 1-indexed; first retry waits ~1s.
902 const base = BASE_BACKOFF_MS * 2 ** (attempt - 1);
903 const jitter = (Math.random() * 0.4 - 0.2) * base; // ±20%
904 return Math.max(0, Math.round(base + jitter));
905 }
906
907 function sleep(ms) {
908 return new Promise((resolve) => setTimeout(resolve, ms));
909 }
910
911 function sleepWithSignal(ms, signal) {
912 if (!signal) {
913 return sleep(ms);
914 }
915 if (signal.aborted) {
916 return Promise.reject(abortError());
917 }
918 return new Promise((resolve, reject) => {
919 let timer = null;
920 const cleanup = () => {
921 if (timer) {
922 clearTimeout(timer);
923 timer = null;
924 }
925 signal.removeEventListener("abort", onAbort);
926 };
927 const onAbort = () => {
928 cleanup();
929 reject(abortError());
930 };
931 timer = setTimeout(() => {
932 cleanup();
933 resolve();
934 }, ms);
935 signal.addEventListener("abort", onAbort, { once: true });
936 });
937 }
938
939 async function withRetry(label, fn, context, signal) {
940 const resolvedContext =
941 context === undefined || context === null ? "runtime" : context;
942 let lastErr;
943 const attemptLimit = maxAttempts(resolvedContext);
944 for (let attempt = 1; attempt <= attemptLimit; attempt++) {
945 if (signal && signal.aborted) {
946 throw abortError();
947 }
948 try {
949 return await fn(attempt);
950 } catch (err) {
951 lastErr = err;
952 if (isAbortError(err) || !isRetryable(err) || attempt === attemptLimit) {
953 break;
954 }
955 const wait = backoffDelay(attempt);
956 logInfo(
957 `${label} failed (attempt ${attempt}/${attemptLimit}): ${err.message}; retrying in ${wait} ms`,
958 );
959 if (attempt === 1) {
960 const hint = installFailureHint(err);
961 if (hint) {
962 process.stderr.write(`${hint}\n`);
963 }
964 }
965 await sleepWithSignal(wait, signal);
966 if (signal && signal.aborted) {
967 throw abortError();
968 }
969 }
970 }
971 const msg = lastErr && lastErr.message ? lastErr.message : String(lastErr);
972 const wrapped = new Error(
973 `${label} failed after ${attemptLimit} attempt(s): ${msg}`,
974 );
975 // Preserve retry classification metadata because the install entrypoint uses
976 // the wrapped error to decide whether optional postinstall may ignore it.
977 if (lastErr && lastErr.code) {
978 wrapped.code = lastErr.code;
979 }
980 if (lastErr && lastErr.name) {
981 wrapped.name = lastErr.name;
982 }
983 if (lastErr && typeof lastErr.status === "number") {
984 wrapped.status = lastErr.status;
985 }
986 if (lastErr && lastErr.nonRetryable) {
987 wrapped.nonRetryable = true;
988 }
989 if (lastErr && lastErr.stack) {
990 wrapped.cause = lastErr;
991 }
992 throw wrapped;
993 }
994
995 // ────────────────────────────────────────────────────────────────────────────
996 // Public download primitives (now retry + progress aware)
997 // ────────────────────────────────────────────────────────────────────────────
998
999 async function followRedirects(url, opts = {}) {
1000 const maxRedirects = 10;
1001 let current = url;
1002 for (let hop = 0; hop < maxRedirects; hop++) {
1003 try {
1004 validateReleaseUrl(current, {
1005 env: opts.env,
1006 allowLoopbackHttp: opts.allowLoopbackHttp,
1007 });
1008 } catch (err) {
1009 throw new NonRetryableError(err.message);
1010 }
1011 const result = await httpRequest(current, opts);
1012 if (result.redirect) {
1013 try {
1014 current = new URL(result.redirect, current).toString();
1015 } catch (err) {
1016 throw new NonRetryableError(
1017 `Invalid redirect URL from ${redactUrl(current)}: ${err.message}`,
1018 );
1019 }
1020 continue;
1021 }
1022 return result;
1023 }
1024 throw new NonRetryableError(`too many redirects starting at ${redactUrl(url)}`);
1025 }
1026
1027 function streamToFile(response, destination, progress, signal) {
1028 return new Promise((resolve, reject) => {
1029 const sink = createWriteStream(destination);
1030 let done = false;
1031 const onAbort = () => {
1032 try {
1033 response.destroy();
1034 } catch {
1035 // ignore
1036 }
1037 finish(abortError());
1038 };
1039 const finish = (err) => {
1040 if (done) return;
1041 done = true;
1042 if (signal) {
1043 signal.removeEventListener("abort", onAbort);
1044 }
1045 if (err) {
1046 sink.destroy();
1047 reject(err);
1048 } else {
1049 resolve();
1050 }
1051 };
1052 response.on("data", (chunk) => {
1053 if (progress) progress.onChunk(chunk.length);
1054 });
1055 response.on("error", (err) => finish(err));
1056 sink.on("error", (err) => finish(err));
1057 sink.on("finish", () => finish(null));
1058 if (signal) {
1059 if (signal.aborted) {
1060 onAbort();
1061 return;
1062 }
1063 signal.addEventListener("abort", onAbort, { once: true });
1064 }
1065 response.pipe(sink);
1066 });
1067 }
1068
1069 async function download(url, destination, options = {}) {
1070 await mkdir(path.dirname(destination), { recursive: true });
1071 const assetName = options.assetName || path.basename(destination);
1072 const context =
1073 options.context === undefined || options.context === null ? "runtime" : options.context;
1074 const attemptLimit = maxAttempts(context);
1075 await withRetry(`download ${assetName}`, async (attempt) => {
1076 const result = await followRedirects(url, {
1077 context,
1078 env: options.env,
1079 allowLoopbackHttp: options.allowLoopbackHttp,
1080 totalTimeoutMs: downloadTimeoutMs(context),
1081 stallMs: downloadStallMs(context),
1082 signal: options.signal,
1083 });
1084 const response = result.response;
1085 const lenHeader = response.headers["content-length"];
1086 const total = lenHeader ? Number.parseInt(lenHeader, 10) : 0;
1087 const progress = createProgressReporter(assetName, Number.isFinite(total) ? total : 0);
1088 if (attempt > 1) {
1089 logInfo(`retry attempt ${attempt}/${attemptLimit} for ${assetName}`);
1090 }
1091 try {
1092 await streamToFile(response, destination, progress, options.signal);
1093 } catch (err) {
1094 // Ensure we don't leave a partial file confusing future attempts.
1095 try {
1096 await unlink(destination);
1097 } catch {
1098 // ignore
1099 }
1100 throw err;
1101 }
1102 progress.finish();
1103 }, context, options.signal);
1104 }
1105
1106 async function downloadText(url, options = {}) {
1107 const context =
1108 options.context === undefined || options.context === null ? "runtime" : options.context;
1109 const totalTimeoutMs =
1110 options.totalTimeoutMs === undefined || options.totalTimeoutMs === null
1111 ? downloadTimeoutMs(context)
1112 : options.totalTimeoutMs;
1113 const stallMs =
1114 options.stallMs === undefined || options.stallMs === null
1115 ? downloadStallMs(context)
1116 : options.stallMs;
1117 return withRetry(`fetch ${redactUrl(url)}`, async () => {
1118 const result = await followRedirects(url, {
1119 context,
1120 env: options.env,
1121 allowLoopbackHttp: options.allowLoopbackHttp,
1122 totalTimeoutMs,
1123 stallMs,
1124 signal: options.signal,
1125 });
1126 const response = result.response;
1127 response.setEncoding("utf8");
1128 // NOTE: do NOT use `for await (const chunk of response)` here.
1129 // `httpRequest` attaches a `data` listener on the response to re-arm
1130 // the stall timer, which puts the stream in flowing mode. The async
1131 // iterator expects paused mode and will silently miss every chunk —
1132 // this manifested as an empty checksum manifest in the npm wrapper
1133 // smoke test ("Checksum manifest is missing <asset>"). Subscribing
1134 // to `data` events directly stacks alongside the stall listener and
1135 // both fire per chunk, so we collect the body correctly without
1136 // disturbing the stall detection.
1137 return new Promise((resolve, reject) => {
1138 const chunks = [];
1139 let settled = false;
1140 const signal = options.signal;
1141 const cleanup = () => {
1142 if (signal) {
1143 signal.removeEventListener("abort", onAbort);
1144 }
1145 };
1146 const finish = (error, value) => {
1147 if (settled) return;
1148 settled = true;
1149 cleanup();
1150 if (error) {
1151 reject(error);
1152 } else {
1153 resolve(value);
1154 }
1155 };
1156 const onAbort = () => {
1157 try {
1158 response.destroy();
1159 } catch {
1160 // ignore
1161 }
1162 finish(abortError());
1163 };
1164 response.on("data", (chunk) => {
1165 chunks.push(chunk);
1166 });
1167 response.on("end", () => {
1168 finish(null, chunks.join(""));
1169 });
1170 response.on("error", (error) => finish(error));
1171 if (signal) {
1172 if (signal.aborted) {
1173 onAbort();
1174 return;
1175 }
1176 signal.addEventListener("abort", onAbort, { once: true });
1177 }
1178 response.resume();
1179 });
1180 }, context, options.signal);
1181 }
1182
1183 async function readLocalVersion(file) {
1184 return readFile(file, "utf8").catch(() => "");
1185 }
1186
1187 async function fileExists(file) {
1188 try {
1189 const result = await stat(file);
1190 return result.isFile();
1191 } catch {
1192 return false;
1193 }
1194 }
1195
1196 function parseChecksumManifest(text) {
1197 const checksums = new Map();
1198 for (const line of text.split(/\r?\n/)) {
1199 const trimmed = line.trim();
1200 if (!trimmed) {
1201 continue;
1202 }
1203 const match = trimmed.match(/^([a-fA-F0-9]{64})\s+\*?(.+)$/);
1204 if (!match) {
1205 throw new NonRetryableError(`Invalid checksum manifest line: ${trimmed}`);
1206 }
1207 checksums.set(match[2], match[1].toLowerCase());
1208 }
1209 return checksums;
1210 }
1211
1212 async function sha256File(filePath) {
1213 const content = await readFile(filePath);
1214 return crypto.createHash("sha256").update(content).digest("hex");
1215 }
1216
1217 async function verifyChecksum(filePath, assetName, checksums, sourceLabel) {
1218 const expected = checksums.get(assetName);
1219 if (!expected) {
1220 const from = sourceLabel ? ` from ${sourceLabel}` : "";
1221 throw new NonRetryableError(`Checksum manifest is missing ${assetName}${from}`);
1222 }
1223 const actual = await sha256File(filePath);
1224 if (actual !== expected) {
1225 // Bytes are corrupted; another fetch is unlikely to help without a fix
1226 // upstream. Mark non-retryable. Never mix a locked source's bytes with
1227 // another source's manifest.
1228 const from = sourceLabel ? ` from ${sourceLabel}` : "";
1229 throw new NonRetryableError(
1230 `Checksum mismatch for ${assetName}${from}: expected ${expected}, got ${actual}`,
1231 );
1232 }
1233 }
1234
1235 async function checksumMatches(filePath, assetName, checksums) {
1236 const expected = checksums.get(assetName);
1237 if (!expected) {
1238 throw new NonRetryableError(`Checksum manifest is missing ${assetName}`);
1239 }
1240 const actual = await sha256File(filePath);
1241 return actual === expected;
1242 }
1243
1244 function formatSourceReceipt(source, version) {
1245 return [
1246 `source=${source.id}`,
1247 `label=${source.label}`,
1248 `base=${source.baseUrl}`,
1249 `version=${version}`,
1250 "",
1251 ].join("\n");
1252 }
1253
1254 async function writeSourceReceipt(targetPath, source, version) {
1255 await writeFile(`${targetPath}.source`, formatSourceReceipt(source, version), "utf8");
1256 }
1257
1258 function assertManifestHasAssets(checksums, requiredAssets, label) {
1259 const missing = [];
1260 for (let i = 0; i < requiredAssets.length; i += 1) {
1261 const asset = requiredAssets[i];
1262 if (!checksums.has(asset)) {
1263 missing.push(asset);
1264 }
1265 }
1266 if (missing.length > 0) {
1267 throw new NonRetryableError(
1268 `${label} checksum manifest is missing ${missing.join(", ")}`,
1269 );
1270 }
1271 }
1272
1273 async function fetchChecksumManifest(url, options) {
1274 const fetchText = options.fetchText || downloadText;
1275 const text = await fetchText(url, {
1276 context: options.context,
1277 env: options.env,
1278 signal: options.signal,
1279 totalTimeoutMs:
1280 options.totalTimeoutMs === undefined || options.totalTimeoutMs === null
1281 ? MANIFEST_TIMEOUT_MS
1282 : options.totalTimeoutMs,
1283 stallMs:
1284 options.stallMs === undefined || options.stallMs === null
1285 ? MANIFEST_STALL_MS
1286 : options.stallMs,
1287 });
1288 return parseChecksumManifest(text);
1289 }
1290
1291 async function loadSourceManifest(source, options) {
1292 const url = releaseAssetUrlFromBase(CHECKSUM_MANIFEST, source.baseUrl);
1293 const checksums = await fetchChecksumManifest(url, options);
1294 assertManifestHasAssets(checksums, options.requiredAssets || [], source.label);
1295 return {
1296 id: source.id,
1297 label: source.label,
1298 baseUrl: source.baseUrl,
1299 checksums,
1300 };
1301 }
1302
1303 function aggregateSourceErrors(options, failures) {
1304 const parts = [];
1305 let allNonRetryable = failures.length > 0;
1306 let anyRetryable = false;
1307 for (let i = 0; i < failures.length; i += 1) {
1308 const failure = failures[i];
1309 const message =
1310 failure.error && failure.error.message
1311 ? failure.error.message
1312 : String(failure.error);
1313 parts.push(`${failure.source.label}: ${message}`);
1314 if (
1315 !(
1316 failure.error &&
1317 (failure.error.nonRetryable || failure.error instanceof NonRetryableError)
1318 )
1319 ) {
1320 allNonRetryable = false;
1321 }
1322 if (isRetryable(failure.error)) {
1323 anyRetryable = true;
1324 }
1325 }
1326 const err = new Error(
1327 `No usable first-party release source for v${options.version}. ${parts.join("; ")}`,
1328 );
1329 if (allNonRetryable) {
1330 err.nonRetryable = true;
1331 } else if (anyRetryable) {
1332 err.retryable = true;
1333 }
1334 return err;
1335 }
1336
1337 async function raceFirstPartyManifests(sources, options) {
1338 logInfo(
1339 `probing ${sources.map((source) => source.label).join(" and ")} checksum manifests`,
1340 );
1341 const controllers = sources.map(() => new AbortController());
1342
1343 return new Promise((resolve, reject) => {
1344 let remaining = sources.length;
1345 const failures = [];
1346 let settled = false;
1347
1348 const finishSuccess = (index, selected) => {
1349 if (settled) {
1350 return;
1351 }
1352 settled = true;
1353 for (let i = 0; i < controllers.length; i += 1) {
1354 if (i !== index) {
1355 try {
1356 controllers[i].abort();
1357 } catch {
1358 // ignore
1359 }
1360 }
1361 }
1362 logInfo(`selected ${selected.label} for v${options.version}`);
1363 resolve(selected);
1364 };
1365
1366 const finishFailure = (source, error) => {
1367 if (settled) {
1368 return;
1369 }
1370 if (isAbortError(error)) {
1371 remaining -= 1;
1372 if (remaining === 0) {
1373 settled = true;
1374 reject(aggregateSourceErrors(options, failures));
1375 }
1376 return;
1377 }
1378 failures.push({ source, error });
1379 remaining -= 1;
1380 if (remaining === 0) {
1381 settled = true;
1382 reject(aggregateSourceErrors(options, failures));
1383 }
1384 };
1385
1386 for (let i = 0; i < sources.length; i += 1) {
1387 const source = sources[i];
1388 loadSourceManifest(source, {
1389 context: options.context,
1390 env: options.env,
1391 fetchText: options.fetchText,
1392 requiredAssets: options.requiredAssets,
1393 signal: controllers[i].signal,
1394 }).then(
1395 (selected) => finishSuccess(i, selected),
1396 (error) => finishFailure(source, error),
1397 );
1398 }
1399 });
1400 }
1401
1402 async function selectReleaseSource(options) {
1403 const version = options.version;
1404 const repo = options.repo || "codewhale-hq/CodeWhale";
1405 const env = options.env || process.env;
1406 const platform =
1407 options.platform === undefined || options.platform === null
1408 ? os.platform()
1409 : options.platform;
1410 const arch =
1411 options.arch === undefined || options.arch === null ? os.arch() : options.arch;
1412 const requiredAssets = options.requiredAssets || [];
1413 const context =
1414 options.context === undefined || options.context === null
1415 ? "runtime"
1416 : options.context;
1417 const fetchText = options.fetchText;
1418 const override = explicitReleaseBase(env);
1419 if (override) {
1420 logInfo(`using explicit release base for v${version}`);
1421 return loadSourceManifest(
1422 {
1423 id: "override",
1424 label: "explicit release base",
1425 baseUrl: override,
1426 },
1427 {
1428 context,
1429 env,
1430 fetchText,
1431 requiredAssets,
1432 },
1433 );
1434 }
1435 if (usesCnbMirror(env)) {
1436 assertCnbMirrorSupportedPlatform(platform, arch);
1437 logInfo(`using CNB first-party mirror for v${version}`);
1438 return loadSourceManifest(
1439 {
1440 id: "cnb",
1441 label: "CNB first-party mirror",
1442 baseUrl: cnbReleaseBaseUrl(version),
1443 },
1444 {
1445 context,
1446 env,
1447 fetchText,
1448 requiredAssets,
1449 },
1450 );
1451 }
1452 if (shouldRaceFirstPartyMirrors(env, platform, arch)) {
1453 const sources = options.sources || firstPartyReleaseSources(version, repo);
1454 return raceFirstPartyManifests(sources, {
1455 version,
1456 context,
1457 env,
1458 fetchText,
1459 requiredAssets,
1460 });
1461 }
1462 logInfo(`using GitHub Releases for v${version}`);
1463 return loadSourceManifest(
1464 {
1465 id: "github",
1466 label: "GitHub Releases",
1467 baseUrl: githubReleaseBaseUrl(version, repo),
1468 },
1469 {
1470 context,
1471 env,
1472 fetchText,
1473 requiredAssets,
1474 },
1475 );
1476 }
1477
1478 async function loadChecksums(version, repo, options = {}) {
1479 return parseChecksumManifest(await downloadText(checksumManifestUrl(version, repo), options));
1480 }
1481
1482 function existingBinaryCandidates(targetPath, assetName) {
1483 const candidates = [targetPath];
1484 const assetPath = path.join(path.dirname(targetPath), assetName);
1485 if (assetPath !== targetPath) {
1486 candidates.push(assetPath);
1487 }
1488 return candidates;
1489 }
1490
1491 async function adoptExistingBinaryIfValid(targetPath, assetName, version, getChecksums, marker) {
1492 const candidates = [];
1493 for (const candidate of existingBinaryCandidates(targetPath, assetName)) {
1494 if (await fileExists(candidate)) {
1495 candidates.push(candidate);
1496 }
1497 }
1498 if (candidates.length === 0) {
1499 return false;
1500 }
1501
1502 const checksums = await getChecksums();
1503 for (const candidate of candidates) {
1504 if (!(await checksumMatches(candidate, assetName, checksums))) {
1505 continue;
1506 }
1507 preflightGlibc(candidate);
1508 if (candidate !== targetPath) {
1509 await rename(candidate, targetPath);
1510 }
1511 if (process.platform !== "win32") {
1512 await chmod(targetPath, 0o755);
1513 }
1514 await writeFile(marker, String(version), "utf8");
1515 return true;
1516 }
1517 return false;
1518 }
1519
1520 async function resolveLockedSource(options) {
1521 let sourceId = options.sourceId;
1522 let sourceLabel = options.sourceLabel;
1523 let baseUrl = options.baseUrl;
1524 if (options.getSource) {
1525 const source = await options.getSource();
1526 sourceId = source.id;
1527 sourceLabel = source.label;
1528 baseUrl = source.baseUrl;
1529 }
1530 return { sourceId, sourceLabel, baseUrl };
1531 }
1532
1533 async function ensureBinary(targetPath, assetName, version, repo, getChecksums, options = {}) {
1534 const marker = `${targetPath}.version`;
1535 const env = options.env || process.env;
1536 const downloadIfNeeded = shouldForceDownload(env);
1537 if (!downloadIfNeeded) {
1538 const existing = await fileExists(targetPath);
1539 if (existing) {
1540 const markerVersion = await readLocalVersion(marker);
1541 if (markerVersion === String(version)) {
1542 return targetPath;
1543 }
1544 }
1545 if (await adoptExistingBinaryIfValid(targetPath, assetName, version, getChecksums, marker)) {
1546 const locked = await resolveLockedSource(options);
1547 if (locked.sourceId) {
1548 await writeSourceReceipt(targetPath, {
1549 id: locked.sourceId,
1550 label: locked.sourceLabel || locked.sourceId,
1551 baseUrl: locked.baseUrl || "",
1552 }, version);
1553 }
1554 return targetPath;
1555 }
1556 }
1557 const checksums = await getChecksums();
1558 const locked = await resolveLockedSource(options);
1559 const url = locked.baseUrl
1560 ? releaseAssetUrlFromBase(assetName, locked.baseUrl)
1561 : releaseAssetUrl(assetName, version, repo);
1562 const destination = `${targetPath}.${process.pid}.${Date.now()}.download`;
1563 const downloadFn = options.download || download;
1564 const progressName = locked.sourceLabel
1565 ? `${assetName} from ${locked.sourceLabel}`
1566 : assetName;
1567 await downloadFn(url, destination, { assetName: progressName, context: options.context, env });
1568 try {
1569 await verifyChecksum(destination, assetName, checksums, locked.sourceLabel);
1570 preflightGlibc(destination);
1571 } catch (error) {
1572 await unlink(destination).catch(() => {});
1573 throw error;
1574 }
1575 if (process.platform !== "win32") {
1576 await chmod(destination, 0o755);
1577 }
1578 await rename(destination, targetPath);
1579 await writeFile(marker, String(version), "utf8");
1580 if (locked.sourceId) {
1581 await writeSourceReceipt(targetPath, {
1582 id: locked.sourceId,
1583 label: locked.sourceLabel || locked.sourceId,
1584 baseUrl: locked.baseUrl || "",
1585 }, version);
1586 }
1587 return targetPath;
1588 }
1589
1590 // Optional install may only downgrade retryable download failures to warnings.
1591 // Unsupported platforms, checksum mismatches, glibc compatibility errors, and
1592 // malformed release metadata must still fail with actionable diagnostics.
1593 function shouldIgnoreInstallFailure(
1594 context,
1595 error,
1596 argv = process.argv.slice(2),
1597 env = process.env,
1598 ) {
1599 return isInstallContext(context) && isOptionalInstall(argv, env) && isRetryable(error);
1600 }
1601
1602 function preflightCompiledHost(file, host) {
1603 if (!host.target.startsWith("linux-")) return;
1604 const required = detectBinaryRequiredGlibc(file);
1605 const available = detectHostGlibc();
1606 if (host.libc === "glibc" && (!available || (required && glibc.compareVersion(available, required) < 0))) {
1607 throw new NonRetryableError("compiled Bun image requires a matching GNU libc; the Codewhale CLI remains static musl. Use Node on a musl-only installation.");
1608 }
1609 if (host.libc === "musl" && required) throw new NonRetryableError("qualified musl host unexpectedly contains GNU libc dependencies");
1610 }
1611
1612 async function prepareCompiledHost({ version, releaseDir, source, context, options }) {
1613 const catalogUrl = releaseAssetUrlFromBase(compiledHosts.HOST_CATALOG, source.baseUrl);
1614 const fetchText = options.fetchText || downloadText;
1615 const text = await fetchText(catalogUrl, { context });
1616 compiledHosts.verifyBytes(Buffer.from(text), source.checksums.get(compiledHosts.HOST_CATALOG), compiledHosts.HOST_CATALOG);
1617 const catalog = compiledHosts.parseCatalog(text, version);
1618 const host = compiledHosts.selectedHost(catalog, options.platform, options.arch);
1619 const suffix = host.target.startsWith("windows-") ? ".exe" : "";
1620 const payloads = [
1621 { asset: host.asset, name: compiledHosts.HOST_NAME + suffix, hash: host.sha256, executable: true },
1622 { asset: host.notices_asset, name: compiledHosts.HOST_NAME + ".LICENSES.txt", hash: host.notices_sha256 },
1623 { asset: host.source_asset, name: compiledHosts.HOST_NAME + ".relink-source.tar.gz", hash: host.source_sha256 },
1624 ];
1625 const stageDir = await fs.promises.mkdtemp(path.join(releaseDir, ".compiled-host-"));
1626 const snapshots = [];
1627 const published = [];
1628 let retainBackups = false;
1629 const existingHash = async (file) => {
1630 try {
1631 const metadata = await fs.promises.lstat(file);
1632 if (!metadata.isFile() || metadata.isSymbolicLink()) throw new NonRetryableError(`refusing nonregular compiled host destination ${file}`);
1633 return compiledHosts.sha256(await readFile(file));
1634 } catch (error) { if (error.code === "ENOENT") return undefined; throw error; }
1635 };
1636 const cleanup = async () => { if (!retainBackups) await fs.promises.rm(stageDir, { recursive: true, force: true }); };
1637 const rollback = async (original) => {
1638 const failures = [];
1639 for (const snapshot of published.slice().reverse()) {
1640 try {
1641 if (await existingHash(snapshot.target) !== snapshot.newHash) throw new Error(`destination changed after publication: ${snapshot.target}`);
1642 if (snapshot.hash) await rename(path.join(stageDir, snapshot.name + ".previous"), snapshot.target);
1643 else await unlink(snapshot.target);
1644 } catch (error) { failures.push(error.message); }
1645 }
1646 if (failures.length) {
1647 retainBackups = true;
1648 throw new NonRetryableError(`${original.message}; rollback incomplete: ${failures.join("; ")}. Recovery files retained at ${stageDir}`);
1649 }
1650 throw original;
1651 };
1652 try {
1653 for (const payload of payloads) {
1654 if (source.checksums.get(payload.asset) !== payload.hash) throw new NonRetryableError(`catalog and checksum manifest disagree for ${payload.asset}`);
1655 const stage = path.join(stageDir, payload.name);
1656 await (options.download || download)(releaseAssetUrlFromBase(payload.asset, source.baseUrl), stage, { context, assetName: payload.asset });
1657 compiledHosts.verifyBytes(await readFile(stage), payload.hash, payload.asset);
1658 if (payload.executable) preflightCompiledHost(stage, host);
1659 if (process.platform !== "win32") await chmod(stage, payload.executable ? 0o755 : 0o644);
1660 }
1661 const receiptName = compiledHosts.HOST_NAME + ".release.json";
1662 await writeFile(path.join(stageDir, receiptName), text, { mode: 0o644 });
1663 const oldReceipt = path.join(releaseDir, receiptName);
1664 const oldReceiptHash = await existingHash(oldReceipt);
1665 let oldPayloadHashes;
1666 if (oldReceiptHash) {
1667 const previous = compiledHosts.selectedHost(compiledHosts.parseCatalog(await readFile(oldReceipt)), options.platform, options.arch);
1668 oldPayloadHashes = [previous.sha256, previous.notices_sha256, previous.source_sha256];
1669 }
1670 const names = [...payloads.map((payload) => payload.name), receiptName];
1671 for (const [index, name] of names.entries()) {
1672 const target = path.join(releaseDir, name);
1673 const hash = await existingHash(target);
1674 if (index < payloads.length && hash && (!oldPayloadHashes || hash !== oldPayloadHashes[index])) throw new NonRetryableError(`refusing unclaimed or modified compiled host destination ${target}`);
1675 if (hash) {
1676 const backup = path.join(stageDir, name + ".previous");
1677 await fs.promises.copyFile(target, backup);
1678 if (compiledHosts.sha256(await readFile(backup)) !== hash) throw new NonRetryableError(`compiled host changed while backing up ${target}`);
1679 }
1680 snapshots.push({ name, target, hash, newHash: compiledHosts.sha256(await readFile(path.join(stageDir, name))) });
1681 }
1682 } catch (error) { await cleanup(); throw error; }
1683 return {
1684 cleanup,
1685 async publish() {
1686 try {
1687 // Validate every destination before publication, then each immediately
1688 // before replacement. Only bytes proven by the prior receipt are owned.
1689 for (const snapshot of snapshots) if (await existingHash(snapshot.target) !== snapshot.hash) throw new NonRetryableError(`compiled host destination changed during installation: ${snapshot.target}`);
1690 for (const snapshot of snapshots) {
1691 if (await existingHash(snapshot.target) !== snapshot.hash) throw new NonRetryableError(`compiled host destination changed during installation: ${snapshot.target}`);
1692 const staged = path.join(stageDir, snapshot.name);
1693 if (snapshot.hash === undefined) {
1694 await fs.promises.link(staged, snapshot.target); // fresh install never clobbers a raced-in file
1695 published.push(snapshot);
1696 await unlink(staged);
1697 } else {
1698 await rename(staged, snapshot.target);
1699 published.push(snapshot);
1700 }
1701 }
1702 } catch (error) { await rollback(error); }
1703 },
1704 };
1705 }
1706
1707 async function installCompiledHost(options) {
1708 const prepared = await prepareCompiledHost(options);
1709 try { await prepared.publish(); } finally { await prepared.cleanup(); }
1710 }
1711
1712 async function run(options = {}) {
1713 const context =
1714 options.context === undefined || options.context === null ? "runtime" : options.context;
1715 const env = options.env || process.env;
1716 if (shouldDisableInstall(env)) {
1717 return;
1718 }
1719 if (shouldSkipOptionalPostinstall(context, process.argv.slice(2), env)) {
1720 logInfo(
1721 "pnpm optional postinstall detected; skipping install-time download. The binary will be checked on first run.",
1722 );
1723 return;
1724 }
1725 const version = resolvePackageVersion(pkg, env);
1726 const repo = resolveRepo(env);
1727 const paths = options.paths || binaryPaths();
1728 if (
1729 isInstallContext(context) &&
1730 (options.platform || os.platform()) === "openharmony" &&
1731 !isQuietInstall(env)
1732 ) {
1733 process.stderr.write(
1734 `codewhale: note: installing ${paths.codewhale.asset}, the native HarmonyOS/OpenHarmony build.\n` +
1735 `It is code-signed, but a native HarmonyOS terminal (HiShell) is not a Linux shell:\n` +
1736 `there is no git and no package manager, and the debugging shell (hdc shell) cannot\n` +
1737 `execute it at all. details: docs/HarmonyOS.md\n` +
1738 `${openHarmonyDirections()}\n`,
1739 );
1740 }
1741 const releaseDir = options.releaseDir || releaseBinaryDirectory();
1742 await mkdir(releaseDir, { recursive: true });
1743
1744 let sourcePromise;
1745 const getSource = () => {
1746 if (!sourcePromise) {
1747 sourcePromise = selectReleaseSource({
1748 version,
1749 repo,
1750 requiredAssets: [paths.codewhale.asset, paths.codew.asset, ...(compiledHosts.requested(env) ? [compiledHosts.HOST_CATALOG] : [])],
1751 context,
1752 env,
1753 platform: options.platform,
1754 arch: options.arch,
1755 sources: options.sources,
1756 fetchText: options.fetchText,
1757 });
1758 }
1759 return sourcePromise;
1760 };
1761 const getChecksums = () => getSource().then((source) => source.checksums);
1762
1763 // Fully validate and stage an explicitly requested companion before any CLI
1764 // replacement. Missing qualification cannot leave an updated CLI behind.
1765 const preparedHost = compiledHosts.requested(env)
1766 ? await prepareCompiledHost({ version, releaseDir, source: await getSource(), context, options })
1767 : undefined;
1768 try {
1769 await Promise.all([
1770 ensureBinary(paths.codewhale.target, paths.codewhale.asset, version, repo, getChecksums, {
1771 context,
1772 getSource,
1773 download: options.download,
1774 env,
1775 }),
1776 ensureBinary(paths.codew.target, paths.codew.asset, version, repo, getChecksums, {
1777 context,
1778 getSource,
1779 download: options.download,
1780 env,
1781 }),
1782 ]); // single binary
1783 if (preparedHost) await preparedHost.publish();
1784 } finally { if (preparedHost) await preparedHost.cleanup(); }
1785 }
1786
1787 async function getBinaryPath(name) {
1788 await run({ context: "runtime" });
1789 const paths = binaryPaths();
1790 if (name === "codewhale") {
1791 return paths.codewhale.target;
1792 }
1793 if (name === "codew") {
1794 return paths.codew.target;
1795 }
1796 if (name === "codewhale-tui") {
1797 // v0.9.5 single-binary: codewhale-tui is now an alias to codewhale for backwards compat
1798 return paths.codewhale.target;
1799 }
1800 throw new Error(`Unknown binary: ${name}`);
1801 }
1802
1803 module.exports = {
1804 getBinaryPath,
1805 installFailureHint,
1806 run,
1807 _internal: {
1808 resolvePackageVersion,
1809 resolveRepo,
1810 isOptionalInstall,
1811 shouldForceDownload,
1812 shouldDisableInstall,
1813 isQuietInstall,
1814 adoptExistingBinaryIfValid,
1815 shouldIgnoreInstallFailure,
1816 shouldSkipOptionalPostinstall,
1817 followRedirects,
1818 httpRequest,
1819 defaultTimeoutMs,
1820 defaultStallMs,
1821 downloadTimeoutMs,
1822 downloadStallMs,
1823 binaryPaths,
1824 installCompiledHost,
1825 prepareCompiledHost,
1826 preflightCompiledHost,
1827 ensureBinary,
1828 maxAttempts,
1829 withRetry,
1830 selectReleaseSource,
1831 downloadText,
1832 download,
1833 parseChecksumManifest,
1834 MANIFEST_TIMEOUT_MS,
1835 MANIFEST_STALL_MS,
1836 },
1837 };
1838
1839 if (require.main === module) {
1840 run({ context: "install" }).catch((error) => {
1841 console.error("codewhale install failed:", error.message);
1842 const hint = installFailureHint(error);
1843 if (hint) {
1844 console.error(hint);
1845 }
1846 if (shouldIgnoreInstallFailure("install", error)) {
1847 console.error(
1848 "Optional install enabled; continuing without a usable binary. The download will be retried on first run.",
1849 );
1850 process.exit(0);
1851 }
1852 process.exit(1);
1853 });
1854 }
1855
1855 lines JAVASCRIPT