@songtonyli/dsh-cli 0.1.65 → 0.1.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +1 -1
  2. package/bin/dsh.mjs +1 -1
  3. package/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js +16 -19
  4. package/node_modules/@babel/runtime/helpers/esm/toPrimitive.js +5 -5
  5. package/node_modules/@babel/runtime/helpers/interopRequireWildcard.js +16 -19
  6. package/node_modules/@babel/runtime/helpers/toPrimitive.js +5 -5
  7. package/node_modules/@babel/runtime/package.json +1 -1
  8. package/node_modules/@deepseek-ai/dsh-client-ui-primitives/package.json +2 -2
  9. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar/lib/client.js +1 -1
  10. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/build/esm/version.js +1 -1
  11. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/build/esnext/version.js +1 -1
  12. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/build/src/version.js +1 -1
  13. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/node_modules/@opentelemetry/core/build/esm/version.js +1 -1
  14. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/node_modules/@opentelemetry/core/build/esnext/version.js +1 -1
  15. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/node_modules/@opentelemetry/core/build/src/version.js +1 -1
  16. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/node_modules/@opentelemetry/core/package.json +2 -2
  17. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/package.json +3 -3
  18. package/node_modules/@deepseek-ai/dsh-tui-app/README.i18n.yaml +6 -6
  19. package/node_modules/@deepseek-ai/dsh-tui-app/README.md +4 -2
  20. package/node_modules/@deepseek-ai/dsh-tui-app/README.zh.md +4 -2
  21. package/node_modules/@deepseek-ai/dsh-tui-app/lib/index.js +1367 -18
  22. package/node_modules/@deepseek-ai/dsh-tui-app/package.json +2 -0
  23. package/node_modules/execa/lib/arguments/command-file.js +55 -23
  24. package/node_modules/execa/lib/arguments/command.js +2 -1
  25. package/node_modules/execa/lib/arguments/cwd.js +10 -6
  26. package/node_modules/execa/lib/arguments/encoding-option.js +11 -0
  27. package/node_modules/execa/lib/arguments/escape.js +2 -2
  28. package/node_modules/execa/lib/arguments/fd-options.js +3 -7
  29. package/node_modules/execa/lib/arguments/options.js +13 -3
  30. package/node_modules/execa/lib/arguments/specific.js +2 -1
  31. package/node_modules/execa/lib/convert/duplex.js +3 -1
  32. package/node_modules/execa/lib/convert/iterable.js +3 -5
  33. package/node_modules/execa/lib/convert/readable.js +3 -1
  34. package/node_modules/execa/lib/convert/writable.js +8 -4
  35. package/node_modules/execa/lib/io/contents.js +8 -11
  36. package/node_modules/execa/lib/io/input-sync.js +8 -5
  37. package/node_modules/execa/lib/io/max-buffer.js +41 -28
  38. package/node_modules/execa/lib/io/output-sync.js +64 -40
  39. package/node_modules/execa/lib/io/strip-newline.js +4 -3
  40. package/node_modules/execa/lib/ipc/buffer-messages.js +12 -2
  41. package/node_modules/execa/lib/ipc/get-each.js +8 -2
  42. package/node_modules/execa/lib/ipc/get-one.js +3 -1
  43. package/node_modules/execa/lib/ipc/graceful.js +3 -2
  44. package/node_modules/execa/lib/ipc/incoming.js +10 -3
  45. package/node_modules/execa/lib/ipc/ipc-input.js +7 -2
  46. package/node_modules/execa/lib/ipc/send.js +3 -1
  47. package/node_modules/execa/lib/ipc/strict.js +13 -7
  48. package/node_modules/execa/lib/ipc/validation.js +1 -1
  49. package/node_modules/execa/lib/methods/bind.js +2 -8
  50. package/node_modules/execa/lib/methods/create.js +3 -1
  51. package/node_modules/execa/lib/methods/main-async.js +21 -11
  52. package/node_modules/execa/lib/methods/main-sync.js +7 -5
  53. package/node_modules/execa/lib/methods/node.js +1 -1
  54. package/node_modules/execa/lib/methods/script.js +1 -1
  55. package/node_modules/execa/lib/methods/template.js +24 -5
  56. package/node_modules/execa/lib/pipe/pipe-arguments.js +36 -5
  57. package/node_modules/execa/lib/pipe/throw.js +5 -3
  58. package/node_modules/execa/lib/resolve/all-async.js +43 -19
  59. package/node_modules/execa/lib/resolve/all-sync.js +27 -15
  60. package/node_modules/execa/lib/resolve/exit-sync.js +13 -5
  61. package/node_modules/execa/lib/resolve/stdio.js +2 -1
  62. package/node_modules/execa/lib/resolve/wait-stream.js +12 -2
  63. package/node_modules/execa/lib/resolve/wait-subprocess.js +3 -1
  64. package/node_modules/execa/lib/return/early-error.js +58 -21
  65. package/node_modules/execa/lib/return/message.js +2 -10
  66. package/node_modules/execa/lib/return/reject.js +1 -1
  67. package/node_modules/execa/lib/stdio/direction.js +36 -5
  68. package/node_modules/execa/lib/stdio/duplicate.js +26 -16
  69. package/node_modules/execa/lib/stdio/handle-async.js +6 -0
  70. package/node_modules/execa/lib/stdio/handle-sync.js +5 -3
  71. package/node_modules/execa/lib/stdio/handle.js +47 -24
  72. package/node_modules/execa/lib/stdio/native.js +3 -6
  73. package/node_modules/execa/lib/stdio/stdio-option.js +13 -18
  74. package/node_modules/execa/lib/stdio/type.js +2 -10
  75. package/node_modules/execa/lib/terminate/cancel.js +7 -0
  76. package/node_modules/execa/lib/terminate/kill-descendants.js +20 -4
  77. package/node_modules/execa/lib/transform/encoding-transform.js +15 -0
  78. package/node_modules/execa/lib/transform/generator.js +13 -2
  79. package/node_modules/execa/lib/transform/split.js +37 -23
  80. package/node_modules/execa/lib/utils/options.js +9 -0
  81. package/node_modules/execa/lib/utils/standard-stream.js +6 -0
  82. package/node_modules/execa/lib/utils/uint-array.js +1 -7
  83. package/node_modules/execa/lib/verbose/log.js +3 -6
  84. package/node_modules/execa/lib/verbose/output.js +3 -1
  85. package/node_modules/execa/package.json +51 -48
  86. package/package.json +3 -3
@@ -1,5 +1,6 @@
1
1
  import {ChildProcess} from 'node:child_process';
2
2
  import isPlainObject from 'is-plain-obj';
3
+ import {ASTRAL_START} from '../arguments/escape.js';
3
4
  import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';
4
5
 
5
6
  // Check whether the template string syntax is being used
@@ -53,13 +54,15 @@ const parseTemplate = ({templates, expressions, tokens, index, template}) => {
53
54
  // - the first array argument, which does not escape backslash sequences
54
55
  // - its `raw` property, which escapes them
55
56
  const splitByWhitespaces = (template, rawTemplate) => {
56
- if (rawTemplate.length === 0) {
57
+ // The template is empty either between two `${expression}`, or when it only contains escaped newlines.
58
+ // Neither holds any whitespace, so neither separates tokens.
59
+ if (template.length === 0) {
57
60
  return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};
58
61
  }
59
62
 
60
63
  const nextTokens = [];
61
64
  let templateStart = 0;
62
- const isLeadingWhitespaces = DELIMITERS.has(rawTemplate[0]);
65
+ let isLeadingWhitespaces = false;
63
66
 
64
67
  for (
65
68
  let templateIndex = 0, rawIndex = 0;
@@ -68,6 +71,11 @@ const splitByWhitespaces = (template, rawTemplate) => {
68
71
  ) {
69
72
  const rawCharacter = rawTemplate[rawIndex];
70
73
  if (DELIMITERS.has(rawCharacter)) {
74
+ // Escaped newlines are ignored, so a whitespace after them is still a leading one
75
+ if (templateIndex === 0) {
76
+ isLeadingWhitespaces = true;
77
+ }
78
+
71
79
  if (templateStart !== templateIndex) {
72
80
  nextTokens.push(template.slice(templateStart, templateIndex));
73
81
  }
@@ -80,7 +88,13 @@ const splitByWhitespaces = (template, rawTemplate) => {
80
88
  templateIndex -= 1;
81
89
  rawIndex += 1;
82
90
  } else if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {
83
- rawIndex = rawTemplate.indexOf('}', rawIndex + 3);
91
+ const closingBraceIndex = rawTemplate.indexOf('}', rawIndex + 3);
92
+ // A code point above the BMP is a surrogate pair, i.e. two characters, in the template string
93
+ if (isAstralEscape(rawTemplate.slice(rawIndex + 3, closingBraceIndex))) {
94
+ templateIndex += 1;
95
+ }
96
+
97
+ rawIndex = closingBraceIndex;
84
98
  } else {
85
99
  rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;
86
100
  }
@@ -95,6 +109,8 @@ const splitByWhitespaces = (template, rawTemplate) => {
95
109
  return {nextTokens, leadingWhitespaces: isLeadingWhitespaces, trailingWhitespaces: isTrailingWhitespaces};
96
110
  };
97
111
 
112
+ const isAstralEscape = codePointHex => Number.parseInt(codePointHex, 16) > ASTRAL_START;
113
+
98
114
  const DELIMITERS = new Set([' ', '\t', '\r', '\n']);
99
115
 
100
116
  // Number of characters in backslash escape sequences: \0 \xXX or \uXXXX
@@ -124,7 +140,8 @@ const parseExpression = expression => {
124
140
  return String(expression);
125
141
  }
126
142
 
127
- if (isPlainObject(expression) && ('stdout' in expression || 'isMaxBuffer' in expression)) {
143
+ // Only own properties are checked: a polluted `Object.prototype.stdout` must not turn any plain object into a subprocess result
144
+ if (isPlainObject(expression) && (Object.hasOwn(expression, 'stdout') || Object.hasOwn(expression, 'isMaxBuffer'))) {
128
145
  return getSubprocessResult(expression);
129
146
  }
130
147
 
@@ -136,7 +153,9 @@ const parseExpression = expression => {
136
153
  throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);
137
154
  };
138
155
 
139
- const getSubprocessResult = ({stdout}) => {
156
+ const getSubprocessResult = result => {
157
+ // Read the own property only: results with `stdout: 'ignore'` have no `stdout` property, which must not be read from a polluted prototype
158
+ const stdout = Object.hasOwn(result, 'stdout') ? result.stdout : undefined;
140
159
  if (typeof stdout === 'string') {
141
160
  return stdout;
142
161
  }
@@ -2,6 +2,7 @@ import {normalizeParameters} from '../methods/parameters.js';
2
2
  import {getStartTime} from '../return/duration.js';
3
3
  import {SUBPROCESS_OPTIONS, getToStream, getFromStream} from '../arguments/fd-options.js';
4
4
  import {isDenoExecPath} from '../arguments/file-url.js';
5
+ import {copyOptions} from '../utils/options.js';
5
6
 
6
7
  // Normalize and validate arguments passed to `source.pipe(destination)`
7
8
  export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...pipeArguments) => {
@@ -30,11 +31,18 @@ export const normalizePipeArguments = ({source, sourcePromise, boundOptions, cre
30
31
  };
31
32
 
32
33
  const getDestinationStream = (boundOptions, createNested, pipeArguments) => {
34
+ let destinationInfo;
35
+
33
36
  try {
34
- const {
35
- destination,
36
- pipeOptions: {from, to, unpipeSignal} = {},
37
- } = getDestination(boundOptions, createNested, ...pipeArguments);
37
+ destinationInfo = getDestination(boundOptions, createNested, ...pipeArguments);
38
+ } catch (error) {
39
+ return {destinationError: error};
40
+ }
41
+
42
+ const {destination, pipeOptions} = destinationInfo;
43
+
44
+ try {
45
+ const {from, to, unpipeSignal} = copyOptions(pipeOptions);
38
46
  const destinationStream = getToStream(destination, to);
39
47
  return {
40
48
  destination,
@@ -43,10 +51,24 @@ const getDestinationStream = (boundOptions, createNested, pipeArguments) => {
43
51
  unpipeSignal,
44
52
  };
45
53
  } catch (error) {
54
+ abortDestination(destination, pipeArguments[0]);
46
55
  return {destinationError: error};
47
56
  }
48
57
  };
49
58
 
59
+ /*
60
+ The destination has already been spawned at that point, since the `to` option is validated afterwards.
61
+ When Execa spawned it, nothing else can end it, so it is terminated. Otherwise, it would keep running, e.g. waiting for its `stdin` forever, which also prevents the current process from exiting. A destination passed by the user is left to them.
62
+ In both cases, its error must be handled, otherwise it becomes an unhandled rejection which crashes the current process, e.g. with `source.pipe(execa('command'), {to: 'fd9'})`. This does not prevent the user from awaiting it.
63
+ */
64
+ const abortDestination = (destination, firstArgument) => {
65
+ if (destination !== firstArgument) {
66
+ destination.kill();
67
+ }
68
+
69
+ destination.catch(() => {});
70
+ };
71
+
50
72
  // Piping subprocesses can use three syntaxes:
51
73
  // - source.pipe('command', commandArguments, pipeOptionsOrDestinationOptions)
52
74
  // - source.pipe`command commandArgument` or source.pipe(pipeOptionsOrDestinationOptions)`command commandArgument`
@@ -79,7 +101,16 @@ const getDestination = (boundOptions, createNested, firstArgument, ...pipeArgume
79
101
  };
80
102
 
81
103
  // Force `stdin: 'pipe'` with the destination subprocess
82
- const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});
104
+ const mapDestinationArguments = ({options}) => ({
105
+ options: {
106
+ __proto__: null,
107
+ ...options,
108
+ // Piping writes to the destination's `stdin`, which is forced even if the user set another value.
109
+ // However, `stdin` cannot be combined with `stdio`, which is needed for `to: 'fd3'` and higher.
110
+ ...((options.stdio === undefined) && {stdin: 'pipe'}),
111
+ piped: true,
112
+ },
113
+ });
83
114
 
84
115
  const getSourceStream = (source, from) => {
85
116
  try {
@@ -38,10 +38,12 @@ const getPipeArgumentsError = ({sourceStream, sourceError, destinationStream, de
38
38
  return destinationError;
39
39
  }
40
40
 
41
- if (sourceError !== undefined) {
42
- endDestinationStream(destinationStream);
43
- return sourceError;
41
+ if (sourceError === undefined) {
42
+ return;
44
43
  }
44
+
45
+ endDestinationStream(destinationStream);
46
+ return sourceError;
45
47
  };
46
48
 
47
49
  // Specific error return value when passing invalid arguments to `subprocess.pipe()` or when using `unpipeSignal`
@@ -1,23 +1,47 @@
1
1
  import mergeStreams from '@sindresorhus/merge-streams';
2
+ import {setAllStream} from '../utils/standard-stream.js';
3
+ import {resumeStream} from '../io/contents.js';
2
4
  import {waitForSubprocessStream} from './stdio.js';
3
5
 
4
6
  // `all` interleaves `stdout` and `stderr`
5
- export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)
6
- ? mergeStreams([stdout, stderr].filter(Boolean))
7
- : undefined;
7
+ export const makeAllStream = ({stdout, stderr}, {all}) => {
8
+ if (!all) {
9
+ return;
10
+ }
11
+
12
+ const fileDescriptors = [[stdout, 1], [stderr, 2]].filter(([stream]) => stream);
13
+ return fileDescriptors.length === 0 ? undefined : setAllStream(mergeStreams(fileDescriptors.map(([stream]) => stream)));
14
+ };
15
+
16
+ // The file descriptors which `result.all` contains, which the `all` options must follow
17
+ // Unlike `subprocess.all`, this excludes the file descriptors which are not buffered, since their output is not included
18
+ export const getAllFds = ({stdout, stderr}, [, bufferStdout, bufferStderr]) => [
19
+ ...(stdout !== null && bufferStdout ? [1] : []),
20
+ ...(stderr !== null && bufferStderr ? [2] : []),
21
+ ];
8
22
 
9
23
  // Read the contents of `subprocess.all` and|or wait for its completion
10
- export const waitForAllStream = ({subprocess, all, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => waitForSubprocessStream({
11
- ...getAllStream(subprocess, all, buffer),
12
- fdNumber: 'all',
13
- encoding,
14
- maxBuffer: maxBuffer[1] + maxBuffer[2],
15
- lines: lines[1] || lines[2],
16
- allMixed: getAllMixed(subprocess, all),
17
- stripFinalNewline,
18
- verboseInfo,
19
- streamInfo,
20
- });
24
+ export const waitForAllStream = ({subprocess, all, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => {
25
+ const {stream, buffer: bufferAll, drainedStream} = getAllStream(subprocess, all, buffer);
26
+ return Promise.all([
27
+ waitForSubprocessStream({
28
+ stream,
29
+ buffer: bufferAll,
30
+ fdNumber: 'all',
31
+ encoding,
32
+ maxBuffer: maxBuffer[1] + maxBuffer[2],
33
+ lines: lines[1] || lines[2],
34
+ allFds: getAllFds(subprocess, buffer),
35
+ allMixed: getAllMixed(subprocess, all),
36
+ stripFinalNewline,
37
+ verboseInfo,
38
+ streamInfo,
39
+ }),
40
+ // When only one of the two file descriptors is buffered, its stream is read instead of the merged one.
41
+ // The merged one is then drained, otherwise it would apply backpressure on that file descriptor and hang the subprocess.
42
+ drainedStream === undefined ? undefined : resumeStream(drainedStream),
43
+ ]).then(([output]) => output);
44
+ };
21
45
 
22
46
  const getAllStream = ({stdout, stderr}, all, [, bufferStdout, bufferStderr]) => {
23
47
  const buffer = bufferStdout || bufferStderr;
@@ -25,15 +49,15 @@ const getAllStream = ({stdout, stderr}, all, [, bufferStdout, bufferStderr]) =>
25
49
  return {stream: all, buffer};
26
50
  }
27
51
 
28
- if (!bufferStdout) {
29
- return {stream: stderr, buffer};
52
+ if (!all) {
53
+ return {stream: undefined, buffer};
30
54
  }
31
55
 
32
- if (!bufferStderr) {
33
- return {stream: stdout, buffer};
56
+ if (!bufferStdout) {
57
+ return {stream: stderr, buffer, drainedStream: all};
34
58
  }
35
59
 
36
- return {stream: all, buffer};
60
+ return bufferStderr ? {stream: all, buffer} : {stream: stdout, buffer, drainedStream: all};
37
61
  };
38
62
 
39
63
  // When `subprocess.stdout` is in objectMode but not `subprocess.stderr` (or the opposite), we need to use both:
@@ -1,33 +1,45 @@
1
1
  import {isUint8Array, concatUint8Arrays} from '../utils/uint-array.js';
2
- import {stripNewline} from '../io/strip-newline.js';
2
+ import {splitLinesSync} from '../transform/split.js';
3
+ import {getStripFinalNewline} from '../io/strip-newline.js';
4
+
5
+ // The file descriptors which `result.all` interleaves. Those are the ones with an output, like with the `all` stream.
6
+ export const getAllSyncFds = ([, stdout, stderr]) => [
7
+ ...(stdout === undefined ? [] : [1]),
8
+ ...(stderr === undefined ? [] : [2]),
9
+ ];
3
10
 
4
11
  // Retrieve `result.all` with synchronous methods
5
- export const getAllSync = ([, stdout, stderr], options) => {
12
+ export const getAllSync = ([, stdout, stderr], allFds, options) => {
6
13
  if (!options.all) {
7
14
  return;
8
15
  }
9
16
 
10
17
  if (stdout === undefined) {
11
- return stderr;
18
+ return splitAllLines(stderr, allFds, options);
12
19
  }
13
20
 
14
21
  if (stderr === undefined) {
15
- return stdout;
16
- }
17
-
18
- if (Array.isArray(stdout)) {
19
- return Array.isArray(stderr)
20
- ? [...stdout, ...stderr]
21
- : [...stdout, stripNewline(stderr, options, 'all')];
22
+ return splitAllLines(stdout, allFds, options);
22
23
  }
23
24
 
24
- if (Array.isArray(stderr)) {
25
- return [stripNewline(stdout, options, 'all'), ...stderr];
25
+ // Like asynchronous methods, `all` is split into lines as soon as the `lines` option applies to either file descriptor.
26
+ // A file descriptor which uses the `lines` option is already split with its own `stripFinalNewline` value, like `result.stdout` and `result.stderr` are. The other one is split with the `stripFinalNewline` value of `result.all`.
27
+ // This differs from asynchronous methods, which cannot tell which file descriptor the merged output's last newline belongs to.
28
+ if (hasLines(options)) {
29
+ return [splitAllLines(stdout, allFds, options), splitAllLines(stderr, allFds, options)].flat();
26
30
  }
27
31
 
28
- if (isUint8Array(stdout) && isUint8Array(stderr)) {
29
- return concatUint8Arrays([stdout, stderr]);
32
+ // Without the `lines` option, arrays can only come from object mode, which does not apply to the other file descriptor
33
+ if (Array.isArray(stdout) || Array.isArray(stderr)) {
34
+ return [stdout, stderr].flat();
30
35
  }
31
36
 
32
- return `${stdout}${stderr}`;
37
+ return isUint8Array(stdout) && isUint8Array(stderr) ? concatUint8Arrays([stdout, stderr]) : `${stdout}${stderr}`;
33
38
  };
39
+
40
+ const hasLines = ({lines}) => Boolean(lines[1] || lines[2]);
41
+
42
+ // Each file descriptor is either already split into lines, or is a string which still needs to be split
43
+ const splitAllLines = (value, allFds, options) => value === undefined || Array.isArray(value) || !hasLines(options)
44
+ ? value
45
+ : splitLinesSync(value, !getStripFinalNewline(options.stripFinalNewline, 'all', allFds), false);
@@ -1,12 +1,20 @@
1
1
  import {DiscardedError} from '../return/final-error.js';
2
- import {isMaxBufferSync} from '../io/max-buffer.js';
2
+ import {handleMaxBufferSync} from '../io/max-buffer.js';
3
3
  import {isFailedExit} from './exit-async.js';
4
4
 
5
5
  // Retrieve exit code, signal name and error information, with synchronous methods
6
- export const getExitResultSync = ({error, status: exitCode, signal, output}, {maxBuffer}) => {
7
- const resultError = getResultError(error, exitCode, signal);
8
- const isTimedOut = resultError?.code === 'ETIMEDOUT';
9
- const isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer);
6
+ export const getExitResultSync = ({error, status: exitCode, signal, output}, {maxBuffer, buffer}) => {
7
+ const initialError = getResultError(error, exitCode, signal);
8
+ const isTimedOut = initialError?.code === 'ETIMEDOUT';
9
+ // A file descriptor over its `maxBuffer` does not stop the subprocess, so the timeout that did is reported instead. That file descriptor is still truncated.
10
+ const {resultError, isMaxBuffer} = isTimedOut
11
+ ? {resultError: initialError, isMaxBuffer: false}
12
+ : handleMaxBufferSync({
13
+ resultError: initialError,
14
+ output,
15
+ maxBuffer,
16
+ buffer,
17
+ });
10
18
  return {
11
19
  resultError,
12
20
  exitCode,
@@ -16,7 +16,7 @@ export const waitForStdioStreams = ({subprocess, encoding, buffer, maxBuffer, li
16
16
  }));
17
17
 
18
18
  // Read the contents of `subprocess.std*` or `subprocess.all` and|or wait for its completion
19
- export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {
19
+ export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, allFds, verboseInfo, streamInfo}) => {
20
20
  if (!stream) {
21
21
  return;
22
22
  }
@@ -38,6 +38,7 @@ export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffe
38
38
  lines,
39
39
  allMixed,
40
40
  stripFinalNewline,
41
+ allFds,
41
42
  verboseInfo,
42
43
  streamInfo,
43
44
  }),
@@ -3,13 +3,23 @@ import {finished} from 'node:stream/promises';
3
3
  // Wraps `finished(stream)` to handle the following case:
4
4
  // - When the subprocess exits, Node.js automatically calls `subprocess.stdin.destroy()`, which we need to ignore.
5
5
  // - However, we still need to throw if `subprocess.stdin.destroy()` is called before subprocess exit.
6
- export const waitForStream = async (stream, fdNumber, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {
6
+ export const waitForStream = async (stream, fdNumber, streamInfo, {
7
+ isSameDirection,
8
+ stopOnExit = false,
9
+ readable = true,
10
+ writable = true,
11
+ } = {}) => {
7
12
  const state = handleStdinDestroy(stream, streamInfo);
8
13
  const abortController = new AbortController();
9
14
  try {
10
15
  await Promise.race([
11
16
  ...(stopOnExit ? [streamInfo.exitPromise] : []),
12
- finished(stream, {cleanup: true, signal: abortController.signal}),
17
+ finished(stream, {
18
+ cleanup: true,
19
+ signal: abortController.signal,
20
+ readable,
21
+ writable,
22
+ }),
13
23
  ]);
14
24
  } catch (error) {
15
25
  if (!state.stdinCleanedUp) {
@@ -136,11 +136,13 @@ const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>
136
136
  // Some `stdin`/`stdout`/`stderr` options create a stream, e.g. when passing a file path.
137
137
  // The `.pipe()` method automatically ends that stream when `subprocess` ends.
138
138
  // This makes sure we wait for the completion of those streams, in order to catch any error.
139
- const waitForCustomStreamsEnd = (fileDescriptors, streamInfo) => fileDescriptors.flatMap(({stdioItems}, fdNumber) => stdioItems
139
+ const waitForCustomStreamsEnd = (fileDescriptors, streamInfo) => fileDescriptors.flatMap(({stdioItems, direction}, fdNumber) => stdioItems
140
140
  .filter(({value, stream = value}) => isNodeStream(stream, {checkOpen: false}) && !isStandardStream(stream))
141
141
  .map(({type, value, stream = value}) => waitForStream(stream, fdNumber, streamInfo, {
142
142
  isSameDirection: TRANSFORM_TYPES.has(type),
143
143
  stopOnExit: type === 'native',
144
+ // Output streams are destinations which are handed back to the user: waiting for their readable side would mean waiting for the user to consume them.
145
+ readable: direction !== 'output' || TRANSFORM_TYPES.has(type),
144
146
  })));
145
147
 
146
148
  // Fails when the subprocess emits an `error` event
@@ -1,4 +1,5 @@
1
1
  import {ChildProcess} from 'node:child_process';
2
+ import {callbackify} from 'node:util';
2
3
  import {
3
4
  PassThrough,
4
5
  Readable,
@@ -15,32 +16,25 @@ export const handleEarlyError = ({error, command, escapedCommand, fileDescriptor
15
16
  cleanupCustomStreams(fileDescriptors);
16
17
 
17
18
  const subprocess = new ChildProcess();
19
+ // The subprocess never spawned, so there is no process to signal.
20
+ // `ChildProcess.prototype.kill()` would signal the current process group instead, since its process id is `0`.
21
+ subprocess.kill = () => false;
18
22
  const all = createDummyStreams(subprocess, fileDescriptors);
19
23
 
20
- const earlyError = makeEarlyError({
24
+ const promise = handleDummyPromise({
21
25
  error,
22
26
  command,
23
27
  escapedCommand,
24
28
  fileDescriptors,
25
29
  options,
26
30
  startTime,
27
- isSync: false,
31
+ verboseInfo,
28
32
  });
29
- const promise = handleDummyPromise(earlyError, verboseInfo, options);
30
33
  return {
31
34
  subprocess,
32
35
  promise,
33
36
  all: options.all ? all : undefined,
34
- convertedStreams: {
35
- readable,
36
- writable,
37
- duplex,
38
- readableStream,
39
- writableStream,
40
- transformStream,
41
- iterable,
42
- [Symbol.asyncIterator]: iterable,
43
- },
37
+ convertedStreams: getConvertedStreams(promise),
44
38
  };
45
39
  };
46
40
 
@@ -66,12 +60,55 @@ const createDummyStream = () => {
66
60
  return stream;
67
61
  };
68
62
 
69
- const readable = () => new Readable({read() {}});
70
- const writable = () => new Writable({write() {}});
71
- const duplex = () => new Duplex({read() {}, write() {}});
72
- const readableStream = () => Readable.toWeb(readable());
73
- const writableStream = () => Writable.toWeb(writable());
74
- const transformStream = () => Duplex.toWeb(duplex());
75
- const iterable = async function * () {};
63
+ // The subprocess never started, so those streams have no contents.
64
+ // Like when the subprocess did start, they end once its promise resolves, or error with its error, as opposed to hanging forever.
65
+ const getConvertedStreams = promise => {
66
+ const waitForPromise = async () => {
67
+ await promise;
68
+ };
69
+
70
+ const endReadable = function () {
71
+ callbackify(waitForPromise)(error => {
72
+ if (error) {
73
+ this.destroy(error);
74
+ } else {
75
+ this.push(null);
76
+ }
77
+ });
78
+ };
76
79
 
77
- const handleDummyPromise = async (error, verboseInfo, options) => handleResult(error, verboseInfo, options);
80
+ const endWritable = callbackify(waitForPromise);
81
+ const writeWritable = (chunk, encoding, done) => {
82
+ endWritable(done);
83
+ };
84
+
85
+ const readable = () => new Readable({read: endReadable});
86
+ const writable = () => new Writable({write: writeWritable, final: endWritable});
87
+ const duplex = () => new Duplex({read: endReadable, write: writeWritable, final: endWritable});
88
+ const iterable = () => readable()[Symbol.asyncIterator]();
89
+
90
+ return {
91
+ readable,
92
+ writable,
93
+ duplex,
94
+ readableStream: () => Readable.toWeb(readable()),
95
+ writableStream: () => Writable.toWeb(writable()),
96
+ transformStream: () => Duplex.toWeb(duplex()),
97
+ iterable,
98
+ [Symbol.asyncIterator]: iterable,
99
+ };
100
+ };
101
+
102
+ // `error` is a promise when the spawn error is only emitted on the next tick
103
+ const handleDummyPromise = async ({error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo}) => {
104
+ const earlyError = makeEarlyError({
105
+ error: await error,
106
+ command,
107
+ escapedCommand,
108
+ fileDescriptors,
109
+ options,
110
+ startTime,
111
+ isSync: false,
112
+ });
113
+ return handleResult(earlyError, verboseInfo, options);
114
+ };
@@ -113,11 +113,7 @@ const getErrorPrefix = ({
113
113
  return `Command was killed with ${signal} (${signalDescription})`;
114
114
  }
115
115
 
116
- if (exitCode !== undefined) {
117
- return `Command failed with exit code ${exitCode}`;
118
- }
119
-
120
- return 'Command failed';
116
+ return exitCode === undefined ? 'Command failed' : `Command failed with exit code ${exitCode}`;
121
117
  };
122
118
 
123
119
  const getForcefulSuffix = (isForcefullyTerminated, forceKillAfterDelay) => isForcefullyTerminated
@@ -149,9 +145,5 @@ const serializeMessageItem = messageItem => {
149
145
  return messageItem;
150
146
  }
151
147
 
152
- if (isUint8Array(messageItem)) {
153
- return uint8ArrayToString(messageItem);
154
- }
155
-
156
- return '';
148
+ return isUint8Array(messageItem) ? uint8ArrayToString(messageItem) : '';
157
149
  };
@@ -5,7 +5,7 @@ import {logResult} from '../verbose/complete.js';
5
5
  export const handleResult = (result, verboseInfo, {reject}) => {
6
6
  logResult(result, verboseInfo);
7
7
 
8
- if (result.failed && reject) {
8
+ if (reject && result.failed) {
9
9
  throw result;
10
10
  }
11
11
 
@@ -10,8 +10,8 @@ import {isWritableStream} from './type.js';
10
10
  // This allows us to know whether to pipe _into_ or _from_ the stream.
11
11
  // When `stdio[fdNumber]` is a single value, this guess is fairly straightforward.
12
12
  // However, when it is an array instead, we also need to make sure the different values are not incompatible with each other.
13
- export const getStreamDirection = (stdioItems, fdNumber, optionName) => {
14
- const directions = stdioItems.map(stdioItem => getStdioItemDirection(stdioItem, fdNumber));
13
+ export const getStreamDirection = ({stdioItems, isStdioArray, fdNumber, optionName}) => {
14
+ const directions = stdioItems.map(stdioItem => getStdioItemDirection(stdioItem, fdNumber, isStdioArray));
15
15
 
16
16
  if (directions.includes('input') && directions.includes('output')) {
17
17
  throw new TypeError(`The \`${optionName}\` option must not be an array of both readable and writable values.`);
@@ -20,10 +20,19 @@ export const getStreamDirection = (stdioItems, fdNumber, optionName) => {
20
20
  return directions.find(Boolean) ?? DEFAULT_DIRECTION;
21
21
  };
22
22
 
23
+ const getStdioItemDirection = (stdioItem, fdNumber, isStdioArray) => {
24
+ const knownDirection = KNOWN_DIRECTIONS[fdNumber];
25
+ const direction = getRequestedDirection(stdioItem);
26
+ if (knownDirection === undefined) {
27
+ return direction;
28
+ }
29
+
30
+ validateKnownDirection(stdioItem, knownDirection, isStdioArray);
31
+ return knownDirection;
32
+ };
33
+
23
34
  // `direction` is set when the user explicitly requests it, e.g. `{value: 'pipe', input: true}`.
24
35
  // It takes precedence over guessing, but not over the fixed direction of `stdin`/`stdout`/`stderr`.
25
- const getStdioItemDirection = (stdioItem, fdNumber) => KNOWN_DIRECTIONS[fdNumber] ?? getRequestedDirection(stdioItem);
26
-
27
36
  // The explicitly requested `direction` must not contradict a value that is intrinsically the other direction.
28
37
  // For example, `{value: writableStream, input: true}` is invalid since a writable value can only be an output.
29
38
  const getRequestedDirection = ({type, value, direction, optionName}) => {
@@ -35,13 +44,34 @@ const getRequestedDirection = ({type, value, direction, optionName}) => {
35
44
  return direction ?? guessedDirection;
36
45
  };
37
46
 
47
+ // `stdin`/`stdout`/`stderr` have a fixed direction, which each value must not contradict.
48
+ // Otherwise, asynchronous methods pipe in the wrong direction and crash, e.g. with `dest.end is not a function`.
49
+ // Only values whose direction is intrinsic to a stream are checked: other values (e.g. `Uint8Array`) are already
50
+ // rejected in the wrong direction when their stream properties are added.
51
+ // A single file descriptor 0, 1 or 2, e.g. `stdin: 1`, is passed as is to `child_process.spawn()` instead of being piped by Execa, so it is not checked. Those are often the same terminal, which is both readable and writable.
52
+ const validateKnownDirection = ({type, value, optionName}, knownDirection, isStdioArray) => {
53
+ if (!STREAM_TYPES.has(type) || (!isStdioArray && getStandardStreamDirection(value) !== undefined)) {
54
+ return;
55
+ }
56
+
57
+ const guessedDirection = guessStreamDirection[type](value);
58
+ if (guessedDirection === undefined || guessedDirection === knownDirection) {
59
+ return;
60
+ }
61
+
62
+ const valueName = guessedDirection === 'input' ? 'readable' : 'writable';
63
+ throw new TypeError(`The \`${optionName}\` option is invalid: a ${valueName} value is always an ${guessedDirection}, but \`${optionName}\` is an ${knownDirection}.`);
64
+ };
65
+
66
+ const STREAM_TYPES = new Set(['native', 'nodeStream', 'webStream']);
67
+
38
68
  // `stdin`/`stdout`/`stderr` have a known direction
39
69
  const KNOWN_DIRECTIONS = ['input', 'output', 'output'];
40
70
 
41
71
  const anyDirection = () => undefined;
42
72
  const alwaysInput = () => 'input';
43
73
 
44
- // `string` can only be added through the `input` option, i.e. does not need to be handled here
74
+ // `string` can only be added through the `input` option, i.e. on `stdin`, so it is always an input
45
75
  const guessStreamDirection = {
46
76
  generator: anyDirection,
47
77
  asyncGenerator: anyDirection,
@@ -50,6 +80,7 @@ const guessStreamDirection = {
50
80
  iterable: alwaysInput,
51
81
  asyncIterable: alwaysInput,
52
82
  uint8Array: alwaysInput,
83
+ string: alwaysInput,
53
84
  webStream: value => isWritableStream(value) ? 'output' : 'input',
54
85
  nodeStream(value) {
55
86
  if (!isNodeReadableStream(value, {checkOpen: false})) {