Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Drives the real shell installer against a local GitHub fixture.
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as NodeChildProcess from "node:child_process";
4import * as NodeCrypto from "node:crypto";
5import * as NodeFSP from "node:fs/promises";
6import * as NodeHttp from "node:http";
7import * as NodeOS from "node:os";
8import * as NodePath from "node:path";
9import { describe, expect, it } from "vite-plus/test";
10
11/** The launcher install.sh, `t3 install`, and `t3 update` write; exec by absolute path. */
12const launcherScript = (executable: string) =>
13 `#!/bin/sh\nexec '${executable.replaceAll("'", "'\\''")}' "$@"\n`;
14
15const nightlies = Array.from({ length: 100 }, (_, index) => ({
16 tag_name: `v1.2.4-nightly.20261020.${200 - index}`,
17}));
18
19describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer home", () => {
20 it("installs a relative home from a directory ending in a newline", async () => {
21 const temporaryRoot = await NodeFSP.realpath(
22 await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-home-")),
23 );
24 const root = NodePath.join(temporaryRoot, "cwd\n");
25 const homeName = "-custom home\\home\n";
26 const home = NodePath.join(root, homeName);
27 const version = "1.2.3";
28 const target = NodePath.join(home, "runtime/versions", version);
29 const launcher = NodePath.join(root, "bin/t3");
30 try {
31 await NodeFSP.mkdir(target, { recursive: true });
32 await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), `${version}\n`);
33 await NodeFSP.writeFile(NodePath.join(target, "t3"), "#!/bin/sh\necho 't3 v1.2.3'\n", {
34 mode: 0o755,
35 });
36 const install = () =>
37 NodeChildProcess.spawnSync("sh", [NodePath.resolve(import.meta.dirname, "install.sh")], {
38 cwd: root,
39 env: {
40 ...process.env,
41 HOME: root,
42 T3CODE_HOME: homeName,
43 T3CODE_VERSION: version,
44 T3CODE_INSTALL_BIN_DIR: NodePath.dirname(launcher),
45 T3CODE_RELEASE_BASE_URL: "http://127.0.0.1:1",
46 },
47 encoding: "utf8",
48 });
49 // The second run replaces the launcher the first wrote, newlines in its path and all.
50 const first = install();
51 expect(first.status, first.stdout + first.stderr).toBe(0);
52 const { status, stdout, stderr } = install();
53 expect(status, stdout + stderr).toBe(0);
54 expect(stderr).toContain(`Installed T3 Code ${version}`);
55 expect(await NodeFSP.readFile(launcher, "utf8")).toBe(
56 launcherScript(NodePath.join(target, "t3")),
57 );
58 expect(
59 NodeChildProcess.execFileSync(launcher, ["--version"], {
60 cwd: NodeOS.tmpdir(),
61 encoding: "utf8",
62 }).trim(),
63 ).toBe("t3 v1.2.3");
64 } finally {
65 await NodeFSP.rm(temporaryRoot, { recursive: true, force: true });
66 }
67 });
68});
69
70// regression: #22490
71describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer channel lookup", () => {
72 it.each([
73 // regression: #32897
74 ["stable", "1.2.3", 1],
75 ["preview", "1.2.4-preview.20261019.50", 0],
76 ])("finds %s %s behind nightlies and %i HTTP 504s", async (channel, version, failures) => {
77 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-index-"));
78 const target = NodePath.join(root, "home/runtime/versions", version);
79 const server = NodeHttp.createServer((request, response) => {
80 if (failures-- > 0) return response.writeHead(504).end();
81 const url = new URL(request.url ?? "/", "http://fixture");
82 const body =
83 url.pathname === "/pingdotgg/t3code/releases/latest" &&
84 request.headers.accept === "application/json"
85 ? { tag_name: "v1.2.3" }
86 : url.pathname === "/repos/pingdotgg/t3code/releases"
87 ? { "1": nightlies, "2": [{ tag_name: `v${version}` }, { tag_name: "v1.2.3" }] }[
88 url.searchParams.get("page") ?? ""
89 ]
90 : undefined;
91 if (body === undefined) response.statusCode = 404;
92 // The API pretty-prints and the installer reads it line by line.
93 response.end(JSON.stringify(body ?? [], null, 2));
94 });
95 try {
96 // An existing completed install isolates release resolution from archive downloads.
97 await NodeFSP.mkdir(target, { recursive: true });
98 await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), `${version}\n`);
99 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
100 const address = server.address();
101 if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
102 const origin = `http://127.0.0.1:${address.port}`;
103 const source = await NodeFSP.readFile(
104 NodePath.resolve(import.meta.dirname, "install.sh"),
105 "utf8",
106 );
107 const installer = NodePath.join(root, "install.sh");
108 await NodeFSP.writeFile(installer, source.replace(/https:\/\/(api\.)?github\.com/g, origin));
109 const { code, output } = await new Promise<{ code: number | null; output: string }>(
110 (resolve, reject) => {
111 const child = NodeChildProcess.spawn("sh", [installer], {
112 env: {
113 ...process.env,
114 T3CODE_VERSION: "",
115 T3CODE_CHANNEL: channel,
116 T3CODE_HOME: NodePath.join(root, "home"),
117 T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin"),
118 // A wrong version must fail here instead of downloading a real release.
119 T3CODE_RELEASE_BASE_URL: origin,
120 },
121 stdio: ["ignore", "pipe", "pipe"],
122 });
123 let output = "";
124 child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
125 child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
126 child.on("error", reject);
127 child.on("close", (code) => resolve({ code, output }));
128 },
129 );
130 expect(code, output).toBe(0);
131 expect(output).toContain(`Installed T3 Code ${version}`);
132 } finally {
133 server.closeAllConnections();
134 await new Promise<void>((resolve) => server.close(() => resolve()));
135 await NodeFSP.rm(root, { recursive: true, force: true });
136 }
137 });
138});
139
140// regression: #35834
141describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
142 "installer archive download",
143 () => {
144 it("names the archive when it returns 404", async () => {
145 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-archive-"));
146 const arch = HostProcess.Architecture.defaultValue() === "arm64" ? "arm64" : "x64";
147 const archive = `t3-1.2.3-linux-${arch}.tar.gz`;
148 const server = NodeHttp.createServer((request, response) => {
149 if (request.url === "/v1.2.3/SHA256SUMS")
150 return response.end(`${"0".repeat(64)} ${archive}\n`);
151 response.writeHead(404).end();
152 });
153 try {
154 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
155 const address = server.address();
156 if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
157 const { code, output } = await new Promise<{ code: number | null; output: string }>(
158 (resolve, reject) => {
159 const child = NodeChildProcess.spawn(
160 "sh",
161 [NodePath.resolve(import.meta.dirname, "install.sh")],
162 {
163 env: {
164 ...process.env,
165 T3CODE_CHANNEL: "",
166 T3CODE_VERSION: "1.2.3",
167 T3CODE_HOME: NodePath.join(root, "home"),
168 T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin"),
169 T3CODE_RELEASE_BASE_URL: `http://127.0.0.1:${address.port}`,
170 },
171 stdio: ["ignore", "pipe", "pipe"],
172 },
173 );
174 let output = "";
175 child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
176 child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
177 child.on("error", reject);
178 child.on("close", (code) => resolve({ code, output }));
179 },
180 );
181 expect(code, output).not.toBe(0);
182 expect(output).toMatch(new RegExp(`t3 install: .*${archive.replaceAll(".", "\\.")}`));
183 } finally {
184 server.closeAllConnections();
185 await new Promise<void>((resolve) => server.close(() => resolve()));
186 await NodeFSP.rm(root, { recursive: true, force: true });
187 }
188 });
189 },
190);
191
192/** Runs an installer for a version that is already unpacked, so only the t3 command step runs. */
193async function installOver(input: {
194 readonly script: "install.sh" | "install.ps1";
195 readonly home: string;
196 readonly binDir: string;
197 readonly env?: NodeJS.ProcessEnv;
198 readonly cwd?: string;
199}) {
200 const target = NodePath.join(input.home, "runtime", "versions", "1.2.3");
201 await NodeFSP.mkdir(target, { recursive: true });
202 await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), "1.2.3\n");
203 const installer = NodePath.resolve(import.meta.dirname, input.script);
204 const [command, args] =
205 input.script === "install.sh"
206 ? ["sh", [installer]]
207 : ["powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", installer]];
208 const result = NodeChildProcess.spawnSync(command, args, {
209 encoding: "utf8",
210 ...(input.cwd === undefined ? {} : { cwd: input.cwd }),
211 env: {
212 ...process.env,
213 T3CODE_CHANNEL: "",
214 T3CODE_VERSION: "1.2.3",
215 T3CODE_HOME: input.home,
216 T3CODE_INSTALL_BIN_DIR: input.binDir,
217 T3CODE_RELEASE_BASE_URL: "http://127.0.0.1:9",
218 ...input.env,
219 },
220 });
221 return { code: result.status, output: `${result.stdout}${result.stderr}`, target };
222}
223
224describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("install.sh t3 command", () => {
225 it("replaces only this home's own launchers and prints a PATH command", async () => {
226 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-link-"));
227 try {
228 const home = NodePath.join(root, "home");
229 const binDir = NodePath.join(root, "bin");
230 const link = NodePath.join(binDir, "t3");
231 await NodeFSP.mkdir(binDir, { recursive: true });
232
233 await NodeFSP.writeFile(link, "#!/bin/sh\necho mine\n");
234 const foreign = await installOver({ script: "install.sh", home, binDir });
235 expect(foreign.code).not.toBe(0);
236 expect(foreign.output).toContain(`another t3 is already at ${link}`);
237 expect(await NodeFSP.readFile(link, "utf8")).toBe("#!/bin/sh\necho mine\n");
238 // Not even from inside the versions folder, where `.` would resolve into it.
239 const fromVersions = await installOver({
240 script: "install.sh",
241 home,
242 binDir,
243 cwd: foreign.target,
244 });
245 expect(fromVersions.code).not.toBe(0);
246 expect(await NodeFSP.readFile(link, "utf8")).toBe("#!/bin/sh\necho mine\n");
247
248 // A link that only looks like it points into versions (join() would normalize the ..).
249 await NodeFSP.rm(link);
250 await NodeFSP.mkdir(NodePath.join(home, "other"), { recursive: true });
251 await NodeFSP.writeFile(NodePath.join(home, "other/t3"), "#!/bin/sh\n");
252 await NodeFSP.symlink(`${home}/runtime/versions/../../other/t3`, link);
253 const climbing = await installOver({ script: "install.sh", home, binDir });
254 expect(climbing.code).not.toBe(0);
255 expect(await NodeFSP.readlink(link)).toBe(`${home}/runtime/versions/../../other/t3`);
256
257 // Only `<version>/t3` counts, not another program inside a version.
258 await NodeFSP.rm(link);
259 await NodeFSP.symlink(NodePath.join(home, "runtime/versions/1.0.0/helper"), link);
260 const sibling = await installOver({ script: "install.sh", home, binDir });
261 expect(sibling.code).not.toBe(0);
262 expect(await NodeFSP.readlink(link)).toBe(
263 NodePath.join(home, "runtime/versions/1.0.0/helper"),
264 );
265
266 // An upgrade over an older version's link, written through a symlinked T3 home.
267 await NodeFSP.rm(link);
268 await NodeFSP.symlink(NodePath.join(home, "runtime/versions/1.0.0/t3"), link);
269 await NodeFSP.symlink(home, NodePath.join(root, "alias"));
270 const upgrade = await installOver({
271 script: "install.sh",
272 home: NodePath.join(root, "alias"),
273 binDir,
274 env: { HOME: root, SHELL: "/bin/zsh", PATH: "/usr/bin:/bin" },
275 });
276 expect(upgrade.code, upgrade.output).toBe(0);
277 expect(await NodeFSP.readFile(link, "utf8")).toBe(
278 launcherScript(NodePath.join(root, "alias/runtime/versions/1.2.3/t3")),
279 );
280 expect(upgrade.output).toContain(
281 `printf '\\n%s\\n' 'export PATH="$PATH:$HOME/bin"' >> ~/.zshrc`,
282 );
283
284 // Containers and CI often have no SHELL; `set -u` must not stop the installer there.
285 const noShell = await installOver({
286 script: "install.sh",
287 home,
288 binDir,
289 env: { HOME: root, SHELL: undefined, PATH: "/usr/bin:/bin" },
290 });
291 expect(noShell.code, noShell.output).toBe(0);
292 expect(noShell.output).toContain(`Add ${binDir} to your PATH`);
293
294 // Its folder on PATH with a trailing slash is still this t3, not another one.
295 const slashed = await installOver({
296 script: "install.sh",
297 home,
298 binDir,
299 env: { HOME: root, PATH: `${binDir}/:/usr/bin:/bin` },
300 });
301 expect(slashed.code, slashed.output).toBe(0);
302 expect(slashed.output).toContain("Run t3 to use T3 Code here");
303
304 // A relative folder is made absolute, so the PATH command never follows the working directory.
305 const relative = await installOver({
306 script: "install.sh",
307 home,
308 binDir: "bin",
309 cwd: root,
310 env: { HOME: root, SHELL: "/bin/zsh", PATH: "/usr/bin:/bin" },
311 });
312 expect(relative.code, relative.output).toBe(0);
313 expect(relative.output).toContain(`'export PATH="$PATH:$HOME/bin"'`);
314
315 // A launcher script someone edited is theirs now.
316 const edited = `${launcherScript(NodePath.join(home, "runtime/versions/1.2.3/t3"))}# mine\n`;
317 await NodeFSP.writeFile(link, edited);
318 const overEdited = await installOver({ script: "install.sh", home, binDir });
319 expect(overEdited.code).not.toBe(0);
320 expect(await NodeFSP.readFile(link, "utf8")).toBe(edited);
321
322 await NodeFSP.rm(link);
323 await NodeFSP.symlink(NodePath.join(home, "bin/t3"), link);
324 const overDesktop = await installOver({
325 script: "install.sh",
326 home: `${home}//`,
327 binDir: `${binDir}/`,
328 });
329 expect(overDesktop.code, overDesktop.output).toBe(0);
330 expect(await NodeFSP.readFile(link, "utf8")).toBe(
331 launcherScript(NodePath.join(home, "runtime/versions/1.2.3/t3")),
332 );
333 } finally {
334 await NodeFSP.rm(root, { recursive: true, force: true });
335 }
336 });
337
338 it("prints a shell-ready launcher command when another t3 runs first", async () => {
339 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-shadow-"));
340 try {
341 const otherBin = NodePath.join(root, "old-bin");
342 const binDir = NodePath.join(root, "new bin");
343 await NodeFSP.mkdir(otherBin, { recursive: true });
344 await NodeFSP.writeFile(NodePath.join(otherBin, "t3"), "#!/bin/sh\n", { mode: 0o755 });
345 const shadowed = await installOver({
346 script: "install.sh",
347 home: NodePath.join(root, "home"),
348 binDir,
349 env: { HOME: root, PATH: `${otherBin}:${binDir}:/usr/bin:/bin` },
350 });
351 expect(shadowed.code, shadowed.output).toBe(0);
352 expect(shadowed.output).toContain(`so run '${binDir}/t3' to use this one.`);
353 } finally {
354 await NodeFSP.rm(root, { recursive: true, force: true });
355 }
356 });
357});
358
359describe.skipIf(HostProcess.Platform.defaultValue() !== "win32")("install.ps1 t3 command", () => {
360 it("replaces only its own t3.cmd, also in non-ASCII and bracketed paths", async () => {
361 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-ps1-"));
362 try {
363 // Windows PowerShell 5.1 reads files as ANSI by default and expands wildcards in paths.
364 const home = NodePath.join(root, "José", ".t3");
365 const binDir = NodePath.join(root, "bin[t3]");
366 const shim = NodePath.join(binDir, "t3.cmd");
367 await NodeFSP.mkdir(binDir, { recursive: true });
368
369 const desktopShim = '@echo off\r\n"C:\\Program Files\\T3 Code\\T3 Code.exe" "x" %*\r\n';
370 await NodeFSP.writeFile(shim, desktopShim);
371 const foreign = await installOver({ script: "install.ps1", home, binDir });
372 expect(foreign.code).not.toBe(0);
373 expect(foreign.output).toContain("another t3 is already at");
374 expect(await NodeFSP.readFile(shim, "utf8")).toBe(desktopShim);
375
376 // A hand-edited wrapper may set its own environment; replacing it would drop that.
377 const edited = `@echo off\r\nset "T3CODE_HOME=D:\\other"\r\n"${NodePath.join(home, "runtime", "versions", "1.0.0", "t3.exe")}" %*`;
378 await NodeFSP.writeFile(shim, edited, "utf8");
379 const wrapper = await installOver({ script: "install.ps1", home, binDir });
380 expect(wrapper.code).not.toBe(0);
381 expect(await NodeFSP.readFile(shim, "utf8")).toBe(edited);
382
383 const climbing = `@echo off\r\n"${NodePath.join(home, "runtime", "versions")}\\..\\other\\t3.exe" %*`;
384 await NodeFSP.writeFile(shim, climbing, "utf8");
385 const outside = await installOver({ script: "install.ps1", home, binDir });
386 expect(outside.code).not.toBe(0);
387 expect(await NodeFSP.readFile(shim, "utf8")).toBe(climbing);
388
389 const older = NodePath.join(home, "runtime", "versions", "1.0.0", "t3.exe");
390 await NodeFSP.writeFile(shim, `@echo off\r\n"${older}" %*`, "utf8");
391 const upgrade = await installOver({ script: "install.ps1", home, binDir });
392 expect(upgrade.code, upgrade.output).toBe(0);
393 expect(await NodeFSP.readFile(shim, "utf8")).toContain(
394 NodePath.join(upgrade.target, "t3.exe"),
395 );
396
397 const again = await installOver({ script: "install.ps1", home, binDir });
398 expect(again.code, again.output).toBe(0);
399
400 // Another t3 first on PATH still runs, so the installer names this one in full.
401 const otherBin = NodePath.join(root, "other");
402 await NodeFSP.mkdir(otherBin);
403 await NodeFSP.writeFile(NodePath.join(otherBin, "t3.cmd"), "@echo off\r\n");
404 // Windows spells it Path; a second PATH key would be ambiguous.
405 const pathKey =
406 Object.keys(process.env).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
407 const shadowed = await installOver({
408 script: "install.ps1",
409 home,
410 binDir,
411 env: { [pathKey]: `${otherBin};${process.env[pathKey] ?? ""}` },
412 });
413 expect(shadowed.code, shadowed.output).toBe(0);
414 expect(shadowed.output).toContain(
415 `Another t3 at ${NodePath.join(otherBin, "t3.cmd")} runs first`,
416 );
417
418 // Its own folder on PATH with a trailing separator is already on PATH.
419 const slashed = await installOver({
420 script: "install.ps1",
421 home,
422 binDir,
423 env: { [pathKey]: `${binDir}\\;${process.env[pathKey] ?? ""}` },
424 });
425 expect(slashed.code, slashed.output).toBe(0);
426 expect(slashed.output).toContain("to use T3 Code here");
427 // The same when the install folder itself is given with a trailing separator.
428 const bothSlashed = await installOver({
429 script: "install.ps1",
430 home,
431 binDir: `${binDir}\\`,
432 env: { [pathKey]: `${binDir}\\;${process.env[pathKey] ?? ""}` },
433 });
434 expect(bothSlashed.code, bothSlashed.output).toBe(0);
435 expect(bothSlashed.output).toContain("to use T3 Code here");
436 } finally {
437 await NodeFSP.rm(root, { recursive: true, force: true });
438 }
439 });
440});
441
442describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer checksum", () => {
443 it.each(
444 ["home\\data", "home\ndata"].flatMap((homeName) =>
445 [true, false].map((validChecksum) => ({ homeName, validChecksum })),
446 ),
447 )(
448 "verifies home $homeName with valid checksum $validChecksum",
449 async ({ homeName, validChecksum }) => {
450 const availableTools = ["sha256sum", "shasum"].filter(
451 (tool) =>
452 NodeChildProcess.spawnSync("sh", ["-c", 'command -v "$1"', "sh", tool]).status === 0,
453 );
454 expect(availableTools.length).toBeGreaterThan(0);
455 for (const checksumTool of availableTools) {
456 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-checksum-"));
457 const home = NodePath.join(root, homeName);
458 const version = "1.2.3";
459 const stem = `t3-${version}-linux-${HostProcess.Architecture.defaultValue()}`;
460 const archiveName = `${stem}.tar.gz`;
461 const server = NodeHttp.createServer();
462 try {
463 const tools = NodePath.join(root, "tools");
464 await NodeFSP.mkdir(tools);
465 for (const command of [
466 "sh",
467 "uname",
468 "tar",
469 "gzip",
470 "cut",
471 "curl",
472 "grep",
473 "mkdir",
474 "mktemp",
475 "rm",
476 "mv",
477 "ln",
478 "chmod",
479 "sed",
480 checksumTool,
481 ]) {
482 const executable = NodeChildProcess.execFileSync(
483 "sh",
484 ["-c", 'command -v "$1"', "sh", command],
485 { encoding: "utf8" },
486 ).trim();
487 await NodeFSP.symlink(executable, NodePath.join(tools, command));
488 }
489 await NodeFSP.mkdir(NodePath.join(root, stem));
490 await NodeFSP.writeFile(
491 NodePath.join(root, stem, "t3"),
492 "#!/bin/sh\necho 't3 v1.2.3'\n",
493 { mode: 0o755 },
494 );
495 const archivePath = NodePath.join(root, archiveName);
496 NodeChildProcess.execFileSync("tar", ["-czf", archivePath, "-C", root, stem]);
497 const archive = await NodeFSP.readFile(archivePath);
498 const digest = NodeCrypto.createHash("sha256").update(archive).digest("hex");
499 server.on("request", (request, response) => {
500 response.end(
501 request.url?.endsWith("/SHA256SUMS")
502 ? `${validChecksum ? digest : "0".repeat(64)} ${archiveName}\n`
503 : archive,
504 );
505 });
506 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
507 const address = server.address();
508 if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
509 const { code, output } = await new Promise<{ code: number | null; output: string }>(
510 (resolve, reject) => {
511 const child = NodeChildProcess.spawn(
512 "sh",
513 [NodePath.resolve(import.meta.dirname, "install.sh")],
514 {
515 env: {
516 ...process.env,
517 PATH: tools,
518 T3CODE_VERSION: version,
519 T3CODE_HOME: home,
520 T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin"),
521 T3CODE_RELEASE_BASE_URL: `http://127.0.0.1:${address.port}`,
522 },
523 stdio: ["ignore", "pipe", "pipe"],
524 },
525 );
526 let output = "";
527 child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
528 child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
529 child.on("error", reject);
530 child.on("close", (code) => resolve({ code, output }));
531 },
532 );
533 const versions = NodePath.join(home, "runtime/versions");
534 if (validChecksum) {
535 expect(code, `${checksumTool}: ${output}`).toBe(0);
536 expect(
537 await NodeFSP.readFile(NodePath.join(versions, version, ".install-complete"), "utf8"),
538 ).toBe("1.2.3\n");
539 expect(
540 NodeChildProcess.execFileSync(NodePath.join(root, "bin/t3"), ["--version"], {
541 encoding: "utf8",
542 }).trim(),
543 ).toBe("t3 v1.2.3");
544 } else {
545 expect(code).not.toBe(0);
546 expect(output).toContain("checksum mismatch");
547 expect(output).not.toContain("Installed T3 Code");
548 expect(await NodeFSP.readdir(versions)).toEqual([]);
549 }
550 } finally {
551 server.closeAllConnections();
552 await new Promise<void>((resolve) => server.close(() => resolve()));
553 await NodeFSP.rm(root, { recursive: true, force: true });
554 }
555 }
556 },
557 );
558});
559
560// regression: #38234
561describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("concurrent installers", () => {
562 it("publishes one runtime without nesting the other install's staging directory", async () => {
563 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-concurrent-"));
564 const version = "1.2.3";
565 const stem = `t3-${version}-linux-${HostProcess.Architecture.defaultValue()}`;
566 const archiveName = `${stem}.tar.gz`;
567 const target = NodePath.join(root, "home/runtime/versions", version);
568 const waiting = new Map<string, NodeHttp.ServerResponse>();
569 const server = NodeHttp.createServer();
570 try {
571 const tools = NodePath.join(root, "tools");
572 await NodeFSP.mkdir(tools);
573 await NodeFSP.mkdir(NodePath.join(root, stem));
574 await NodeFSP.writeFile(NodePath.join(root, stem, "t3"), "#!/bin/sh\necho 't3 v1.2.3'\n", {
575 mode: 0o755,
576 });
577 const archivePath = NodePath.join(root, archiveName);
578 NodeChildProcess.execFileSync("tar", ["-czf", archivePath, "-C", root, stem]);
579 const archive = await NodeFSP.readFile(archivePath);
580 const digest = NodeCrypto.createHash("sha256").update(archive).digest("hex");
581 server.on("request", (request, response) => {
582 if (request.url?.startsWith("/ready/")) {
583 waiting.set(request.url.slice(7), response);
584 if (waiting.size === 2) waiting.get("first")!.end("go");
585 } else if (request.url === "/published") {
586 waiting.get("second")!.end("go");
587 response.end("ok");
588 } else {
589 response.end(
590 request.url?.endsWith("/SHA256SUMS") ? `${digest} ${archiveName}\n` : archive,
591 );
592 }
593 });
594 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
595 const address = server.address();
596 if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
597 const origin = `http://127.0.0.1:${address.port}`;
598 const realMv = NodeChildProcess.execFileSync("sh", ["-c", "command -v mv"], {
599 encoding: "utf8",
600 }).trim();
601 // Hold publication until both installers have removed the destination, then let them rename in order.
602 const wrapper = NodePath.join(tools, "mv.mjs");
603 await NodeFSP.writeFile(
604 wrapper,
605 `
606import { execFileSync } from 'node:child_process';
607await fetch(process.env.T3_TEST_ORIGIN + '/ready/' + process.env.T3_TEST_INSTALLER);
608execFileSync(${JSON.stringify(realMv)}, process.argv.slice(2));
609if (process.env.T3_TEST_INSTALLER === 'first') await fetch(process.env.T3_TEST_ORIGIN + '/published');
610`,
611 );
612 await NodeFSP.writeFile(
613 NodePath.join(tools, "mv"),
614 `#!/bin/sh\nexec '${process.execPath}' '${wrapper}' "$@"\n`,
615 { mode: 0o755 },
616 );
617 const install = (id: string) =>
618 new Promise<{ code: number | null; output: string }>((resolve, reject) => {
619 const child = NodeChildProcess.spawn(
620 "sh",
621 [NodePath.join(import.meta.dirname, "install.sh")],
622 {
623 env: {
624 ...process.env,
625 PATH: `${tools}:${process.env.PATH}`,
626 T3CODE_VERSION: version,
627 T3CODE_HOME: NodePath.join(root, "home"),
628 T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin", id),
629 T3CODE_RELEASE_BASE_URL: origin,
630 T3_TEST_ORIGIN: origin,
631 T3_TEST_INSTALLER: id,
632 },
633 stdio: ["ignore", "pipe", "pipe"],
634 },
635 );
636 let output = "";
637 child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
638 child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
639 child.on("error", reject);
640 child.on("close", (code) => resolve({ code, output }));
641 });
642 const results = await Promise.all([install("first"), install("second")]);
643 for (const result of results) expect(result.code, result.output).toBe(0);
644 expect(
645 (await NodeFSP.readdir(target)).filter((name) => name.startsWith(".staging-")),
646 "concurrent installs must not leave a nested runtime",
647 ).toEqual([]);
648 } finally {
649 server.closeAllConnections();
650 await new Promise<void>((resolve) => server.close(() => resolve()));
651 await NodeFSP.rm(root, { recursive: true, force: true });
652 }
653 });
654});