Code coverage report for lib/server.js

Statements: 40.65% (50 / 123)      Branches: 31.08% (23 / 74)      Functions: 29.17% (7 / 24)      Lines: 40.98% (50 / 122)      Ignored: none     

All files » lib/ » server.js
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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 2641   1           1               1   1 8   8 8   8 8                                                 1 1                   1 1               1       1               1           1   1             1               1 1 1         1 1                 1 1       1             1                                         1 1           1       1 1 1   1 1   1 1 1   1 1 1           1   1                                   1 4     1                                           1                       1                                        
module.exports = beefy
 
var spawn = require('child_process').spawn
  , http = require('http')
  , path = require('path')
  , url = require('url')
  , fs = require('fs')
 
var response_stream = require('response-stream')
  , sse = require('sse-stream')('/-/live-reload')
  , through = require('through')
  , colors = require('colors')
  , watchr = require('watchr')
  , mime = require('mime')
  , script_injector = require('script-injector')
 
var fake_index_html = fs.readFileSync(path.join(__dirname, 'fake_index.html'), 'utf8')
 
function beefy(cwd, browserify_path, browserify_args, entry_points, live_reload, log, custom_handler) {
  var server = http.createServer(beefy_server)
 
  log = log || function noop() {}
  custom_handler = custom_handler || function noop() {}
 
  Eif(!live_reload) {
    return server
  }
 
  var should_reload = false
    , connections = []
 
  sse.install(server)
  sse.on('connection', function(conn) {
    connections.push(conn)
    conn.once('end', function() {
      connections.splice(connections.indexOf(conn), 1)
    })
  })
 
  watchr.watch({
      path: cwd
    , listener: do_reload
    , ignoreHiddenFiles: true
    , ignorePatterns: true
  })
 
  server.reload = do_reload
 
  return server
 
  function beefy_server(req, resp) {
    var parsed = url.parse(req.url, true)
      , pathname = parsed.pathname.slice(1) || 'index.html'
      , filepath = path.resolve(path.join(cwd, pathname))
      , logged_pathname = '/'+pathname
      , query = parsed.query || {}
      , logged_color = null
      , start = Date.now()
      , bytesize = 0
      , stream
 
    Eif((pathname in entry_points) || 'browserify' in query) {
      stream = handle_browserify(
          req
        , resp
        , pathname
        , entry_points[pathname]
      )
    }
 
    Iif(!stream && fs.existsSync(filepath)) {
      stream = handle_static(filepath)
    }
 
    Iif(!stream && live_reload && pathname === '-/live-reload') {
      resp.writeHead(200, {'content-type': 'application/json'})
      resp.end(JSON.stringify({
        should_reload: should_reload
      }))
      return should_reload = false
    }
 
    Iif(!stream && live_reload && pathname === '-/live-reload.js') {
      resp.writeHead(200, {'content-type': 'text/javascript'})
      resp.end(';('+live_reload_code+')()')
      return
    }
 
    Iif(!stream && custom_handler(req, resp)) return
 
    Iif(!stream && /html/.test(req.headers.accept || '')) {
      logged_pathname = logged_pathname.blue + ' ' + '(generated)'
      logged_color = 'grey'
      stream = response_stream(fake_index(query))
      stream.setHeader('content-type', 'text/html')
    }
 
    Iif(!stream) {
      stream = response_stream(through())
      stream.writeHead(404, {'content-type': 'text/plain'})
      process.nextTick(function() {
        stream.end('not found')
      })
    }
 
    logged_pathname = stream.logged_pathname || logged_pathname
    logged_color = stream.logged_color || logged_color
    stream
      .on('end', do_log)
      .on('data', do_tally)
      .pipe(resp)
 
    function do_log() {
      log(
          ''+resp.statusCode
        , Date.now() - start
        , bytesize
        , logged_pathname
        , logged_color
      )
    }
 
    function do_tally(data) {
      bytesize += data.length
    }
  }
 
  function do_reload() {
    should_reload = true
    connections.forEach(function(conn) {
      conn.write('reload')
    })
  }
 
  function handle_static(filepath) {
    var stat = fs.lstatSync(filepath)
      , stream
 
    if(stat.isDirectory()) {
      filepath = path.join(filepath, 'index.html')
      if(!fs.existsSync(filepath)) {
        return
      }
      return handle_static(filepath)
    }
 
    stream = fs.createReadStream(filepath)
    if(live_reload && path.extname(filepath) === '.html') {
      stream = stream.pipe(script_injector(live_reload_code))
    }
    stream = response_stream(stream)
    stream.setHeader('content-type', mime.lookup(filepath))
    return stream
  }
 
  function handle_browserify(req, resp, original, pathname) {
    var error = []
      , logged_path
      , stream
      , args
      , bfy
 
    args = pathname === null ?
      browserify_args.slice() :
      [pathname].concat(browserify_args)
 
    args.unshift(browserify_path)
    logged_path = '/' + original + ' -> ' + args.map(to_local).join(' ')
    args.shift()
 
    bfy = spawn(browserify_path, args)
    stream = response_stream(bfy.stdout)
 
    stream.setHeader('content-type', 'text/javascript')
    stream.logged_pathname = logged_path
    stream.logged_color = 'magenta'
 
    bfy.stderr.on('data', [].push.bind(error))
    bfy.stderr.on('end', function() {
      Iif(error.length) {
        bfyerror(error.join(''))
        process.stdout.write(error.join(''))
      }
    })
 
    return stream
 
    function bfyerror(data) {
      resp.end('('+function errored(error) {
        if(!document.body) {
          return document.addEventListener('DOMContentLoaded', function() {
            errored(error)
          })
        }
 
        var pre = document.createElement('pre')
        pre.textContent = error
 
        document.body.children.length ?
          document.body.insertBefore(pre, document.body.children[0]) :
          document.body.appendChild(pre)
      }+'('+JSON.stringify(data+'')+'))')
    }
  }
 
  function to_local(path) {
    return path.replace(cwd, '.')
  }
 
  function fake_index(query) {
    var stream = through()
      , ENTRY_POINT_URL = Object.keys(entry_points)[0]
      , index_path
      , html
 
    index_path = query.p || ENTRY_POINT_URL.replace(cwd, '')
 
    if(query.p) {
      index_path += '?browserify'
    }
 
    html = fake_index_html
      .replace('{{ PATH }}', index_path)
      .replace('{{ LIVE }}', live_reload ? '<script src="/-/live-reload.js"></script>' : '')
    process.nextTick(function() {
      stream.end(html)
    })
 
    return stream
  }
 
  function live_reload_code() {
    if(window.EventSource) {
      var es = (new EventSource('/-/live-reload'))
      es.onmessage = function(ev) {
        if(ev.data === 'reload') {
          window.location.reload()
        }
      }
    } else {
      setTimeout(iter, 2000)
    }
 
    function iter() {
      var xhr = new XMLHttpRequest()
      xhr.open('GET', '/-/live-reload')
      xhr.onreadystatechange = function() {
        if(xhr.readyState !== 4) {
          return
        }
 
        if(/true/.test(xhr.responseText)) {
          return window.location = window.location
        }
        xhr =
        xhr.onreadystatechange = null
        setTimeout(iter, 2000)
      }
 
      xhr.send(null)
    }
  }
}