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

DesktopCliCommand.ts

255 lines11.3 KB

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