index.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. const errors = require('./lib/errors')
  2. class EventListener {
  3. constructor () {
  4. this.list = []
  5. this.count = 0
  6. }
  7. append (ctx, name, fn, once) {
  8. this.count++
  9. ctx.emit('newListener', name, fn) // Emit BEFORE adding
  10. this.list.push([fn, once])
  11. }
  12. prepend (ctx, name, fn, once) {
  13. this.count++
  14. ctx.emit('newListener', name, fn) // Emit BEFORE adding
  15. this.list.unshift([fn, once])
  16. }
  17. remove (ctx, name, fn) {
  18. for (let i = 0, n = this.list.length; i < n; i++) {
  19. const l = this.list[i]
  20. if (l[0] === fn) {
  21. this.list.splice(i, 1)
  22. if (this.count === 1) delete ctx._events[name]
  23. ctx.emit('removeListener', name, fn) // Emit AFTER removing
  24. this.count--
  25. return
  26. }
  27. }
  28. }
  29. removeAll (ctx, name) {
  30. const list = [...this.list]
  31. this.list = []
  32. if (this.count === list.length) delete ctx._events[name]
  33. for (let i = list.length - 1; i >= 0; i--) {
  34. ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
  35. }
  36. this.count -= list.length
  37. }
  38. emit (ctx, name, ...args) {
  39. const list = [...this.list]
  40. for (let i = 0, n = list.length; i < n; i++) {
  41. const l = list[i]
  42. if (l[1] === true) this.remove(ctx, name, l[0])
  43. l[0].call(ctx, ...args)
  44. }
  45. return list.length > 0
  46. }
  47. }
  48. function appendListener (ctx, name, fn, once) {
  49. const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  50. e.append(ctx, name, fn, once)
  51. return ctx
  52. }
  53. function prependListener (ctx, name, fn, once) {
  54. const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  55. e.prepend(ctx, name, fn, once)
  56. return ctx
  57. }
  58. function removeListener (ctx, name, fn) {
  59. const e = ctx._events[name]
  60. if (e !== undefined) e.remove(ctx, name, fn)
  61. return ctx
  62. }
  63. function throwUnhandledError (...args) {
  64. let err
  65. if (args.length > 0) err = args[0]
  66. if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)
  67. if (Error.captureStackTrace) {
  68. Error.captureStackTrace(err, exports.prototype.emit)
  69. }
  70. queueMicrotask(() => { throw err })
  71. }
  72. module.exports = exports = class EventEmitter {
  73. constructor () {
  74. this._events = Object.create(null)
  75. }
  76. addListener (name, fn) {
  77. return appendListener(this, name, fn, false)
  78. }
  79. addOnceListener (name, fn) {
  80. return appendListener(this, name, fn, true)
  81. }
  82. prependListener (name, fn) {
  83. return prependListener(this, name, fn, false)
  84. }
  85. prependOnceListener (name, fn) {
  86. return prependListener(this, name, fn, true)
  87. }
  88. removeListener (name, fn) {
  89. return removeListener(this, name, fn)
  90. }
  91. on (name, fn) {
  92. return appendListener(this, name, fn, false)
  93. }
  94. once (name, fn) {
  95. return appendListener(this, name, fn, true)
  96. }
  97. off (name, fn) {
  98. return removeListener(this, name, fn)
  99. }
  100. emit (name, ...args) {
  101. if (name === 'error' && this._events.error === undefined) throwUnhandledError(...args)
  102. const e = this._events[name]
  103. return e === undefined ? false : e.emit(this, name, ...args)
  104. }
  105. listeners (name) {
  106. const e = this._events[name]
  107. return e === undefined ? [] : [...e.list]
  108. }
  109. listenerCount (name) {
  110. const e = this._events[name]
  111. return e === undefined ? 0 : e.list.length
  112. }
  113. getMaxListeners () {
  114. return EventEmitter.defaultMaxListeners
  115. }
  116. setMaxListeners (n) {}
  117. removeAllListeners (name) {
  118. if (arguments.length === 0) {
  119. for (const key of Reflect.ownKeys(this._events)) {
  120. if (key === 'removeListener') continue
  121. this.removeAllListeners(key)
  122. }
  123. this.removeAllListeners('removeListener')
  124. } else {
  125. const e = this._events[name]
  126. if (e !== undefined) e.removeAll(this, name)
  127. }
  128. return this
  129. }
  130. }
  131. exports.EventEmitter = exports
  132. exports.defaultMaxListeners = 10
  133. exports.on = function on (emitter, name, opts = {}) {
  134. const {
  135. signal
  136. } = opts
  137. if (signal && signal.aborted) {
  138. throw errors.OPERATION_ABORTED(signal.reason)
  139. }
  140. let error = null
  141. let done = false
  142. const events = []
  143. const promises = []
  144. emitter.on(name, onevent)
  145. if (name !== 'error') emitter.on('error', onerror)
  146. if (signal) signal.addEventListener('abort', onabort)
  147. return {
  148. next () {
  149. if (events.length) {
  150. return Promise.resolve({ value: events.shift(), done: false })
  151. }
  152. if (error) {
  153. const err = error
  154. error = null
  155. return Promise.reject(err)
  156. }
  157. if (done) return onclose()
  158. return new Promise((resolve, reject) =>
  159. promises.push({ resolve, reject })
  160. )
  161. },
  162. return () {
  163. return onclose()
  164. },
  165. throw (err) {
  166. return onerror(err)
  167. },
  168. [Symbol.asyncIterator] () {
  169. return this
  170. }
  171. }
  172. function onevent (...args) {
  173. if (promises.length) {
  174. promises.shift().resolve({ value: args, done: false })
  175. } else {
  176. events.push(args)
  177. }
  178. }
  179. function onerror (err) {
  180. if (promises.length) {
  181. promises.shift().reject(err)
  182. } else {
  183. error = err
  184. }
  185. return Promise.resolve({ done: true })
  186. }
  187. function onabort () {
  188. onerror(errors.OPERATION_ABORTED(signal.reason))
  189. }
  190. function onclose () {
  191. emitter.off(name, onevent)
  192. if (name !== 'error') emitter.off('error', onerror)
  193. if (signal) signal.removeEventListener('abort', onabort)
  194. done = true
  195. if (promises.length) promises.shift().resolve({ done: true })
  196. return Promise.resolve({ done: true })
  197. }
  198. }
  199. exports.once = function once (emitter, name, opts = {}) {
  200. const {
  201. signal
  202. } = opts
  203. if (signal && signal.aborted) {
  204. throw errors.OPERATION_ABORTED(signal.reason)
  205. }
  206. return new Promise((resolve, reject) => {
  207. if (signal) signal.addEventListener('abort', onabort)
  208. emitter.once(name, (...args) => {
  209. if (signal) signal.removeEventListener('abort', onabort)
  210. resolve(args)
  211. })
  212. function onabort () {
  213. reject(errors.OPERATION_ABORTED(signal.reason))
  214. }
  215. })
  216. }