@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
js 145 lines 5.37 KB
Raw
1 #!/usr/bin/env node
2 // @ts-check
3
4 import { spawn } from "node:child_process";
5 import * as NodeModule from "node:module";
6 import { pathToFileURL } from "node:url";
7 import * as SemVer from "effect/SemVer";
8 import * as SemVerRange from "effect/SemVerRange";
9 import path from "pathe";
10
11 const binDir = path.dirname(import.meta.filename);
12 const entry = path.join(binDir, "alchemy.js");
13 const args = process.argv.slice(2);
14
15 // Alchemy's own TSX carries `@jsxRuntime automatic` pragmas and sigil's
16 // jsx-dev-runtime is the production runtime, so Bun's startup JSX choice
17 // (from the caller's tsconfig and NODE_ENV) cannot break the CLI. NODE_ENV
18 // still names the mode for everything else.
19 process.env.NODE_ENV = "production";
20
21 /**
22 * `bun run`/`bunx` start a node-shebang bin under Node but always point
23 * npm_execpath at bun. npm_config_user_agent only names the package-manager
24 * role (e.g. nub reports `bun/<v>` for a bun project while running Node).
25 */
26 const launchedByBun = () => path.basename(process.env.npm_execpath ?? "").startsWith("bun");
27
28 /**
29 * `execve` needs a Node that has it and a platform that does (not Windows),
30 * and must not sever an IPC channel a parent holds to this process.
31 */
32 const canReplaceProcess = () =>
33 process.platform !== "win32" && process.execve !== undefined && process.send === undefined;
34
35 if (typeof globalThis.Bun !== "undefined") {
36 await runUnderBun();
37 } else if (launchedByBun()) {
38 handOffToBun();
39 } else {
40 await runUnderNode();
41 }
42
43 /** Already running under bun: nothing to set up. */
44 async function runUnderBun() {
45 await import(pathToFileURL(entry).href);
46 }
47
48 /**
49 * Started by bun as a package manager: run the CLI under bun, as asked.
50 * `npm_execpath` is the bun binary itself. Where possible this process is
51 * replaced outright (same pid, fds and process group, so the terminal's
52 * signals and the exit status are the CLI's own); otherwise the CLI runs as
53 * a child sharing this terminal.
54 */
55 function handOffToBun() {
56 const bun = /** @type {string} */ (process.env.npm_execpath);
57 const bunArgs = [entry, ...args];
58 try {
59 if (canReplaceProcess()) {
60 process.execve(bun, [bun, ...bunArgs], process.env);
61 } else {
62 runAsChild(bun, bunArgs);
63 }
64 } catch (error) {
65 const message = error instanceof Error ? error.message : String(error);
66 process.stderr.write(`alchemy: could not start ${bun}: ${message}\n`);
67 process.exit(1);
68 }
69 }
70
71 /**
72 * Run `program` as a foreground child: signals, IPC messages and the exit
73 * status (or signal) are forwarded so the parent cannot tell the difference.
74 *
75 * @param {string} program
76 * @param {ReadonlyArray<string>} programArgs
77 */
78 function runAsChild(program, programArgs) {
79 const child = spawn(program, programArgs, {
80 stdio: process.send ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
81 });
82 child.on("error", (error) => {
83 process.stderr.write(`alchemy: could not start ${program}: ${error.message}\n`);
84 process.exit(1);
85 });
86
87 /** @type {Array<NodeJS.Signals>} */
88 const signals = ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT", "SIGUSR1", "SIGUSR2"];
89 for (const signal of signals) process.on(signal, () => child.kill(signal));
90
91 if (process.send) {
92 const serializable = /** @param {unknown} message */ (message) =>
93 /** @type {import("node:child_process").Serializable} */ (message);
94 child.on("message", (message, handle) => process.send?.(serializable(message), handle));
95 process.on("message", (message, handle) => child.send(serializable(message), handle));
96 process.on("disconnect", () => child.disconnect());
97 }
98
99 child.on("close", (code, signal) => {
100 if (signal) process.kill(process.pid, signal);
101 else process.exit(code ?? 0);
102 });
103 }
104
105 /**
106 * Plain Node: check the version, install the Oxc TypeScript loader, then
107 * run the CLI. A checkout (outside node_modules) runs from `src/` with the
108 * dev-mode hooks; a published install runs its built `lib/`.
109 */
110 async function runUnderNode() {
111 if (!supportsModuleHooks()) {
112 process.stderr.write(
113 `alchemy: node ${process.versions.node} is not supported. ` +
114 "Upgrade to node 22.22.3, 24.11.1 or newer.\n",
115 );
116 process.exit(1);
117 }
118 NodeModule.enableCompileCache?.();
119 // `--fast-distilled` opts in to distilled's lazy service stubs (see
120 // register-oxc.js). The env var carries the choice to the loader and to
121 // every Node child alchemy starts with it (dev exec child, sidecar).
122 // Flags after a `--` separator belong to someone else.
123 const separator = args.indexOf("--");
124 if ((separator === -1 ? args : args.slice(0, separator)).includes("--fast-distilled")) {
125 process.env.ALCHEMY_FAST_DISTILLED = "1";
126 }
127 const isCheckout = !(binDir.includes("/node_modules/") || binDir.includes("\\node_modules\\"));
128 const register = isCheckout ? "register-dev-mode.js" : "register-oxc.js";
129 await import(new URL(register, import.meta.url).href);
130 await import(pathToFileURL(entry).href);
131 }
132
133 /**
134 * Oxc's loader needs complete `module.registerHooks` support: 24.11.1 and
135 * 25.1 carry the load-step fix for imported CommonJS (nodejs/node#59929).
136 * Keep this in sync with `isRegisterHooksSupported` in src/Util/Node.ts; the
137 * launcher must run before any TypeScript can be loaded.
138 */
139 function supportsModuleHooks() {
140 return SemVerRange.matches(
141 SemVerRange.parseUnsafe(">=22.22.3 <23.0.0-0 || >=24.11.1 <25.0.0-0 || >=25.1.0"),
142 SemVer.parseUnsafe(process.versions.node),
143 { includePrerelease: true },
144 );
145 }