Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

t3.mjs

186 lines6.5 KB

1#!/usr/bin/env node
2// Share the installer's runtime cache; pre-0.0.41 services re-enter here over IPC.
3import { spawn, spawnSync } from "node:child_process";
4import crypto from "node:crypto";
5import fs from "node:fs";
6import os from "node:os";
7import path from "node:path";
8​
9const { version } = JSON.parse(
10 fs.readFileSync(path.join(import.meta.dirname, "../package.json"), "utf8"),
11);
12​
13const SUPPORTED = ["darwin-arm64", "linux-arm64", "linux-x64", "win32-arm64", "win32-x64"];
14​
15function t3Home() {
16 const raw = (process.env.T3CODE_HOME || "").trim();
17 if (raw === "") return path.join(os.homedir(), ".t3");
18 if (raw === "~") return os.homedir();
19 if (raw.startsWith("~/") || raw.startsWith("~\\")) return path.join(os.homedir(), raw.slice(2));
20 return path.resolve(raw);
22​
23async function get(url) {
24 const response = await fetch(url);
25 if (response.status === 404) {
26 throw new Error(
27 `${url} does not exist yet. If ${version} was just released, try again in a few minutes.`,
28 );
29 }
30 if (!response.ok) throw new Error(`GET ${url} returned HTTP ${response.status}`);
31 return response;
33​
34async function download(url, file) {
35 const response = await get(url);
36 const total = Number(response.headers.get("content-length")) || 0;
37 const hash = crypto.createHash("sha256");
38 const out = fs.openSync(file, "w");
39 const tty = process.stderr.isTTY;
40 let received = 0;
41 let shown = -1;
42 try {
43 for await (const chunk of response.body) {
44 hash.update(chunk);
45 fs.writeSync(out, chunk);
46 received += chunk.byteLength;
47 // Redraw once per percent (or per MB without a length), not per chunk.
48 const step = total ? Math.floor((received * 100) / total) : Math.floor(received / 1048576);
49 if (tty && step !== shown) {
50 shown = step;
51 const percent = total ? ` ${step}%` : "";
52 process.stderr.write(
53 `\r\x1b[2Kt3: downloading T3 Code ${version}${percent} (${(received / 1048576).toFixed(1)} MB)`,
54 );
55 }
56 }
57 } finally {
58 fs.closeSync(out);
59 if (tty) process.stderr.write("\r\x1b[2K");
60 }
61 return hash.digest("hex");
63​
64async function install(dir, key) {
65 const archive = `t3-${version}-${key}.${process.platform === "win32" ? "zip" : "tar.gz"}`;
66 const base = (
67 process.env.T3CODE_RELEASE_BASE_URL || "https://github.com/pingdotgg/t3code/releases/download"
68 ).replace(/\/+$/, "");
69 const sums = await (await get(`${base}/v${version}/SHA256SUMS`)).text();
70 const expected = /^([0-9a-f]{64})\s+\*?(.+)$/im;
71 const line = sums
72 .split(/\r?\n/)
73 .map((l) => expected.exec(l.trim()))
74 .find((m) => m && m[2] === archive);
75 if (!line) throw new Error(`${archive} is not listed in the release's SHA256SUMS`);
76​
77 // Stage beside the destination and rename atomically to avoid half-installed versions.
78 fs.mkdirSync(path.dirname(dir), { recursive: true });
79 const staging = fs.mkdtempSync(`${dir}.staging-`);
80 try {
81 const file = path.join(staging, archive);
82 if ((await download(`${base}/v${version}/${archive}`, file)) !== line[1].toLowerCase()) {
83 throw new Error(`checksum mismatch for ${archive}`);
84 }
85 // Windows' own tar.exe reads zip; a Git-for-Windows tar on PATH cannot.
86 const tar =
87 process.platform === "win32" ? `${process.env.SystemRoot}\\System32\\tar.exe` : "tar";
88 const extract = spawnSync(tar, ["-xf", file, "-C", staging, "--strip-components=1"], {
89 stdio: "inherit",
90 });
91 if (extract.status !== 0) throw new Error(`could not extract ${archive}`);
92 fs.rmSync(file);
93 fs.writeFileSync(path.join(staging, ".install-complete"), `${version}\n`);
94 publish(staging, dir);
95 } finally {
96 fs.rmSync(staging, { recursive: true, force: true });
97 }
99​
100const isComplete = (dir) => {
101 try {
102 return fs.readFileSync(path.join(dir, ".install-complete"), "utf8").trim() === version;
103 } catch {
104 return false;
105 }
106};
107​
108/** Preserve concurrently published complete installs; replace only incomplete folders without the completion marker. */
109function publish(staging, dir) {
110 try {
111 fs.renameSync(staging, dir);
112 return;
113 } catch (error) {
114 if (isComplete(dir)) return;
115 if (!fs.existsSync(dir)) throw error;
116 }
117 const lock = `${dir}.lock`;
118 try {
119 fs.mkdirSync(lock);
120 } catch (error) {
121 if (error.code !== "EEXIST") throw error;
122 throw new Error(
123 `another t3 is installing ${version}. If none is running, delete ${lock} and try again.`,
124 { cause: error },
125 );
126 }
127 const stale = `${staging}.stale`;
128 try {
129 // A peer may have published between our marker check and taking the lock.
130 if (isComplete(dir)) return;
131 // Move it aside rather than deleting in place: once the folder is empty, a
132 // peer's first rename can land in it.
133 fs.renameSync(dir, stale);
134 try {
135 fs.renameSync(staging, dir);
136 } catch (error) {
137 if (!isComplete(dir)) throw error;
138 }
139 } finally {
140 fs.rmSync(lock, { recursive: true, force: true });
141 fs.rmSync(stale, { recursive: true, force: true });
142 }
144​
145async function main() {
146 const key = `${process.platform}-${process.arch}`;
147 if (!SUPPORTED.includes(key)) {
148 throw new Error(
149 `no T3 Code CLI build is available for ${key} (supported: ${SUPPORTED.join(", ")}).\n` +
150 "The desktop app is at https://github.com/pingdotgg/t3code/releases",
151 );
152 }
153 const dir = path.join(t3Home(), "runtime", "versions", version);
154 if (!isComplete(dir)) await install(dir, key);
155​
156 // Service IPC and signals must reach the child; terminal Ctrl-C already does, so do not forward SIGINT twice.
157 const ipc = process.send !== undefined;
158 const child = spawn(
159 path.join(dir, process.platform === "win32" ? "t3.exe" : "t3"),
160 process.argv.slice(2),
161 {
162 stdio: ipc ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
163 // The executable lives in the T3 home, so this is how it knows npm launched it.
164 env: { ...process.env, T3CODE_NPM_LAUNCHER_PATH: import.meta.filename },
165 },
166 );
167 if (ipc) {
168 process.on("message", (message) => child.connected && child.send(message));
169 child.on("message", (message) => process.connected && process.send(message));
170 process.on("disconnect", () => child.connected && child.disconnect());
171 }
172 for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
173 process.on(signal, () => (ipc || signal !== "SIGINT") && child.kill(signal));
174 }
175 child.on("error", (error) => fail(error));
176 child.on("exit", (code, signal) =>
177 process.exit(code ?? 128 + (os.constants.signals[signal] || 1)),
178 );
180​
181function fail(error) {
182 process.stderr.write(`t3: ${error.message}\n`);
183 process.exit(1);
185​
186await main().catch(fail);