All files / advanced-spawn-async/lib/functions/core index.ts

100% Statements 30/30
100% Branches 6/6
100% Functions 9/9
100% Lines 27/27
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  1x                       7x   7x 7x 7x   7x 16x 16x     7x 1x 1x     12x                       13x 13x               13x 12x   12x 3x   9x         7x 7x   7x 1x 1x   6x             7x             1x  
import { IsomorphicSpawn, SpawnFactory, Options } from '../../types'
import { TerminationError, InternalError } from '../../classes'
 
function callSpawn<
  Process extends IsomorphicSpawn.Return
> (
  spawn: IsomorphicSpawn<Process>,
  command: string,
  args: string[] = [],
  options: Options = {}
): SpawnFactory<Process> {
  type Info = SpawnFactory.TerminationInformation<Process>
 
  const process = spawn(command, args, options)
 
  let stdout = ''
  let stderr = ''
  let output = ''
 
  process.stdout.on('data', chunk => {
    stdout += chunk
    output += chunk
  })
 
  process.stderr.on('data', chunk => {
    stderr += chunk
    output += chunk
  })
 
  const mkinfo = (status: number, signal: string | null): Info => ({
    command,
    args,
    options,
    stdout,
    stderr,
    output,
    status,
    signal,
    process
  })
 
  const createPromise = (event: Options.TerminationEvent) => new Promise<Info>((resolve, reject) => {
    process.on('error', error => reject(new InternalError({
      command,
      args,
      options,
      process,
      error
    })))
 
    process.on(event, (status, signal) => {
      const info = mkinfo(status, signal)
 
      if (status) {
        reject(new TerminationError(info))
      } else {
        resolve(info)
      }
    })
  })
 
  const [onclose, onexit] = (() => {
    const { event } = options
 
    if (event) {
      const promise = createPromise(event)
      return [promise, promise]
    } else {
      return [
        createPromise('close'),
        createPromise('exit')
      ]
    }
  })()
 
  return {
    onclose,
    onexit,
    process
  }
}
 
export = callSpawn