-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspawn.ts
More file actions
967 lines (917 loc) · 33.7 KB
/
spawn.ts
File metadata and controls
967 lines (917 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
/**
* @fileoverview Child process spawning utilities with cross-platform support.
* Provides enhanced spawn functionality with stdio handling and error management.
*
* SECURITY: Array-Based Arguments Prevent Command Injection
*
* This module uses array-based arguments for all command execution, which is the
* PRIMARY DEFENSE against command injection attacks. When you pass arguments as
* an array to spawn():
*
* spawn('npx', ['sfw', tool, ...args], { shell: true })
*
* Node.js handles escaping automatically. Each argument is passed directly to the
* OS without shell interpretation. Shell metacharacters like ; | & $ ( ) ` are
* treated as LITERAL STRINGS, not as commands. This approach is secure even when
* shell: true is used on Windows for .cmd/.bat file resolution.
*
* UNSAFE ALTERNATIVE (not used in this codebase):
* spawn(`npx sfw ${tool} ${args.join(' ')}`, { shell: true }) // ✖ VULNERABLE
*
* String concatenation allows injection. For example, if tool = "foo; rm -rf /",
* the shell would execute both commands. Array-based arguments prevent this.
*
* References:
* - https://nodejs.org/api/child_process.html#child_processspawncommand-args-options
* - https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet.html
*/
import process from 'node:process'
import { isArray } from './arrays'
import { whichSync } from './bin'
import { getAbortSignal } from './constants/process'
import { stackWithCauses } from './errors'
import { getOwn, hasOwn } from './objects'
import { isPath } from './paths/normalize'
import { getDefaultSpinner } from './spinner'
import { stripAnsi } from './strings'
import type { SendHandle, Serializable, StdioOptions } from 'node:child_process'
import type { EventEmitter } from 'node:events'
// @ts-expect-error - external vendored module
import type npmCliPromiseSpawnType from './external/@npmcli/promise-spawn'
const abortSignal = getAbortSignal()
const spinner = getDefaultSpinner()
// Cache for lazy stack trace computation.
const stackCache = new WeakMap<Error, string>()
// Cache for binary path resolutions to avoid repeated PATH searches.
// Validated with existsSync() which is much cheaper than PATH search.
const spawnBinPathCache = new Map<string, string>()
// Define BufferEncoding type for TypeScript compatibility.
type BufferEncoding = globalThis.BufferEncoding
const windowsScriptExtRegExp = /\.(?:cmd|bat|ps1)$/i
let _npmCliPromiseSpawn: typeof npmCliPromiseSpawnType | undefined
let _path: typeof import('node:path') | undefined
let _fs: typeof import('node:fs') | undefined
let _child_process: typeof import('node:child_process') | undefined
/**
* Options for spawning a child process with promise-based completion.
*
* @property {string | undefined} cwd - Current working directory for the process
* @property {NodeJS.ProcessEnv | undefined} env - Environment variables for the process
* @property {number | undefined} gid - Group identity of the process (POSIX only)
* @property {boolean | string | undefined} shell - Whether to run command in shell, or path to shell
* @property {AbortSignal | undefined} signal - Signal to abort the process
* @property {StdioType | undefined} stdio - Stdio configuration (`'pipe'`, `'ignore'`, `'inherit'`, or array)
* @property {boolean | undefined} stdioString - Convert stdio output to strings (default: `true`)
* @property {number | undefined} timeout - Maximum time in milliseconds before killing the process
* @property {number | undefined} uid - User identity of the process (POSIX only)
* @property {boolean | undefined} windowsVerbatimArguments - Don't quote or escape arguments on Windows (requires shell: true). Use when you need exact argument control. Default: false
*/
export type PromiseSpawnOptions = {
cwd?: string | undefined
env?: NodeJS.ProcessEnv | undefined
gid?: number | undefined
shell?: boolean | string | undefined
signal?: AbortSignal | undefined
stdio?: StdioType | undefined
stdioString?: boolean | undefined
timeout?: number | undefined
uid?: number | undefined
windowsVerbatimArguments?: boolean | undefined
}
/**
* Result returned by {@link spawn} when the child process completes.
* This is a Promise that resolves with process exit information and output,
* with additional properties for accessing the running process and stdin stream.
*
* @property {ChildProcess} process - The running child process instance
* @property {WritableStreamType | null} stdin - Writable stream for process stdin, or `null` if not piped
*
* @example
* const result = spawn('echo', ['hello'])
* result.stdin?.write('additional input\n')
* const { code, stdout } = await result
* console.log(stdout) // 'hello'
*/
export type PromiseSpawnResult = Promise<{
cmd: string
args: string[] | readonly string[]
code: number
signal: NodeJS.Signals | null
stdout: string | Buffer
stderr: string | Buffer
}> & {
process: ChildProcess
stdin: WritableStreamType | null
}
/**
* Error object thrown when a spawned process fails.
* Extends the standard Error with process-specific information including exit code,
* signal, command details, and captured output.
*
* @property {string[]} args - Arguments passed to the command
* @property {string} cmd - Command that was executed
* @property {number} code - Process exit code
* @property {string} name - Error name (typically `'Error'`)
* @property {string} message - Error message describing the failure
* @property {NodeJS.Signals | null} signal - Signal that terminated the process, if any
* @property {string} stack - Stack trace of the error
* @property {string | Buffer} stderr - Standard error output from the process
* @property {string | Buffer} stdout - Standard output from the process
*
* @example
* try {
* await spawn('exit', ['1'])
* } catch (error) {
* if (isSpawnError(error)) {
* console.error(`Command failed with code ${error.code}`)
* console.error(`stderr: ${error.stderr}`)
* }
* }
*/
export type SpawnError = {
args: string[]
cmd: string
code: number
name: string
message: string
signal: NodeJS.Signals | null
stack: string
stderr: string | Buffer
stdout: string | Buffer
}
/**
* Spawn error variant where stdout and stderr are guaranteed to be strings.
* This type is used when `stdioString: true` is set in spawn options.
*
* @property {string} stdout - Standard output as a string
* @property {string} stderr - Standard error as a string
*/
export type SpawnErrorWithOutputString = SpawnError & {
stdout: string
stderr: string
}
/**
* Spawn error variant where stdout and stderr are guaranteed to be Buffers.
* This type is used when `stdioString: false` is set in spawn options.
*
* @property {Buffer} stdout - Standard output as a Buffer
* @property {Buffer} stderr - Standard error as a Buffer
*/
export type SpawnErrorWithOutputBuffer = SpawnError & {
stdout: Buffer
stderr: Buffer
}
/**
* Extra options passed to the underlying promise-spawn implementation.
* This is an open-ended object for passing additional metadata or configuration.
*/
export type SpawnExtra = Record<string, unknown>
/**
* Valid values for individual stdio streams.
* - `'pipe'` - Creates a pipe between child and parent (default)
* - `'ignore'` - Ignores the stream
* - `'inherit'` - Uses parent's stream
* - `'overlapped'` - Windows-specific overlapped I/O
*/
export type IOType = 'pipe' | 'ignore' | 'inherit' | 'overlapped'
/**
* Configuration for process stdio (stdin, stdout, stderr) streams.
* Can be a single value applied to all streams, or an array specifying each stream individually.
* - `'ipc'` - Creates an IPC channel for communication with the parent
*
* @example
* // All streams piped
* stdio: 'pipe'
*
* @example
* // Custom configuration per stream: [stdin, stdout, stderr]
* stdio: ['ignore', 'pipe', 'pipe']
*/
export type StdioType = IOType | 'ipc' | Array<IOType | 'ipc'>
/**
* Result object returned by {@link spawnSync} when the child process completes synchronously.
*
* @template T - Type of stdout/stderr (string or Buffer)
* @property {number} pid - Process ID of the spawned child
* @property {Array<T | null>} output - Array containing stdout/stderr values
* @property {T} stdout - Standard output from the process
* @property {T} stderr - Standard error from the process
* @property {number | null} status - Exit code, or `null` if killed by signal
* @property {NodeJS.Signals | null} signal - Signal that terminated the process, or `null`
* @property {Error | undefined} error - Error object if the spawn failed
*/
export interface SpawnSyncReturns<T> {
pid: number
output: Array<T | null>
stdout: T
stderr: T
status: number | null
signal: NodeJS.Signals | null
error?: Error | undefined
}
/*@__NO_SIDE_EFFECTS__*/
// Duplicated from Node.js child_process.SpawnOptions
// These are the options passed to child_process.spawn()
interface NodeSpawnOptions {
cwd?: string | URL | undefined
env?: NodeJS.ProcessEnv | undefined
argv0?: string | undefined
stdio?: StdioOptions | undefined
detached?: boolean | undefined
uid?: number | undefined
gid?: number | undefined
serialization?: 'json' | 'advanced' | undefined
shell?: boolean | string | undefined
windowsVerbatimArguments?: boolean | undefined
windowsHide?: boolean | undefined
signal?: AbortSignal | undefined
timeout?: number | undefined
killSignal?: NodeJS.Signals | number | undefined
}
// Duplicated from Node.js child_process.ChildProcess
// This represents a spawned child process
interface ChildProcess extends EventEmitter {
stdin: NodeJS.WritableStream | null
stdout: NodeJS.ReadableStream | null
stderr: NodeJS.ReadableStream | null
readonly channel?: unknown
readonly stdio: [
NodeJS.WritableStream | null,
NodeJS.ReadableStream | null,
NodeJS.ReadableStream | null,
NodeJS.ReadableStream | NodeJS.WritableStream | null | undefined,
NodeJS.ReadableStream | NodeJS.WritableStream | null | undefined,
]
readonly killed: boolean
readonly pid?: number | undefined
readonly connected: boolean
readonly exitCode: number | null
readonly signalCode: NodeJS.Signals | null
readonly spawnargs: string[]
readonly spawnfile: string
kill(signal?: NodeJS.Signals | number): boolean
send(message: Serializable, callback?: (error: Error | null) => void): boolean
send(
message: Serializable,
sendHandle?: SendHandle | undefined,
callback?: (error: Error | null) => void,
): boolean
send(
message: Serializable,
sendHandle?: SendHandle | undefined,
options?: { keepOpen?: boolean | undefined } | undefined,
callback?: (error: Error | null) => void,
): boolean
disconnect(): void
unref(): void
ref(): void
}
// Duplicated from Node.js stream.Writable
interface WritableStreamType {
writable: boolean
writableEnded: boolean
writableFinished: boolean
writableHighWaterMark: number
writableLength: number
writableObjectMode: boolean
writableCorked: number
destroyed: boolean
write(
chunk: unknown,
encoding?: BufferEncoding | undefined,
callback?: (error?: Error | null) => void,
): boolean
write(chunk: unknown, callback?: (error?: Error | null) => void): boolean
end(cb?: () => void): this
end(chunk: unknown, cb?: () => void): this
end(
chunk: unknown,
encoding?: BufferEncoding | undefined,
cb?: () => void,
): this
cork(): void
uncork(): void
destroy(error?: Error | undefined): this
}
/**
* Options for spawning a child process with {@link spawn}.
* Extends Node.js spawn options with additional Socket-specific functionality.
*
* @property {string | URL | undefined} cwd - Current working directory
* @property {NodeJS.ProcessEnv | undefined} env - Environment variables
* @property {number | undefined} gid - Group identity (POSIX)
* @property {boolean | string | undefined} shell - Run command in shell
* @property {AbortSignal | undefined} signal - Abort signal
* @property {import('./spinner').Spinner | undefined} spinner - Spinner instance to pause during execution
* @property {StdioType | undefined} stdio - Stdio configuration
* @property {boolean | undefined} stdioString - Convert output to strings (default: `true`)
* @property {boolean | undefined} stripAnsi - Remove ANSI codes from output (default: `true`)
* @property {number | undefined} timeout - Timeout in milliseconds
* @property {number | undefined} uid - User identity (POSIX)
* @property {boolean | undefined} windowsVerbatimArguments - Don't quote or escape arguments on Windows (requires shell: true). Use when you need exact argument control. Default: false
*/
export type SpawnOptions = import('./objects').Remap<
NodeSpawnOptions & {
spinner?: import('./spinner').Spinner | undefined
stdioString?: boolean
stripAnsi?: boolean
}
>
export type SpawnResult = PromiseSpawnResult
/**
* Result object returned when a spawned process completes.
*
* @property {string} cmd - Command that was executed
* @property {string[] | readonly string[]} args - Arguments passed to the command
* @property {number} code - Process exit code
* @property {NodeJS.Signals | null} signal - Signal that terminated the process, if any
* @property {string | Buffer} stdout - Standard output (string if `stdioString: true`, Buffer otherwise)
* @property {string | Buffer} stderr - Standard error (string if `stdioString: true`, Buffer otherwise)
*/
export type SpawnStdioResult = {
cmd: string
args: string[] | readonly string[]
code: number
signal: NodeJS.Signals | null
stdout: string | Buffer
stderr: string | Buffer
}
/**
* Options for synchronously spawning a child process with {@link spawnSync}.
* Same as {@link SpawnOptions} but excludes the `spinner` property (not applicable for synchronous execution).
*/
export type SpawnSyncOptions = Omit<SpawnOptions, 'spinner'>
/**
* Lazily load the `child_process` module to avoid Webpack bundling issues.
*
* @returns The Node.js `child_process` module
*
* @example
* const childProcess = getChildProcess()
* childProcess.spawnSync('ls', ['-la'])
*/
/*@__NO_SIDE_EFFECTS__*/
function getChildProcess() {
if (_child_process === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_child_process = /*@__PURE__*/ require('node:child_process')
}
return _child_process as typeof import('node:child_process')
}
/**
* Lazily load the fs module to avoid Webpack errors.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getFs() {
if (_fs === undefined) {
_fs = /*@__PURE__*/ require('node:fs')
}
return _fs as typeof import('node:fs')
}
/*@__NO_SIDE_EFFECTS__*/
function getNpmCliPromiseSpawn() {
if (_npmCliPromiseSpawn === undefined) {
_npmCliPromiseSpawn = /*@__PURE__*/ require('./external/@npmcli/promise-spawn')
}
return _npmCliPromiseSpawn!
}
/**
* Lazily load the path module to avoid Webpack errors.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getPath() {
if (_path === undefined) {
_path = /*@__PURE__*/ require('node:path')
}
return _path as typeof import('node:path')
}
/**
* Strip ANSI escape codes from spawn result stdout and stderr.
* Modifies the result object in place to remove color codes and formatting.
*
* @param {unknown} result - Spawn result object with stdout/stderr properties
* @returns {unknown} The modified result object
*/
/*@__NO_SIDE_EFFECTS__*/
function stripAnsiFromSpawnResult(result: unknown): unknown {
const res = result as {
stdout?: string | Buffer
stderr?: string | Buffer
}
const { stderr, stdout } = res
if (typeof stdout === 'string') {
res.stdout = stripAnsi(stdout)
}
if (typeof stderr === 'string') {
res.stderr = stripAnsi(stderr)
}
return res
}
/**
* Enhances spawn error with better context.
* Converts generic "command failed" to detailed error with command, exit code, and stderr.
*
* @example
* ```typescript
* try {
* await spawn('git', ['status'])
* } catch (err) {
* throw enhanceSpawnError(err)
* }
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function enhanceSpawnError(error: unknown): unknown {
if (error === null || typeof error !== 'object') {
return error
}
if (!isSpawnError(error)) {
return error
}
const err = error as SpawnError
const { args, cmd, code, signal, stderr } = err
const stderrText =
typeof stderr === 'string' ? stderr : (stderr?.toString() ?? '')
// Build enhanced message.
let enhancedMessage = `Command failed: ${cmd}`
if (args && args.length > 0) {
const argsStr = args.join(' ')
if (argsStr.length < 100) {
enhancedMessage += ` ${argsStr}`
} else {
enhancedMessage += ` ${argsStr.slice(0, 97)}...`
}
}
if (signal) {
enhancedMessage += ` (terminated by ${signal})`
} else if (code !== undefined) {
enhancedMessage += ` (exit code ${code})`
}
// Add first line of stderr for context.
const trimmedStderr = stderrText.trim()
if (trimmedStderr) {
const firstLine = trimmedStderr.split('\n')[0] ?? ''
if (firstLine.length < 200) {
enhancedMessage += `\n${firstLine}`
} else {
enhancedMessage += `\n${firstLine.slice(0, 197)}...`
}
}
// Check if this is a synthetic error (generic "command failed" message).
const isSynthetic = err.message === 'command failed'
if (isSynthetic) {
// Modify the error directly.
Object.defineProperty(err, 'message', {
__proto__: null,
value: enhancedMessage,
writable: true,
enumerable: false,
configurable: true,
} as PropertyDescriptor)
return err
}
// Create enhanced error with original error as cause.
const enhancedError = new Error(enhancedMessage, {
cause: err,
}) as SpawnError
// Copy all spawn error properties except message and stack.
const descriptors = Object.getOwnPropertyDescriptors(err)
Reflect.deleteProperty(descriptors, 'message')
Reflect.deleteProperty(descriptors, 'stack')
Object.defineProperties(enhancedError, descriptors)
// Build stack lazily on first access using WeakMap cache.
Object.defineProperty(enhancedError, 'stack', {
__proto__: null,
configurable: true,
enumerable: false,
get() {
let stack = stackCache.get(enhancedError)
if (stack === undefined) {
try {
stack = stackWithCauses(err)
} catch {
stack = err.stack ?? new Error().stack ?? ''
}
stackCache.set(enhancedError, stack)
}
return stack
},
} as PropertyDescriptor)
return enhancedError
}
/**
* Check if a value is a spawn error with expected error properties.
* Tests for common error properties from child process failures.
*
* @param {unknown} value - Value to check
* @returns {boolean} `true` if the value has spawn error properties
*
* @example
* try {
* await spawn('nonexistent-command')
* } catch (error) {
* if (isSpawnError(error)) {
* console.error(`Spawn failed: ${error.code}`)
* }
* }
*/
/*@__NO_SIDE_EFFECTS__*/
export function isSpawnError(value: unknown): value is SpawnError {
if (value === null || typeof value !== 'object') {
return false
}
// Check for spawn-specific error properties.
const err = value as Record<string, unknown>
return (
(hasOwn(err, 'code') && typeof err['code'] !== 'undefined') ||
(hasOwn(err, 'errno') && typeof err['errno'] !== 'undefined') ||
(hasOwn(err, 'syscall') && typeof err['syscall'] === 'string')
)
}
/**
* Check if stdio configuration matches a specific type.
* When called with one argument, validates if it's a valid stdio type.
* When called with two arguments, checks if the stdio config matches the specified type.
*
* @param {string | string[]} stdio - Stdio configuration to check
* @param {StdioType | undefined} type - Expected stdio type (optional)
* @returns {boolean} `true` if stdio matches the type or is valid
*
* @example
* // Check if valid stdio type
* isStdioType('pipe') // true
* isStdioType('invalid') // false
*
* @example
* // Check if stdio matches specific type
* isStdioType('pipe', 'pipe') // true
* isStdioType(['pipe', 'pipe', 'pipe'], 'pipe') // true
* isStdioType('ignore', 'pipe') // false
*/
/*@__NO_SIDE_EFFECTS__*/
export function isStdioType(
stdio: string | string[],
type?: StdioType | undefined,
): boolean {
// If called with one argument, check if it's a valid stdio type.
// biome-ignore lint/complexity/noArguments: Function overload detection for single vs two-arg calls.
if (arguments.length === 1) {
const validTypes = ['pipe', 'ignore', 'inherit', 'overlapped']
return typeof stdio === 'string' && validTypes.includes(stdio)
}
// Original two-argument behavior.
// Accept null/undefined as equivalent to 'pipe' because Node.js defaults
// unspecified stdio entries to 'pipe'. Tests explicitly cover this contract.
return (
stdio === type ||
((stdio === null || stdio === undefined) && type === 'pipe') ||
(isArray(stdio) &&
stdio.length > 2 &&
stdio[0] === type &&
stdio[1] === type &&
stdio[2] === type)
)
}
/**
* Spawn a child process and return a promise that resolves when it completes.
* Provides enhanced error handling, output capture, and cross-platform support.
*
* SECURITY: This function uses array-based arguments which prevent command injection.
* Arguments in the `args` array are passed directly to the OS without shell
* interpretation. Shell metacharacters (;|&$()`) are treated as literal strings,
* not as commands or operators. This is the PRIMARY SECURITY DEFENSE.
*
* Even when shell: true is used (on Windows for .cmd/.bat execution), the array-based
* approach remains secure because Node.js properly escapes each argument before passing
* to the shell.
*
* @param {string} cmd - Command to execute (not user-controlled)
* @param {string[] | readonly string[] | undefined} args - Array of arguments (safe even with user input)
* @param {SpawnOptions | undefined} options - Spawn options for process configuration
* @param {SpawnExtra | undefined} extra - Extra options for promise-spawn
* @returns {SpawnResult} Promise that resolves with process exit information
*
* @throws {SpawnError} When the process exits with non-zero code or is terminated by signal
*
* @example
* // Basic usage - spawn and wait for completion
* const result = await spawn('git', ['status'])
* console.log(result.stdout)
*
* @example
* // With options - set working directory and environment
* const result = await spawn('npm', ['install'], {
* cwd: '/path/to/project',
* env: { NODE_ENV: 'production' }
* })
*
* @example
* // ✔ DO THIS - Array-based arguments (safe)
* spawn('git', ['commit', '-m', userMessage])
* // Each argument is properly escaped, even if userMessage = "foo; rm -rf /"
*
* @example
* // ✖ NEVER DO THIS - String concatenation (vulnerable)
* spawn(`git commit -m "${userMessage}"`, { shell: true })
* // Vulnerable to injection if userMessage = '"; rm -rf / #'
*
* @example
* // Access stdin for interactive processes
* const result = spawn('cat', [])
* result.stdin?.write('Hello\n')
* result.stdin?.end()
* const { stdout } = await result
* console.log(stdout) // 'Hello'
*
* @example
* // Handle errors with exit codes
* try {
* await spawn('exit', ['1'])
* } catch (error) {
* if (isSpawnError(error)) {
* console.error(`Failed with code ${error.code}`)
* console.error(error.stderr)
* }
* }
*/
export function spawn(
cmd: string,
args?: string[] | readonly string[],
options?: SpawnOptions | undefined,
extra?: SpawnExtra | undefined,
): SpawnResult {
const {
spinner: optionsSpinner = spinner,
stripAnsi: shouldStripAnsi = true,
...rawSpawnOptions
} = { __proto__: null, ...options } as SpawnOptions
const spinnerInstance = optionsSpinner
const spawnOptions = { __proto__: null, ...rawSpawnOptions }
const { env, shell, stdio, stdioString = true } = spawnOptions
const cwd = spawnOptions.cwd ? String(spawnOptions.cwd) : undefined
// Resolve binary names to full paths using which.
// If cmd is not a path (absolute or relative), resolve it via PATH.
// If cmd is already a path, use it as-is.
let actualCmd = cmd
if (!isPath(cmd)) {
// Binary name - check cache first, validate with existsSync().
const fs = getFs()
const cached = spawnBinPathCache.get(cmd)
if (cached) {
if (fs.existsSync(cached)) {
actualCmd = cached
} else {
// Cached path no longer exists, remove stale entry.
spawnBinPathCache.delete(cmd)
}
}
// If not cached or cache was stale, resolve via PATH.
if (actualCmd === cmd) {
const resolved = whichSync(cmd, { cwd, nothrow: true })
if (resolved && typeof resolved === 'string') {
actualCmd = resolved
// Cache the result.
spawnBinPathCache.set(cmd, resolved)
}
}
// If which returns null, keep original cmd and let spawn fail naturally
}
// Windows cmd.exe command resolution for .cmd/.bat/.ps1 files:
//
// When shell: true is used on Windows with script files (.cmd, .bat, .ps1),
// cmd.exe can have issues executing full paths. The solution is to use just
// the command basename without extension and let cmd.exe find it via PATH.
//
// How cmd.exe resolves commands:
// 1. Searches current directory first
// 2. Then searches each directory in PATH environment variable
// 3. For each directory, tries extensions from PATHEXT (.COM, .EXE, .BAT, .CMD, etc.)
// 4. Executes the first match found
//
// Example: Given 'C:\pnpm\pnpm.cmd' with shell: true
// 1. Extract basename without extension: 'pnpm'
// 2. cmd.exe searches PATH directories for 'pnpm'
// 3. PATHEXT causes it to try 'pnpm.com', 'pnpm.exe', 'pnpm.bat', 'pnpm.cmd', etc.
// 4. Finds and executes 'C:\pnpm\pnpm.cmd'
//
// This approach is consistent with how other tools handle Windows execution:
// - npm's promise-spawn: uses which.sync() to find commands in PATH
// - cross-spawn: spawns cmd.exe with escaped arguments
// - execa: uses cross-spawn under the hood for Windows support
//
// See: https://github.com/nodejs/node/issues/3675
// Inline WIN32 constant for coverage mode compatibility
const WIN32 = process.platform === 'win32'
if (WIN32 && shell && windowsScriptExtRegExp.test(actualCmd)) {
// Only strip the extension if the command doesn't contain a path.
// If it's an absolute or relative path, keep it intact so cmd.exe
// executes the exact file. Stripping would fail for files in directories
// not in PATH (e.g., temp directories, project-local bins).
if (!isPath(actualCmd)) {
// Extract just the command name without extension for PATH lookup.
actualCmd = getPath().basename(actualCmd, getPath().extname(actualCmd))
}
}
// The stdio option can be a string or an array.
// https://nodejs.org/api/child_process.html#optionsstdio
const wasSpinning = !!spinnerInstance?.isSpinning
const shouldStopSpinner =
wasSpinning &&
!isStdioType(stdio as string | string[], 'ignore') &&
!isStdioType(stdio as string | string[], 'pipe')
const shouldRestartSpinner = shouldStopSpinner
if (shouldStopSpinner) {
spinnerInstance.stop()
}
// npmCliPromiseSpawn is lazily loaded via getNpmCliPromiseSpawn()
// Use __proto__: null to prevent prototype pollution when passing to
// third-party code, Node.js built-ins, or JavaScript built-in methods.
// https://github.com/npm/promise-spawn
// https://github.com/nodejs/node/blob/v24.0.1/lib/child_process.js#L674-L678
// Preserve Windows process.env Proxy behavior when no custom env is provided.
// On Windows, process.env is a Proxy that provides case-insensitive access
// (PATH vs Path vs path). Spreading creates a plain object that loses this.
// Only spread when we have custom environment variables to merge.
const envToUse = env
? ({
__proto__: null,
...process.env,
...env,
} as unknown as NodeJS.ProcessEnv)
: process.env
const promiseSpawnOpts = {
__proto__: null,
cwd: typeof spawnOptions.cwd === 'string' ? spawnOptions.cwd : undefined,
env: envToUse,
signal: abortSignal,
stdio: spawnOptions.stdio,
stdioString,
shell: spawnOptions.shell,
windowsVerbatimArguments: spawnOptions.windowsVerbatimArguments,
timeout: spawnOptions.timeout,
uid: spawnOptions.uid,
gid: spawnOptions.gid,
} as unknown as PromiseSpawnOptions
/* c8 ignore start - External npmCliPromiseSpawn call */
const npmCliPromiseSpawn = getNpmCliPromiseSpawn()
const spawnPromise = npmCliPromiseSpawn(
actualCmd,
args ? [...args] : [],
promiseSpawnOpts as Parameters<typeof npmCliPromiseSpawnType>[2],
extra,
)
/* c8 ignore stop */
const oldSpawnPromise = spawnPromise
let newSpawnPromise: PromiseSpawnResult
if (shouldStripAnsi && stdioString) {
newSpawnPromise = spawnPromise
.then((result: unknown) => {
const strippedResult = stripAnsiFromSpawnResult(result)
// Add exitCode as an alias for code.
if ('code' in (strippedResult as { code?: number })) {
;(strippedResult as { code: number; exitCode: number }).exitCode = (
strippedResult as { code: number }
).code
}
return strippedResult
})
.catch((error: unknown) => {
const strippedError = stripAnsiFromSpawnResult(error)
const enhancedError = enhanceSpawnError(strippedError)
throw enhancedError
}) as PromiseSpawnResult
} else {
newSpawnPromise = spawnPromise
.then((result: unknown) => {
// Add exitCode as an alias for code.
if (result !== null && typeof result === 'object' && 'code' in result) {
const res = result as typeof result & {
exitCode: number
code: number
}
res.exitCode = res.code
return res
}
return result
})
.catch((error: unknown) => {
const enhancedError = enhanceSpawnError(error)
throw enhancedError
}) as PromiseSpawnResult
}
if (shouldRestartSpinner) {
newSpawnPromise = newSpawnPromise.finally(() => {
spinnerInstance.start()
}) as PromiseSpawnResult
}
// Copy process and stdin properties from original promise
;(newSpawnPromise as unknown as PromiseSpawnResult).process =
oldSpawnPromise.process
;(newSpawnPromise as unknown as PromiseSpawnResult).stdin = (
oldSpawnPromise as unknown as PromiseSpawnResult
).stdin
return newSpawnPromise as SpawnResult
}
/**
* Synchronously spawn a child process and wait for it to complete.
* Blocks execution until the process exits, returning all output and exit information.
*
* WARNING: This function blocks the event loop. Use {@link spawn} for async operations.
*
* @param {string} cmd - Command to execute
* @param {string[] | readonly string[] | undefined} args - Array of arguments
* @param {SpawnSyncOptions | undefined} options - Spawn options for process configuration
* @returns {SpawnSyncReturns<string | Buffer>} Process result with exit code and captured output
*
* @example
* // Basic synchronous spawn
* const result = spawnSync('git', ['status'])
* console.log(result.stdout)
* console.log(result.status) // exit code
*
* @example
* // With options
* const result = spawnSync('npm', ['install'], {
* cwd: '/path/to/project',
* stdioString: true
* })
* if (result.status !== 0) {
* console.error(result.stderr)
* }
*
* @example
* // Get raw buffer output
* const result = spawnSync('cat', ['binary-file'], {
* stdioString: false
* })
* console.log(result.stdout) // Buffer
*
* @example
* // Handle process errors
* const result = spawnSync('nonexistent-command')
* if (result.error) {
* console.error('Failed to spawn:', result.error)
* }
*/
export function spawnSync(
cmd: string,
args?: string[] | readonly string[],
options?: SpawnSyncOptions | undefined,
): SpawnSyncReturns<string | Buffer> {
// Resolve binary names to full paths using whichSync.
// If cmd is not a path (absolute or relative), resolve it via PATH.
// If cmd is already a path, use it as-is.
let actualCmd = cmd
if (!isPath(cmd)) {
// Binary name - resolve via PATH using whichSync
const resolved = whichSync(cmd, {
cwd: getOwn(options, 'cwd') as string | undefined,
nothrow: true,
})
if (resolved && typeof resolved === 'string') {
actualCmd = resolved
}
// If whichSync returns null, keep original cmd and let spawn fail naturally
}
// Windows cmd.exe command resolution for .cmd/.bat/.ps1 files:
// See spawn() function above for detailed explanation of this approach.
const shell = getOwn(options, 'shell')
// Inline WIN32 constant for coverage mode compatibility
const WIN32 = process.platform === 'win32'
if (WIN32 && shell && windowsScriptExtRegExp.test(actualCmd)) {
// Only strip the extension if the command doesn't contain a path.
// If it's an absolute or relative path, keep it intact so cmd.exe
// executes the exact file. Stripping would fail for files in directories
// not in PATH (e.g., temp directories, project-local bins).
if (!isPath(actualCmd)) {
// Extract just the command name without extension for PATH lookup.
actualCmd = getPath().basename(actualCmd, getPath().extname(actualCmd))
}
}
const { stripAnsi: shouldStripAnsi = true, ...rawSpawnOptions } = {
__proto__: null,
...options,
} as SpawnSyncOptions
const { stdioString: rawStdioString = true } = rawSpawnOptions
const rawEncoding = rawStdioString ? 'utf8' : 'buffer'
const spawnOptions = {
encoding: rawEncoding,
...rawSpawnOptions,
} as NodeSpawnOptions & { encoding: BufferEncoding | 'buffer' }
const stdioString = spawnOptions.encoding !== 'buffer'
const result = getChildProcess().spawnSync(actualCmd, args, spawnOptions)
if (stdioString) {
const { stderr, stdout } = result
if (stdout) {
result.stdout = stdout.toString().trim()
}
if (stderr) {
result.stderr = stderr.toString().trim()
}
}
return (
shouldStripAnsi && stdioString ? stripAnsiFromSpawnResult(result) : result
) as SpawnSyncReturns<string | Buffer>
}