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

NodePtyAdapter.ts

189 lines6.1 KB

1import * as NodeModule from "node:module";
2​
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
10​
11import * as PtyAdapter from "./PtyAdapter.ts";
12​
13export class NodePtyModuleLoadError extends Schema.TaggedError<NodePtyModuleLoadError>()(
14 "NodePtyModuleLoadError",
15 {
16 platform: Schema.String,
17 architecture: Schema.String,
18 cause: Schema.Defect(),
19 },
20) {
21 override get message(): string {
22 return `Failed to load node-pty for ${this.platform}-${this.architecture}.`;
23 }
25​
26type NodePtyModuleLoader = () => Promise<typeof import("node-pty")>;
27​
28// node-pty stays external to the CLI bundle because it dlopens a native
29// addon. Inside a Node single-executable, `import()` cannot load files from
30// disk (only built-ins resolve), while `require` always reads the real
31// filesystem, so both the module and its spawn-helper resolve through it.
32const requireForNodePty = NodeModule.createRequire(import.meta.url);
33​
34const loadNodePty: NodePtyModuleLoader = () =>
35 Promise.resolve().then(() => requireForNodePty("node-pty") as typeof import("node-pty"));
36​
37/** Injectable so tests can substitute a fake module; `require` bypasses module mocks. */
38export const NodePtyModuleLoaderRef = Context.Reference<NodePtyModuleLoader>(
39 "server/terminal/NodePtyModuleLoader",
40 { defaultValue: () => loadNodePty },
41);
42​
43let didEnsureSpawnHelperExecutable = false;
44​
45const resolveNodePtySpawnHelperPath = Effect.gen(function* () {
46 const path = yield* Path.Path;
47 const fs = yield* FileSystem.FileSystem;
48 const platform = yield* HostProcessPlatform;
49 const architecture = yield* HostProcessArchitecture;
50​
51 const packageJsonPath = requireForNodePty.resolve("node-pty/package.json");
52 const packageDir = path.dirname(packageJsonPath);
53 const candidates = [
54 path.join(packageDir, "build", "Release", "spawn-helper"),
55 path.join(packageDir, "build", "Debug", "spawn-helper"),
56 path.join(packageDir, "prebuilds", `${platform}-${architecture}`, "spawn-helper"),
57 ];
58​
59 for (const candidate of candidates) {
60 if (yield* fs.exists(candidate)) {
61 return candidate;
62 }
63 }
64 return null;
65}).pipe(Effect.orElseSucceed(() => null));
66​
67const ensureNodePtySpawnHelperExecutable = Effect.fn(function* () {
68 const fs = yield* FileSystem.FileSystem;
69 const platform = yield* HostProcessPlatform;
70 if (platform === "win32") return;
71 if (didEnsureSpawnHelperExecutable) return;
72​
73 const helperPath = yield* resolveNodePtySpawnHelperPath;
74 if (!helperPath) return;
75 didEnsureSpawnHelperExecutable = true;
76​
77 if (!(yield* fs.exists(helperPath))) {
78 return;
79 }
80​
81 // Best-effort: avoid FileSystem.stat in packaged mode where some fs metadata can be missing.
82 yield* fs.chmod(helperPath, 0o755).pipe(Effect.orElseSucceed(() => undefined));
83});
84​
85class NodePtyProcess implements PtyAdapter.PtyProcess {
86 private readonly process: import("node-pty").IPty;
87 private readonly platform: NodeJS.Platform;
88​
89 constructor(process: import("node-pty").IPty, platform: NodeJS.Platform) {
90 this.process = process;
91 this.platform = platform;
92 }
93​
94 get pid(): number {
95 return this.process.pid;
96 }
97​
98 write(data: string): void {
99 this.process.write(data);
100 }
101​
102 resize(cols: number, rows: number): void {
103 this.process.resize(cols, rows);
104 }
105​
106 kill(signal?: string): void {
107 // node-pty terminates the Windows process tree without a POSIX signal.
108 this.process.kill(this.platform === "win32" ? undefined : signal);
109 }
110​
111 onData(callback: (data: string) => void): () => void {
112 const disposable = this.process.onData(callback);
113 return () => {
114 disposable.dispose();
115 };
116 }
117​
118 onExit(callback: (event: PtyAdapter.PtyExitEvent) => void): () => void {
119 const disposable = this.process.onExit((event) => {
120 callback({
121 exitCode: event.exitCode,
122 signal: event.signal ?? null,
123 });
124 });
125 return () => {
126 disposable.dispose();
127 };
128 }
130​
131export const make = Effect.fn("NodePtyAdapter.make")(function* () {
132 const loadNodePtyModule = yield* NodePtyModuleLoaderRef;
133 const fs = yield* FileSystem.FileSystem;
134 const path = yield* Path.Path;
135 const platform = yield* HostProcessPlatform;
136 const architecture = yield* HostProcessArchitecture;
137​
138 const nodePty = yield* Effect.tryPromise({
139 try: loadNodePtyModule,
140 catch: (cause) =>
141 new NodePtyModuleLoadError({
142 platform,
143 architecture,
144 cause,
145 }),
146 }).pipe(Effect.orDie);
147​
148 const ensureNodePtySpawnHelperExecutableCached = yield* Effect.cached(
149 ensureNodePtySpawnHelperExecutable().pipe(
150 Effect.provideService(FileSystem.FileSystem, fs),
151 Effect.provideService(Path.Path, path),
152 Effect.provideService(HostProcessPlatform, platform),
153 Effect.provideService(HostProcessArchitecture, architecture),
154 Effect.orElseSucceed(() => undefined),
155 ),
156 );
157​
158 return PtyAdapter.PtyAdapter.of({
159 spawn: Effect.fn("NodePtyAdapter.spawn")(function* (input) {
160 yield* ensureNodePtySpawnHelperExecutableCached;
161 // node-pty only writes `name` into the child's TERM on the Unix path;
162 // the ConPTY path leaves the environment untouched, so Windows children
163 // inherit a missing or 16-color TERM unless it is set here.
164 const env =
165 platform === "win32" && input.env["TERM"] === undefined
166 ? { ...input.env, TERM: "xterm-256color" }
167 : input.env;
168 const ptyProcess = yield* Effect.try({
169 try: () =>
170 nodePty.spawn(input.shell, input.args ?? [], {
171 cwd: input.cwd,
172 cols: input.cols,
173 rows: input.rows,
174 env,
175 name: "xterm-256color",
176 }),
177 catch: (cause) =>
178 new PtyAdapter.PtySpawnError({
179 adapter: "node-pty",
180 shell: input.shell,
181 cause,
182 }),
183 });
184 return new NodePtyProcess(ptyProcess, platform);
185 }),
186 });
187});
188​
189export const layer = Layer.effect(PtyAdapter.PtyAdapter, make());