Open History to see the last commit
1import * as Data from "effect/Data";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as PlatformError from "effect/PlatformError";
8import * as Scope from "effect/Scope";
9import * as Stream from "effect/Stream";
10import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
11import {
12 collectUint8StreamText,
13 type CollectedUint8StreamText,
14} from "./stream/collectUint8StreamText.ts";
15
16export interface ProcessRunInput {
17 readonly command: string;
18 readonly args: ReadonlyArray<string>;
19 readonly cwd?: string | undefined;
20 readonly spawnCwd?: string | undefined;
21 readonly timeout?: Duration.Input | undefined;
22 readonly env?: NodeJS.ProcessEnv | undefined;
23 readonly stdin?: string | undefined;
24 readonly maxOutputBytes?: number | undefined;
25 readonly outputMode?: "error" | "truncate" | undefined;
26 readonly truncatedMarker?: string | undefined;
27 readonly shell?: boolean | string | undefined;
28 /**
29 * On timeout, return a synthetic timedOut result.
30 * Partial stdout/stderr are not preserved.
31 */
32 readonly timeoutBehavior?: "error" | "timedOutResult" | undefined;
33}
34
35export interface ProcessRunOutput {
36 readonly stdout: string;
37 readonly stderr: string;
38 readonly code: ChildProcessSpawner.ExitCode | null;
39 readonly timedOut: boolean;
40 readonly stdoutTruncated: boolean;
41 readonly stderrTruncated: boolean;
42}
43
44export class ProcessSpawnError extends Data.TaggedError("ProcessSpawnError")<{
45 readonly command: string;
46 readonly args: ReadonlyArray<string>;
47 readonly cwd?: string | undefined;
48 readonly cause: unknown;
49}> {}
50
51export class ProcessStdinError extends Data.TaggedError("ProcessStdinError")<{
52 readonly command: string;
53 readonly args: ReadonlyArray<string>;
54 readonly cwd?: string | undefined;
55 readonly cause: unknown;
56}> {}
57
58export class ProcessOutputLimitError extends Data.TaggedError("ProcessOutputLimitError")<{
59 readonly command: string;
60 readonly args: ReadonlyArray<string>;
61 readonly cwd?: string | undefined;
62 readonly stream: "stdout" | "stderr";
63 readonly maxBytes: number;
64}> {}
65
66export class ProcessReadError extends Data.TaggedError("ProcessReadError")<{
67 readonly command: string;
68 readonly args: ReadonlyArray<string>;
69 readonly cwd?: string | undefined;
70 readonly stream: "stdout" | "stderr" | "exitCode";
71 readonly cause: unknown;
72}> {}
73
74export class ProcessTimeoutError extends Data.TaggedError("ProcessTimeoutError")<{
75 readonly command: string;
76 readonly args: ReadonlyArray<string>;
77 readonly cwd?: string | undefined;
78 readonly timeoutMs: number;
79}> {}
80
81export type ProcessRunError =
82 | ProcessSpawnError
83 | ProcessStdinError
84 | ProcessOutputLimitError
85 | ProcessReadError
86 | ProcessTimeoutError;
87
88export interface ProcessRunnerShape {
89 readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
90}
91
92export class ProcessRunner extends Context.Service<ProcessRunner, ProcessRunnerShape>()(
93 "t3/processRunner",
94) {}
95
96const DEFAULT_TIMEOUT = "60 seconds";
97const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
98
99const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
100 /is not recognized as an internal or external command/i,
101 /n.o . reconhecido como um comando interno/i,
102 /non . riconosciuto come comando interno o esterno/i,
103 /n.est pas reconnu en tant que commande interne/i,
104 /no se reconoce como un comando interno o externo/i,
105 /wird nicht als interner oder externer befehl/i,
106] as const;
107
108function hasWindowsCommandNotFoundMessage(output: string): boolean {
109 return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));
110}
111
112export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
113 if (process.platform !== "win32") return false;
114 if (code === 9009) return true;
115 return hasWindowsCommandNotFoundMessage(stderr);
116}
117
118const collectText = Effect.fn("processRunner.collectText")(function* (input: {
119 readonly command: string;
120 readonly args: ReadonlyArray<string>;
121 readonly cwd?: string | undefined;
122 readonly streamName: "stdout" | "stderr";
123 readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
124 readonly maxOutputBytes: number;
125 readonly outputMode: "error" | "truncate";
126 readonly truncatedMarker: string;
127}) {
128 const stream = input.stream.pipe(
129 Stream.mapError(
130 (cause) =>
131 new ProcessReadError({
132 command: input.command,
133 args: input.args,
134 cwd: input.cwd,
135 stream: input.streamName,
136 cause,
137 }),
138 ),
139 );
140
141 if (input.outputMode === "truncate") {
142 return yield* collectUint8StreamText({
143 stream,
144 maxBytes: input.maxOutputBytes,
145 truncatedMarker: input.truncatedMarker,
146 });
147 }
148
149 return yield* stream.pipe(
150 Stream.runFoldEffect<
151 {
152 readonly chunks: Uint8Array<ArrayBufferLike>[];
153 readonly bytes: number;
154 },
155 Uint8Array<ArrayBufferLike>,
156 ProcessOutputLimitError | ProcessReadError,
157 never
158 >(
159 () => ({ chunks: [], bytes: 0 }),
160 (state, chunk) => {
161 const remainingBytes = input.maxOutputBytes - state.bytes;
162 if (remainingBytes <= 0 || chunk.byteLength > remainingBytes) {
163 return Effect.fail(
164 new ProcessOutputLimitError({
165 command: input.command,
166 args: input.args,
167 cwd: input.cwd,
168 stream: input.streamName,
169 maxBytes: input.maxOutputBytes,
170 }),
171 );
172 }
173
174 state.chunks.push(chunk);
175 return Effect.succeed({
176 chunks: state.chunks,
177 bytes: state.bytes + chunk.byteLength,
178 });
179 },
180 ),
181 Effect.map(
182 (state): CollectedUint8StreamText => ({
183 text: Buffer.concat(state.chunks, state.bytes).toString("utf8"),
184 bytes: state.bytes,
185 truncated: false,
186 }),
187 ),
188 );
189});
190
191function finalizeRunProcess<R>(
192 effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
193 input: ProcessRunInput,
194): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
195 const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
196 const timeoutBehavior = input.timeoutBehavior ?? "error";
197
198 return effect.pipe(
199 Effect.scoped,
200 Effect.timeoutOption(timeout),
201 Effect.flatMap((result) => {
202 if (Option.isSome(result)) {
203 return Effect.succeed(result.value);
204 }
205 if (timeoutBehavior === "timedOutResult") {
206 return Effect.succeed({
207 stdout: "",
208 stderr: "",
209 code: null,
210 timedOut: true,
211 stdoutTruncated: false,
212 stderrTruncated: false,
213 } satisfies ProcessRunOutput);
214 }
215 return Effect.fail(
216 new ProcessTimeoutError({
217 command: input.command,
218 args: input.args,
219 cwd: input.cwd,
220 timeoutMs: Duration.toMillis(timeout),
221 }),
222 );
223 }),
224 );
225}
226
227const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
228 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
229 input: ProcessRunInput,
230): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
231 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
232 const outputMode = input.outputMode ?? "error";
233 const truncatedMarker = input.truncatedMarker ?? "";
234
235 const child = yield* spawner
236 .spawn(
237 ChildProcess.make(input.command, [...input.args], {
238 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
239 ...(input.env !== undefined
240 ? {
241 env: input.env,
242 extendEnv: true,
243 }
244 : {}),
245 ...(input.shell !== undefined ? { shell: input.shell } : {}),
246 }),
247 )
248 .pipe(
249 Effect.mapError(
250 (cause) =>
251 new ProcessSpawnError({
252 command: input.command,
253 args: input.args,
254 cwd: input.cwd,
255 cause,
256 }),
257 ),
258 );
259
260 const writeStdin =
261 input.stdin === undefined
262 ? Effect.void
263 : Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
264 Effect.mapError(
265 (cause) =>
266 new ProcessStdinError({
267 command: input.command,
268 args: input.args,
269 cwd: input.cwd,
270 cause,
271 }),
272 ),
273 );
274
275 const [stdout, stderr] = yield* Effect.all(
276 [
277 collectText({
278 command: input.command,
279 args: input.args,
280 cwd: input.cwd,
281 streamName: "stdout",
282 stream: child.stdout,
283 maxOutputBytes,
284 outputMode,
285 truncatedMarker,
286 }),
287 collectText({
288 command: input.command,
289 args: input.args,
290 cwd: input.cwd,
291 streamName: "stderr",
292 stream: child.stderr,
293 maxOutputBytes,
294 outputMode,
295 truncatedMarker,
296 }),
297 writeStdin,
298 ],
299 { concurrency: "unbounded" },
300 );
301
302 const exitCode = yield* child.exitCode.pipe(
303 Effect.mapError(
304 (cause) =>
305 new ProcessReadError({
306 command: input.command,
307 args: input.args,
308 cwd: input.cwd,
309 stream: "exitCode",
310 cause,
311 }),
312 ),
313 );
314
315 return {
316 stdout: stdout.text,
317 stderr: stderr.text,
318 code: exitCode,
319 timedOut: false,
320 stdoutTruncated: stdout.truncated,
321 stderrTruncated: stderr.truncated,
322 } satisfies ProcessRunOutput;
323});
324
325export const make = Effect.fn("makeProcessRunner")(function* () {
326 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
327
328 const run: ProcessRunnerShape["run"] = (input) =>
329 finalizeRunProcess(runProcessCore(spawner, input), input);
330
331 return ProcessRunner.of({
332 run,
333 });
334});
335
336export const layer = Layer.effect(ProcessRunner, make());