eventsource.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. var original = require('original')
  2. var parse = require('url').parse
  3. var events = require('events')
  4. var https = require('https')
  5. var http = require('http')
  6. var util = require('util')
  7. var httpsOptions = [
  8. 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers',
  9. 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity'
  10. ]
  11. var bom = [239, 187, 191]
  12. var colon = 58
  13. var space = 32
  14. var lineFeed = 10
  15. var carriageReturn = 13
  16. function hasBom (buf) {
  17. return bom.every(function (charCode, index) {
  18. return buf[index] === charCode
  19. })
  20. }
  21. /**
  22. * Creates a new EventSource object
  23. *
  24. * @param {String} url the URL to which to connect
  25. * @param {Object} [eventSourceInitDict] extra init params. See README for details.
  26. * @api public
  27. **/
  28. function EventSource (url, eventSourceInitDict) {
  29. var readyState = EventSource.CONNECTING
  30. Object.defineProperty(this, 'readyState', {
  31. get: function () {
  32. return readyState
  33. }
  34. })
  35. Object.defineProperty(this, 'url', {
  36. get: function () {
  37. return url
  38. }
  39. })
  40. var self = this
  41. self.reconnectInterval = 1000
  42. self.connectionInProgress = false
  43. function onConnectionClosed (message) {
  44. if (readyState === EventSource.CLOSED) return
  45. readyState = EventSource.CONNECTING
  46. _emit('error', new Event('error', {message: message}))
  47. // The url may have been changed by a temporary
  48. // redirect. If that's the case, revert it now.
  49. if (reconnectUrl) {
  50. url = reconnectUrl
  51. reconnectUrl = null
  52. }
  53. setTimeout(function () {
  54. if (readyState !== EventSource.CONNECTING || self.connectionInProgress) {
  55. return
  56. }
  57. self.connectionInProgress = true
  58. connect()
  59. }, self.reconnectInterval)
  60. }
  61. var req
  62. var lastEventId = ''
  63. if (eventSourceInitDict && eventSourceInitDict.headers && eventSourceInitDict.headers['Last-Event-ID']) {
  64. lastEventId = eventSourceInitDict.headers['Last-Event-ID']
  65. delete eventSourceInitDict.headers['Last-Event-ID']
  66. }
  67. var discardTrailingNewline = false
  68. var data = ''
  69. var eventName = ''
  70. var reconnectUrl = null
  71. function connect () {
  72. var options = parse(url)
  73. var isSecure = options.protocol === 'https:'
  74. options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' }
  75. if (lastEventId) options.headers['Last-Event-ID'] = lastEventId
  76. if (eventSourceInitDict && eventSourceInitDict.headers) {
  77. for (var i in eventSourceInitDict.headers) {
  78. var header = eventSourceInitDict.headers[i]
  79. if (header) {
  80. options.headers[i] = header
  81. }
  82. }
  83. }
  84. // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`,
  85. // but for now exists as a backwards-compatibility layer
  86. options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized)
  87. if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) {
  88. options.createConnection = eventSourceInitDict.createConnection
  89. }
  90. // If specify http proxy, make the request to sent to the proxy server,
  91. // and include the original url in path and Host headers
  92. var useProxy = eventSourceInitDict && eventSourceInitDict.proxy
  93. if (useProxy) {
  94. var proxy = parse(eventSourceInitDict.proxy)
  95. isSecure = proxy.protocol === 'https:'
  96. options.protocol = isSecure ? 'https:' : 'http:'
  97. options.path = url
  98. options.headers.Host = options.host
  99. options.hostname = proxy.hostname
  100. options.host = proxy.host
  101. options.port = proxy.port
  102. }
  103. // If https options are specified, merge them into the request options
  104. if (eventSourceInitDict && eventSourceInitDict.https) {
  105. for (var optName in eventSourceInitDict.https) {
  106. if (httpsOptions.indexOf(optName) === -1) {
  107. continue
  108. }
  109. var option = eventSourceInitDict.https[optName]
  110. if (option !== undefined) {
  111. options[optName] = option
  112. }
  113. }
  114. }
  115. // Pass this on to the XHR
  116. if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) {
  117. options.withCredentials = eventSourceInitDict.withCredentials
  118. }
  119. req = (isSecure ? https : http).request(options, function (res) {
  120. self.connectionInProgress = false
  121. // Handle HTTP errors
  122. if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
  123. _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))
  124. onConnectionClosed()
  125. return
  126. }
  127. // Handle HTTP redirects
  128. if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
  129. if (!res.headers.location) {
  130. // Server sent redirect response without Location header.
  131. _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))
  132. return
  133. }
  134. if (res.statusCode === 307) reconnectUrl = url
  135. url = res.headers.location
  136. process.nextTick(connect)
  137. return
  138. }
  139. if (res.statusCode !== 200) {
  140. _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))
  141. return self.close()
  142. }
  143. readyState = EventSource.OPEN
  144. res.on('close', function () {
  145. res.removeAllListeners('close')
  146. res.removeAllListeners('end')
  147. onConnectionClosed()
  148. })
  149. res.on('end', function () {
  150. res.removeAllListeners('close')
  151. res.removeAllListeners('end')
  152. onConnectionClosed()
  153. })
  154. _emit('open', new Event('open'))
  155. // text/event-stream parser adapted from webkit's
  156. // Source/WebCore/page/EventSource.cpp
  157. var isFirst = true
  158. var buf
  159. var startingPos = 0
  160. var startingFieldLength = -1
  161. res.on('data', function (chunk) {
  162. buf = buf ? Buffer.concat([buf, chunk]) : chunk
  163. if (isFirst && hasBom(buf)) {
  164. buf = buf.slice(bom.length)
  165. }
  166. isFirst = false
  167. var pos = 0
  168. var length = buf.length
  169. while (pos < length) {
  170. if (discardTrailingNewline) {
  171. if (buf[pos] === lineFeed) {
  172. ++pos
  173. }
  174. discardTrailingNewline = false
  175. }
  176. var lineLength = -1
  177. var fieldLength = startingFieldLength
  178. var c
  179. for (var i = startingPos; lineLength < 0 && i < length; ++i) {
  180. c = buf[i]
  181. if (c === colon) {
  182. if (fieldLength < 0) {
  183. fieldLength = i - pos
  184. }
  185. } else if (c === carriageReturn) {
  186. discardTrailingNewline = true
  187. lineLength = i - pos
  188. } else if (c === lineFeed) {
  189. lineLength = i - pos
  190. }
  191. }
  192. if (lineLength < 0) {
  193. startingPos = length - pos
  194. startingFieldLength = fieldLength
  195. break
  196. } else {
  197. startingPos = 0
  198. startingFieldLength = -1
  199. }
  200. parseEventStreamLine(buf, pos, fieldLength, lineLength)
  201. pos += lineLength + 1
  202. }
  203. if (pos === length) {
  204. buf = void 0
  205. } else if (pos > 0) {
  206. buf = buf.slice(pos)
  207. }
  208. })
  209. })
  210. req.on('error', function (err) {
  211. self.connectionInProgress = false
  212. onConnectionClosed(err.message)
  213. })
  214. if (req.setNoDelay) req.setNoDelay(true)
  215. req.end()
  216. }
  217. connect()
  218. function _emit () {
  219. if (self.listeners(arguments[0]).length > 0) {
  220. self.emit.apply(self, arguments)
  221. }
  222. }
  223. this._close = function () {
  224. if (readyState === EventSource.CLOSED) return
  225. readyState = EventSource.CLOSED
  226. if (req.abort) req.abort()
  227. if (req.xhr && req.xhr.abort) req.xhr.abort()
  228. }
  229. function parseEventStreamLine (buf, pos, fieldLength, lineLength) {
  230. if (lineLength === 0) {
  231. if (data.length > 0) {
  232. var type = eventName || 'message'
  233. _emit(type, new MessageEvent(type, {
  234. data: data.slice(0, -1), // remove trailing newline
  235. lastEventId: lastEventId,
  236. origin: original(url)
  237. }))
  238. data = ''
  239. }
  240. eventName = void 0
  241. } else if (fieldLength > 0) {
  242. var noValue = fieldLength < 0
  243. var step = 0
  244. var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString()
  245. if (noValue) {
  246. step = lineLength
  247. } else if (buf[pos + fieldLength + 1] !== space) {
  248. step = fieldLength + 1
  249. } else {
  250. step = fieldLength + 2
  251. }
  252. pos += step
  253. var valueLength = lineLength - step
  254. var value = buf.slice(pos, pos + valueLength).toString()
  255. if (field === 'data') {
  256. data += value + '\n'
  257. } else if (field === 'event') {
  258. eventName = value
  259. } else if (field === 'id') {
  260. lastEventId = value
  261. } else if (field === 'retry') {
  262. var retry = parseInt(value, 10)
  263. if (!Number.isNaN(retry)) {
  264. self.reconnectInterval = retry
  265. }
  266. }
  267. }
  268. }
  269. }
  270. module.exports = EventSource
  271. util.inherits(EventSource, events.EventEmitter)
  272. EventSource.prototype.constructor = EventSource; // make stacktraces readable
  273. ['open', 'error', 'message'].forEach(function (method) {
  274. Object.defineProperty(EventSource.prototype, 'on' + method, {
  275. /**
  276. * Returns the current listener
  277. *
  278. * @return {Mixed} the set function or undefined
  279. * @api private
  280. */
  281. get: function get () {
  282. var listener = this.listeners(method)[0]
  283. return listener ? (listener._listener ? listener._listener : listener) : undefined
  284. },
  285. /**
  286. * Start listening for events
  287. *
  288. * @param {Function} listener the listener
  289. * @return {Mixed} the set function or undefined
  290. * @api private
  291. */
  292. set: function set (listener) {
  293. this.removeAllListeners(method)
  294. this.addEventListener(method, listener)
  295. }
  296. })
  297. })
  298. /**
  299. * Ready states
  300. */
  301. Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0})
  302. Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1})
  303. Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2})
  304. EventSource.prototype.CONNECTING = 0
  305. EventSource.prototype.OPEN = 1
  306. EventSource.prototype.CLOSED = 2
  307. /**
  308. * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed)
  309. *
  310. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close
  311. * @api public
  312. */
  313. EventSource.prototype.close = function () {
  314. this._close()
  315. }
  316. /**
  317. * Emulates the W3C Browser based WebSocket interface using addEventListener.
  318. *
  319. * @param {String} type A string representing the event type to listen out for
  320. * @param {Function} listener callback
  321. * @see https://developer.mozilla.org/en/DOM/element.addEventListener
  322. * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
  323. * @api public
  324. */
  325. EventSource.prototype.addEventListener = function addEventListener (type, listener) {
  326. if (typeof listener === 'function') {
  327. // store a reference so we can return the original function again
  328. listener._listener = listener
  329. this.on(type, listener)
  330. }
  331. }
  332. /**
  333. * Emulates the W3C Browser based WebSocket interface using dispatchEvent.
  334. *
  335. * @param {Event} event An event to be dispatched
  336. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
  337. * @api public
  338. */
  339. EventSource.prototype.dispatchEvent = function dispatchEvent (event) {
  340. if (!event.type) {
  341. throw new Error('UNSPECIFIED_EVENT_TYPE_ERR')
  342. }
  343. // if event is instance of an CustomEvent (or has 'details' property),
  344. // send the detail object as the payload for the event
  345. this.emit(event.type, event.detail)
  346. }
  347. /**
  348. * Emulates the W3C Browser based WebSocket interface using removeEventListener.
  349. *
  350. * @param {String} type A string representing the event type to remove
  351. * @param {Function} listener callback
  352. * @see https://developer.mozilla.org/en/DOM/element.removeEventListener
  353. * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
  354. * @api public
  355. */
  356. EventSource.prototype.removeEventListener = function removeEventListener (type, listener) {
  357. if (typeof listener === 'function') {
  358. listener._listener = undefined
  359. this.removeListener(type, listener)
  360. }
  361. }
  362. /**
  363. * W3C Event
  364. *
  365. * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
  366. * @api private
  367. */
  368. function Event (type, optionalProperties) {
  369. Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })
  370. if (optionalProperties) {
  371. for (var f in optionalProperties) {
  372. if (optionalProperties.hasOwnProperty(f)) {
  373. Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true })
  374. }
  375. }
  376. }
  377. }
  378. /**
  379. * W3C MessageEvent
  380. *
  381. * @see http://www.w3.org/TR/webmessaging/#event-definitions
  382. * @api private
  383. */
  384. function MessageEvent (type, eventInitDict) {
  385. Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })
  386. for (var f in eventInitDict) {
  387. if (eventInitDict.hasOwnProperty(f)) {
  388. Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true })
  389. }
  390. }
  391. }