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

invocation.ts

215 lines8.1 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 {
9 HostProcessArguments,
10 HostProcessEnvironment,
11 HostProcessExecutablePath,
12 HostProcessIsExecutable,
13 HostProcessPlatform,
14} from "@t3tools/shared/hostProcess";
15import { isCommandAvailable } from "@t3tools/shared/shell";
16​
17import packageJson from "../../package.json" with { type: "json" };
18​
19export type CliRunner = "npx" | "pnpm dlx" | "bunx";
20​
21/**
22 * How the CLI was launched, judged by where its entry script lives. Each
23 * package runner executes out of a distinctive cache/temp layout:
24 *
25 * npx ~/.npm/_npx/<hash>/node_modules/...
26 * pnpm dlx ~/.cache/pnpm/dlx/..., $PNPM_HOME/.pnpm/dlx/...,
27 * or %LOCALAPPDATA%/pnpm-cache/dlx/... on Windows
28 * bunx ~/.bun/install/cache/... or $TMPDIR/bunx-<uid>-<spec>/...
29 *
30 * Global installs and repo checkouts match none of these and return null.
31 * Detection is best-effort; callers must fail closed to a plain `t3` command.
32 */
33function detectCliRunner(entryPath: string): CliRunner | null {
34 const path = entryPath.replaceAll("\\", "/");
35 if (path.includes("/_npx/")) {
36 return "npx";
37 }
38 if (
39 path.includes("/pnpm/dlx/") ||
40 path.includes("/.pnpm/dlx/") ||
41 path.includes("/pnpm-cache/dlx/")
42 ) {
43 return "pnpm dlx";
44 }
45 if (path.includes("/.bun/install/cache/") || path.includes("/bunx-")) {
46 return "bunx";
47 }
48 return null;
50​
51const InstallManifest = Schema.Struct({
52 name: Schema.String,
53 version: Schema.String,
54 bin: Schema.optionalKey(Schema.Struct({ t3: Schema.String })),
55 optionalDependencies: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
56});
57const decodeInstallManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(InstallManifest));
58​
59/** Prove the running package and its global bin belong together before suggesting an update. */
60export const resolveServerInstallation = Effect.gen(function* () {
61 const fs = yield* FileSystem.FileSystem;
62 const path = yield* Path.Path;
63 const args = yield* HostProcessArguments;
64 const executable = yield* HostProcessIsExecutable;
65 const executablePath = yield* HostProcessExecutablePath;
66 const platform = yield* HostProcessPlatform;
67 const entry = yield* fs.realPath(executable ? executablePath : (args[1] ?? ""));
68 const match =
69 /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.js|node_modules\/@t3code\/t3-[^/]+\/t3)$/.exec(
70 entry,
71 );
72 if (!match) {
73 const runner = detectCliRunner(entry);
74 return runner === null
75 ? null
76 : ({ kind: runner === "pnpm dlx" ? "pnpm-dlx" : runner } satisfies ServerInstallation);
77 }
78 // A global prefix can contain runner-like names; prove its ownership first.
79 // Windows shims and other package managers need their own ownership proof.
80 if (platform === "win32") return null;
81 const prefix = match[1] || "/";
82 if (
83 prefix.includes("/node_modules/") ||
84 /\/(?:Cellar|Caskroom)\//i.test(prefix) ||
85 /\/mise\/installs\/(?!node\/)[^/]+\//.test(prefix)
86 )
87 return null;
88​
89 const packageRoot = path.join(prefix, "lib/node_modules/t3");
90 const manifest = yield* fs
91 .readFileString(path.join(packageRoot, "package.json"))
92 .pipe(Effect.flatMap(decodeInstallManifest));
93 if (manifest.name !== "t3" || !manifest.bin) return null;
94 const bin = yield* fs.realPath(path.join(packageRoot, manifest.bin.t3));
95 const globalBin = yield* fs.realPath(path.join(prefix, "bin/t3"));
96 if (globalBin !== bin) return null;
97 if (executable) {
98 const nativeManifest = yield* fs
99 .readFileString(path.join(path.dirname(entry), "package.json"))
100 .pipe(Effect.flatMap(decodeInstallManifest));
101 if (
102 manifest.bin.t3 !== "./bin/t3.js" ||
103 manifest.optionalDependencies?.[nativeManifest.name] !== nativeManifest.version ||
104 nativeManifest.version !== manifest.version
105 )
106 return null;
107 } else if (bin !== entry) {
108 return null;
109 }
110 return { kind: "npm-global", prefix } satisfies ServerInstallation;
111}).pipe(Effect.orElseSucceed(() => null));
112​
113/**
114 * The `t3` package spec to suggest. The literal spec the user typed (e.g.
115 * `t3@nightly`) is resolved away before our process starts, so re-derive it
116 * from the running version: nightly builds re-suggest the nightly channel,
117 * anything else suggests the bare package.
118 */
119function suggestedPackageSpec(version: string): string {
120 const channel = /^[^-+]+-(nightly|preview)\./.exec(version)?.[1];
121 return channel === undefined ? "t3" : `t3@${channel}`;
123​
124/**
125 * Render a `t3 <subcommand>` suggestion that matches how this process was
126 * launched, so copy/pasting it actually works: `npx t3 connect` suggests
127 * `npx t3 serve`, a global install suggests `t3 serve`, and a nightly build
128 * keeps the `@nightly` tag.
129 */
130export function formatCliCommand(input: {
131 readonly subcommand: string;
132 readonly entryPath: string;
133 readonly version: string;
134}): string {
135 const runner = detectCliRunner(input.entryPath);
136 if (runner === null) {
137 return `t3 ${input.subcommand}`;
138 }
139 return `${runner} ${suggestedPackageSpec(input.version)} ${input.subcommand}`;
141​
142/** `formatCliCommand` against this process's real entry path and version. */
143export const resolveCliCommand = (subcommand: string) =>
144 Effect.map(HostProcessArguments, (processArguments) =>
145 formatCliCommand({
146 subcommand,
147 entryPath: processArguments[1] ?? "",
148 version: packageJson.version,
149 }),
150 );
151​
152/** Quotes `value` for a POSIX shell when it needs it. */
153const shellWord = (value: string) =>
154 /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`;
155​
156/**
157 * The launcher a person can type to run this install when `t3` is not on
158 * PATH: the desktop app's `t3` shim, which the app and the shim itself name in
159 * `T3CODE_CLI_PATH`, or a standalone binary's own path. Script installs (a
160 * repo checkout) have no single launcher and keep plain `t3`.
161 */
162const resolveInstallLauncher = Effect.gen(function* () {
163 const fs = yield* FileSystem.FileSystem;
164 const shim = (yield* HostProcessEnvironment).T3CODE_CLI_PATH?.trim();
165 if (shim && (yield* fs.exists(shim).pipe(Effect.orElseSucceed(() => false)))) {
166 return Option.some(shim);
167 }
168 return (yield* HostProcessIsExecutable)
169 ? Option.some(yield* HostProcessExecutablePath)
170 : Option.none<string>();
171});
172​
173/**
174 * `t3 <subcommand>` for a person to run on this host: `t3` when it is on PATH,
175 * the package runner this process came from, or else the absolute path of the
176 * launcher for this install, such as the one the desktop app installs.
177 */
178const resolveHostCliCommand = (subcommand: string) =>
179 Effect.gen(function* () {
180 const command = yield* resolveCliCommand(subcommand);
181 if (command !== `t3 ${subcommand}`) return { command, launcher: false };
182 if (yield* isCommandAvailable("t3")) return { command, launcher: false };
183 const launcher = yield* resolveInstallLauncher;
184 return Option.isSome(launcher)
185 ? { command: `${shellWord(launcher.value)} ${subcommand}`, launcher: true }
186 : { command, launcher: false };
187 });
188​
189/**
190 * `t3 <subcommand>` as root, for setup a person runs once on the host. `sudo`
191 * resets PATH on most distributions, which drops a user-installed Node (nvm,
192 * fnm, a tarball) and with it `npx` or a global `t3`, so the command carries
193 * PATH through unless Node is on root's PATH too. An absolute launcher needs
194 * neither.
195 */
196export const resolveRootCliCommand = (subcommand: string) =>
197 Effect.gen(function* () {
198 const { command, launcher } = yield* resolveHostCliCommand(subcommand);
199 if (launcher) return `sudo ${command}`;
200 const executablePath = yield* HostProcessExecutablePath;
201 const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>
202 executablePath.startsWith(`${directory}/`),
203 );
204 return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;
205 });
206​
207/** Debian and Ubuntu's sudo `secure_path`, minus snap. */
208const ROOT_PATH_DIRECTORIES = [
209 "/usr/local/sbin",
210 "/usr/local/bin",
211 "/usr/sbin",
212 "/usr/bin",
213 "/sbin",
214 "/bin",
215];