Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as TestClock from "effect/testing/TestClock";
10
11import packageJson from "../../package.json" with { type: "json" };
12import { installCli, isForegroundProcStat, isForegroundPs, offerCliInstall } from "./install.ts";
13
14const VERSION = packageJson.version;
15
16/** A standalone runtime in a temp T3 home, started by the npm launcher from an npx cache. */
17const setup = Effect.gen(function* () {
18 const fs = yield* FileSystem.FileSystem;
19 const path = yield* Path.Path;
20 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-install-" });
21 const runtimeDir = path.join(root, ".t3/runtime");
22 const executable = path.join(runtimeDir, "versions", VERSION, "t3");
23 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
24 yield* fs.writeFileString(executable, "");
25 const npmPackage = path.join(root, ".npm/_npx/abc/node_modules/t3");
26 yield* fs.makeDirectory(path.join(npmPackage, "bin"), { recursive: true });
27 yield* fs.writeFileString(
28 path.join(npmPackage, "package.json"),
29 JSON.stringify({ name: "t3", version: VERSION }),
30 );
31 const binDir = path.join(root, "bin");
32 const provide = <A, E, R>(effect: Effect.Effect<A, E, R>, env: NodeJS.ProcessEnv = {}) =>
33 effect.pipe(
34 Effect.provideService(HostProcess.Platform, "linux"),
35 Effect.provideService(HostProcess.HomeDirectory, root),
36 Effect.provideService(HostProcess.IsExecutable, true),
37 Effect.provideService(HostProcess.ExecutablePath, executable),
38 Effect.provideService(HostProcess.Environment, {
39 PATH: "/usr/bin",
40 SHELL: "/bin/zsh",
41 T3CODE_INSTALL_BIN_DIR: binDir,
42 T3CODE_NPM_LAUNCHER_PATH: path.join(npmPackage, "bin/t3.mjs"),
43 ...env,
44 }),
45 );
46 return { root, npmPackage, runtimeDir, executable, link: path.join(binDir, "t3"), provide };
47});
48
49it.layer(NodeServices.layer)("t3 install", (it) => {
50 it.effect("links the running runtime, records it, and never replaces another t3", () =>
51 Effect.gen(function* () {
52 const fs = yield* FileSystem.FileSystem;
53 const path = yield* Path.Path;
54 const { root, runtimeDir, executable, link, provide } = yield* setup;
55
56 const older = path.join(runtimeDir, "versions/0.0.1/t3");
57 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
58 yield* fs.symlink(older, link);
59 const installed = yield* provide(installCli());
60 assert.equal(yield* fs.readLink(link), executable);
61 assert.isFalse(installed.onPath);
62 assert.include(installed.pathCommand, "$HOME/bin");
63
64 // A link written through a symlinked T3 home is still ours.
65 const alias = path.join(root, "alias");
66 yield* fs.symlink(path.join(root, ".t3"), alias);
67 yield* fs.remove(link);
68 yield* fs.symlink(path.join(alias, "runtime/versions", VERSION, "t3"), link);
69 const onPath = yield* provide(installCli(), { PATH: `/usr/bin:${path.join(root, "bin")}/` });
70 assert.isTrue(onPath.onPath);
71 // Another t3 earlier on PATH still runs first, so `t3` would not run this one.
72 const otherBin = path.join(root, "other-bin");
73 yield* fs.makeDirectory(otherBin);
74 yield* fs.writeFileString(path.join(otherBin, "t3"), "");
75 const shadowed = yield* provide(installCli(), {
76 PATH: `${otherBin}:${path.join(root, "bin")}`,
77 });
78 assert.isFalse(shadowed.onPath);
79 assert.equal(shadowed.shadowedBy, path.join(otherBin, "t3"));
80 assert.isUndefined(shadowed.pathCommand);
81 const recorded = yield* fs.readFileString(path.join(runtimeDir, "launchers"));
82 assert.equal(recorded, `\n${yield* fs.realPath(path.join(root, "bin"))}/t3\n`);
83
84 yield* fs.remove(link);
85 yield* fs.writeFileString(link, "#!/bin/sh\n");
86 const error = yield* provide(installCli()).pipe(Effect.flip);
87 assert.include(error.message, "Another t3 is already at");
88 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\n");
89
90 // Only `<version>/t3` is ours, not another program inside a version.
91 yield* fs.remove(link);
92 yield* fs.symlink(path.join(runtimeDir, "versions/0.0.1/node"), link);
93 const sibling = yield* provide(installCli()).pipe(Effect.flip);
94 assert.include(sibling.message, "Another t3 is already at");
95 // This home's desktop launcher is replaced, as install.sh does.
96 yield* fs.remove(link);
97 yield* fs.symlink(path.join(root, ".t3/bin/t3"), link);
98 yield* provide(installCli());
99 assert.equal(yield* fs.readLink(link), executable);
100
101 // A failed swap over our own link leaves a staging path it did not create alone.
102 yield* fs.remove(link);
103 yield* fs.symlink(older, link);
104 const staging = `${link}.${process.pid}.tmp`;
105 yield* fs.writeFileString(staging, "someone else's\n");
106 const linkFailed = yield* provide(installCli()).pipe(Effect.flip);
107 assert.include(linkFailed.message, "Could not link");
108 assert.equal(yield* fs.readFileString(staging), "someone else's\n");
109 yield* fs.remove(staging);
110
111 // An empty spot is created exclusively: a file that appears first is kept.
112 yield* fs.remove(link);
113 const racing = installCli().pipe(
114 Effect.provideService(FileSystem.FileSystem, {
115 ...fs,
116 symlink: (target, path) =>
117 fs
118 .writeFileString(path, "#!/bin/sh\necho raced\n")
119 .pipe(Effect.andThen(fs.symlink(target, path))),
120 }),
121 );
122 assert.include((yield* provide(racing).pipe(Effect.flip)).message, "Could not link");
123 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\necho raced\n");
124 yield* fs.remove(link);
125
126 // Windows writes a t3.cmd: only over its own, and only for paths cmd can run.
127 const shim = path.join(root, "bin", "t3.cmd");
128 const windows = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
129 provide(effect.pipe(Effect.provideService(HostProcess.Platform, "win32")));
130 const desktopShim =
131 '@echo off\r\nrem Written by T3 Code\r\n"C:\\T3 Code\\T3 Code.exe" "x" %*\r\n';
132 yield* fs.writeFileString(shim, desktopShim);
133 const foreignShim = yield* windows(installCli()).pipe(Effect.flip);
134 assert.include(foreignShim.message, "Another t3 is already at");
135 assert.equal(yield* fs.readFileString(shim), desktopShim);
136 // A user's wrapper that also runs a managed t3.exe is still theirs.
137 const wrapper = `@echo off\r\nset FOO=1\r\n"${path.join(runtimeDir, "versions/0.0.1/t3.exe")}" %*`;
138 yield* fs.writeFileString(shim, wrapper);
139 yield* windows(installCli()).pipe(Effect.flip);
140 assert.equal(yield* fs.readFileString(shim), wrapper);
141 // A dangling symlink is not free; writing through it would land outside the bin folder.
142 const elsewhere = path.join(root, "elsewhere.cmd");
143 yield* fs.remove(shim);
144 yield* fs.symlink(elsewhere, shim);
145 yield* windows(installCli()).pipe(Effect.flip);
146 assert.isFalse(yield* fs.exists(elsewhere));
147 yield* fs.remove(shim);
148 yield* fs.writeFileString(
149 shim,
150 `@echo off\r\n"${path.join(runtimeDir, "versions/0.0.1/t3.exe")}" %*`,
151 );
152 const windowsInstalled = yield* windows(installCli());
153 assert.equal(yield* fs.readFileString(shim), `@echo off\r\n"${executable}" %*`);
154 // A PowerShell command for this window; the saved PATH is left to the user.
155 assert.equal(windowsInstalled.pathCommand, `$env:Path += ';${path.join(root, "bin")}'`);
156 const unrunnable = yield* windows(
157 installCli().pipe(
158 Effect.provideService(
159 HostProcess.ExecutablePath,
160 path.join(runtimeDir, "versions/100%/t3"),
161 ),
162 ),
163 ).pipe(Effect.flip);
164 assert.include(unrunnable.message, "has % or non-ASCII characters");
165 }).pipe(Effect.scoped),
166 );
167
168 it.effect("asks npx users without a t3 command once per minor release and installs on yes", () =>
169 Effect.gen(function* () {
170 const fs = yield* FileSystem.FileSystem;
171 const path = yield* Path.Path;
172 const { root, npmPackage, runtimeDir, executable, link, provide } = yield* setup;
173 let asked = 0;
174 const offer = (
175 answer: boolean | undefined | Effect.Effect<boolean>,
176 options: {
177 readonly args?: ReadonlyArray<string>;
178 readonly env?: NodeJS.ProcessEnv;
179 readonly interactive?: boolean;
180 readonly foreground?: boolean;
181 } = {},
182 ) =>
183 provide(
184 offerCliInstall({
185 args: options.args ?? ["connect"],
186 interactive: options.interactive ?? true,
187 foreground: Effect.succeed(options.foreground ?? true),
188 confirm: Effect.andThen(
189 Effect.sync(() => (asked += 1)),
190 Effect.isEffect(answer) ? answer : Effect.succeed(answer),
191 ),
192 }),
193 options.env,
194 );
195
196 // Scripts, CI, sudo, dumb terminals, background jobs, and help never ask.
197 yield* offer(false, { interactive: false });
198 yield* offer(false, { env: { CI: "true" } });
199 yield* offer(false, { env: { SUDO_USER: "theo" } });
200 yield* offer(false, { env: { TERM: "dumb" } });
201 yield* offer(false, { env: { npm_config_yes: "true" } });
202 yield* offer(false, { args: ["--completions", "zsh"] });
203 yield* offer(false, { foreground: false });
204 yield* offer(false, { args: ["connect", "--help"] });
205 yield* offer(false, { args: ["--log-level", "debug", "install"] });
206 yield* offer(false, { args: ["status", "--json"] });
207 yield* offer(false, { args: ["up", "--yes"] });
208 yield* offer(false, { args: ["status", "--json=true"] });
209 const globalBin = path.join(root, "global-bin");
210 yield* fs.makeDirectory(globalBin);
211 yield* fs.writeFileString(path.join(globalBin, "t3"), "");
212 yield* offer(false, { env: { PATH: globalBin } });
213 assert.equal(asked, 0);
214 assert.isFalse(yield* fs.exists(link));
215
216 // A runner's own .bin on PATH is not an installed t3.
217 const npxBin = path.join(npmPackage, "../.bin");
218 const pnpmBin = path.join(root, ".cache/pnpm/dlx/abc/node_modules/.bin");
219 for (const bin of [npxBin, pnpmBin]) {
220 yield* fs.makeDirectory(bin, { recursive: true });
221 yield* fs.writeFileString(path.join(bin, "t3"), "");
222 }
223 assert.isFalse(yield* offer(undefined, { env: { PATH: `${npxBin}:${pnpmBin}` } }));
224 assert.equal(asked, 1);
225 assert.isFalse(yield* fs.exists(path.join(runtimeDir, "install-prompt-declined")));
226 asked = 0;
227
228 // `service install` is not `t3 install`; it still leaves the command unlinked.
229 yield* offer(false, { args: ["service", "install"] });
230 assert.equal(asked, 1);
231 yield* offer(false);
232 assert.equal(asked, 1);
233 assert.isFalse(yield* fs.exists(link));
234
235 yield* fs.writeFileString(path.join(runtimeDir, "install-prompt-declined"), "0.0\n");
236 yield* offer(true);
237 assert.equal(asked, 2);
238 assert.equal(yield* fs.readLink(link), executable);
239
240 yield* fs.remove(path.join(runtimeDir, "install-prompt-declined"));
241 yield* offer(true);
242 assert.equal(asked, 2);
243
244 // A yes that cannot install, and no answer at all, also wait for the next minor release.
245 const declined = path.join(runtimeDir, "install-prompt-declined");
246 yield* fs.remove(link);
247 yield* fs.remove(path.join(runtimeDir, "launchers"));
248 yield* fs.writeFileString(link, "#!/bin/sh\necho mine\n");
249 asked = 0;
250 assert.isTrue(yield* offer(true));
251 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\necho mine\n");
252 assert.equal(
253 (yield* fs.readFileString(declined)).trim(),
254 VERSION.split(".").slice(0, 2).join("."),
255 );
256 yield* offer(true);
257 assert.equal(asked, 1);
258
259 yield* fs.remove(declined);
260 yield* fs.remove(link);
261 const waiting = yield* Deferred.make<void>();
262 const unanswered = yield* offer(
263 Effect.andThen(Deferred.succeed(waiting, undefined), Effect.never),
264 ).pipe(Effect.forkChild);
265 yield* Deferred.await(waiting);
266 yield* TestClock.adjust("30 seconds");
267 assert.isTrue(yield* Fiber.join(unanswered));
268 assert.isTrue(yield* fs.exists(declined));
269 assert.isFalse(yield* fs.exists(link));
270 }).pipe(Effect.scoped),
271 );
272
273 it.effect("reads the terminal's foreground group from /proc and ps", () =>
274 Effect.sync(() => {
275 // The command name can hold spaces and parentheses.
276 const stat = (pgrp: number, tpgid: number) =>
277 `4242 (t3 (serve) x) S 100 ${pgrp} 100 34816 ${tpgid} 4194560 0 0`;
278 assert.isTrue(isForegroundProcStat(stat(4242, 4242)));
279 assert.isFalse(isForegroundProcStat(stat(4242, 4300)));
280 assert.isFalse(isForegroundProcStat(stat(4242, -1)));
281 assert.isFalse(isForegroundProcStat(""));
282 assert.isTrue(isForegroundPs(" 4242 4242\n"));
283 assert.isFalse(isForegroundPs(" 4300 4242\n"));
284 assert.isFalse(isForegroundPs(" -1 4242\n"));
285 assert.isFalse(isForegroundPs(""));
286 }),
287 );
288});