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

install.ts

391 lines16.1 KB

1import * as HostProcess from "@t3tools/shared/HostProcess";
2import { pathSetupCommand, resolveCommandPath } from "@t3tools/shared/shell";
3import * as Console from "effect/Console";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import { Command, Prompt } from "effect/cli";
11import * as ChildProcess from "effect/process/ChildProcess";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13​
14import packageJson from "../../package.json" with { type: "json" };
15import {
16 generatedWindowsShimTarget,
17 isVersionExecutable,
18 readPosixLauncherTarget,
19 recordPinnedRuntimeLauncher,
20 writePosixLauncher,
21} from "../cloud/pinnedRuntime.ts";
22import {
23 detectCliRunner,
24 hostShellWord,
25 resolveCliCommand,
26 resolveEntryPath,
27} from "./invocation.ts";
28​
29export class CliInstallError extends Schema.TaggedError<CliInstallError>()("CliInstallError", {
30 reason: Schema.String,
31 cause: Schema.optional(Schema.Defect()),
32}) {
33 override get message(): string {
34 return this.reason;
35 }
37​
38/** `<T3 home>/runtime/versions/<version>/t3`: the layout the install scripts and npm launcher share. */
39const standaloneRuntime = Effect.gen(function* () {
40 const path = yield* Path.Path;
41 if (!(yield* HostProcess.IsExecutable)) return Option.none();
42 const executable = yield* HostProcess.ExecutablePath;
43 const versionsDir = path.dirname(path.dirname(executable));
44 const runtimeDir = path.dirname(versionsDir);
45 if (path.basename(versionsDir) !== "versions" || path.basename(runtimeDir) !== "runtime") {
46 return Option.none();
47 }
48 return Option.some({ executable, versionsDir, runtimeDir });
49});
50​
51/** Installs this runtime as the `t3` command the way the install scripts do, replacing only our own launcher. */
52export const installCli = Effect.fn("cli.install.install")(function* () {
53 const fs = yield* FileSystem.FileSystem;
54 const path = yield* Path.Path;
55 const platform = yield* HostProcess.Platform;
56 const environment = yield* HostProcess.Environment;
57 const home = yield* HostProcess.HomeDirectory;
58 const runtime = yield* standaloneRuntime;
59 const windows = platform === "win32";
60 if (Option.isNone(runtime)) {
61 const script = windows
62 ? "irm https://t3.codes/install.ps1 | iex"
63 : "curl -fsSL https://t3.codes/install.sh | sh";
64 return yield* new CliInstallError({
65 reason: `Only the standalone t3 can install itself. Use \`${script}\`, or Settings in the desktop app.`,
66 });
67 }
68 const { executable, versionsDir, runtimeDir } = runtime.value;
69 // cmd.exe expands `%` and reads the shim in the OEM code page, so such a path would not run.
70 if (windows && /[%\u0080-\uffff]/.test(executable)) {
71 return yield* new CliInstallError({
72 reason: `A t3.cmd cannot run ${executable}, because the path has % or non-ASCII characters. Keep using npx t3.`,
73 });
74 }
75 // Absolute, so the PATH hint never adds a folder that changes with the working directory.
76 const binDir = path.resolve(
77 environment.T3CODE_INSTALL_BIN_DIR?.trim() || path.join(home, ".local", "bin"),
78 );
79 const name = windows ? "t3.cmd" : "t3";
80 const link = path.join(binDir, name);
81 const failed = (reason: string) => (cause: unknown) => new CliInstallError({ reason, cause });
82​
83 // Resolve fully so a link through a symlinked T3 home still counts as ours; a dangling one
84 // (a pruned version) falls back to its own text.
85 const realVersionsDir = yield* fs
86 .realPath(versionsDir)
87 .pipe(Effect.orElseSucceed(() => versionsDir));
88 const current = windows
89 ? yield* fs.readFileString(link).pipe(Effect.map(generatedWindowsShimTarget), Effect.option)
90 : yield* fs.readLink(link).pipe(
91 Effect.flatMap((target) =>
92 fs.realPath(link).pipe(Effect.orElseSucceed(() => path.resolve(binDir, target))),
93 ),
94 // Not a link: the script this command and the install scripts write.
95 Effect.catch(() => readPosixLauncherTarget(link)),
96 Effect.option,
97 Effect.map(Option.filter((target) => target !== undefined)),
98 );
99 // A dangling symlink is occupied too: writing the shim would follow it.
100 const occupied =
101 Option.isSome(current) ||
102 (yield* fs.exists(link)) ||
103 Option.isSome(yield* fs.readLink(link).pipe(Effect.option));
104 if (
105 occupied &&
106 !(
107 Option.isSome(current) &&
108 current.value !== undefined &&
109 (isVersionExecutable(path, versionsDir, current.value) ||
110 isVersionExecutable(path, realVersionsDir, current.value) ||
111 // This home's desktop launcher, which install.sh also replaces.
112 current.value === path.join(path.dirname(runtimeDir), "bin", name))
113 )
114 ) {
115 return yield* new CliInstallError({
116 reason: `Another t3 is already at ${link}. Remove it, then run this again.`,
117 });
118 }
119​
120 yield* fs
121 .makeDirectory(binDir, { recursive: true })
122 .pipe(Effect.mapError(failed(`Could not create ${binDir}.`)));
123 // An empty spot is created exclusively, so a file that appears after the check above is kept.
124 if (windows) {
125 yield* fs
126 .writeFileString(link, `@echo off\r\n"${executable}" %*`, occupied ? {} : { flag: "wx" })
127 .pipe(Effect.mapError(failed(`Could not write ${link}.`)));
128 } else {
129 yield* writePosixLauncher({ launcher: link, executable, exclusive: !occupied }).pipe(
130 Effect.mapError(failed(`Could not write ${link}.`)),
131 );
132 }
133​
134 // Pruning keeps what recorded launchers point at; a background service cannot see binDir otherwise.
135 const recorded = path.join(
136 yield* fs.realPath(binDir).pipe(Effect.orElseSucceed(() => binDir)),
137 name,
138 );
139 yield* recordPinnedRuntimeLauncher({
140 baseDir: path.dirname(runtimeDir),
141 launcher: recorded,
142 }).pipe(
143 Effect.catch(() =>
144 Console.error(
145 `Warning: could not record ${recorded} in ${path.join(runtimeDir, "launchers")}. Cleanup may remove the version it runs.`,
146 ),
147 ),
148 );
149​
150 // resolve() drops trailing separators, so `~/.local/bin/` on PATH still matches.
151 const normalize = (value: string) =>
152 windows ? path.resolve(value).toLowerCase() : path.resolve(value);
153 const same = (entry: string) => entry !== "" && normalize(entry) === normalize(binDir);
154 const rawPath = environment.PATH ?? environment.Path ?? "";
155 const entries = rawPath === "" ? [] : rawPath.split(windows ? ";" : ":");
156 let cwd = yield* Effect.catchDefect(HostProcess.WorkingDirectory, () => Effect.undefined);
157 // A t3 earlier on PATH runs instead, and an added folder goes last. Runner caches (npx's own
158 // .bin) are not installs.
159 const firstOther = Effect.gen(function* () {
160 for (const entry of entries) {
161 const absolute = path.isAbsolute(entry);
162 if ((windows || absolute) && same(entry)) return null;
163 const dir = absolute ? entry : windows || !cwd ? undefined : path.resolve(cwd, entry);
164 if (dir === undefined || detectCliRunner(`${dir}/`) !== null) continue;
165 for (const name of windows ? ["t3.cmd", "t3.exe"] : ["t3"]) {
166 const candidate = path.join(dir, name);
167 if (!(yield* resolveCommandPath(candidate, { env: environment }))) continue;
168 if (windows) return candidate;
169 const resolved = yield* fs.realPath(candidate).pipe(Effect.orElseSucceed(() => candidate));
170 if (normalize(resolved) !== normalize(recorded)) return candidate;
171 if (absolute) return null;
172 cwd = undefined; // Ours already won in cwd; later relative entries lose.
173 }
174 }
175 return undefined;
176 });
177 // null: this launcher runs first; a path: another t3 does; undefined: no t3 on PATH.
178 const found = yield* firstOther;
179 return {
180 link,
181 onPath: found === null,
182 shadowedBy: found ?? undefined,
183 pathCommand:
184 found !== undefined
185 ? undefined
186 : windows
187 ? // PowerShell; it covers this window only, since changing the saved PATH would flatten
188 // its %VAR% entries. A `;` would split the folder.
189 binDir.includes(";")
190 ? undefined
191 : `$env:Path += ';${binDir.replaceAll("'", "''")}'`
192 : pathSetupCommand({
193 directory: binDir,
194 home,
195 shell: environment.SHELL,
196 platform,
197 configHome: environment.XDG_CONFIG_HOME,
198 zdotdir: environment.ZDOTDIR,
199 }),
200 binDir,
201 };
202});
203​
204const reportInstalled = Effect.fn("cli.install.report")(function* (
205 installed: Effect.Success<ReturnType<typeof installCli>>,
206) {
207 yield* Console.log(`Installed t3 ${packageJson.version} at ${installed.link}.`);
208 if (installed.shadowedBy !== undefined) {
209 const platform = yield* HostProcess.Platform;
210 // Command Prompt and PowerShell share no quoted form, so Windows keeps the bare path.
211 const launcher =
212 platform === "win32" ? installed.link : hostShellWord(platform, installed.link);
213 return yield* Console.log(
214 `Another t3 at ${installed.shadowedBy} runs first, so run ${launcher} to use this one.`,
215 );
216 }
217 if (installed.onPath) return yield* Console.log("Run `t3` to get started.");
218 if (installed.pathCommand === undefined) {
219 return yield* Console.log(`Add ${installed.binDir} to your PATH, then run \`t3\`.`);
220 }
221 if ((yield* HostProcess.Platform) === "win32") {
222 yield* Console.log(
223 `${installed.binDir} is not on your PATH yet. In this PowerShell window, run:`,
224 );
225 yield* Console.log(` ${installed.pathCommand}`);
226 return yield* Console.log("Then run `t3`. For new windows, add the folder to your PATH.");
227 }
228 yield* Console.log(`${installed.binDir} is not on your PATH yet. Add it with:`);
229 yield* Console.log(` ${installed.pathCommand}`);
230 yield* Console.log("Then open a new terminal and run `t3`.");
231});
232​
233export const installCommand = Command.make("install").pipe(
234 Command.withDescription("Install this version as the `t3` command."),
235 Command.withHandler(() => installCli().pipe(Effect.flatMap(reportInstalled))),
236);
237​
238/** Saying no lasts until the next minor release: `0.2` covers `0.2.5` and `0.2.6-nightly.…`. */
239const minorRelease = (version: string) => version.split(".").slice(0, 2).join(".");
240​
241const SKIPPED_ARGUMENTS = new Set([
242 "help",
243 "--help",
244 "-h",
245 "--version",
246 "-v",
247 "--completions",
248 // Scripts and machine-readable output; a prompt would stall them or corrupt their output.
249 "--json",
250 "--yes",
251 "-y",
252]);
253​
254/** The subcommand, past global flags that may come first (two take a value). */
255const topLevelCommand = (args: ReadonlyArray<string>) => {
256 for (let index = 0; index < args.length; index++) {
257 const arg = args[index]!;
258 if (arg === "--log-level" || arg === "--completions") index++;
259 else if (!arg.startsWith("-")) return arg;
260 }
261 return undefined;
262};
263​
264/** Agents can run commands in a terminal that nobody answers; no answer counts as no. */
265const PROMPT_TIMEOUT = Duration.seconds(30);
266​
267/** `/proc/<pid>/stat` fields after the parenthesized command name: state ppid pgrp session tty_nr tpgid. */
268export const isForegroundProcStat = (stat: string) => {
269 const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
270 return fields[2] !== undefined && fields[2] !== "" && fields[2] === fields[5];
271};
272​
273/** Output of `ps -o tpgid=,pgid=`; tpgid is -1 without a controlling terminal. */
274export const isForegroundPs = (output: string) => {
275 const [tpgid, pgid] = output.trim().split(/\s+/);
276 return tpgid !== undefined && tpgid !== "" && tpgid === pgid;
277};
278​
279/**
280 * A background job (`npx t3 serve &`) that reads the terminal is stopped by the shell, so only
281 * the terminal's foreground process group may prompt. Unknown counts as background.
282 */
283export const inTerminalForeground = Effect.gen(function* () {
284 const fs = yield* FileSystem.FileSystem;
285 const platform = yield* HostProcess.Platform;
286 if (platform === "win32") return true;
287 if (platform === "linux") {
288 return isForegroundProcStat(
289 yield* fs.readFileString("/proc/self/stat").pipe(Effect.orElseSucceed(() => "")),
290 );
291 }
292 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
293 return isForegroundPs(
294 yield* spawner
295 .string(
296 // Absolute: under npx, PATH starts with a project's node_modules/.bin.
297 ChildProcess.make("/bin/ps", ["-o", "tpgid=,pgid=", "-p", String(process.pid)], {
298 stdin: "ignore",
299 stderr: "ignore",
300 }),
301 )
302 .pipe(Effect.orElseSucceed(() => "")),
303 );
304});
305​
306/**
307 * Before a command run through npx, pnpm dlx, or bunx at a terminal, asks to install the `t3`
308 * command. Yes is the default. No, no answer, or a failed install is saved in the T3 home until
309 * the next minor release. Returns false when the user quits the prompt, so the command does not run.
310 */
311export const offerCliInstall = Effect.fn("cli.install.offer")(function* <E, R, E2, R2>(input: {
312 readonly args: ReadonlyArray<string>;
313 readonly interactive: boolean;
314 readonly foreground: Effect.Effect<boolean, E2, R2>;
315 /** Undefined when the user quits the prompt. */
316 readonly confirm: Effect.Effect<boolean | void, E, R>;
317}) {
318 const fs = yield* FileSystem.FileSystem;
319 const path = yield* Path.Path;
320 const platform = yield* HostProcess.Platform;
321 const environment = yield* HostProcess.Environment;
322 if (!input.interactive || environment.CI || environment.SUDO_USER) return true;
323 if (environment.TERM === "dumb") return true;
324 // `npx --yes` asks for no prompts; npm passes it on to the command as npm_config_yes.
325 if (environment.npm_config_yes === "true") return true;
326 // `--json=true` and `-y=true` are the same flags.
327 if (input.args.some((arg) => SKIPPED_ARGUMENTS.has(arg.split("=")[0]!))) return true;
328 const command = topLevelCommand(input.args);
329 if (command === "install" || command === "uninstall") return true;
330 if (detectCliRunner(yield* resolveEntryPath) === null) return true;
331 const runtime = yield* standaloneRuntime;
332 if (Option.isNone(runtime)) return true;
333 const { runtimeDir } = runtime.value;
334​
335 // Any t3 already installed means no prompt: ours (even when off PATH) or another on PATH.
336 // Runners put their own cache's node_modules/.bin on PATH, so skip those.
337 const windows = platform === "win32";
338 const names = windows ? ["t3.cmd", "t3.exe"] : ["t3"];
339 const launchers = yield* fs
340 .readFileString(path.join(runtimeDir, "launchers"))
341 .pipe(Effect.orElseSucceed(() => ""));
342 const candidates = [
343 ...launchers.split(/\r?\n/).filter((launcher) => path.isAbsolute(launcher)),
344 path.join(path.dirname(runtimeDir), "bin", windows ? "t3.cmd" : "t3"),
345 ...(environment.PATH ?? environment.Path ?? "")
346 .split(windows ? ";" : ":")
347 .filter(
348 (directory) => path.isAbsolute(directory) && detectCliRunner(`${directory}/`) === null,
349 )
350 .flatMap((directory) => names.map((name) => path.join(directory, name))),
351 ];
352 for (const candidate of candidates) {
353 if (yield* resolveCommandPath(candidate, { env: environment })) return true;
354 }
355​
356 const declinedFile = path.join(runtimeDir, "install-prompt-declined");
357 const declined = yield* fs.readFileString(declinedFile).pipe(Effect.orElseSucceed(() => ""));
358 const minor = minorRelease(packageJson.version);
359 if (declined.trim() === minor) return true;
360 if (!(yield* input.foreground)) return true;
361​
362 const installHint = `Run \`${yield* resolveCliCommand("install")}\` any time.`;
363 const saveDecline = fs.writeFileString(declinedFile, `${minor}\n`).pipe(Effect.ignore);
364 const answer = yield* input.confirm.pipe(Effect.timeoutOption(PROMPT_TIMEOUT));
365 if (Option.isNone(answer)) {
366 yield* saveDecline;
367 yield* Console.log(`\nNo answer, so t3 was not installed. ${installHint}\n`);
368 return true;
369 }
370 if (answer.value === undefined) return false;
371 if (!answer.value) {
372 yield* saveDecline;
373 yield* Console.log(`Skipped. ${installHint}\n`);
374 return true;
375 }
376 yield* installCli().pipe(
377 Effect.flatMap(reportInstalled),
378 Effect.catch((error) =>
379 Effect.andThen(saveDecline, Console.error(`Could not install t3: ${error.message}`)),
380 ),
381 );
382 yield* Console.log("");
383 return true;
384});
385​
386export const confirmCliInstall = Prompt.run(
387 Prompt.Confirm({
388 message: "Install the t3 command? Then you can run `t3` directly.",
389 initial: true,
390 }),
391).pipe(Effect.catchTags({ QuitError: () => Effect.void }));