Open History to see the last commit
1import type { DesktopCliCommandState } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9import * as ChildProcess from "effect/process/ChildProcess";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11
12import * as DesktopCliShim from "./DesktopCliShim.ts";
13import * as DesktopEnvironment from "./DesktopEnvironment.ts";
14
15export class DesktopCliCommandError extends Schema.TaggedError<DesktopCliCommandError>()(
16 "DesktopCliCommandError",
17 { message: Schema.String },
18) {}
19
20const unixCandidates = (home: string, platform: NodeJS.Platform) =>
21 platform === "darwin"
22 ? ["/opt/homebrew/bin", "/usr/local/bin", `${home}/.local/bin`, `${home}/bin`]
23 : [`${home}/.local/bin`, `${home}/bin`];
24
25const pathEntries = (value: string | undefined, separator: string) =>
26 (value ?? "").split(separator).filter((entry) => entry.length > 0);
27
28const sameWindowsPath = (left: string, right: string) =>
29 left.replace(/[\\/]+$/, "").toLowerCase() === right.replace(/[\\/]+$/, "").toLowerCase();
30
31// Preserve REG_EXPAND_SZ and %VAR% expansion; notify Explorer with WM_SETTINGCHANGE.
32// Failed reads must exit nonzero to prevent replacing PATH wholesale.
33const WINDOWS_USER_PATH_SCRIPT = `
34$ErrorActionPreference = 'Stop'
35if ($env:T3_SET -eq '1') {
36 $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
37 $kind = [Microsoft.Win32.RegistryValueKind]::ExpandString
38 if ($key.GetValueNames() -contains 'Path' -and $key.GetValueKind('Path') -eq 'String') {
39 $kind = [Microsoft.Win32.RegistryValueKind]::String
40 }
41 $key.SetValue('Path', $env:T3_PATH, $kind)
42 Add-Type -Namespace T3 -Name Env -MemberDefinition '[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern System.IntPtr SendMessageTimeout(System.IntPtr hWnd, uint Msg, System.UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out System.UIntPtr lpdwResult);'
43 $result = [System.UIntPtr]::Zero
44 [void][T3.Env]::SendMessageTimeout([System.IntPtr]0xffff, 0x1A, [System.UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result)
45} else {
46 $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
47 $value = if ($key) { $key.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } else { '' }
48 [Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([string]$value)))
49}
50`;
51
52export class DesktopCliCommand extends Context.Service<
53 DesktopCliCommand,
54 {
55 readonly state: Effect.Effect<DesktopCliCommandState>;
56 readonly install: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
57 readonly uninstall: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
58 }
59>()("@t3tools/desktop/app/DesktopCliCommand") {}
60
61/** @public */
62export const make = Effect.gen(function* () {
63 const environment = yield* DesktopEnvironment.DesktopEnvironment;
64 const fs = yield* FileSystem.FileSystem;
65 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
66 const path = environment.path;
67 const windows = environment.platform === "win32";
68 const launcher = DesktopCliShim.launcherPath(environment);
69 const binDirectory = path.dirname(launcher);
70 const ownedPathMarker = path.join(environment.stateDir, "cli-command-path-entry");
71
72 const fail = (message: string) => new DesktopCliCommandError({ message });
73 const exists = (target: string) => fs.exists(target).pipe(Effect.orElseSucceed(() => false));
74 const writableDirectory = (directory: string) =>
75 fs.access(directory, { writable: true }).pipe(
76 Effect.as(true),
77 Effect.orElseSucceed(() => false),
78 );
79
80 const isOurLink = Effect.fn("DesktopCliCommand.isOurLink")(
81 function* (link: string) {
82 yield* fs.readLink(link);
83 // The launcher is a few KB; never read a large binary another `t3` links to.
84 const info = yield* fs.stat(link);
85 if (info.type !== "File" || Number(info.size) > 16_384) return false;
86 const content = yield* fs.readFileString(link);
87 return content.includes(DesktopCliShim.MARKER);
88 },
89 Effect.orElseSucceed(() => false),
90 );
91
92 const powershell = (env: Record<string, string>) =>
93 Effect.scoped(
94 Effect.gen(function* () {
95 const root = process.env.SystemRoot ?? process.env.WINDIR;
96 const handle = yield* spawner.spawn(
97 ChildProcess.make(
98 root ? `${root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe` : "powershell.exe",
99 ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_USER_PATH_SCRIPT],
100 { stdin: "ignore", stderr: "ignore", env, extendEnv: true },
101 ),
102 );
103 const [stdout, exitCode] = yield* Effect.all(
104 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
105 { concurrency: "unbounded" },
106 );
107 if (exitCode !== 0) return yield* Effect.fail(`powershell exited with ${exitCode}`);
108 return stdout;
109 }),
110 );
111 const readUserPath = powershell({}).pipe(
112 Effect.map((encoded) => Buffer.from(encoded.trim(), "base64").toString("utf8")),
113 Effect.mapError(() => fail("Could not read your PATH, so it was left unchanged.")),
114 );
115 const writeUserPath = (value: string) =>
116 powershell({ T3_SET: "1", T3_PATH: value }).pipe(
117 Effect.asVoid,
118 Effect.mapError(() => fail("Could not update your PATH.")),
119 );
120
121 const firstOnPath = Effect.gen(function* () {
122 for (const directory of pathEntries(process.env.PATH, ":")) {
123 const candidate = path.join(directory, "t3");
124 if (yield* exists(candidate)) return Option.some(candidate);
125 }
126 return Option.none<string>();
127 });
128
129 const foreignFirstOnPath = Effect.gen(function* () {
130 if (windows) return Option.none<string>();
131 const first = yield* firstOnPath;
132 if (Option.isNone(first) || (yield* isOurLink(first.value))) return Option.none<string>();
133 return first;
134 });
135
136 const installedAt = Effect.gen(function* () {
137 if (windows) {
138 if (!(yield* exists(ownedPathMarker))) return Option.none<string>();
139 const entries = pathEntries(yield* readUserPath, ";");
140 return entries.some((entry) => sameWindowsPath(entry, binDirectory))
141 ? Option.some(launcher)
142 : Option.none<string>();
143 }
144 for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) {
145 const link = path.join(directory, "t3");
146 if (yield* isOurLink(link)) return Option.some(link);
147 }
148 return Option.none<string>();
149 });
150
151 const state: DesktopCliCommand["Service"]["state"] = Effect.gen(function* () {
152 if (!environment.isPackaged) {
153 return { supported: false, installedPath: null, onPath: false } as const;
154 }
155 const installed = yield* installedAt;
156 const shadowedBy = yield* foreignFirstOnPath;
157 const shadow = Option.isSome(shadowedBy) ? { shadowedBy: shadowedBy.value } : {};
158 if (Option.isNone(installed)) {
159 return { supported: true, installedPath: null, onPath: false, ...shadow };
160 }
161 const first = yield* firstOnPath;
162 const onPath = windows || (Option.isSome(first) && (yield* isOurLink(first.value)));
163 return { supported: true, installedPath: installed.value, onPath, ...shadow };
164 }).pipe(Effect.orElseSucceed(() => ({ supported: false, installedPath: null, onPath: false })));
165
166 const ensureLauncher = DesktopCliShim.install.pipe(
167 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
168 Effect.provideService(FileSystem.FileSystem, fs),
169 Effect.flatMap(
170 Option.match({
171 onNone: () => Effect.fail(fail(`Could not set up the t3 launcher at ${launcher}.`)),
172 onSome: () => Effect.void,
173 }),
174 ),
175 );
176
177 const install: DesktopCliCommand["Service"]["install"] = Effect.gen(function* () {
178 if (!environment.isPackaged) return yield* fail("The t3 command needs an installed app.");
179 yield* ensureLauncher;
180 if (windows) {
181 const entries = pathEntries(yield* readUserPath, ";");
182 if (!entries.some((entry) => sameWindowsPath(entry, binDirectory))) {
183 yield* writeUserPath([...entries, binDirectory].join(";"));
184 yield* fs
185 .writeFileString(ownedPathMarker, `${binDirectory}\n`)
186 .pipe(Effect.mapError(() => fail("Added t3 to your PATH but could not record it.")));
187 }
188 return yield* state;
189 }
190 const existing = yield* installedAt;
191 if (Option.isSome(existing)) {
192 const target = yield* fs.readLink(existing.value).pipe(Effect.option);
193 if (Option.getOrUndefined(target) === launcher) return yield* state;
194 yield* fs
195 .remove(existing.value)
196 .pipe(Effect.mapError(() => fail(`Could not replace ${existing.value}.`)));
197 }
198 const shadowedBy = yield* foreignFirstOnPath;
199 if (Option.isSome(shadowedBy)) {
200 return yield* fail(
201 `Another t3 at ${shadowedBy.value} runs first in a new terminal. Remove it, or run the launcher directly at ${launcher}.`,
202 );
203 }
204 const onPath = pathEntries(process.env.PATH, ":");
205 const candidates = unixCandidates(environment.homeDirectory, environment.platform);
206 for (const directory of [
207 ...candidates.filter((candidate) => onPath.includes(candidate)),
208 ...candidates.filter((candidate) => !onPath.includes(candidate)),
209 ]) {
210 const link = path.join(directory, "t3");
211 const created = (yield* exists(directory))
212 ? yield* writableDirectory(directory)
213 : yield* fs.makeDirectory(directory, { recursive: true }).pipe(
214 Effect.as(true),
215 Effect.orElseSucceed(() => false),
216 );
217 if (!created) continue;
218 const linked = yield* fs.symlink(launcher, link).pipe(
219 Effect.as(true),
220 Effect.orElseSucceed(() => false),
221 );
222 if (linked) return yield* state;
223 }
224 return yield* fail(
225 `Another t3 command is already installed, or no folder on your PATH is writable. Run the launcher directly at ${launcher}.`,
226 );
227 }).pipe(Effect.withSpan("desktop.cliCommand.install"));
228
229 const uninstall: DesktopCliCommand["Service"]["uninstall"] = Effect.gen(function* () {
230 if (windows) {
231 if (yield* exists(ownedPathMarker)) {
232 const entries = pathEntries(yield* readUserPath, ";");
233 const kept = entries.filter((entry) => !sameWindowsPath(entry, binDirectory));
234 if (kept.length !== entries.length) yield* writeUserPath(kept.join(";"));
235 yield* fs.remove(ownedPathMarker).pipe(Effect.ignore);
236 }
237 return yield* state;
238 }
239 for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) {
240 const link = path.join(directory, "t3");
241 if (yield* isOurLink(link)) {
242 yield* fs.remove(link).pipe(Effect.mapError(() => fail(`Could not remove ${link}.`)));
243 }
244 }
245 return yield* state;
246 }).pipe(Effect.withSpan("desktop.cliCommand.uninstall"));
247
248 return DesktopCliCommand.of({ state, install, uninstall });
249});
250
251export const layer = Layer.effect(DesktopCliCommand, make);