eventsource.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. 'use strict'
  2. const { pipeline } = require('node:stream')
  3. const { fetching } = require('../fetch')
  4. const { makeRequest } = require('../fetch/request')
  5. const { webidl } = require('../webidl')
  6. const { EventSourceStream } = require('./eventsource-stream')
  7. const { parseMIMEType } = require('../fetch/data-url')
  8. const { createFastMessageEvent } = require('../websocket/events')
  9. const { isNetworkError } = require('../fetch/response')
  10. const { kEnumerableProperty } = require('../../core/util')
  11. const { environmentSettingsObject } = require('../fetch/util')
  12. let experimentalWarned = false
  13. /**
  14. * A reconnection time, in milliseconds. This must initially be an implementation-defined value,
  15. * probably in the region of a few seconds.
  16. *
  17. * In Comparison:
  18. * - Chrome uses 3000ms.
  19. * - Deno uses 5000ms.
  20. *
  21. * @type {3000}
  22. */
  23. const defaultReconnectionTime = 3000
  24. /**
  25. * The readyState attribute represents the state of the connection.
  26. * @typedef ReadyState
  27. * @type {0|1|2}
  28. * @readonly
  29. * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev
  30. */
  31. /**
  32. * The connection has not yet been established, or it was closed and the user
  33. * agent is reconnecting.
  34. * @type {0}
  35. */
  36. const CONNECTING = 0
  37. /**
  38. * The user agent has an open connection and is dispatching events as it
  39. * receives them.
  40. * @type {1}
  41. */
  42. const OPEN = 1
  43. /**
  44. * The connection is not open, and the user agent is not trying to reconnect.
  45. * @type {2}
  46. */
  47. const CLOSED = 2
  48. /**
  49. * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin".
  50. * @type {'anonymous'}
  51. */
  52. const ANONYMOUS = 'anonymous'
  53. /**
  54. * Requests for the element will have their mode set to "cors" and their credentials mode set to "include".
  55. * @type {'use-credentials'}
  56. */
  57. const USE_CREDENTIALS = 'use-credentials'
  58. /**
  59. * The EventSource interface is used to receive server-sent events. It
  60. * connects to a server over HTTP and receives events in text/event-stream
  61. * format without closing the connection.
  62. * @extends {EventTarget}
  63. * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
  64. * @api public
  65. */
  66. class EventSource extends EventTarget {
  67. #events = {
  68. open: null,
  69. error: null,
  70. message: null
  71. }
  72. #url
  73. #withCredentials = false
  74. /**
  75. * @type {ReadyState}
  76. */
  77. #readyState = CONNECTING
  78. #request = null
  79. #controller = null
  80. #dispatcher
  81. /**
  82. * @type {import('./eventsource-stream').eventSourceSettings}
  83. */
  84. #state
  85. /**
  86. * Creates a new EventSource object.
  87. * @param {string} url
  88. * @param {EventSourceInit} [eventSourceInitDict={}]
  89. * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
  90. */
  91. constructor (url, eventSourceInitDict = {}) {
  92. // 1. Let ev be a new EventSource object.
  93. super()
  94. webidl.util.markAsUncloneable(this)
  95. const prefix = 'EventSource constructor'
  96. webidl.argumentLengthCheck(arguments, 1, prefix)
  97. if (!experimentalWarned) {
  98. experimentalWarned = true
  99. process.emitWarning('EventSource is experimental, expect them to change at any time.', {
  100. code: 'UNDICI-ES'
  101. })
  102. }
  103. url = webidl.converters.USVString(url)
  104. eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict')
  105. this.#dispatcher = eventSourceInitDict.node.dispatcher || eventSourceInitDict.dispatcher
  106. this.#state = {
  107. lastEventId: '',
  108. reconnectionTime: eventSourceInitDict.node.reconnectionTime
  109. }
  110. // 2. Let settings be ev's relevant settings object.
  111. // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
  112. const settings = environmentSettingsObject
  113. let urlRecord
  114. try {
  115. // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings.
  116. urlRecord = new URL(url, settings.settingsObject.baseUrl)
  117. this.#state.origin = urlRecord.origin
  118. } catch (e) {
  119. // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException.
  120. throw new DOMException(e, 'SyntaxError')
  121. }
  122. // 5. Set ev's url to urlRecord.
  123. this.#url = urlRecord.href
  124. // 6. Let corsAttributeState be Anonymous.
  125. let corsAttributeState = ANONYMOUS
  126. // 7. If the value of eventSourceInitDict's withCredentials member is true,
  127. // then set corsAttributeState to Use Credentials and set ev's
  128. // withCredentials attribute to true.
  129. if (eventSourceInitDict.withCredentials === true) {
  130. corsAttributeState = USE_CREDENTIALS
  131. this.#withCredentials = true
  132. }
  133. // 8. Let request be the result of creating a potential-CORS request given
  134. // urlRecord, the empty string, and corsAttributeState.
  135. const initRequest = {
  136. redirect: 'follow',
  137. keepalive: true,
  138. // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
  139. mode: 'cors',
  140. credentials: corsAttributeState === 'anonymous'
  141. ? 'same-origin'
  142. : 'omit',
  143. referrer: 'no-referrer'
  144. }
  145. // 9. Set request's client to settings.
  146. initRequest.client = environmentSettingsObject.settingsObject
  147. // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list.
  148. initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]]
  149. // 11. Set request's cache mode to "no-store".
  150. initRequest.cache = 'no-store'
  151. // 12. Set request's initiator type to "other".
  152. initRequest.initiator = 'other'
  153. initRequest.urlList = [new URL(this.#url)]
  154. // 13. Set ev's request to request.
  155. this.#request = makeRequest(initRequest)
  156. this.#connect()
  157. }
  158. /**
  159. * Returns the state of this EventSource object's connection. It can have the
  160. * values described below.
  161. * @returns {ReadyState}
  162. * @readonly
  163. */
  164. get readyState () {
  165. return this.#readyState
  166. }
  167. /**
  168. * Returns the URL providing the event stream.
  169. * @readonly
  170. * @returns {string}
  171. */
  172. get url () {
  173. return this.#url
  174. }
  175. /**
  176. * Returns a boolean indicating whether the EventSource object was
  177. * instantiated with CORS credentials set (true), or not (false, the default).
  178. */
  179. get withCredentials () {
  180. return this.#withCredentials
  181. }
  182. #connect () {
  183. if (this.#readyState === CLOSED) return
  184. this.#readyState = CONNECTING
  185. const fetchParams = {
  186. request: this.#request,
  187. dispatcher: this.#dispatcher
  188. }
  189. // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection.
  190. const processEventSourceEndOfBody = (response) => {
  191. if (!isNetworkError(response)) {
  192. return this.#reconnect()
  193. }
  194. }
  195. // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody...
  196. fetchParams.processResponseEndOfBody = processEventSourceEndOfBody
  197. // and processResponse set to the following steps given response res:
  198. fetchParams.processResponse = (response) => {
  199. // 1. If res is an aborted network error, then fail the connection.
  200. if (isNetworkError(response)) {
  201. // 1. When a user agent is to fail the connection, the user agent
  202. // must queue a task which, if the readyState attribute is set to a
  203. // value other than CLOSED, sets the readyState attribute to CLOSED
  204. // and fires an event named error at the EventSource object. Once the
  205. // user agent has failed the connection, it does not attempt to
  206. // reconnect.
  207. if (response.aborted) {
  208. this.close()
  209. this.dispatchEvent(new Event('error'))
  210. return
  211. // 2. Otherwise, if res is a network error, then reestablish the
  212. // connection, unless the user agent knows that to be futile, in
  213. // which case the user agent may fail the connection.
  214. } else {
  215. this.#reconnect()
  216. return
  217. }
  218. }
  219. // 3. Otherwise, if res's status is not 200, or if res's `Content-Type`
  220. // is not `text/event-stream`, then fail the connection.
  221. const contentType = response.headersList.get('content-type', true)
  222. const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure'
  223. const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream'
  224. if (
  225. response.status !== 200 ||
  226. contentTypeValid === false
  227. ) {
  228. this.close()
  229. this.dispatchEvent(new Event('error'))
  230. return
  231. }
  232. // 4. Otherwise, announce the connection and interpret res's body
  233. // line by line.
  234. // When a user agent is to announce the connection, the user agent
  235. // must queue a task which, if the readyState attribute is set to a
  236. // value other than CLOSED, sets the readyState attribute to OPEN
  237. // and fires an event named open at the EventSource object.
  238. // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
  239. this.#readyState = OPEN
  240. this.dispatchEvent(new Event('open'))
  241. // If redirected to a different origin, set the origin to the new origin.
  242. this.#state.origin = response.urlList[response.urlList.length - 1].origin
  243. const eventSourceStream = new EventSourceStream({
  244. eventSourceSettings: this.#state,
  245. push: (event) => {
  246. this.dispatchEvent(createFastMessageEvent(
  247. event.type,
  248. event.options
  249. ))
  250. }
  251. })
  252. pipeline(response.body.stream,
  253. eventSourceStream,
  254. (error) => {
  255. if (
  256. error?.aborted === false
  257. ) {
  258. this.close()
  259. this.dispatchEvent(new Event('error'))
  260. }
  261. })
  262. }
  263. this.#controller = fetching(fetchParams)
  264. }
  265. /**
  266. * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
  267. * @returns {void}
  268. */
  269. #reconnect () {
  270. // When a user agent is to reestablish the connection, the user agent must
  271. // run the following steps. These steps are run in parallel, not as part of
  272. // a task. (The tasks that it queues, of course, are run like normal tasks
  273. // and not themselves in parallel.)
  274. // 1. Queue a task to run the following steps:
  275. // 1. If the readyState attribute is set to CLOSED, abort the task.
  276. if (this.#readyState === CLOSED) return
  277. // 2. Set the readyState attribute to CONNECTING.
  278. this.#readyState = CONNECTING
  279. // 3. Fire an event named error at the EventSource object.
  280. this.dispatchEvent(new Event('error'))
  281. // 2. Wait a delay equal to the reconnection time of the event source.
  282. setTimeout(() => {
  283. // 5. Queue a task to run the following steps:
  284. // 1. If the EventSource object's readyState attribute is not set to
  285. // CONNECTING, then return.
  286. if (this.#readyState !== CONNECTING) return
  287. // 2. Let request be the EventSource object's request.
  288. // 3. If the EventSource object's last event ID string is not the empty
  289. // string, then:
  290. // 1. Let lastEventIDValue be the EventSource object's last event ID
  291. // string, encoded as UTF-8.
  292. // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header
  293. // list.
  294. if (this.#state.lastEventId.length) {
  295. this.#request.headersList.set('last-event-id', this.#state.lastEventId, true)
  296. }
  297. // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.
  298. this.#connect()
  299. }, this.#state.reconnectionTime)?.unref()
  300. }
  301. /**
  302. * Closes the connection, if any, and sets the readyState attribute to
  303. * CLOSED.
  304. */
  305. close () {
  306. webidl.brandCheck(this, EventSource)
  307. if (this.#readyState === CLOSED) return
  308. this.#readyState = CLOSED
  309. this.#controller.abort()
  310. this.#request = null
  311. }
  312. get onopen () {
  313. return this.#events.open
  314. }
  315. set onopen (fn) {
  316. if (this.#events.open) {
  317. this.removeEventListener('open', this.#events.open)
  318. }
  319. const listener = webidl.converters.EventHandlerNonNull(fn)
  320. if (listener !== null) {
  321. this.addEventListener('open', listener)
  322. this.#events.open = fn
  323. } else {
  324. this.#events.open = null
  325. }
  326. }
  327. get onmessage () {
  328. return this.#events.message
  329. }
  330. set onmessage (fn) {
  331. if (this.#events.message) {
  332. this.removeEventListener('message', this.#events.message)
  333. }
  334. const listener = webidl.converters.EventHandlerNonNull(fn)
  335. if (listener !== null) {
  336. this.addEventListener('message', listener)
  337. this.#events.message = fn
  338. } else {
  339. this.#events.message = null
  340. }
  341. }
  342. get onerror () {
  343. return this.#events.error
  344. }
  345. set onerror (fn) {
  346. if (this.#events.error) {
  347. this.removeEventListener('error', this.#events.error)
  348. }
  349. const listener = webidl.converters.EventHandlerNonNull(fn)
  350. if (listener !== null) {
  351. this.addEventListener('error', listener)
  352. this.#events.error = fn
  353. } else {
  354. this.#events.error = null
  355. }
  356. }
  357. }
  358. const constantsPropertyDescriptors = {
  359. CONNECTING: {
  360. __proto__: null,
  361. configurable: false,
  362. enumerable: true,
  363. value: CONNECTING,
  364. writable: false
  365. },
  366. OPEN: {
  367. __proto__: null,
  368. configurable: false,
  369. enumerable: true,
  370. value: OPEN,
  371. writable: false
  372. },
  373. CLOSED: {
  374. __proto__: null,
  375. configurable: false,
  376. enumerable: true,
  377. value: CLOSED,
  378. writable: false
  379. }
  380. }
  381. Object.defineProperties(EventSource, constantsPropertyDescriptors)
  382. Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors)
  383. Object.defineProperties(EventSource.prototype, {
  384. close: kEnumerableProperty,
  385. onerror: kEnumerableProperty,
  386. onmessage: kEnumerableProperty,
  387. onopen: kEnumerableProperty,
  388. readyState: kEnumerableProperty,
  389. url: kEnumerableProperty,
  390. withCredentials: kEnumerableProperty
  391. })
  392. webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([
  393. {
  394. key: 'withCredentials',
  395. converter: webidl.converters.boolean,
  396. defaultValue: () => false
  397. },
  398. {
  399. key: 'dispatcher', // undici only
  400. converter: webidl.converters.any
  401. },
  402. {
  403. key: 'node', // undici only
  404. converter: webidl.dictionaryConverter([
  405. {
  406. key: 'reconnectionTime',
  407. converter: webidl.converters['unsigned long'],
  408. defaultValue: () => defaultReconnectionTime
  409. },
  410. {
  411. key: 'dispatcher',
  412. converter: webidl.converters.any
  413. }
  414. ]),
  415. defaultValue: () => ({})
  416. }
  417. ])
  418. module.exports = {
  419. EventSource,
  420. defaultReconnectionTime
  421. }