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, launcherPath: null } as const;
154 }
155 const launcherPath = (yield* exists(launcher)) ? launcher : null;
156 const installed = yield* installedAt;
157 const shadowedBy = yield* foreignFirstOnPath;
158 const shadow = Option.isSome(shadowedBy) ? { shadowedBy: shadowedBy.value } : {};
159 if (Option.isNone(installed)) {
160 return { supported: true, installedPath: null, onPath: false, launcherPath, ...shadow };
161 }
162 const first = yield* firstOnPath;
163 const onPath = windows || (Option.isSome(first) && (yield* isOurLink(first.value)));
164 return { supported: true, installedPath: installed.value, onPath, launcherPath, ...shadow };
165 }).pipe(
166 Effect.orElseSucceed(() => ({
167 supported: false,
168 installedPath: null,
169 onPath: false,
170 launcherPath: null,
171 })),
172 );
173
174 const ensureLauncher = DesktopCliShim.install.pipe(
175 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
176 Effect.provideService(FileSystem.FileSystem, fs),
177 Effect.flatMap(
178 Option.match({
179 onNone: () => Effect.fail(fail(`Could not set up the t3 launcher at ${launcher}.`)),
180 onSome: () => Effect.void,
181 }),
182 ),
183 );
184
185 const install: DesktopCliCommand["Service"]["install"] = Effect.gen(function* () {
186 if (!environment.isPackaged) return yield* fail("The t3 command needs an installed app.");
187 yield* ensureLauncher;
188 if (windows) {
189 const entries = pathEntries(yield* readUserPath, ";");
190 if (!entries.some((entry) => sameWindowsPath(entry, binDirectory))) {
191 yield* writeUserPath([...entries, binDirectory].join(";"));
192 yield* fs
193 .writeFileString(ownedPathMarker, `${binDirectory}\n`)
194 .pipe(Effect.mapError(() => fail("Added t3 to your PATH but could not record it.")));
195 }
196 return yield* state;
197 }
198 const existing = yield* installedAt;
199 if (Option.isSome(existing)) {
200 const target = yield* fs.readLink(existing.value).pipe(Effect.option);
201 if (Option.getOrUndefined(target) === launcher) return yield* state;
202 yield* fs
203 .remove(existing.value)
204 .pipe(Effect.mapError(() => fail(`Could not replace ${existing.value}.`)));
205 }
206 const shadowedBy = yield* foreignFirstOnPath;
207 if (Option.isSome(shadowedBy)) {
208 return yield* fail(
209 `Another t3 at ${shadowedBy.value} runs first in a new terminal. Remove it, or run the launcher directly at ${launcher}.`,
210 );
211 }
212 const onPath = pathEntries(process.env.PATH, ":");
213 const candidates = unixCandidates(environment.homeDirectory, environment.platform);
214 for (const directory of [
215 ...candidates.filter((candidate) => onPath.includes(candidate)),
216 ...candidates.filter((candidate) => !onPath.includes(candidate)),
217 ]) {
218 const link = path.join(directory, "t3");
219 const created = (yield* exists(directory))
220 ? yield* writableDirectory(directory)
221 : yield* fs.makeDirectory(directory, { recursive: true }).pipe(
222 Effect.as(true),
223 Effect.orElseSucceed(() => false),
224 );
225 if (!created) continue;
226 const linked = yield* fs.symlink(launcher, link).pipe(
227 Effect.as(true),
228 Effect.orElseSucceed(() => false),
229 );
230 if (linked) return yield* state;
231 }
232 return yield* fail(
233 `Another t3 command is already installed, or no folder on your PATH is writable. Run the launcher directly at ${launcher}.`,
234 );
235 }).pipe(Effect.withSpan("desktop.cliCommand.install"));
236
237 const uninstall: DesktopCliCommand["Service"]["uninstall"] = Effect.gen(function* () {
238 if (windows) {
239 if (yield* exists(ownedPathMarker)) {
240 const entries = pathEntries(yield* readUserPath, ";");
241 const kept = entries.filter((entry) => !sameWindowsPath(entry, binDirectory));
242 if (kept.length !== entries.length) yield* writeUserPath(kept.join(";"));
243 yield* fs.remove(ownedPathMarker).pipe(Effect.ignore);
244 }
245 return yield* state;
246 }
247 for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) {
248 const link = path.join(directory, "t3");
249 if (yield* isOurLink(link)) {
250 yield* fs.remove(link).pipe(Effect.mapError(() => fail(`Could not remove ${link}.`)));
251 }
252 }
253 return yield* state;
254 }).pipe(Effect.withSpan("desktop.cliCommand.uninstall"));
255
256 return DesktopCliCommand.of({ state, install, uninstall });
257});
258
259export const layer = Layer.effect(DesktopCliCommand, make);