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

NodeChildProcessSpawner.ts

713 lines24.1 KB

1/**
2 * Shared Node.js implementation of the child process spawner service.
3 *
4 * This module adapts `node:child_process.spawn` to the Effect
5 * `ChildProcessSpawner` service. Provide {@link layer} to run `ChildProcess`
6 * commands in Node-compatible runtimes: commands get scoped process handles
7 * with stdin sinks, stdout and stderr streams, exit-code waiting,
8 * interruption-time cleanup, process killing, and custom file-descriptor pipes.
9 *
10 * The implementation sits below the command-building API. It validates and
11 * resolves `cwd` through the Effect `FileSystem` and `Path` services,
12 * translates Node errno failures to `PlatformError`, and uses scopes to
13 * terminate referenced children when the owning effect is interrupted or
14 * finalized. Pipelines are flattened by {@link flattenCommand} and spawned one
15 * process at a time, wiring the selected source stream (`stdout`, `stderr`,
16 * `all`, or `fdN`) to the destination `stdin` or `fdN`.
17 *
18 * @since 4.0.0
19 */
20import type * as Arr from "effect/Array"
21import * as Deferred from "effect/Deferred"
22import * as Effect from "effect/Effect"
23import * as Exit from "effect/Exit"
24import * as FileSystem from "effect/FileSystem"
25import * as Layer from "effect/Layer"
26import * as Path from "effect/Path"
27import type * as PlatformError from "effect/PlatformError"
28import * as Predicate from "effect/Predicate"
29import type * as Scope from "effect/Scope"
30import * as Sink from "effect/Sink"
31import * as Stream from "effect/Stream"
32import * as ChildProcess from "effect/unstable/process/ChildProcess"
33import type { ChildProcessHandle } from "effect/unstable/process/ChildProcessSpawner"
34import {
35 ChildProcessSpawner,
36 ExitCode,
37 make as makeSpawner,
38 makeHandle,
39 ProcessId
40} from "effect/unstable/process/ChildProcessSpawner"
41import * as NodeChildProcess from "node:child_process"
42import { handleErrnoException } from "./internal/utils.ts"
43import * as NodeSink from "./NodeSink.ts"
44import * as NodeStream from "./NodeStream.ts"
45​
46const toError = (error: unknown): Error =>
47 error instanceof globalThis.Error
48 ? error
49 : new globalThis.Error(String(error))
50​
51const toPlatformError = (
52 method: string,
53 error: NodeJS.ErrnoException,
54 command: ChildProcess.Command
55): PlatformError.PlatformError => {
56 const { commands } = flattenCommand(command)
57 const commandStr = commands.reduce((acc, curr) => {
58 const cmd = `${curr.command} ${curr.args.join(" ")}`
59 return acc.length === 0 ? cmd : `${acc} | ${cmd}`
60 }, "")
61 return handleErrnoException("ChildProcess", method)(error, [commandStr])
63​
64type ExitCodeWithSignal = readonly [code: number | null, signal: NodeJS.Signals | null]
65type ExitSignal = Deferred.Deferred<ExitCodeWithSignal>
66​
67const make = Effect.gen(function*() {
68 const fs = yield* FileSystem.FileSystem
69 const path = yield* Path.Path
70​
71 const resolveWorkingDirectory = Effect.fnUntraced(
72 function*(options: ChildProcess.CommandOptions) {
73 if (Predicate.isUndefined(options.cwd)) return undefined
74 // Validate that the specified directory is accessible
75 yield* fs.access(options.cwd)
76 return path.resolve(options.cwd)
77 }
78 )
79​
80 const resolveEnvironment = (options: ChildProcess.CommandOptions) => {
81 return options.extendEnv
82 ? { ...globalThis.process.env, ...options.env }
83 : options.env
84 }
85​
86 const inputToStdioOption = (input: ChildProcess.CommandInput | undefined): NodeChildProcess.IOType | undefined =>
87 Stream.isStream(input) ? "pipe" : input
88​
89 const outputToStdioOption = (input: ChildProcess.CommandOutput | undefined): NodeChildProcess.IOType | undefined =>
90 Sink.isSink(input) ? "pipe" : input
91​
92 const resolveStdinOption = (options: ChildProcess.CommandOptions): ChildProcess.StdinConfig => {
93 const defaultConfig: ChildProcess.StdinConfig = { stream: "pipe", encoding: "utf-8", endOnDone: true }
94 if (Predicate.isUndefined(options.stdin)) {
95 return defaultConfig
96 }
97 if (typeof options.stdin === "string") {
98 return { ...defaultConfig, stream: options.stdin }
99 }
100 if (Stream.isStream(options.stdin)) {
101 return { ...defaultConfig, stream: options.stdin }
102 }
103 return {
104 stream: options.stdin.stream,
105 encoding: options.stdin.encoding ?? defaultConfig.encoding,
106 endOnDone: options.stdin.endOnDone ?? defaultConfig.endOnDone
107 }
108 }
109​
110 const resolveOutputOption = (
111 options: ChildProcess.CommandOptions,
112 streamName: "stdout" | "stderr"
113 ): ChildProcess.StdoutConfig => {
114 const option = options[streamName]
115 if (Predicate.isUndefined(option)) {
116 return { stream: "pipe" }
117 }
118 if (typeof option === "string") {
119 return { stream: option }
120 }
121 if (Sink.isSink(option)) {
122 return { stream: option }
123 }
124 return { stream: option.stream }
125 }
126​
127 interface ResolvedAdditionalFd {
128 readonly fd: number
129 readonly config: ChildProcess.AdditionalFdConfig
130 }
131​
132 const resolveAdditionalFds = (
133 options: ChildProcess.CommandOptions
134 ): ReadonlyArray<ResolvedAdditionalFd> => {
135 if (Predicate.isUndefined(options.additionalFds)) {
136 return []
137 }
138 const result: Array<ResolvedAdditionalFd> = []
139 for (const [name, config] of Object.entries(options.additionalFds)) {
140 const fd = ChildProcess.parseFdName(name)
141 if (Predicate.isNotUndefined(fd)) {
142 result.push({ fd, config })
143 }
144 }
145 // Sort by fd number to ensure correct ordering
146 return result.sort((a, b) => a.fd - b.fd)
147 }
148​
149 const buildStdioArray = (
150 stdinConfig: ChildProcess.StdinConfig,
151 stdoutConfig: ChildProcess.StdoutConfig,
152 stderrConfig: ChildProcess.StderrConfig,
153 additionalFds: ReadonlyArray<ResolvedAdditionalFd>
154 ): NodeChildProcess.StdioOptions => {
155 const stdio: Array<NodeChildProcess.IOType | undefined> = [
156 inputToStdioOption(stdinConfig.stream),
157 outputToStdioOption(stdoutConfig.stream),
158 outputToStdioOption(stderrConfig.stream)
159 ]
160​
161 if (additionalFds.length === 0) {
162 return stdio as NodeChildProcess.StdioOptions
163 }
164​
165 // Find the maximum fd number to size the array correctly
166 const maxFd = additionalFds.reduce((max, { fd }) => Math.max(max, fd), 2)
167​
168 // Fill gaps with "ignore"
169 for (let i = 3; i <= maxFd; i++) {
170 stdio[i] = "ignore"
171 }
172​
173 // Set up additional fds as "pipe"
174 for (const { fd } of additionalFds) {
175 stdio[fd] = "pipe"
176 }
177​
178 return stdio as NodeChildProcess.StdioOptions
179 }
180​
181 const setupAdditionalFds = Effect.fnUntraced(function*(
182 command: ChildProcess.StandardCommand,
183 childProcess: NodeChildProcess.ChildProcess,
184 additionalFds: ReadonlyArray<ResolvedAdditionalFd>
185 ) {
186 if (additionalFds.length === 0) {
187 return {
188 getInputFd: () => Sink.drain,
189 getOutputFd: () => Stream.empty
190 }
191 }
192​
193 const inputSinks = new Map<number, Sink.Sink<void, Uint8Array, never, PlatformError.PlatformError>>()
194 const outputStreams = new Map<number, Stream.Stream<Uint8Array, PlatformError.PlatformError>>()
195​
196 for (const { config, fd } of additionalFds) {
197 const nodeStream = childProcess.stdio[fd]
198​
199 switch (config.type) {
200 case "input": {
201 // Create a sink to write to for input file descriptors
202 let sink: Sink.Sink<void, Uint8Array, never, PlatformError.PlatformError> = Sink.drain
203 if (nodeStream && "write" in nodeStream) {
204 sink = NodeSink.fromWritable({
205 evaluate: () => nodeStream,
206 onError: (error) => toPlatformError(`fromWritable(fd${fd})`, toError(error), command)
207 })
208 }
209​
210 // If user provided a stream, pipe it into the sink
211 if (config.stream) {
212 yield* Effect.forkScoped(Stream.run(config.stream, sink))
213 }
214​
215 inputSinks.set(fd, sink)
216​
217 break
218 }
219 case "output": {
220 // Create a stream to read from for output file descriptors
221 let stream: Stream.Stream<Uint8Array, PlatformError.PlatformError> = Stream.empty
222 if (nodeStream && "read" in nodeStream) {
223 stream = NodeStream.fromReadable({
224 evaluate: () => nodeStream,
225 onError: (error) => toPlatformError(`fromReadable(fd${fd})`, toError(error), command)
226 })
227 }
228​
229 // If user provided a sink, transduce the stream through it
230 if (config.sink) {
231 stream = Stream.transduce(stream, config.sink)
232 }
233​
234 outputStreams.set(fd, stream)
235​
236 break
237 }
238 }
239 }
240​
241 return {
242 getInputFd: (fd: number) => inputSinks.get(fd) ?? Sink.drain,
243 getOutputFd: (fd: number) => outputStreams.get(fd) ?? Stream.empty
244 }
245 })
246​
247 const setupChildStdin = (
248 command: ChildProcess.StandardCommand,
249 childProcess: NodeChildProcess.ChildProcess,
250 config: ChildProcess.StdinConfig
251 ) =>
252 Effect.suspend(() => {
253 // If the child process has a standard input stream, connect it to the
254 // sink that will attached to the process handle
255 let sink: Sink.Sink<void, unknown, never, PlatformError.PlatformError> = Sink.drain
256 if (Predicate.isNotNull(childProcess.stdin)) {
257 sink = NodeSink.fromWritable({
258 evaluate: () => childProcess.stdin!,
259 onError: (error) => toPlatformError("fromWritable(stdin)", toError(error), command),
260 endOnDone: config.endOnDone,
261 encoding: config.encoding
262 })
263 }
264​
265 // If the user provided a `Stream`, run it into the stdin sink
266 if (Stream.isStream(config.stream)) {
267 return Effect.as(Effect.forkScoped(Stream.run(config.stream, sink)), sink)
268 }
269​
270 return Effect.succeed(sink)
271 })
272​
273 const setupChildOutputStreams = (
274 command: ChildProcess.StandardCommand,
275 childProcess: NodeChildProcess.ChildProcess,
276 stdoutConfig: ChildProcess.StdoutConfig,
277 stderrConfig: ChildProcess.StderrConfig
278 ): {
279 stdout: Stream.Stream<Uint8Array, PlatformError.PlatformError>
280 stderr: Stream.Stream<Uint8Array, PlatformError.PlatformError>
281 all: Stream.Stream<Uint8Array, PlatformError.PlatformError>
282 } => {
283 let stdout = childProcess.stdout ?
284 NodeStream.fromReadable({
285 evaluate: () => childProcess.stdout!,
286 onError: (error) => toPlatformError("fromReadable(stdout)", toError(error), command)
287 }) :
288 Stream.empty
289 let stderr = childProcess.stderr ?
290 NodeStream.fromReadable({
291 evaluate: () => childProcess.stderr!,
292 onError: (error) => toPlatformError("fromReadable(stderr)", toError(error), command)
293 }) :
294 Stream.empty
295​
296 if (Sink.isSink(stdoutConfig.stream)) {
297 stdout = Stream.transduce(stdout, stdoutConfig.stream)
298 }
299 if (Sink.isSink(stderrConfig.stream)) {
300 stderr = Stream.transduce(stderr, stderrConfig.stream)
301 }
302​
303 const all = Stream.merge(stdout, stderr)
304​
305 return { stdout, stderr, all }
306 }
307​
308 const spawn = (
309 command: ChildProcess.StandardCommand,
310 spawnOptions: NodeChildProcess.SpawnOptions
311 ) =>
312 Effect.callback<
313 readonly [NodeChildProcess.ChildProcess, ExitSignal],
314 PlatformError.PlatformError
315 >((resume) => {
316 const deferred = Deferred.makeUnsafe<ExitCodeWithSignal>()
317 const handle = NodeChildProcess.spawn(
318 command.command,
319 command.args,
320 spawnOptions
321 )
322 handle.on("error", (error) => {
323 resume(Effect.fail(toPlatformError("spawn", error, command)))
324 })
325 handle.on("exit", (...args) => {
326 Deferred.doneUnsafe(deferred, Exit.succeed(args))
327 })
328 handle.on("spawn", () => {
329 resume(Effect.succeed([handle, deferred]))
330 })
331 return Effect.sync(() => {
332 handle.kill("SIGTERM")
333 })
334 })
335​
336 const killProcessGroup = (
337 command: ChildProcess.StandardCommand,
338 childProcess: NodeChildProcess.ChildProcess,
339 signal: NodeJS.Signals
340 ) => {
341 if (globalThis.process.platform === "win32") {
342 return Effect.callback<void, PlatformError.PlatformError>((resume) => {
343 NodeChildProcess.exec(`taskkill /pid ${childProcess.pid} /T /F`, (error) => {
344 if (error) {
345 resume(Effect.fail(toPlatformError("kill", toError(error), command)))
346 } else {
347 resume(Effect.void)
348 }
349 })
350 })
351 }
352 return Effect.try({
353 try: () => {
354 globalThis.process.kill(-childProcess.pid!, signal)
355 },
356 catch: (error) => toPlatformError("kill", toError(error), command)
357 })
358 }
359​
360 const killProcessGroupOnExit = (
361 childProcess: NodeChildProcess.ChildProcess,
362 signal: NodeJS.Signals
363 ): void => {
364 if (globalThis.process.platform === "win32") {
365 NodeChildProcess.exec(`taskkill /pid ${childProcess.pid} /T /F`, () => {
366 // ignore errors during best-effort cleanup
367 })
368 return
369 }
370 try {
371 globalThis.process.kill(-childProcess.pid!, signal)
372 } catch {
373 // ignore errors during best-effort cleanup
374 }
375 }
376​
377 const killProcess = (
378 command: ChildProcess.StandardCommand,
379 childProcess: NodeChildProcess.ChildProcess,
380 signal: NodeJS.Signals
381 ) =>
382 Effect.suspend(() => {
383 const killed = childProcess.kill(signal)
384 if (!killed) {
385 const error = new globalThis.Error("Failed to kill child process")
386 return Effect.fail(toPlatformError("kill", error, command))
387 }
388 return Effect.void
389 })
390​
391 const withTimeout = (
392 childProcess: NodeChildProcess.ChildProcess,
393 command: ChildProcess.StandardCommand,
394 options: ChildProcess.KillOptions | undefined
395 ) =>
396 <A, E, R>(
397 kill: (
398 command: ChildProcess.StandardCommand,
399 childProcess: NodeChildProcess.ChildProcess,
400 signal: NodeJS.Signals
401 ) => Effect.Effect<A, E, R>
402 ) => {
403 const killSignal = options?.killSignal ?? "SIGTERM"
404 return Predicate.isUndefined(options?.forceKillAfter)
405 ? kill(command, childProcess, killSignal)
406 : Effect.timeoutOrElse(kill(command, childProcess, killSignal), {
407 duration: options.forceKillAfter,
408 orElse: () => kill(command, childProcess, "SIGKILL")
409 })
410 }
411​
412 /**
413 * Get the appropriate source stream from a process handle based on the
414 * `from` pipe option.
415 */
416 const getSourceStream = (
417 handle: ChildProcessHandle,
418 from: ChildProcess.PipeFromOption | undefined
419 ): Stream.Stream<Uint8Array, PlatformError.PlatformError> => {
420 const fromOption = from ?? "stdout"
421 switch (fromOption) {
422 case "stdout":
423 return handle.stdout
424 case "stderr":
425 return handle.stderr
426 case "all":
427 return handle.all
428 default: {
429 // Handle fd3, fd4, etc.
430 const fd = ChildProcess.parseFdName(fromOption)
431 if (Predicate.isNotUndefined(fd)) {
432 return handle.getOutputFd(fd)
433 }
434 // Fallback to stdout for invalid fd names
435 return handle.stdout
436 }
437 }
438 }
439​
440 const spawnCommand: (
441 command: ChildProcess.Command
442 ) => Effect.Effect<
443 ChildProcessHandle,
444 PlatformError.PlatformError,
445 Scope.Scope
446 > = Effect.fnUntraced(function*(cmd) {
447 switch (cmd._tag) {
448 case "StandardCommand": {
449 const stdinConfig = resolveStdinOption(cmd.options)
450 const stdoutConfig = resolveOutputOption(cmd.options, "stdout")
451 const stderrConfig = resolveOutputOption(cmd.options, "stderr")
452 const resolvedAdditionalFds = resolveAdditionalFds(cmd.options)
453 let isReferenced = true
454 let cleanupOnNonZeroExit = false
455​
456 const cwd = yield* resolveWorkingDirectory(cmd.options)
457 const env = resolveEnvironment(cmd.options)
458 const stdio = buildStdioArray(stdinConfig, stdoutConfig, stderrConfig, resolvedAdditionalFds)
459​
460 const [childProcess, exitSignal] = yield* Effect.acquireRelease(
461 spawn(cmd, {
462 cwd,
463 env,
464 stdio,
465 detached: cmd.options.detached ?? process.platform !== "win32",
466 shell: cmd.options.shell
467 }),
468 Effect.fnUntraced(function*([childProcess, exitSignal]) {
469 const exited = yield* Deferred.isDone(exitSignal)
470 const killWithTimeout = withTimeout(childProcess, cmd, cmd.options)
471 if (exited) {
472 // Process already exited, check if children need cleanup
473 const [code] = yield* Deferred.await(exitSignal)
474 if (code !== 0 && Predicate.isNotNull(code)) {
475 // Non-zero exit code ,attempt to clean up process group
476 return yield* Effect.ignore(killWithTimeout(killProcessGroup))
477 }
478 return yield* Effect.void
479 }
480 if (!isReferenced) {
481 return yield* Effect.void
482 }
483 // Process is still running, kill it
484 return yield* killWithTimeout((command, childProcess, signal) =>
485 Effect.catch(
486 killProcessGroup(command, childProcess, signal),
487 () => killProcess(command, childProcess, signal)
488 )
489 ).pipe(
490 Effect.andThen(Deferred.await(exitSignal)),
491 Effect.ignore
492 )
493 })
494 )
495​
496 const pid = ProcessId(childProcess.pid!)
497 childProcess.on("exit", (code) => {
498 if (cleanupOnNonZeroExit && code !== 0 && Predicate.isNotNull(code)) {
499 killProcessGroupOnExit(childProcess, cmd.options.killSignal ?? "SIGTERM")
500 }
501 })
502 const reref = Effect.sync(() => {
503 if (!isReferenced) {
504 childProcess.ref()
505 isReferenced = true
506 cleanupOnNonZeroExit = false
507 }
508 })
509 const unref = Effect.sync(() => {
510 if (isReferenced) {
511 childProcess.unref()
512 isReferenced = false
513 cleanupOnNonZeroExit = true
514 }
515 return reref
516 })
517 const stdin = yield* setupChildStdin(cmd, childProcess, stdinConfig)
518 const { all, stderr, stdout } = setupChildOutputStreams(cmd, childProcess, stdoutConfig, stderrConfig)
519 const { getInputFd, getOutputFd } = yield* setupAdditionalFds(cmd, childProcess, resolvedAdditionalFds)
520 const isRunning = Effect.map(Deferred.isDone(exitSignal), (done) => !done)
521 const exitCode = Effect.flatMap(Deferred.await(exitSignal), ([code, signal]) => {
522 if (Predicate.isNotNull(code)) {
523 return Effect.succeed(ExitCode(code))
524 }
525 // If code is `null`, then `signal` must be defined. See the NodeJS
526 // documentation for the `"exit"` event on a `child_process`.
527 // https://nodejs.org/api/child_process.html#child_process_event_exit
528 const error = new globalThis.Error(`Process interrupted due to receipt of signal: '${signal}'`)
529 return Effect.fail(toPlatformError("exitCode", error, cmd))
530 })
531 const kill = (options?: ChildProcess.KillOptions | undefined) => {
532 const killWithTimeout = withTimeout(childProcess, cmd, options)
533 return killWithTimeout((command, childProcess, signal) =>
534 Effect.catch(
535 killProcessGroup(command, childProcess, signal),
536 () => killProcess(command, childProcess, signal)
537 )
538 ).pipe(
539 Effect.andThen(Deferred.await(exitSignal)),
540 Effect.asVoid
541 )
542 }
543​
544 return makeHandle({
545 pid,
546 exitCode,
547 isRunning,
548 kill,
549 stdin,
550 stdout,
551 stderr,
552 all,
553 getInputFd,
554 getOutputFd,
555 unref
556 })
557 }
558 case "PipedCommand": {
559 const { commands, pipeOptions } = flattenCommand(cmd)
560 const [root, ...pipeline] = commands
561​
562 const handles = [yield* spawnCommand(root)]
563​
564 for (let i = 0; i < pipeline.length; i++) {
565 const command = pipeline[i]
566 const options = pipeOptions[i] ?? {}
567 const stdinConfig = resolveStdinOption(command.options)
568​
569 // Get the appropriate stream from the source based on `from` option
570 const sourceStream = Stream.unwrap(
571 Effect.succeed(getSourceStream(handles[handles.length - 1], options.from))
572 )
573​
574 // Determine where to pipe: stdin or custom fd
575 const toOption = options.to ?? "stdin"
576​
577 if (toOption === "stdin") {
578 // Pipe to stdin (default behavior)
579 handles.push(
580 yield* spawnCommand(ChildProcess.make(command.command, command.args, {
581 ...command.options,
582 stdin: { ...stdinConfig, stream: sourceStream }
583 }))
584 )
585 } else {
586 // Pipe to custom fd (fd3, fd4, etc.)
587 const fd = ChildProcess.parseFdName(toOption)
588 if (Predicate.isNotUndefined(fd)) {
589 const fdName = ChildProcess.fdName(fd) as `fd${number}`
590 const existingFds = command.options.additionalFds ?? {}
591 handles.push(
592 yield* spawnCommand(ChildProcess.make(command.command, command.args, {
593 ...command.options,
594 additionalFds: {
595 ...existingFds,
596 [fdName]: { type: "input" as const, stream: sourceStream }
597 }
598 }))
599 )
600 } else {
601 // Invalid fd name, fall back to stdin
602 handles.push(
603 yield* spawnCommand(ChildProcess.make(command.command, command.args, {
604 ...command.options,
605 stdin: { ...stdinConfig, stream: sourceStream }
606 }))
607 )
608 }
609 }
610 }
611​
612 const handle = handles[handles.length - 1]
613 const unref = Effect.gen(function*() {
614 const rerefs: Array<Effect.Effect<void, PlatformError.PlatformError>> = []
615 for (const handle of handles) {
616 rerefs.push(yield* handle.unref)
617 }
618 return Effect.forEach([...rerefs].reverse(), (reref) => reref, { discard: true })
619 })
620​
621 return makeHandle({
622 pid: handle.pid,
623 exitCode: handle.exitCode,
624 isRunning: handle.isRunning,
625 kill: handle.kill,
626 stdin: handle.stdin,
627 stdout: handle.stdout,
628 stderr: handle.stderr,
629 all: handle.all,
630 getInputFd: handle.getInputFd,
631 getOutputFd: handle.getOutputFd,
632 unref
633 })
634 }
635 }
636 })
637​
638 return makeSpawner(spawnCommand)
639})
640​
641/**
642 * Layer that provides the `NodeChildProcessSpawner` implementation.
643 *
644 * @category layers
645 * @since 4.0.0
646 */
647export const layer: Layer.Layer<
648 ChildProcessSpawner,
649 never,
650 FileSystem.FileSystem | Path.Path
651> = Layer.effect(ChildProcessSpawner, make)
652​
653// =============================================================================
654// Internal Helpers
655// =============================================================================
656​
657/**
658 * Result of flattening a pipeline of commands.
659 *
660 * @category models
661 * @since 4.0.0
662 */
663export interface FlattenedPipeline {
664 readonly commands: Arr.NonEmptyReadonlyArray<ChildProcess.StandardCommand>
665 readonly pipeOptions: ReadonlyArray<ChildProcess.PipeOptions>
667​
668/**
669 * Flattens a `Command` into an array of `StandardCommand`s along with pipe
670 * options for each connection.
671 *
672 * @category utils
673 * @since 4.0.0
674 */
675export const flattenCommand = (
676 command: ChildProcess.Command
677): FlattenedPipeline => {
678 const commands: Array<ChildProcess.StandardCommand> = []
679 const pipeOptions: Array<ChildProcess.PipeOptions> = []
680​
681 const flatten = (cmd: ChildProcess.Command): void => {
682 switch (cmd._tag) {
683 case "StandardCommand": {
684 commands.push(cmd)
685 break
686 }
687 case "PipedCommand": {
688 // Recursively flatten left side first
689 flatten(cmd.left)
690 // Store the pipe options for this connection
691 pipeOptions.push(cmd.options)
692 // Then flatten right side
693 flatten(cmd.right)
694 break
695 }
696 }
697 }
698​
699 flatten(command)
700​
701 // The commands array is guaranteed to be non-empty since we always have at
702 // least one command in the input. We validate this at runtime and return a
703 // properly typed tuple.
704 if (commands.length === 0) {
705 // This should never happen given a valid Command input
706 throw new Error("flattenCommand produced empty commands array")
707 }
708​
709 const [first, ...rest] = commands
710 const nonEmptyCommands: Arr.NonEmptyReadonlyArray<ChildProcess.StandardCommand> = [first, ...rest]
711​
712 return { commands: nonEmptyCommands, pipeOptions }