All files eventsource.js

92.82% Statements 181/195
81.3% Branches 100/123
90.48% Functions 19/21
93.62% Lines 176/188
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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 3901x 1x 1x 1x 1x 1x   1x                         54x 54x   5x       54x   9x       54x 54x     1776x 1773x 1773x       1773x 1x 1x   1773x 1735x 1x   1734x         54x 54x 3x 3x     54x 54x 54x   54x     1790x 1790x 1790x 1790x 1790x 3x 5x 5x 4x             1790x       1790x 1790x 3x 3x   3x 3x 3x 3x 3x 3x       1790x 1x 5x       5x 5x 5x         1790x   58x 1x 1x 1x       57x 4x   2x 2x   2x 2x 2x 2x     53x 3x 3x     50x 50x           50x 49x 49x 49x   50x       49x 49x 163x   163x 163x   163x 223x 8x 4x   8x     223x 223x     223x 166670x 166670x 147x 147x   166523x 8x 8x 166515x 97x       223x 118x     105x   105x     163x 49x 114x           1790x 1790x 1790x     54x     1870x 385x       54x 9x 9x 9x 9x       105x 48x 41x 41x         41x   48x 57x 55x 55x 55x   55x   55x 5x   50x   55x   55x 55x   55x 46x 9x 4x 5x 5x                     1x   1x 1x   1x 3x                                       59x 59x               1x 1x 1x   1x 1x 1x               1x 9x                       1x 64x   62x 62x                         1x 1x 1x 1x                     1829x 1829x 6x 6x 6x                         41x 41x 123x 123x        
var original = require('original')
var parse = require('url').parse
var events = require('events')
var https = require('https')
var http = require('http')
var util = require('util')
 
var httpsOptions = [
  'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers',
  'rejectUnauthorized', 'secureProtocol', 'servername'
]
 
/**
 * Creates a new EventSource object
 *
 * @param {String} url the URL to which to connect
 * @param {Object} [eventSourceInitDict] extra init params. See README for details.
 * @api public
 **/
function EventSource (url, eventSourceInitDict) {
  var readyState = EventSource.CONNECTING
  Object.defineProperty(this, 'readyState', {
    get: function () {
      return readyState
    }
  })
 
  Object.defineProperty(this, 'url', {
    get: function () {
      return url
    }
  })
 
  var self = this
  self.reconnectInterval = 1000
 
  function onConnectionClosed () {
    if (readyState === EventSource.CLOSED) return
    readyState = EventSource.CONNECTING
    _emit('error', new Event('error'))
 
    // The url may have been changed by a temporary
    // redirect. If that's the case, revert it now.
    if (reconnectUrl) {
      url = reconnectUrl
      reconnectUrl = null
    }
    setTimeout(function () {
      if (readyState !== EventSource.CONNECTING) {
        return
      }
      connect()
    }, self.reconnectInterval)
  }
 
  var req
  var lastEventId = ''
  if (eventSourceInitDict && eventSourceInitDict.headers && eventSourceInitDict.headers['Last-Event-ID']) {
    lastEventId = eventSourceInitDict.headers['Last-Event-ID']
    delete eventSourceInitDict.headers['Last-Event-ID']
  }
 
  var discardTrailingNewline = false
  var data = ''
  var eventName = ''
 
  var reconnectUrl = null
 
  function connect () {
    var options = parse(url)
    var isSecure = options.protocol === 'https:'
    options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' }
    if (lastEventId) options.headers['Last-Event-ID'] = lastEventId
    if (eventSourceInitDict && eventSourceInitDict.headers) {
      for (var i in eventSourceInitDict.headers) {
        var header = eventSourceInitDict.headers[i]
        if (header) {
          options.headers[i] = header
        }
      }
    }
 
    // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`,
    // but for now exists as a backwards-compatibility layer
    options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized)
 
    // If specify http proxy, make the request to sent to the proxy server,
    // and include the original url in path and Host headers
    var useProxy = eventSourceInitDict && eventSourceInitDict.proxy
    if (useProxy) {
      var proxy = parse(eventSourceInitDict.proxy)
      isSecure = proxy.protocol === 'https:'
 
      options.protocol = isSecure ? 'https:' : 'http:'
      options.path = url
      options.headers.Host = options.host
      options.hostname = proxy.hostname
      options.host = proxy.host
      options.port = proxy.port
    }
 
    // If https options are specified, merge them into the request options
    if (eventSourceInitDict && eventSourceInitDict.https) {
      for (var optName in eventSourceInitDict.https) {
        Iif (httpsOptions.indexOf(optName) === -1) {
          continue
        }
 
        var option = eventSourceInitDict.https[optName]
        Eif (option !== undefined) {
          options[optName] = option
        }
      }
    }
 
    req = (isSecure ? https : http).request(options, function (res) {
      // Handle HTTP errors
      if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
        _emit('error', new Event('error', {status: res.statusCode}))
        onConnectionClosed()
        return
      }
 
      // Handle HTTP redirects
      if (res.statusCode === 301 || res.statusCode === 307) {
        if (!res.headers.location) {
          // Server sent redirect response without Location header.
          _emit('error', new Event('error', {status: res.statusCode}))
          return
        }
        if (res.statusCode === 307) reconnectUrl = url
        url = res.headers.location
        process.nextTick(connect)
        return
      }
 
      if (res.statusCode !== 200) {
        _emit('error', new Event('error', {status: res.statusCode}))
        return self.close()
      }
 
      readyState = EventSource.OPEN
      res.on('close', function () {
        res.removeAllListeners('close')
        res.removeAllListeners('end')
        onConnectionClosed()
      })
 
      res.on('end', function () {
        res.removeAllListeners('close')
        res.removeAllListeners('end')
        onConnectionClosed()
      })
      _emit('open', new Event('open'))
 
      // text/event-stream parser adapted from webkit's
      // Source/WebCore/page/EventSource.cpp
      var buf = ''
      res.on('data', function (chunk) {
        buf += chunk
 
        var pos = 0
        var length = buf.length
 
        while (pos < length) {
          if (discardTrailingNewline) {
            if (buf[pos] === '\n') {
              ++pos
            }
            discardTrailingNewline = false
          }
 
          var lineLength = -1
          var fieldLength = -1
          var c
 
          for (var i = pos; lineLength < 0 && i < length; ++i) {
            c = buf[i]
            if (c === ':') {
              Eif (fieldLength < 0) {
                fieldLength = i - pos
              }
            } else if (c === '\r') {
              discardTrailingNewline = true
              lineLength = i - pos
            } else if (c === '\n') {
              lineLength = i - pos
            }
          }
 
          if (lineLength < 0) {
            break
          }
 
          parseEventStreamLine(buf, pos, fieldLength, lineLength)
 
          pos += lineLength + 1
        }
 
        if (pos === length) {
          buf = ''
        } else Iif (pos > 0) {
          buf = buf.slice(pos)
        }
      })
    })
 
    req.on('error', onConnectionClosed)
    Eif (req.setNoDelay) req.setNoDelay(true)
    req.end()
  }
 
  connect()
 
  function _emit () {
    if (self.listeners(arguments[0]).length > 0) {
      self.emit.apply(self, arguments)
    }
  }
 
  this._close = function () {
    Iif (readyState === EventSource.CLOSED) return
    readyState = EventSource.CLOSED
    Eif (req.abort) req.abort()
    Iif (req.xhr && req.xhr.abort) req.xhr.abort()
  }
 
  function parseEventStreamLine (buf, pos, fieldLength, lineLength) {
    if (lineLength === 0) {
      if (data.length > 0) {
        var type = eventName || 'message'
        _emit(type, new MessageEvent(type, {
          data: data.slice(0, -1), // remove trailing newline
          lastEventId: lastEventId,
          origin: original(url)
        }))
        data = ''
      }
      eventName = void 0
    } else if (fieldLength > 0) {
      var noValue = fieldLength < 0
      var step = 0
      var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength))
 
      Iif (noValue) {
        step = lineLength
      } else if (buf[pos + fieldLength + 1] !== ' ') {
        step = fieldLength + 1
      } else {
        step = fieldLength + 2
      }
      pos += step
 
      var valueLength = lineLength - step
      var value = buf.slice(pos, pos + valueLength)
 
      if (field === 'data') {
        data += value + '\n'
      } else if (field === 'event') {
        eventName = value
      } else Eif (field === 'id') {
        lastEventId = value
      } else if (field === 'retry') {
        var retry = parseInt(value, 10)
        if (!Number.isNaN(retry)) {
          self.reconnectInterval = retry
        }
      }
    }
  }
}
 
module.exports = EventSource
 
util.inherits(EventSource, events.EventEmitter)
EventSource.prototype.constructor = EventSource; // make stacktraces readable
 
['open', 'error', 'message'].forEach(function (method) {
  Object.defineProperty(EventSource.prototype, 'on' + method, {
    /**
     * Returns the current listener
     *
     * @return {Mixed} the set function or undefined
     * @api private
     */
    get: function get () {
      var listener = this.listeners(method)[0]
      return listener ? (listener._listener ? listener._listener : listener) : undefined
    },
 
    /**
     * Start listening for events
     *
     * @param {Function} listener the listener
     * @return {Mixed} the set function or undefined
     * @api private
     */
    set: function set (listener) {
      this.removeAllListeners(method)
      this.addEventListener(method, listener)
    }
  })
})
 
/**
 * Ready states
 */
Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0})
Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1})
Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2})
 
EventSource.prototype.CONNECTING = 0
EventSource.prototype.OPEN = 1
EventSource.prototype.CLOSED = 2
 
/**
 * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed)
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close
 * @api public
 */
EventSource.prototype.close = function () {
  this._close()
}
 
/**
 * Emulates the W3C Browser based WebSocket interface using addEventListener.
 *
 * @param {String} type A string representing the event type to listen out for
 * @param {Function} listener callback
 * @see https://developer.mozilla.org/en/DOM/element.addEventListener
 * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
 * @api public
 */
EventSource.prototype.addEventListener = function addEventListener (type, listener) {
  if (typeof listener === 'function') {
    // store a reference so we can return the original function again
    listener._listener = listener
    this.on(type, listener)
  }
}
 
/**
 * Emulates the W3C Browser based WebSocket interface using removeEventListener.
 *
 * @param {String} type A string representing the event type to remove
 * @param {Function} listener callback
 * @see https://developer.mozilla.org/en/DOM/element.removeEventListener
 * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
 * @api public
 */
EventSource.prototype.removeEventListener = function removeEventListener (type, listener) {
  Eif (typeof listener === 'function') {
    listener._listener = undefined
    this.removeListener(type, listener)
  }
}
 
/**
 * W3C Event
 *
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
 * @api private
 */
function Event (type, optionalProperties) {
  Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })
  if (optionalProperties) {
    for (var f in optionalProperties) {
      Eif (optionalProperties.hasOwnProperty(f)) {
        Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true })
      }
    }
  }
}
 
/**
 * W3C MessageEvent
 *
 * @see http://www.w3.org/TR/webmessaging/#event-definitions
 * @api private
 */
function MessageEvent (type, eventInitDict) {
  Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })
  for (var f in eventInitDict) {
    Eif (eventInitDict.hasOwnProperty(f)) {
      Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true })
    }
  }
}