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

NodePtyAdapter.ts

172 lines5.2 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.TaggedErrorClass<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​
73 constructor(process: import("node-pty").IPty) {
74 this.process = process;
75 }
76​
77 get pid(): number {
78 return this.process.pid;
79 }
80​
81 write(data: string): void {
82 this.process.write(data);
83 }
84​
85 resize(cols: number, rows: number): void {
86 this.process.resize(cols, rows);
87 }
88​
89 kill(signal?: string): void {
90 this.process.kill(signal);
91 }
92​
93 onData(callback: (data: string) => void): () => void {
94 const disposable = this.process.onData(callback);
95 return () => {
96 disposable.dispose();
97 };
98 }
99​
100 onExit(callback: (event: PtyAdapter.PtyExitEvent) => void): () => void {
101 const disposable = this.process.onExit((event) => {
102 callback({
103 exitCode: event.exitCode,
104 signal: event.signal ?? null,
105 });
106 });
107 return () => {
108 disposable.dispose();
109 };
110 }
112​
113export const make = Effect.fn("NodePtyAdapter.make")(function* (
114 loadNodePtyModule: NodePtyModuleLoader = () => import("node-pty"),
115) {
116 const fs = yield* FileSystem.FileSystem;
117 const path = yield* Path.Path;
118 const platform = yield* HostProcessPlatform;
119 const architecture = yield* HostProcessArchitecture;
120​
121 const nodePty = yield* Effect.tryPromise({
122 try: loadNodePtyModule,
123 catch: (cause) =>
124 new NodePtyModuleLoadError({
125 platform,
126 architecture,
127 cause,
128 }),
129 }).pipe(Effect.orDie);
130​
131 const ensureNodePtySpawnHelperExecutableCached = yield* Effect.cached(
132 ensureNodePtySpawnHelperExecutable().pipe(
133 Effect.provideService(FileSystem.FileSystem, fs),
134 Effect.provideService(Path.Path, path),
135 Effect.provideService(HostProcessPlatform, platform),
136 Effect.provideService(HostProcessArchitecture, architecture),
137 Effect.orElseSucceed(() => undefined),
138 ),
139 );
140​
141 return PtyAdapter.PtyAdapter.of({
142 spawn: Effect.fn("NodePtyAdapter.spawn")(function* (input) {
143 yield* ensureNodePtySpawnHelperExecutableCached;
144 // node-pty only writes `name` into the child's TERM on the Unix path;
145 // the ConPTY path leaves the environment untouched, so Windows children
146 // inherit a missing or 16-color TERM unless it is set here.
147 const env =
148 platform === "win32" && input.env["TERM"] === undefined
149 ? { ...input.env, TERM: "xterm-256color" }
150 : input.env;
151 const ptyProcess = yield* Effect.try({
152 try: () =>
153 nodePty.spawn(input.shell, input.args ?? [], {
154 cwd: input.cwd,
155 cols: input.cols,
156 rows: input.rows,
157 env,
158 name: "xterm-256color",
159 }),
160 catch: (cause) =>
161 new PtyAdapter.PtySpawnError({
162 adapter: "node-pty",
163 shell: input.shell,
164 cause,
165 }),
166 });
167 return new NodePtyProcess(ptyProcess);
168 }),
169 });
170});
171​
172export const layer = Layer.effect(PtyAdapter.PtyAdapter, make());