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

invocation.ts

277 lines10.6 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Path from "effect/Path";
5import * as Schema from "effect/Schema";
6​
7import type { ServerInstallation } from "@t3tools/contracts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import { resolveCommandPath } from "@t3tools/shared/shell";
10​
11import packageJson from "../../package.json" with { type: "json" };
12import {
13 findPosixLauncher,
14 readPosixLauncherTarget,
15 resolveLauncherPath,
16} from "../cloud/pinnedRuntime.ts";
17​
18const PINNED_RUNTIME_ENTRY = /^(.*)\/runtime\/versions\/[^/]+\/t3$/;
19​
20export type CliRunner = "npx" | "pnpm dlx" | "bunx";
21​
22/** Detection is best-effort; callers must fail closed to a plain `t3` command. */
23export function detectCliRunner(entryPath: string): CliRunner | null {
24 const path = entryPath.replaceAll("\\", "/");
25 if (path.includes("/_npx/")) {
26 return "npx";
27 }
28 if (
29 path.includes("/pnpm/dlx/") ||
30 path.includes("/.pnpm/dlx/") ||
31 path.includes("/pnpm-cache/dlx/")
32 ) {
33 return "pnpm dlx";
34 }
35 if (path.includes("/.bun/install/cache/") || path.includes("/bunx-")) {
36 return "bunx";
37 }
38 return null;
40​
41const InstallManifest = Schema.Struct({
42 name: Schema.String,
43 version: Schema.String,
44 bin: Schema.optionalKey(Schema.Struct({ t3: Schema.String })),
45});
46const decodeInstallManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(InstallManifest));
47​
48/**
49 * `T3CODE_NPM_LAUNCHER_PATH` is inherited by child shells, so accept it only for this package
50 * version to avoid claiming another `t3` invocation is the npm install.
51 */
52export const resolveNpmLauncherPath = Effect.gen(function* () {
53 const npmLauncher = (yield* HostProcess.Environment).T3CODE_NPM_LAUNCHER_PATH?.trim();
54 if (!npmLauncher) return Option.none<string>();
55 const fs = yield* FileSystem.FileSystem;
56 const path = yield* Path.Path;
57 const manifest = yield* fs
58 .readFileString(path.join(path.dirname(npmLauncher), "../package.json"))
59 .pipe(Effect.flatMap(decodeInstallManifest), Effect.option);
60 return Option.isSome(manifest) &&
61 manifest.value.name === "t3" &&
62 manifest.value.version === packageJson.version
63 ? Option.some(npmLauncher)
64 : Option.none<string>();
65});
66​
67export const resolveEntryPath = Effect.gen(function* () {
68 const npmLauncher = yield* resolveNpmLauncherPath;
69 if (Option.isSome(npmLauncher)) return npmLauncher.value;
70 if (yield* HostProcess.IsExecutable) return yield* HostProcess.ExecutablePath;
71 return (yield* HostProcess.Arguments)[1] ?? "";
72});
73​
74export const resolveServerInstallation = Effect.gen(function* () {
75 const fs = yield* FileSystem.FileSystem;
76 const path = yield* Path.Path;
77 const platform = yield* HostProcess.Platform;
78 const entry = yield* fs.realPath(yield* resolveEntryPath);
79 const runtime = PINNED_RUNTIME_ENTRY.exec(entry);
80 if (runtime) {
81 const launchedAs = yield* resolveLauncherPath;
82 if (launchedAs === undefined) return null;
83 const link = yield* fs.readLink(launchedAs).pipe(Effect.option);
84 // A launcher script execs the runtime itself, so look for the script that runs it.
85 const launcher = Option.isSome(link)
86 ? launchedAs
87 : yield* findPosixLauncher({
88 launchedAs,
89 versionsDir: path.join(runtime[1] || "/", "runtime/versions"),
90 });
91 // None for a runtime started directly, as SSH launches do, or through a copy.
92 if (launcher === undefined) return null;
93 const target = Option.isSome(link)
94 ? path.resolve(path.dirname(launcher), link.value)
95 : yield* readPosixLauncherTarget(launcher);
96 // Keep the home as the launcher spells it; `t3 update` only repoints launchers into that spelling.
97 const linked = target === undefined ? null : PINNED_RUNTIME_ENTRY.exec(target);
98 if (!linked || (yield* fs.realPath(linked[1] || "/")) !== (runtime[1] || "/")) return null;
99 return {
100 kind: "t3-launcher",
101 launcher,
102 baseDir: linked[1] || "/",
103 } satisfies ServerInstallation;
104 }
105 const match = /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.mjs)$/.exec(entry);
106 if (!match) {
107 const runner = detectCliRunner(entry);
108 return runner === null
109 ? null
110 : ({ kind: runner === "pnpm dlx" ? "pnpm-dlx" : runner } satisfies ServerInstallation);
111 }
112 if (platform === "win32") return null;
113 const prefix = match[1] || "/";
114 if (
115 prefix.includes("/node_modules/") ||
116 /\/(?:Cellar|Caskroom)\//i.test(prefix) ||
117 /\/mise\/installs\/(?!node\/)[^/]+\//.test(prefix)
118 )
119 return null;
120​
121 const packageRoot = path.join(prefix, "lib/node_modules/t3");
122 const manifest = yield* fs
123 .readFileString(path.join(packageRoot, "package.json"))
124 .pipe(Effect.flatMap(decodeInstallManifest));
125 if (manifest.name !== "t3" || !manifest.bin) return null;
126 const bin = yield* fs.realPath(path.join(packageRoot, manifest.bin.t3));
127 const globalBin = yield* fs.realPath(path.join(prefix, "bin/t3"));
128 if (globalBin !== bin || bin !== entry) return null;
129 return { kind: "npm-global", prefix } satisfies ServerInstallation;
130}).pipe(Effect.orElseSucceed(() => null));
131​
132/** The original package spec is unavailable at startup; infer its channel from the version. */
133function suggestedPackageSpec(version: string): string {
134 const channel = /^[^-+]+-(nightly|preview)\./.exec(version)?.[1];
135 return channel === undefined ? "t3" : `t3@${channel}`;
137​
138function formatCliCommand(input: {
139 readonly subcommand: string;
140 readonly entryPath: string;
141 readonly version: string;
142}): string {
143 const runner = detectCliRunner(input.entryPath);
144 if (runner === null) {
145 return `t3 ${input.subcommand}`;
146 }
147 return `${runner} ${suggestedPackageSpec(input.version)} ${input.subcommand}`;
149​
150export const resolveCliCommand = (subcommand: string) =>
151 Effect.map(resolveEntryPath, (entryPath) =>
152 formatCliCommand({ subcommand, entryPath, version: packageJson.version }),
153 );
154​
155const shellWord = (value: string) =>
156 /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`;
157​
158/** The npm launcher starts the runtime named by its package version, so only the package manager moves it. */
159export function packageUpdateCommand(
160 installation: ServerInstallation,
161 version: string,
162): string | null {
163 const spec = `t3@${version}`;
164 switch (installation.kind) {
165 case "npm-global":
166 return `npm install --global --prefix ${shellWord(installation.prefix)} ${spec}`;
167 case "pnpm-dlx":
168 return `pnpm dlx ${spec}`;
169 case "npx":
170 case "bunx":
171 return `${installation.kind} ${spec}`;
172 case "t3-launcher":
173 return null;
174 }
176​
177/** PowerShell also treats typographic quotes as delimiters; escape them and suppress expansion. */
178const powershellWord = (value: string) =>
179 `"${value
180 .replaceAll("`", "``")
181 .replaceAll("$", "`$")
182 .replace(/["\u201C\u201D\u201E]/g, "$&$&")}"`;
183​
184export const hostShellWord = (platform: NodeJS.Platform, value: string) =>
185 platform === "win32" ? powershellWord(value) : shellWord(value);
186​
187/** Script installs have no single launcher; desktop shims and standalone binaries do. */
188const resolveInstallLauncher = Effect.gen(function* () {
189 const fs = yield* FileSystem.FileSystem;
190 const shim = (yield* HostProcess.Environment).T3CODE_CLI_PATH?.trim();
191 if (shim && (yield* fs.exists(shim).pipe(Effect.orElseSucceed(() => false)))) {
192 return Option.some(shim);
193 }
194 return (yield* HostProcess.IsExecutable)
195 ? Option.some(yield* HostProcess.ExecutablePath)
196 : Option.none<string>();
197});
198​
199/**
200 * Uses this install's `t3` on PATH, the originating runner, or its absolute launcher path.
201 * Arguments are quoted for POSIX shells or PowerShell on Windows.
202 */
203export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand")(function* (
204 subcommand: string,
205 args: ReadonlyArray<string> = [],
206) {
207 const platform = yield* HostProcess.Platform;
208 const withArgs = (prefix: string) =>
209 // An empty subcommand names the root `t3` command.
210 [prefix.trimEnd(), ...args.map((arg) => hostShellWord(platform, arg))].join(" ");
211 const command = yield* resolveCliCommand(subcommand);
212 if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };
213 const onPath = yield* resolveCommandPath("t3");
214 if (onPath !== null) {
215 const shim = (yield* HostProcess.Environment).T3CODE_CLI_PATH?.trim();
216 const fs = yield* FileSystem.FileSystem;
217 const real = (file: string) => fs.realPath(file).pipe(Effect.orElseSucceed(() => null));
218 // Windows `t3.cmd` shims are text files that never realpath to the executable they run.
219 const own = shim
220 ? yield* real(shim)
221 : platform !== "win32" && (yield* HostProcess.IsExecutable)
222 ? yield* resolveEntryPath.pipe(
223 Effect.flatMap((entry) =>
224 real(entry).pipe(Effect.map((resolved) => resolved ?? entry)),
225 ),
226 )
227 : null;
228 if (own === null || own === (yield* real(onPath))) {
229 return { command: withArgs(command), launcher: false };
230 }
231 }
232 const launcher = yield* resolveInstallLauncher;
233 if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false };
234 // PowerShell runs a quoted path only through the call operator.
235 const quoted = hostShellWord(platform, launcher.value);
236 const call = platform === "win32" ? `& ${quoted}` : quoted;
237 return { command: withArgs(`${call} ${subcommand}`), launcher: true };
238});
239​
240/** A hint's command, run against the caller's `--base-dir` when one was given. */
241export const resolveHostCliHint = (
242 subcommand: string,
243 baseDir: Option.Option<string>,
244 args: ReadonlyArray<string> = [],
245) =>
246 resolveHostCliCommand(subcommand, [
247 ...Option.match(baseDir, { onNone: () => [], onSome: (dir) => ["--base-dir", dir] }),
248 ...args,
249 ]).pipe(Effect.map(({ command }) => command));
250​
251/**
252 * `sudo` resets PATH on most distributions, which drops a user-installed Node
253 * (nvm, fnm, a tarball) and with it `npx` or a global `t3`, so the command
254 * carries PATH through unless Node is on root's PATH too. An absolute launcher
255 * needs neither.
256 */
257export const resolveRootCliCommand = Effect.fn("invocation.resolveRootCliCommand")(function* (
258 subcommand: string,
259 args: ReadonlyArray<string> = [],
260) {
261 const { command, launcher } = yield* resolveHostCliCommand(subcommand, args);
262 if (launcher) return `sudo ${command}`;
263 const executablePath = yield* HostProcess.ExecutablePath;
264 const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>
265 executablePath.startsWith(`${directory}/`),
266 );
267 return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;
268});
269​
270const ROOT_PATH_DIRECTORIES = [
271 "/usr/local/sbin",
272 "/usr/local/bin",
273 "/usr/sbin",
274 "/usr/bin",
275 "/sbin",
276 "/bin",
277];