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

DesktopCliShim.ts

173 lines7.0 KB

1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5​
6import * as DesktopEnvironment from "./DesktopEnvironment.ts";
7import { makeComponentLogger } from "./DesktopObservability.ts";
8​
9// An AppImage mounts somewhere new each run, so its launcher mounts the
10// AppImage itself instead of pointing into it.
11const { logInfo, logWarning } = makeComponentLogger("desktop-cli-shim");
12​
13export const MARKER = "Written by T3 Code: runs the desktop app's bundled t3 CLI.";
14​
15const SERVER_ENTRY = "apps/server/dist/bin.mjs";
16​
17const shellWord = (value: string) => `'${value.replaceAll("'", `'"'"'`)}'`;
18/** cmd.exe expands `%` even inside quotes; Windows paths cannot contain `"`. */
19const cmdText = (value: string) => value.replaceAll("%", "%%");
20const cmdWord = (value: string) => `"${cmdText(value)}"`;
21​
22const MOVED = "T3 Code has moved or been removed. Open the app once to update this command.";
23​
24export type CliShimTarget =
25 | { readonly kind: "appimage"; readonly appImage: string; readonly executableName: string }
26 | { readonly kind: "direct"; readonly executable: string; readonly entry: string }
27 | { readonly kind: "windows"; readonly executable: string; readonly entry: string };
28​
29/**
30 * Electron runs the server as plain Node with `ELECTRON_RUN_AS_NODE`, which
31 * reads the entry from inside the asar archive. The launcher's own path and the
32 * app's T3 home are written in, so the command the server shows is absolute and
33 * `sudo`, which clears the environment, still runs against this install's home.
34 */
35export const renderCliShim = (input: {
36 readonly target: CliShimTarget;
37 readonly shimPath: string;
38 readonly t3Home: string;
39}) => {
40 const { target } = input;
41 if (target.kind === "windows") {
42 const utf8 = [target.executable, target.entry, input.shimPath, input.t3Home].some((value) =>
43 [...value].some((character) => character.codePointAt(0)! > 0x7f),
44 );
45 const restore = utf8 ? ["chcp %t3_codepage% >nul"] : [];
46 return [
47 "@echo off",
48 `rem ${MARKER}`,
49 // Delayed expansion would rewrite `!name!` in paths and arguments.
50 "setlocal EnableExtensions DisableDelayedExpansion",
51 // Only a non-ASCII path needs the console switched to UTF-8 to read it; a
52 // Ctrl-C that ends the batch skips the restore, so the switch is left out
53 // for the common all-ASCII install.
54 ...(utf8
55 ? [
56 `for /f "tokens=2 delims=:." %%c in ('chcp') do set "t3_codepage=%%c"`,
57 "chcp 65001 >nul",
58 ]
59 : []),
60 `set "T3CODE_CLI_PATH=${cmdText(input.shimPath)}"`,
61 `if not defined T3CODE_HOME set "T3CODE_HOME=${cmdText(input.t3Home)}"`,
62 'set "ELECTRON_RUN_AS_NODE=1"',
63 // Electron's Windows executable starts without stdin; this tells the CLI to reopen the console.
64 'set "T3CODE_DESKTOP_CLI_LAUNCHER=1"',
65 // A goto, not a parenthesized block: "Program Files (x86)" would close the block early.
66 `if exist ${cmdWord(target.executable)} goto run`,
67 ...restore,
68 `echo ${MOVED} 1>&2`,
69 "exit /b 127",
70 ":run",
71 `${cmdWord(target.executable)} ${cmdWord(target.entry)} %*`,
72 'set "t3_exit=%ERRORLEVEL%"',
73 ...restore,
74 "exit /b %t3_exit%",
75 "",
76 ].join("\r\n");
77 }
78 const header = [
79 "#!/bin/sh",
80 `# ${MARKER}`,
81 `export T3CODE_CLI_PATH=${shellWord(input.shimPath)}`,
82 `home=${shellWord(input.t3Home)}`,
83 'export T3CODE_HOME="${T3CODE_HOME:-$home}"',
84 "export ELECTRON_RUN_AS_NODE=1",
85 `app=${shellWord(target.kind === "appimage" ? target.appImage : target.executable)}`,
86 'if [ ! -x "$app" ]; then',
87 ` echo "${MOVED}" >&2`,
88 " exit 127",
89 "fi",
90 ];
91 if (target.kind === "direct") {
92 return [...header, `exec "$app" ${shellWord(target.entry)} "$@"`, ""].join("\n");
93 }
94 const run = (root: string) =>
95 `"${root}/${target.executableName}" "${root}/resources/app.asar/${SERVER_ENTRY}" "$@"`;
96 return [
97 ...header,
98 // Extract-and-run would make the runtime start the app instead of mounting it.
99 "unset APPIMAGE_EXTRACT_AND_RUN",
100 // The AppImage runtime prints its mount point, then stays mounted until
101 // killed. Background jobs ignore Ctrl-C, so the traps unmount it on any exit.
102 "work=$(mktemp -d) || exit 1",
103 '"$app" --appimage-mount >"$work/mount" 2>/dev/null &',
104 "mounter=$!",
105 `trap 'kill "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`,
106 "trap 'exit 130' INT TERM",
107 "mount=",
108 'while kill -0 "$mounter" 2>/dev/null; do',
109 ' mount=$(head -n 1 "$work/mount")',
110 ' [ -d "$mount" ] && break',
111 " mount=",
112 " sleep 0.05",
113 "done",
114 // Without FUSE the runtime cannot mount (it prints why and exits); extracting the image still works.
115 'if [ -z "$mount" ]; then',
116 ' (cd "$work" && "$app" --appimage-extract >/dev/null) || { echo "Could not open $app." >&2; exit 1; }',
117 ' mount="$work/squashfs-root"',
118 "fi",
119 run("$mount"),
120 "",
121 ].join("\n");
122};
123​
124export const launcherPath = (environment: DesktopEnvironment.DesktopEnvironment["Service"]) =>
125 environment.path.join(
126 environment.baseDir,
127 "bin",
128 environment.platform === "win32" ? "t3.cmd" : "t3",
129 );
130​
131export const install = Effect.gen(function* () {
132 const environment = yield* DesktopEnvironment.DesktopEnvironment;
133 if (!environment.isPackaged) return Option.none<string>();
134 const fs = yield* FileSystem.FileSystem;
135 const path = environment.path;
136 const windows = environment.platform === "win32";
137 const shimPath = launcherPath(environment);
138 const entry = path.join(environment.serverRoot, SERVER_ENTRY);
139 const target: CliShimTarget = windows
140 ? { kind: "windows", executable: process.execPath, entry }
141 : Option.match(environment.appImagePath, {
142 onSome: (appImage) => ({
143 kind: "appimage" as const,
144 appImage,
145 executableName: path.basename(process.execPath),
146 }),
147 onNone: () => ({ kind: "direct" as const, executable: process.execPath, entry }),
148 });
149 const content = renderCliShim({ target, shimPath, t3Home: environment.baseDir });
150​
151 return yield* Effect.gen(function* () {
152 const existing = yield* fs.readFileString(shimPath).pipe(Effect.option);
153 if (Option.isSome(existing) && !existing.value.includes(MARKER)) {
154 yield* logWarning("leaving a t3 launcher the app did not write", { shimPath });
155 return Option.none<string>();
156 }
157 if (Option.getOrUndefined(existing) !== content) {
158 yield* fs.makeDirectory(path.dirname(shimPath), { recursive: true });
159 const staging = `${shimPath}.${process.pid}.tmp`;
160 yield* fs.writeFileString(staging, content, { mode: 0o755 });
161 yield* fs.rename(staging, shimPath);
162 yield* logInfo("installed t3 launcher", { shimPath });
163 }
164 return Option.some(shimPath);
165 }).pipe(
166 Effect.catchCause((cause) =>
167 logWarning("could not install t3 launcher", { shimPath, cause: Cause.pretty(cause) }).pipe(
168 Effect.as(Option.none<string>()),
169 ),
170 ),
171 Effect.withSpan("desktop.cliShim.install"),
172 );
173});