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

NodePtyAdapter.ts

175 lines5.4 KB

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