Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as PlatformError from "effect/PlatformError";
6import * as Sink from "effect/Sink";
7import * as Stream from "effect/Stream";
8import { ChildProcessSpawner } from "effect/process";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import { SpawnExecutableResolution } from "@t3tools/shared/shell";
11
12import * as ProcessRunner from "./processRunner.ts";
13
14type ChildProcessCommand = {
15 readonly command: string;
16 readonly args: ReadonlyArray<string>;
17 readonly options: {
18 readonly shell?: boolean | string;
19 };
20};
21
22function asChildProcessCommand(command: unknown): ChildProcessCommand {
23 return command as ChildProcessCommand;
24}
25
26function makeHandle(input: {
27 readonly stdout?: string | Stream.Stream<Uint8Array>;
28 readonly stderr?: string | Stream.Stream<Uint8Array>;
29 readonly code?: number;
30 readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
31 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
32}) {
33 return ChildProcessSpawner.makeHandle({
34 pid: ChildProcessSpawner.ProcessId(1),
35 exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
36 isRunning: Effect.succeed(false),
37 kill: () => Effect.void,
38 unref: Effect.succeed(Effect.void),
39 stdin: input.stdin ?? Sink.drain,
40 stdout:
41 typeof input.stdout === "string"
42 ? Stream.encodeText(Stream.make(input.stdout))
43 : (input.stdout ?? Stream.empty),
44 stderr:
45 typeof input.stderr === "string"
46 ? Stream.encodeText(Stream.make(input.stderr))
47 : (input.stderr ?? Stream.empty),
48 all: Stream.empty,
49 getInputFd: () => Sink.drain,
50 getOutputFd: () => Stream.empty,
51 });
52}
53
54function makeSpawner(
55 f: (
56 command: ChildProcessCommand,
57 ) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>,
58) {
59 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
60}
61
62const runWith =
63 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
64 (input: ProcessRunner.ProcessRunInput) =>
65 Effect.service(ProcessRunner.ProcessRunner).pipe(
66 Effect.flatMap((runner) =>
67 runner.run({
68 ...input,
69 }),
70 ),
71 Effect.provide(
72 ProcessRunner.layer.pipe(
73 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
74 ),
75 ),
76 );
77
78describe("runProcess", () => {
79 it.effect("resolves and escapes Windows command shims before spawning", () => {
80 const spawner = makeSpawner((command) =>
81 Effect.sync(() => {
82 expect(command.command).toBe(
83 [
84 '^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"',
85 '^"repos^"',
86 '^"pr^"',
87 '^"list^"',
88 '^"--source-branch^"',
89 '^"feature^ ^&^ release^"',
90 ].join(" "),
91 );
92 expect(command.args).toEqual([]);
93 expect(command.options.shell).toBe(true);
94 return makeHandle({ stdout: "[]" });
95 }),
96 );
97
98 return runWith(spawner)({
99 command: "az",
100 args: ["repos", "pr", "list", "--source-branch", "feature & release"],
101 env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
102 }).pipe(
103 Effect.provideService(HostProcess.Platform, "win32"),
104 Effect.provideService(HostProcess.Environment, {
105 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
106 PATHEXT: ".COM;.EXE;.BAT;.CMD",
107 }),
108 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
109 env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
110 env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
111 ? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
112 : undefined,
113 ),
114 Effect.map((result) => {
115 expect(result.stdout).toBe("[]");
116 }),
117 );
118 });
119
120 it.effect("types spawn failures that the platform spawner throws synchronously", () =>
121 Effect.gen(function* () {
122 // A non-directory entry on PATH makes node's spawn throw ENOTDIR
123 // synchronously. The platform spawner calls it inside `Effect.callback`,
124 // so the throw arrives as a defect rather than a typed error.
125 const defect = Object.assign(new Error("spawn jj ENOTDIR"), { code: "ENOTDIR" });
126 const spawner = makeSpawner(() =>
127 Effect.callback<never, never>(() => {
128 throw defect;
129 }),
130 );
131
132 const error = yield* runWith(spawner)({
133 command: "jj",
134 args: ["--version"],
135 cwd: "/repo",
136 }).pipe(Effect.flip);
137
138 expect(error._tag).toBe("ProcessSpawnError");
139 if (error._tag !== "ProcessSpawnError") {
140 return expect.fail("Expected ProcessSpawnError");
141 }
142 expect(error).toMatchObject({ command: "jj", argumentCount: 1, cwd: "/repo" });
143 expect(error.cause).toBe(defect);
144 }),
145 );
146
147 it.effect("fails when output exceeds max buffer in default mode", () =>
148 Effect.gen(function* () {
149 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
150
151 const error = yield* runWith(spawner)({
152 command: "fake",
153 args: ["stdout-bytes", "2048"],
154 maxOutputBytes: 128,
155 }).pipe(Effect.flip);
156
157 expect(error._tag).toBe("ProcessOutputLimitError");
158 if (error._tag !== "ProcessOutputLimitError") {
159 return expect.fail("Expected ProcessOutputLimitError");
160 }
161 expect(error).toMatchObject({
162 stream: "stdout",
163 maxBytes: 128,
164 observedBytes: 2048,
165 });
166 expect(error.message).toBe(
167 "Process 'fake' stdout produced 2048 bytes, exceeding the 128 byte limit",
168 );
169 }),
170 );
171
172 it.effect("accepts output at the byte limit followed by an empty chunk", () =>
173 Effect.gen(function* () {
174 const output = new TextEncoder().encode("exactly");
175 const spawner = makeSpawner(() =>
176 Effect.succeed(
177 makeHandle({
178 stdout: Stream.make(output, new Uint8Array()),
179 }),
180 ),
181 );
182
183 const result = yield* runWith(spawner)({
184 command: "fake",
185 args: ["exact-limit"],
186 maxOutputBytes: output.byteLength,
187 });
188
189 expect(result.stdout).toBe("exactly");
190 }),
191 );
192
193 it.effect("fails fast on output limit before timeout for long-running output", () =>
194 Effect.gen(function* () {
195 const textChunk = "x".repeat(64);
196 const spawner = makeSpawner(() =>
197 Effect.succeed(
198 makeHandle({
199 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
200 Stream.encodeText,
201 ),
202 exitCode: Effect.never,
203 }),
204 ),
205 );
206
207 const error = yield* runWith(spawner)({
208 command: "fake",
209 args: ["spam-stdout"],
210 maxOutputBytes: 128,
211 timeout: "2 seconds",
212 }).pipe(Effect.flip);
213
214 expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
215 }),
216 );
217
218 it.effect("truncates output when outputMode is truncate", () =>
219 Effect.gen(function* () {
220 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
221
222 const result = yield* runWith(spawner)({
223 command: "fake",
224 args: ["stdout-bytes", "2048"],
225 maxOutputBytes: 128,
226 outputMode: "truncate",
227 });
228
229 expect(result.code).toBe(0);
230 expect(result.stdout.length).toBeLessThanOrEqual(128);
231 expect(result.stdoutTruncated).toBe(true);
232 expect(result.stderrTruncated).toBe(false);
233 }),
234 );
235
236 it.effect("writes stdin before waiting for exit", () =>
237 Effect.gen(function* () {
238 const stdinWritten = yield* Deferred.make<void>();
239 const decoder = new TextDecoder();
240 const spawner = makeSpawner(() =>
241 Effect.succeed(
242 makeHandle({
243 stdout: "stdin payload",
244 stdin: Sink.forEach((chunk: Uint8Array) => {
245 const text = decoder.decode(chunk, { stream: true });
246 return text.includes("stdin payload")
247 ? Deferred.succeed(stdinWritten, undefined)
248 : Effect.void;
249 }),
250 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
251 }),
252 ),
253 );
254
255 const result = yield* runWith(spawner)({
256 command: "fake",
257 args: ["stdin-echo"],
258 stdin: "stdin payload",
259 });
260
261 expect(result.stdout).toBe("stdin payload");
262 expect(result.code).toBe(0);
263 }),
264 );
265
266 for (const {} of ["timeout", "success"] as const) {
267 }
268});
269
270describe("isWindowsCommandNotFound", () => {
271 it.effect("matches the localized German cmd.exe error text", () =>
272 Effect.gen(function* () {
273 const isCommandNotFound = yield* ProcessRunner.isWindowsCommandNotFound(
274 1,
275 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
276 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
277 expect(isCommandNotFound).toBe(true);
278 }),
279 );
280});