Skip to content

Commit

Permalink
chore: move promisifyStream to utils (#925)
Browse files Browse the repository at this point in the history
  • Loading branch information
antongolub authored Oct 30, 2024
1 parent 2f8066c commit 2f2b709
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 27 deletions.
29 changes: 2 additions & 27 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
once,
parseDuration,
preferLocalBin,
promisifyStream,
quote,
quotePowerShell,
} from './util.js'
Expand Down Expand Up @@ -359,7 +360,7 @@ export class ProcessPromise extends Promise<ProcessOutput> {
}

from.pipe(dest)
return ProcessPromise.promisifyStream(dest)
return promisifyStream(dest)
}

abort(reason?: string) {
Expand Down Expand Up @@ -530,32 +531,6 @@ export class ProcessPromise extends Promise<ProcessOutput> {
): Promise<ProcessOutput | T> {
return super.catch(onrejected)
}

private static promisifyStream<S extends Writable>(
stream: S
): S & PromiseLike<void> {
return new Proxy(stream as S & PromiseLike<void>, {
get(target, key) {
if (key === 'then') {
return (res: any = noop, rej: any = noop) =>
new Promise((_res, _rej) =>
target
.once('error', () => _rej(rej()))
.once('finish', () => _res(res()))
)
}
const value = Reflect.get(target, key)
if (key === 'pipe' && typeof value === 'function') {
return function (...args: any) {
return ProcessPromise.promisifyStream(
value.apply(target, args) as S
)
}
}
return value
},
})
}
}

type GettersRecord<T extends Record<any, any>> = { [K in keyof T]: () => T[K] }
Expand Down
24 changes: 24 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import os from 'node:os'
import path from 'node:path'
import fs from 'node:fs'
import { chalk } from './vendor-core.js'
import type { Writable } from 'node:stream'

export { isStringLiteral } from './vendor-core.js'

Expand Down Expand Up @@ -449,3 +450,26 @@ export const once = <T extends (...args: any[]) => any>(fn: T) => {
return (result = fn(...args))
}
}

export const promisifyStream = <S extends Writable>(
stream: S
): S & PromiseLike<void> =>
new Proxy(stream as S & PromiseLike<void>, {
get(target, key) {
if (key === 'then') {
return (res: any = noop, rej: any = noop) =>
new Promise((_res, _rej) =>
target
.once('error', () => _rej(rej()))
.once('finish', () => _res(res()))
)
}
const value = Reflect.get(target, key)
if (key === 'pipe' && typeof value === 'function') {
return function (...args: any) {
return promisifyStream(value.apply(target, args) as S)
}
}
return value
},
})

0 comments on commit 2f2b709

Please sign in to comment.