Skip to content
Myr

stream.js

This file

Path

lib/stream.js

179 lines · 7.6 KiB · JavaScript

Last changed by

Improve `killSignal` option (#728)ehmickybefore adoptioncf36c1d

History of this file

Take it

The walk stopped after 200 commits: lines older than df08cfb point at it.

Allow `stdin` to be a sync/async iterable (#604)ehmickybefore adoptionec380db

line 1why, one step back
1import {once} from 'node:events';

Support file path and URL types in the `stdout` and `stderr` options (#621)ehmickybefore adoptionb369efe

line 2why, one step back
2import {finished} from 'node:stream/promises';

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

line 3why, one step back
3import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';

Require Node.js 18Sindre Sorhusbefore adoption834e372

line 4why, one step back
4import mergeStreams from '@sindresorhus/merge-streams';

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

line 5why, one step back
5import {throwOnTimeout, cleanupOnExit} from './kill.js';

Fix Node.js streams not being cleaned up on process error (#660)ehmickybefore adoption61a1623

line 6why, one step back
6import {STANDARD_STREAMS} from './stdio/native.js';

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

line 7why, one step back
7import {generatorToDuplexStream} from './stdio/generator.js';

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

lines 8–9why, one step back
8
9// `all` interleaves `stdout` and `stderr`

Fix `all` option combined with `ignore` (#703)ehmickybefore adoption7707fc7

lines 10–12why, one step back
10export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)
11 ? mergeStreams([stdout, stderr].filter(Boolean))12 : undefined;

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

lines 13–14why, one step back
13
14// On failure, `result.stdout|stderr|all` should contain the currently buffered stream

Improve error handling (#647)ehmickybefore adoption5b6d859

lines 15–16why, one step back
15// They are automatically closed and flushed by Node.js when the child process exits
16// We guarantee this by calling `childProcess.kill()`

Fix `error.stdout|stderr|all` type when `encoding` option is used (#652)ehmickybefore adoptioncff6847

lines 17–18why, one step back
17// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve
18const getBufferedData = async (streamPromise, encoding) => {

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

lines 19–21why, one step back
19 try {
20 return await streamPromise;21 } catch (error) {

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

lines 22–24why, one step back
22 return error.bufferedData === undefined || Array.isArray(error.bufferedData)
23 ? error.bufferedData24 : applyEncoding(error.bufferedData, encoding);

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

lines 25–27why, one step back
25 }
26};27

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

line 28why, one step back
28const getStdioPromise = ({stream, stdioStreams, encoding, buffer, maxBuffer}) => stdioStreams[0].direction === 'output'

Upgrade `merge-streams` (#717)ehmickybefore adoption8ef8e90

line 29why, one step back
29 ? getStreamPromise({stream, encoding, buffer, maxBuffer})

Simplify `std*` options logic (#691)ehmickybefore adoption98b0ee3

line 30why, one step back
30 : undefined;

Add `result.stdio` and `error.stdio` (#676)ehmickybefore adoption62a5207

line 31why, one step back
31

Upgrade `merge-streams` (#717)ehmickybefore adoption8ef8e90

line 32why, one step back
32const getAllPromise = ({spawned, encoding, buffer, maxBuffer}) => getStreamPromise({stream: getAllStream(spawned, encoding), encoding, buffer, maxBuffer: maxBuffer * 2});

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

lines 33–50why, one step back
33
34// When `childProcess.stdout` is in objectMode but not `childProcess.stderr` (or the opposite), we need to use both:35// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk36// - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array37// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.38const getAllStream = ({all, stdout, stderr}, encoding) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode39 ? all.pipe(generatorToDuplexStream({value: allStreamGenerator, encoding}).value)40 : all;4142const allStreamGenerator = {43 async * transform(chunks) {44 yield * chunks;45 },46 binary: true,47 writableObjectMode: true,48 readableObjectMode: true,49};50

Upgrade `merge-streams` (#717)ehmickybefore adoption8ef8e90

line 51why, one step back
51const getStreamPromise = async ({stream, encoding, buffer, maxBuffer}) => {

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

lines 52–55why, one step back
52 if (!stream || !buffer) {
53 return;54 }55

Upgrade `merge-streams` (#717)ehmickybefore adoption8ef8e90

line 56why, one step back
56 if (stream.readableObjectMode) {

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

lines 57–59why, one step back
57 return getStreamAsArray(stream, {maxBuffer});
58 }59

Fix `encoding` option (#696)ehmickybefore adoptionb6f9fa2

lines 60–62why, one step back
60 const contents = encoding === 'buffer'
61 ? await getStreamAsArrayBuffer(stream, {maxBuffer})62 : await getStream(stream, {maxBuffer});

Fix `error.stdout|stderr|all` type when `encoding` option is used (#652)ehmickybefore adoptioncff6847

lines 63–65why, one step back
63 return applyEncoding(contents, encoding);
64};65

Fix `encoding` option (#696)ehmickybefore adoptionb6f9fa2

line 66why, one step back
66const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

line 67why, one step back
67

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

line 68why, one step back
68// Retrieve streams created by the `std*` options

Simplify `std*` options logic (#691)ehmickybefore adoption98b0ee3

line 69why, one step back
69const getCustomStreams = stdioStreamsGroups => stdioStreamsGroups.flat().filter(({type}) => type !== 'native');

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

line 70why, one step back
70

Wait for `WritableStream` completion (#645)ehmickybefore adoptionfb73bd1

lines 71–77why, one step back
71// Some `stdout`/`stderr` options create a stream, e.g. when passing a file path.
72// The `.pipe()` method automatically ends that stream when `childProcess.stdout|stderr` ends.73// This makes sure we want for the completion of those streams, in order to catch any error.74// Since we want to end those streams, they cannot be infinite, except for `process.stdout|stderr`.75// However, for the `stdin`/`input`/`inputFile` options, we only wait for errors, not completion.76// This is because source streams completion should end destination streams, but not the other way around.77// This allows for source streams to pipe to multiple destinations.

Improve syntax of `std*: filePath` option (#671)ehmickybefore adoption90e0e13

line 78why, one step back
78// We make an exception for `fileUrl` and `filePath`, since we create that source stream and we know it is piped to a single destination.

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

lines 79–81why, one step back
79const waitForCustomStreamsEnd = customStreams => customStreams
80 .filter(({value, type, direction}) => shouldWaitForCustomStream(value, type, direction))81 .map(({value}) => finished(value));

Allow `stdin` to be a sync/async iterable (#604)ehmickybefore adoptionec380db

line 82why, one step back
82

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

lines 83–85why, one step back
83const throwOnCustomStreamsError = customStreams => customStreams
84 .filter(({value, type, direction}) => !shouldWaitForCustomStream(value, type, direction))85 .map(({value}) => throwOnStreamError(value));

Support file path and URL types in the `stdout` and `stderr` options (#621)ehmickybefore adoptionb369efe

line 86why, one step back
86

Improve syntax of `std*: filePath` option (#671)ehmickybefore adoption90e0e13

lines 87–88why, one step back
87const shouldWaitForCustomStream = (value, type, direction) => (type === 'fileUrl' || type === 'filePath')
88 || (direction === 'output' && !STANDARD_STREAMS.includes(value));

Refactor execa promise to use `async/await` (#653)ehmickybefore adoptiond69fd23

line 89why, one step back
89

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

lines 90–91why, one step back
90const throwIfStreamError = stream => stream === null ? [] : [throwOnStreamError(stream)];
91

Allow `stdin` to be a sync/async iterable (#604)ehmickybefore adoptionec380db

lines 92–96why, one step back
92const throwOnStreamError = async stream => {
93 const [error] = await once(stream, 'error');94 throw error;95};96

Improve error handling (#647)ehmickybefore adoption5b6d859

lines 97–99why, one step back
97// The streams created by the `std*` options are automatically ended by `.pipe()`.
98// However `.pipe()` only does so when the source stream ended, not when it errored.99// Therefore, when `childProcess.stdin|stdout|stderr` errors, those streams must be manually destroyed.

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

line 100why, one step back
100const cleanupStdioStreams = (customStreams, error) => {

Simplify `std*` options logic (#691)ehmickybefore adoption98b0ee3

lines 101–103why, one step back
101 for (const {value} of customStreams) {
102 if (!STANDARD_STREAMS.includes(value)) {103 value.destroy(error);

Allow `stdin`/`stdout`/`stderr` to be an array (#643)ehmickybefore adoption7efd50c

lines 104–107why, one step back
104 }
105 }106};107

Improve process termination (#724)ehmickybefore adoption1c48d37

lines 108–130why, one step back
108// Like `once()` except it never rejects, especially not on `error` event.
109const pEvent = (eventEmitter, eventName) => new Promise(resolve => {110 eventEmitter.once(eventName, (...payload) => {111 resolve([eventName, ...payload]);112 });113});114115const throwOnProcessError = async processErrorPromise => {116 const [, error] = await processErrorPromise;117 throw error;118};119120// First the `spawn` event is emitted, then `exit`.121// If the `error` event is emitted:122// - before `spawn`: `exit` is never emitted.123// - after `spawn`: `exit` is always emitted.124// We only want to listen to `exit` if it will be emitted, i.e. if `spawn` has been emitted.125// Therefore, the arguments order of `Promise.race()` is significant.126const waitForFailedProcess = async (processSpawnPromise, processErrorPromise, processExitPromise) => {127 const [eventName] = await Promise.race([processSpawnPromise, processErrorPromise]);128 return eventName === 'spawn' ? processExitPromise : [];129};130

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

line 131why, one step back
131// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)

Improve graceful exit (#714)ehmickybefore adoption5eeaab5

line 132why, one step back
132export const getSpawnedResult = async ({

Support file path and URL types in the `stdout` and `stderr` options (#621)ehmickybefore adoptionb369efe

line 133why, one step back
133 spawned,

Improve `killSignal` option (#728)ehmickybefore adoptioncf36c1d

line 134why, one step back
134 options: {encoding, buffer, maxBuffer, timeoutDuration: timeout, cleanup, detached},

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

line 135why, one step back
135 context,

Simplify `std*` options logic (#691)ehmickybefore adoption98b0ee3

line 136why, one step back
136 stdioStreamsGroups,

Improve graceful exit (#714)ehmickybefore adoption5eeaab5

lines 137–138why, one step back
137 controller,
138}) => {

Improve process termination (#724)ehmickybefore adoption1c48d37

lines 139–142why, one step back
139 const processSpawnPromise = pEvent(spawned, 'spawn');
140 const processErrorPromise = pEvent(spawned, 'error');141 const processExitPromise = pEvent(spawned, 'exit');142

Improve graceful exit (#714)ehmickybefore adoption5eeaab5

line 143why, one step back
143 const removeExitHandler = cleanupOnExit(spawned, cleanup, detached);

Simplify `std*` options logic (#691)ehmickybefore adoption98b0ee3

line 144why, one step back
144 const customStreams = getCustomStreams(stdioStreamsGroups);

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

line 145why, one step back
145

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

line 146why, one step back
146 const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, stdioStreams: stdioStreamsGroups[index], encoding, buffer, maxBuffer}));

Upgrade `merge-streams` (#717)ehmickybefore adoption8ef8e90

line 147why, one step back
147 const allPromise = getAllPromise({spawned, encoding, buffer, maxBuffer});

Wait for streams completion on errors (#722)ehmickybefore adoption195369f

line 148why, one step back
148 const customStreamsEndPromises = waitForCustomStreamsEnd(customStreams);

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

lines 149–150why, one step back
149
150 try {

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

lines 151–152why, one step back
151 return await Promise.race([
152 Promise.all([

Improve process termination (#724)ehmickybefore adoption1c48d37

lines 153–154why, one step back
153 undefined,
154 processExitPromise,

Add `result.stdio` and `error.stdio` (#676)ehmickybefore adoption62a5207

line 155why, one step back
155 Promise.all(stdioPromises),

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

line 156why, one step back
156 allPromise,

Wait for streams completion on errors (#722)ehmickybefore adoption195369f

line 157why, one step back
157 ...customStreamsEndPromises,

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

line 158why, one step back
158 ]),

Improve process termination (#724)ehmickybefore adoption1c48d37

line 159why, one step back
159 throwOnProcessError(processErrorPromise),

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

lines 160–161why, one step back
160 ...throwOnCustomStreamsError(customStreams),
161 ...throwIfStreamError(spawned.stdin),

Improve `killSignal` option (#728)ehmickybefore adoptioncf36c1d

line 162why, one step back
162 ...throwOnTimeout(timeout, context, controller),

Support file path and URL types in the `stdout` and `stderr` options (#621)ehmickybefore adoptionb369efe

line 163why, one step back
163 ]);

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

line 164why, one step back
164 } catch (error) {

Improve error handling (#647)ehmickybefore adoption5b6d859

lines 165–166why, one step back
165 spawned.kill();
166 const results = await Promise.all([

Improve process termination (#724)ehmickybefore adoption1c48d37

lines 167–168why, one step back
167 error,
168 waitForFailedProcess(processSpawnPromise, processErrorPromise, processExitPromise),

Add `result.stdio` and `error.stdio` (#676)ehmickybefore adoption62a5207

line 169why, one step back
169 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),

Fix `error.stdout|stderr|all` type when `encoding` option is used (#652)ehmickybefore adoptioncff6847

line 170why, one step back
170 getBufferedData(allPromise, encoding),

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

line 171why, one step back
171 ]);

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

line 172why, one step back
172 cleanupStdioStreams(customStreams, error);

Wait for streams completion on errors (#722)ehmickybefore adoption195369f

line 173why, one step back
173 await Promise.allSettled(customStreamsEndPromises);

Improve error handling (#647)ehmickybefore adoption5b6d859

line 174why, one step back
174 return results;

Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767

line 175why, one step back
175 } finally {

Improve graceful exit (#714)ehmickybefore adoption5eeaab5

lines 176–177why, one step back
176 controller.abort();
177 removeExitHandler?.();

Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb

lines 178–179why, one step back
178 }
179};