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

NodeChildProcessSpawner.ts

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