@songtonyli/dsh-cli 0.1.64 → 0.1.66

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 (91) hide show
  1. package/README.md +1 -1
  2. package/bin/dsh.mjs +1 -1
  3. package/node_modules/@deepseek-ai/dsh-client-ui-primitives/package.json +2 -2
  4. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar/lib/client.js +1 -1
  5. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/build/esm/version.js +1 -1
  6. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/build/esnext/version.js +1 -1
  7. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/build/src/version.js +1 -1
  8. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/node_modules/@opentelemetry/core/build/esm/version.js +1 -1
  9. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/node_modules/@opentelemetry/core/build/esnext/version.js +1 -1
  10. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/node_modules/@opentelemetry/core/build/src/version.js +1 -1
  11. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/node_modules/@opentelemetry/core/package.json +2 -2
  12. package/node_modules/@deepseek-ai/dsh-otel/node_modules/@opentelemetry/resources/package.json +3 -3
  13. package/node_modules/@deepseek-ai/dsh-sandbox/README.i18n.yaml +2 -2
  14. package/node_modules/@deepseek-ai/dsh-sandbox/README.md +1 -1
  15. package/node_modules/@deepseek-ai/dsh-sandbox/README.zh.md +1 -1
  16. package/node_modules/@deepseek-ai/dsh-sandbox/lib/index.js +13 -4
  17. package/node_modules/@deepseek-ai/dsh-sandbox-apple-container/README.i18n.yaml +2 -2
  18. package/node_modules/@deepseek-ai/dsh-sandbox-apple-container/README.md +2 -2
  19. package/node_modules/@deepseek-ai/dsh-sandbox-apple-container/README.zh.md +2 -2
  20. package/node_modules/@deepseek-ai/dsh-sandbox-apple-container/lib/index.js +14 -1
  21. package/node_modules/@deepseek-ai/dsh-tool-bash/lib/index.js +3 -1
  22. package/node_modules/@deepseek-ai/dsh-tui-app/README.md +3 -2
  23. package/node_modules/@deepseek-ai/dsh-tui-app/README.zh.md +3 -2
  24. package/node_modules/@deepseek-ai/dsh-tui-app/lib/index.js +977 -16
  25. package/node_modules/@deepseek-ai/dsh-tui-app/package.json +2 -0
  26. package/node_modules/execa/lib/arguments/command-file.js +55 -23
  27. package/node_modules/execa/lib/arguments/command.js +2 -1
  28. package/node_modules/execa/lib/arguments/cwd.js +10 -6
  29. package/node_modules/execa/lib/arguments/encoding-option.js +11 -0
  30. package/node_modules/execa/lib/arguments/escape.js +2 -2
  31. package/node_modules/execa/lib/arguments/fd-options.js +3 -7
  32. package/node_modules/execa/lib/arguments/options.js +13 -3
  33. package/node_modules/execa/lib/arguments/specific.js +2 -1
  34. package/node_modules/execa/lib/convert/duplex.js +3 -1
  35. package/node_modules/execa/lib/convert/iterable.js +3 -5
  36. package/node_modules/execa/lib/convert/readable.js +3 -1
  37. package/node_modules/execa/lib/convert/writable.js +8 -4
  38. package/node_modules/execa/lib/io/contents.js +8 -11
  39. package/node_modules/execa/lib/io/input-sync.js +8 -5
  40. package/node_modules/execa/lib/io/max-buffer.js +41 -28
  41. package/node_modules/execa/lib/io/output-sync.js +64 -40
  42. package/node_modules/execa/lib/io/strip-newline.js +4 -3
  43. package/node_modules/execa/lib/ipc/buffer-messages.js +12 -2
  44. package/node_modules/execa/lib/ipc/get-each.js +8 -2
  45. package/node_modules/execa/lib/ipc/get-one.js +3 -1
  46. package/node_modules/execa/lib/ipc/graceful.js +3 -2
  47. package/node_modules/execa/lib/ipc/incoming.js +10 -3
  48. package/node_modules/execa/lib/ipc/ipc-input.js +7 -2
  49. package/node_modules/execa/lib/ipc/send.js +3 -1
  50. package/node_modules/execa/lib/ipc/strict.js +13 -7
  51. package/node_modules/execa/lib/ipc/validation.js +1 -1
  52. package/node_modules/execa/lib/methods/bind.js +2 -8
  53. package/node_modules/execa/lib/methods/create.js +3 -1
  54. package/node_modules/execa/lib/methods/main-async.js +21 -11
  55. package/node_modules/execa/lib/methods/main-sync.js +7 -5
  56. package/node_modules/execa/lib/methods/node.js +1 -1
  57. package/node_modules/execa/lib/methods/script.js +1 -1
  58. package/node_modules/execa/lib/methods/template.js +24 -5
  59. package/node_modules/execa/lib/pipe/pipe-arguments.js +36 -5
  60. package/node_modules/execa/lib/pipe/throw.js +5 -3
  61. package/node_modules/execa/lib/resolve/all-async.js +43 -19
  62. package/node_modules/execa/lib/resolve/all-sync.js +27 -15
  63. package/node_modules/execa/lib/resolve/exit-sync.js +13 -5
  64. package/node_modules/execa/lib/resolve/stdio.js +2 -1
  65. package/node_modules/execa/lib/resolve/wait-stream.js +12 -2
  66. package/node_modules/execa/lib/resolve/wait-subprocess.js +3 -1
  67. package/node_modules/execa/lib/return/early-error.js +58 -21
  68. package/node_modules/execa/lib/return/message.js +2 -10
  69. package/node_modules/execa/lib/return/reject.js +1 -1
  70. package/node_modules/execa/lib/stdio/direction.js +36 -5
  71. package/node_modules/execa/lib/stdio/duplicate.js +26 -16
  72. package/node_modules/execa/lib/stdio/handle-async.js +6 -0
  73. package/node_modules/execa/lib/stdio/handle-sync.js +5 -3
  74. package/node_modules/execa/lib/stdio/handle.js +47 -24
  75. package/node_modules/execa/lib/stdio/native.js +3 -6
  76. package/node_modules/execa/lib/stdio/stdio-option.js +13 -18
  77. package/node_modules/execa/lib/stdio/type.js +2 -10
  78. package/node_modules/execa/lib/terminate/cancel.js +7 -0
  79. package/node_modules/execa/lib/terminate/kill-descendants.js +20 -4
  80. package/node_modules/execa/lib/transform/encoding-transform.js +15 -0
  81. package/node_modules/execa/lib/transform/generator.js +13 -2
  82. package/node_modules/execa/lib/transform/split.js +37 -23
  83. package/node_modules/execa/lib/utils/options.js +9 -0
  84. package/node_modules/execa/lib/utils/standard-stream.js +6 -0
  85. package/node_modules/execa/lib/utils/uint-array.js +1 -7
  86. package/node_modules/execa/lib/verbose/log.js +3 -6
  87. package/node_modules/execa/lib/verbose/output.js +3 -1
  88. package/node_modules/execa/package.json +51 -48
  89. package/node_modules/http-cache-semantics/index.js +32 -9
  90. package/node_modules/http-cache-semantics/package.json +3 -3
  91. package/package.json +3 -3
@@ -4,42 +4,45 @@ import {runGeneratorsSync} from '../transform/generator.js';
4
4
  import {splitLinesSync} from '../transform/split.js';
5
5
  import {joinToString, joinToUint8Array, bufferToUint8Array} from '../utils/uint-array.js';
6
6
  import {FILE_TYPES} from '../stdio/type.js';
7
+ import {getFileTarget} from '../stdio/duplicate.js';
7
8
  import {truncateMaxBufferSync} from './max-buffer.js';
8
9
 
9
10
  // Apply `stdout`/`stderr` options, after spawning, in sync mode
10
- export const transformOutputSync = ({fileDescriptors, syncResult: {output}, options, isMaxBuffer, verboseInfo}) => {
11
- if (output === null) {
12
- return {output: Array.from({length: 3})};
13
- }
14
-
15
- const state = {};
11
+ export const transformOutputSync = ({fileDescriptors, syncResult, options, verboseInfo}) => {
12
+ const output = syncResult.output ?? getSpawnFailureOutput(options);
16
13
  const outputFiles = new Set();
14
+ // Transforms, `verbose` and file writes apply to a single file descriptor each, so their errors must not affect the other ones
15
+ const errors = [];
17
16
  const transformedOutput = output.map((result, fdNumber) =>
18
17
  transformOutputResultSync({
19
18
  result,
20
19
  fileDescriptors,
21
20
  fdNumber,
22
- state,
21
+ errors,
23
22
  outputFiles,
24
- isMaxBuffer,
25
23
  verboseInfo,
26
24
  }, options));
27
- return {output: transformedOutput, ...state};
25
+ return {output: transformedOutput, error: errors.find(error => error !== undefined)};
28
26
  };
29
27
 
28
+ // When the subprocess fails to spawn, `spawnSync()` returns no output. Like with asynchronous methods, each piped output is empty instead.
29
+ // This is the output `spawnSync()` returns when the subprocess succeeds without printing anything: `stdin` and non-piped file descriptors are `null`. Input pipes on other file descriptors cannot be used with synchronous methods.
30
+ const getSpawnFailureOutput = ({stdio}) => stdio.map((stdioOption, fdNumber) => fdNumber !== 0 && stdioOption === 'pipe' ? new Uint8Array() : null);
31
+
30
32
  const transformOutputResultSync = (
31
- {result, fileDescriptors, fdNumber, state, outputFiles, isMaxBuffer, verboseInfo},
33
+ {result, fileDescriptors, fdNumber, errors, outputFiles, verboseInfo},
32
34
  {buffer, encoding, lines, stripFinalNewline, maxBuffer},
33
35
  ) => {
34
36
  if (result === null) {
35
37
  return;
36
38
  }
37
39
 
38
- const truncatedResult = truncateMaxBufferSync(result, isMaxBuffer, maxBuffer);
40
+ const truncatedResult = truncateMaxBufferSync(result, fdNumber, {maxBuffer, buffer});
39
41
  const uint8ArrayResult = bufferToUint8Array(truncatedResult);
40
42
  const {stdioItems, objectMode} = fileDescriptors[fdNumber];
41
- const chunks = runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state);
42
- const {serializedResult, finalResult = serializedResult} = serializeChunks({
43
+ // Empty output must not be passed as a chunk: with a binary encoding, no line is split, so transforms would wrongly run on it
44
+ const {chunks, error: transformError} = runOutputGeneratorsSync(uint8ArrayResult.length === 0 ? [] : [uint8ArrayResult], stdioItems, encoding);
45
+ const {serializedResult, finalResult} = serializeChunks({
43
46
  chunks,
44
47
  objectMode,
45
48
  encoding,
@@ -48,61 +51,61 @@ const transformOutputResultSync = (
48
51
  fdNumber,
49
52
  });
50
53
 
51
- logOutputSync({
54
+ const logError = logOutputSync({
52
55
  serializedResult,
53
56
  fdNumber,
54
- state,
55
57
  verboseInfo,
56
58
  encoding,
57
59
  stdioItems,
58
60
  objectMode,
59
61
  });
60
62
 
63
+ const error = transformError ?? logError;
64
+ errors.push(error);
65
+
61
66
  const returnedResult = buffer[fdNumber] ? finalResult : undefined;
62
67
 
63
68
  try {
64
- if (state.error === undefined) {
65
- writeToFiles(serializedResult, stdioItems, outputFiles);
69
+ if (error === undefined) {
70
+ writeToFiles(chunks, stdioItems, outputFiles);
66
71
  }
67
72
 
68
73
  return returnedResult;
69
- } catch (error) {
70
- state.error = error;
74
+ } catch (writeError) {
75
+ errors.push(writeError);
71
76
  return returnedResult;
72
77
  }
73
78
  };
74
79
 
75
80
  // Applies transform generators to `stdout`/`stderr`
76
- const runOutputGeneratorsSync = (chunks, stdioItems, encoding, state) => {
81
+ const runOutputGeneratorsSync = (chunks, stdioItems, encoding) => {
77
82
  try {
78
- return runGeneratorsSync(chunks, stdioItems, encoding, false);
83
+ // `error` is set, so that a polluted `Object.prototype.error` is not read when destructuring
84
+ return {chunks: runGeneratorsSync(chunks, stdioItems, encoding, false), error: undefined};
79
85
  } catch (error) {
80
- state.error = error;
81
- return chunks;
86
+ return {chunks, error};
82
87
  }
83
88
  };
84
89
 
85
90
  // The contents is converted to three stages:
86
- // - serializedResult: used when the target is a file path/URL or a file descriptor (including 'inherit')
91
+ // - serializedResult: used by `verbose`
87
92
  // - finalResult/returnedResult: returned as `result.std*`
88
93
  const serializeChunks = ({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber}) => {
89
94
  if (objectMode) {
90
- return {serializedResult: chunks};
95
+ return {serializedResult: chunks, finalResult: chunks};
91
96
  }
92
97
 
93
98
  if (encoding === 'buffer') {
94
- return {serializedResult: joinToUint8Array(chunks)};
99
+ const serializedResult = joinToUint8Array(chunks);
100
+ return {serializedResult, finalResult: serializedResult};
95
101
  }
96
102
 
97
103
  const serializedResult = joinToString(chunks, encoding);
98
- if (lines[fdNumber]) {
99
- return {serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode)};
100
- }
101
-
102
- return {serializedResult};
104
+ const finalResult = lines[fdNumber] ? splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode) : serializedResult;
105
+ return {serializedResult, finalResult};
103
106
  };
104
107
 
105
- const logOutputSync = ({serializedResult, fdNumber, state, verboseInfo, encoding, stdioItems, objectMode}) => {
108
+ const logOutputSync = ({serializedResult, fdNumber, verboseInfo, encoding, stdioItems, objectMode}) => {
106
109
  if (!shouldLogOutput({
107
110
  stdioItems,
108
111
  encoding,
@@ -117,20 +120,41 @@ const logOutputSync = ({serializedResult, fdNumber, state, verboseInfo, encoding
117
120
  try {
118
121
  logLinesSync(linesArray, fdNumber, verboseInfo);
119
122
  } catch (error) {
120
- state.error ??= error;
123
+ return error;
121
124
  }
122
125
  };
123
126
 
124
127
  // When the `std*` target is a file path/URL or a file descriptor
125
- const writeToFiles = (serializedResult, stdioItems, outputFiles) => {
128
+ // Object mode cannot be used with those targets.
129
+ const writeToFiles = (chunks, stdioItems, outputFiles) => {
126
130
  const fileItems = stdioItems.filter(({type}) => FILE_TYPES.has(type));
127
- for (const {path, append} of fileItems) {
128
- const pathString = typeof path === 'string' ? path : path.toString();
129
- if (append || outputFiles.has(pathString)) {
130
- appendFileSync(path, serializedResult);
131
+ if (fileItems.length === 0) {
132
+ return;
133
+ }
134
+
135
+ // Like with asynchronous methods, the bytes are written as is, not the text decoded with the `encoding` option, which would change them
136
+ const contents = joinToUint8Array(chunks);
137
+ const writtenPaths = new Set();
138
+
139
+ for (const stdioItem of fileItems) {
140
+ const {type, append} = stdioItem;
141
+ // A `filePath` and a `fileUrl` can target the same file, so they must share the same key
142
+ const path = type === 'fileNumber' ? stdioItem.path : getFileTarget(stdioItem);
143
+
144
+ // A single file descriptor can target the same file twice, e.g. `stdout: [{file}, {file}]`.
145
+ // Its output is a single stream, so it must only be written once.
146
+ if (writtenPaths.has(path)) {
147
+ continue;
148
+ }
149
+
150
+ writtenPaths.add(path);
151
+ // Like with asynchronous methods, when several file descriptors target the same file, the first one decides whether it is appended to
152
+ if (append || outputFiles.has(path)) {
153
+ appendFileSync(path, contents);
131
154
  } else {
132
- outputFiles.add(pathString);
133
- writeFileSync(path, serializedResult);
155
+ writeFileSync(path, contents);
134
156
  }
157
+
158
+ outputFiles.add(path);
135
159
  }
136
160
  };
@@ -2,11 +2,12 @@ import stripFinalNewlineFunction from 'strip-final-newline';
2
2
 
3
3
  // Apply `stripFinalNewline` option, which applies to `result.stdout|stderr|all|stdio[*]`.
4
4
  // If the `lines` option is used, it is applied on each line, but using a different function.
5
- export const stripNewline = (value, {stripFinalNewline}, fdNumber) => getStripFinalNewline(stripFinalNewline, fdNumber) && value !== undefined && !Array.isArray(value)
5
+ export const stripNewline = (value, {stripFinalNewline}, fdNumber, allFds) => value !== undefined && !Array.isArray(value) && getStripFinalNewline(stripFinalNewline, fdNumber, allFds)
6
6
  ? stripFinalNewlineFunction(value)
7
7
  : value;
8
8
 
9
9
  // Retrieve `stripFinalNewline` option value, including with `subprocess.all`
10
- export const getStripFinalNewline = (stripFinalNewline, fdNumber) => fdNumber === 'all'
11
- ? stripFinalNewline[1] || stripFinalNewline[2]
10
+ // With `subprocess.all`, `allFds` are the file descriptors it actually interleaves. Only those are considered, otherwise a single one would be stripped because another one defaults to being stripped.
11
+ export const getStripFinalNewline = (stripFinalNewline, fdNumber, allFds) => fdNumber === 'all'
12
+ ? allFds.some(allFd => stripFinalNewline[allFd])
12
13
  : stripFinalNewline[fdNumber];
@@ -19,6 +19,8 @@ export const waitForIpcOutput = async ({
19
19
  const isVerbose = shouldLogIpc(verboseInfo);
20
20
  const buffer = getFdSpecificValue(bufferArray, 'ipc');
21
21
  const maxBuffer = getFdSpecificValue(maxBufferArray, 'ipc');
22
+ // A throwing `verbose` function must not prevent the following messages from being buffered
23
+ const logErrors = [];
22
24
 
23
25
  for await (const message of loopOnMessages({
24
26
  anyProcess: subprocess,
@@ -29,15 +31,23 @@ export const waitForIpcOutput = async ({
29
31
  reference: true,
30
32
  })) {
31
33
  if (buffer) {
32
- checkIpcMaxBuffer(subprocess, ipcOutput, maxBuffer);
34
+ checkIpcMaxBuffer(ipcOutput, maxBuffer);
33
35
  ipcOutput.push(message);
34
36
  }
35
37
 
36
38
  if (isVerbose) {
37
- logIpcOutput(message, verboseInfo);
39
+ try {
40
+ logIpcOutput(message, verboseInfo);
41
+ } catch (error) {
42
+ logErrors.push(error);
43
+ }
38
44
  }
39
45
  }
40
46
 
47
+ if (logErrors.length > 0) {
48
+ throw logErrors[0];
49
+ }
50
+
41
51
  return ipcOutput;
42
52
  };
43
53
 
@@ -1,12 +1,18 @@
1
1
  import {once, on} from 'node:events';
2
- import {validateIpcMethod, disconnect, getStrictResponseError} from './validation.js';
2
+ import {copyOptions} from '../utils/options.js';
3
+ import {
4
+ validateIpcMethod,
5
+ disconnect,
6
+ getStrictResponseError,
7
+ } from './validation.js';
3
8
  import {getIpcEmitter, isConnected} from './forward.js';
4
9
  import {addReference, removeReference} from './reference.js';
5
10
 
6
11
  export const internalGetEachMessageOptions = Symbol('internalGetEachMessageOptions');
7
12
 
8
13
  // Like `[sub]process.on('message')` but promise-based
9
- export const getEachMessage = (subprocessInfo, options = {}) => {
14
+ export const getEachMessage = (subprocessInfo, rawOptions) => {
15
+ const options = copyOptions(rawOptions);
10
16
  const {reference = true} = options;
11
17
  // Internal callers can stop the IPC listener without exposing cancellation or pipe-awaiting options as public API.
12
18
  const {signal, shouldAwait = !subprocessInfo.isSubprocess} = options[internalGetEachMessageOptions] ?? {};
@@ -1,4 +1,5 @@
1
1
  import {once, on} from 'node:events';
2
+ import {copyOptions} from '../utils/options.js';
2
3
  import {
3
4
  validateIpcMethod,
4
5
  throwOnEarlyDisconnect,
@@ -11,7 +12,8 @@ import {addReference, removeReference} from './reference.js';
11
12
  export const internalGetOneMessageOptions = Symbol('internalGetOneMessageOptions');
12
13
 
13
14
  // Like `[sub]process.once('message')` but promise-based
14
- export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, options = {}) => {
15
+ export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, rawOptions) => {
16
+ const options = copyOptions(rawOptions);
15
17
  const {reference = true, filter} = options;
16
18
  const {signal} = options[internalGetOneMessageOptions] ?? {};
17
19
 
@@ -33,13 +33,14 @@ const startIpc = async ({anyProcess, channel, isSubprocess, ipc}) => {
33
33
  return;
34
34
  }
35
35
 
36
- isCancelListening = true;
37
-
36
+ // This is validated before the flag is set, so that a call which throws keeps failing on subsequent calls
38
37
  if (!ipc) {
39
38
  throwOnMissingParent();
40
39
  return;
41
40
  }
42
41
 
42
+ isCancelListening = true;
43
+
43
44
  if (channel === null) {
44
45
  abortOnDisconnect();
45
46
  return;
@@ -24,7 +24,9 @@ import {handleAbort, abortOnDisconnect} from './graceful.js';
24
24
  // To solve those problems, instead of buffering messages, we debounce them.
25
25
  // The `message` event so it is emitted at most once per macrotask.
26
26
  export const onMessage = async ({anyProcess, channel, isSubprocess, ipcEmitter}, wrappedMessage) => {
27
- if (handleStrictResponse(wrappedMessage) || handleAbort(wrappedMessage)) {
27
+ // `gracefulCancel` messages are only ever sent by the current process to its subprocess.
28
+ // Only the subprocess must interpret them, otherwise a subprocess could abort its parent's own `cancelSignal`, or make it silently drop a message.
29
+ if (handleStrictResponse(wrappedMessage, anyProcess) || (isSubprocess && handleAbort(wrappedMessage))) {
28
30
  return;
29
31
  }
30
32
 
@@ -40,8 +42,9 @@ export const onMessage = async ({anyProcess, channel, isSubprocess, ipcEmitter},
40
42
  }
41
43
 
42
44
  while (incomingMessages.length > 0) {
45
+ // The message being processed is the oldest one, which is not `wrappedMessage` after the first iteration
43
46
  // eslint-disable-next-line no-await-in-loop
44
- await waitForOutgoingMessages(anyProcess, ipcEmitter, wrappedMessage);
47
+ await waitForOutgoingMessages(anyProcess, ipcEmitter, incomingMessages[0]);
45
48
  // eslint-disable-next-line no-await-in-loop
46
49
  await scheduler.yield();
47
50
 
@@ -62,7 +65,11 @@ export const onMessage = async ({anyProcess, channel, isSubprocess, ipcEmitter},
62
65
 
63
66
  // If the `message` event is currently debounced, the `disconnect` event must wait for it
64
67
  export const onDisconnect = async ({anyProcess, channel, isSubprocess, ipcEmitter, boundOnMessage}) => {
65
- abortOnDisconnect();
68
+ // Like `gracefulCancel` messages, only the disconnection from the parent process aborts `getCancelSignal()`.
69
+ // Otherwise, disconnecting from one of the current process' own subprocesses would abort it.
70
+ if (isSubprocess) {
71
+ abortOnDisconnect();
72
+ }
66
73
 
67
74
  const incomingMessages = INCOMING_MESSAGES.get(anyProcess);
68
75
  while (incomingMessages?.length > 0) {
@@ -11,7 +11,8 @@ export const validateIpcInputOption = ({ipcInput, ipc, serialization}) => {
11
11
  throw new Error('The `ipcInput` option cannot be set unless the `ipc` option is `true`.');
12
12
  }
13
13
 
14
- validateIpcInput[serialization](ipcInput);
14
+ // An invalid `serialization` option is reported by `node:child_process` when spawning, like when `ipcInput` is not used
15
+ validateIpcInput[serialization]?.(ipcInput);
15
16
  };
16
17
 
17
18
  const validateAdvancedInput = ipcInput => {
@@ -24,13 +25,17 @@ const validateAdvancedInput = ipcInput => {
24
25
 
25
26
  const validateJsonInput = ipcInput => {
26
27
  try {
27
- JSON.stringify(ipcInput);
28
+ // `JSON.stringify()` returns `undefined` instead of throwing for values it cannot represent, such as functions and symbols
29
+ if (JSON.stringify(ipcInput) === undefined) {
30
+ throw new TypeError('The value cannot be represented as JSON.');
31
+ }
28
32
  } catch (error) {
29
33
  throw new Error('The `ipcInput` option is not serializable with JSON.', {cause: error});
30
34
  }
31
35
  };
32
36
 
33
37
  const validateIpcInput = {
38
+ __proto__: null,
34
39
  advanced: validateAdvancedInput,
35
40
  json: validateJsonInput,
36
41
  };
@@ -1,4 +1,5 @@
1
1
  import {promisify} from 'node:util';
2
+ import {copyOptions} from '../utils/options.js';
2
3
  import {
3
4
  validateIpcMethod,
4
5
  handleEpipeError,
@@ -12,7 +13,8 @@ import {handleSendStrict, waitForStrictResponse} from './strict.js';
12
13
  // We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.
13
14
  // Users would still need to `await subprocess` after the method is done.
14
15
  // Also, this would prevent `unhandledRejection` event from being emitted, making it silent.
15
- export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, {strict = false} = {}) => {
16
+ export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, options) => {
17
+ const {strict = false} = copyOptions(options);
16
18
  const methodName = 'sendMessage';
17
19
  validateIpcMethod({
18
20
  methodName,
@@ -22,7 +22,8 @@ export const handleSendStrict = ({anyProcess, channel, isSubprocess, message, st
22
22
  };
23
23
  };
24
24
 
25
- let count = 0n;
25
+ // This is a plain number, not a `BigInt`, since it must be serializable with `serialization: 'json'`
26
+ let count = 0;
26
27
 
27
28
  // Handles when both processes are calling `sendMessage()` with `strict` at the same time.
28
29
  // If neither process is listening, this would create a deadlock. We detect it and throw.
@@ -33,7 +34,7 @@ export const validateStrictDeadlock = (outgoingMessages, wrappedMessage) => {
33
34
 
34
35
  for (const {id} of outgoingMessages) {
35
36
  if (id !== undefined) {
36
- STRICT_RESPONSES[id].resolve({isDeadlock: true, hasListeners: false});
37
+ STRICT_RESPONSES[id].deferred.resolve({isDeadlock: true, hasListeners: false});
37
38
  }
38
39
  }
39
40
  };
@@ -61,14 +62,19 @@ export const handleStrictRequest = async ({wrappedMessage, anyProcess, channel,
61
62
  return message;
62
63
  };
63
64
 
64
- // Reception of the acknowledgment response
65
- export const handleStrictResponse = wrappedMessage => {
65
+ // Reception of the acknowledgment response.
66
+ // Ids are shared by all processes, so the response must come from the process the message was sent to. Otherwise, a subprocess could acknowledge a message sent to another one.
67
+ export const handleStrictResponse = (wrappedMessage, anyProcess) => {
66
68
  if (wrappedMessage?.type !== RESPONSE_TYPE) {
67
69
  return false;
68
70
  }
69
71
 
70
72
  const {id, message: hasListeners} = wrappedMessage;
71
- STRICT_RESPONSES[id]?.resolve({isDeadlock: false, hasListeners});
73
+ const strictResponse = STRICT_RESPONSES[id];
74
+ if (strictResponse?.anyProcess === anyProcess) {
75
+ strictResponse.deferred.resolve({isDeadlock: false, hasListeners});
76
+ }
77
+
72
78
  return true;
73
79
  };
74
80
 
@@ -79,7 +85,7 @@ export const waitForStrictResponse = async (wrappedMessage, anyProcess, isSubpro
79
85
  }
80
86
 
81
87
  const deferred = createDeferred();
82
- STRICT_RESPONSES[wrappedMessage.id] = deferred;
88
+ STRICT_RESPONSES[wrappedMessage.id] = {deferred, anyProcess};
83
89
  const controller = new AbortController();
84
90
 
85
91
  try {
@@ -101,7 +107,7 @@ export const waitForStrictResponse = async (wrappedMessage, anyProcess, isSubpro
101
107
  }
102
108
  };
103
109
 
104
- const STRICT_RESPONSES = {};
110
+ const STRICT_RESPONSES = {__proto__: null};
105
111
 
106
112
  const throwOnDisconnect = async (anyProcess, isSubprocess, {signal}) => {
107
113
  incrementMaxListeners(anyProcess, 1, signal);
@@ -54,7 +54,7 @@ export const getAbortDisconnectError = () => new Error(`\`cancelSignal\` aborted
54
54
 
55
55
  // When the subprocess uses `cancelSignal` but not the current process
56
56
  export const throwOnMissingParent = () => {
57
- throw new Error('`getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option.');
57
+ throw new Error('`getCancelSignal()` cannot be used without setting the `gracefulCancel` option to `true`.');
58
58
  };
59
59
 
60
60
  // EPIPE can happen when sending a message to a subprocess that is closing but has not disconnected yet
@@ -9,15 +9,9 @@ export const mergeOptions = (boundOptions, options) => {
9
9
  optionName,
10
10
  mergeOption(optionName, safeBoundOptions[optionName], optionValue),
11
11
  ]));
12
- return {...safeBoundOptions, ...mergedOptions};
12
+ return {__proto__: null, ...safeBoundOptions, ...mergedOptions};
13
13
  };
14
14
 
15
- const mergeOption = (optionName, boundOptionValue, optionValue) => {
16
- if (DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue)) {
17
- return {...boundOptionValue, ...optionValue};
18
- }
19
-
20
- return optionValue;
21
- };
15
+ const mergeOption = (optionName, boundOptionValue, optionValue) => DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue) ? {...boundOptionValue, ...optionValue} : optionValue;
22
16
 
23
17
  const DEEP_OPTIONS = new Set(['env', ...FD_SPECIFIC_OPTIONS]);
@@ -50,10 +50,12 @@ const parseArguments = ({mapArguments, firstArgument, nextArguments, deepOptions
50
50
  : [firstArgument, ...nextArguments];
51
51
  const [initialFile, initialArguments, initialOptions] = normalizeParameters(...callArguments);
52
52
  const mergedOptions = mergeOptions(mergeOptions(deepOptions, boundOptions), initialOptions);
53
+ // `mapArguments()` returns a plain object, so its result is read from a null-prototype copy.
54
+ // Otherwise a polluted `Object.prototype` would replace every option, or switch the execution mode.
53
55
  const {
54
56
  options = mergedOptions,
55
57
  isSync = false,
56
- } = mapArguments({options: mergedOptions});
58
+ } = {__proto__: null, ...mapArguments({options: mergedOptions})};
57
59
  return {
58
60
  file: initialFile,
59
61
  commandArguments: initialArguments,
@@ -1,4 +1,4 @@
1
- import {setMaxListeners} from 'node:events';
1
+ import {setMaxListeners, once} from 'node:events';
2
2
  import {spawn} from 'node:child_process';
3
3
  import {MaxBufferError} from 'get-stream';
4
4
  import {handleCommand} from '../arguments/command.js';
@@ -17,7 +17,7 @@ import {subprocessKill} from '../terminate/kill.js';
17
17
  import {getSpawnOptions, getKillFunction} from '../terminate/kill-descendants.js';
18
18
  import {cleanupOnExit} from '../terminate/cleanup.js';
19
19
  import {pipeToSubprocess} from '../pipe/setup.js';
20
- import {makeAllStream} from '../resolve/all-async.js';
20
+ import {makeAllStream, getAllFds} from '../resolve/all-async.js';
21
21
  import {waitForSubprocessResult} from '../resolve/wait-subprocess.js';
22
22
  import {addConvertedStreams} from '../convert/add.js';
23
23
  import {createDeferred} from '../utils/deferred.js';
@@ -74,13 +74,9 @@ const handleAsyncArguments = (rawFile, rawArguments, rawOptions) => {
74
74
 
75
75
  // Options normalization logic specific to async methods.
76
76
  // Prevent passing the `timeout` option directly to `child_process.spawn()`.
77
- const handleAsyncOptions = ({timeout, signal, ...options}) => {
78
- if (signal !== undefined) {
79
- throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');
80
- }
81
-
82
- return {...options, timeoutDuration: timeout};
83
- };
77
+ // The `signal` option is not passed either: it has been renamed and is validated in `normalizeOptions()`, for both synchronous and asynchronous methods.
78
+ // The returned object keeps a null prototype, otherwise a polluted `Object.prototype` would inject option values.
79
+ const handleAsyncOptions = ({timeout, signal, ...options}) => ({__proto__: null, ...options, timeoutDuration: timeout});
84
80
 
85
81
  const spawnSubprocessAsync = ({file, commandArguments, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors}) => {
86
82
  let subprocess;
@@ -98,6 +94,20 @@ const spawnSubprocessAsync = ({file, commandArguments, options, startTime, verbo
98
94
  });
99
95
  }
100
96
 
97
+ // With EMFILE or ENFILE, Node.js does not create the subprocess' streams, and emits the error on the next tick instead of throwing it.
98
+ // The listener must be added right away, or that error would crash the current process.
99
+ if (subprocess.stdio === undefined) {
100
+ return handleEarlyError({
101
+ error: once(subprocess, 'error').then(([error]) => error),
102
+ command,
103
+ escapedCommand,
104
+ fileDescriptors,
105
+ options,
106
+ startTime,
107
+ verboseInfo,
108
+ });
109
+ }
110
+
101
111
  const controller = new AbortController();
102
112
  setMaxListeners(Infinity, controller.signal);
103
113
 
@@ -188,7 +198,7 @@ const handlePromise = async ({subprocess, kill, all: allStream, options, startTi
188
198
  onInternalError.resolve();
189
199
 
190
200
  const stdio = stdioResults.map((stdioResult, fdNumber) => stripNewline(stdioResult, options, fdNumber));
191
- const all = stripNewline(allResult, options, 'all');
201
+ const all = stripNewline(allResult, options, 'all', getAllFds(subprocess, options.buffer));
192
202
  const result = getAsyncResult({
193
203
  errorInfo,
194
204
  exitCode,
@@ -205,7 +215,7 @@ const handlePromise = async ({subprocess, kill, all: allStream, options, startTi
205
215
  return handleResult(result, verboseInfo, options);
206
216
  };
207
217
 
208
- const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, ipcOutput, context, options, command, escapedCommand, startTime}) => 'error' in errorInfo
218
+ const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, ipcOutput, context, options, command, escapedCommand, startTime}) => Object.hasOwn(errorInfo, 'error')
209
219
  ? makeError({
210
220
  error: errorInfo.error,
211
221
  command,
@@ -9,7 +9,7 @@ import {stripNewline} from '../io/strip-newline.js';
9
9
  import {addInputOptionsSync} from '../io/input-sync.js';
10
10
  import {transformOutputSync} from '../io/output-sync.js';
11
11
  import {getMaxBufferSync} from '../io/max-buffer.js';
12
- import {getAllSync} from '../resolve/all-sync.js';
12
+ import {getAllSync, getAllSyncFds} from '../resolve/all-sync.js';
13
13
  import {getExitResultSync} from '../resolve/exit-sync.js';
14
14
 
15
15
  // Main shared logic for all sync methods: `execaSync()`, `$.sync()`
@@ -52,7 +52,8 @@ const normalizeSyncOptions = options => options.node && !options.ipc ? {...optio
52
52
 
53
53
  // Options validation logic specific to sync methods
54
54
  const validateSyncOptions = ({ipc, ipcInput, detached, cancelSignal, killDescendants}) => {
55
- if (ipcInput) {
55
+ // Any value can be sent over IPC, including falsy ones, so only `undefined` means the option is not set
56
+ if (ipcInput !== undefined) {
56
57
  throwInvalidSyncOption('ipcInput');
57
58
  }
58
59
 
@@ -96,11 +97,11 @@ const spawnSubprocessSync = ({file, commandArguments, options, command, escapedC
96
97
  fileDescriptors,
97
98
  syncResult,
98
99
  options,
99
- isMaxBuffer,
100
100
  verboseInfo,
101
101
  });
102
102
  const stdio = output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options, fdNumber));
103
- const all = stripNewline(getAllSync(output, options), options, 'all');
103
+ const allFds = getAllSyncFds(output);
104
+ const all = stripNewline(getAllSync(output, allFds, options), options, 'all', allFds);
104
105
  return getSyncResult({
105
106
  error,
106
107
  exitCode,
@@ -120,7 +121,8 @@ const runSubprocessSync = ({file, commandArguments, options, command, escapedCom
120
121
  try {
121
122
  addInputOptionsSync(fileDescriptors, options);
122
123
  const normalizedOptions = normalizeSpawnSyncOptions(options);
123
- return spawnSync(...concatenateShell(file, commandArguments, normalizedOptions));
124
+ // Keep the null prototype, otherwise a polluted `Object.prototype.failed` would make the result look like an early error
125
+ return {__proto__: null, ...spawnSync(...concatenateShell(file, commandArguments, normalizedOptions))};
124
126
  } catch (error) {
125
127
  return makeEarlyError({
126
128
  error,
@@ -8,7 +8,7 @@ export const mapNode = ({options}) => {
8
8
  throw new TypeError('The "node" option cannot be false with `execaNode()`.');
9
9
  }
10
10
 
11
- return {options: {...options, node: true}};
11
+ return {options: {__proto__: null, ...options, node: true}};
12
12
  };
13
13
 
14
14
  // Applies the `node: true` option, and the related `nodePath`/`nodeOptions` options.
@@ -11,7 +11,7 @@ export const mapScriptAsync = ({options}) => getScriptOptions(options);
11
11
  const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});
12
12
 
13
13
  // `$` is like `execa` but with script-friendly options: `{stdin: 'inherit', preferLocal: true}`
14
- const getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});
14
+ const getScriptOptions = options => ({options: {__proto__: null, ...getScriptStdinOption(options), ...options}});
15
15
 
16
16
  const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined
17
17
  ? {stdin: 'inherit'}