dispatcher-weakref.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict'
  2. const { kConnected, kSize } = require('../../core/symbols')
  3. class CompatWeakRef {
  4. constructor (value) {
  5. this.value = value
  6. }
  7. deref () {
  8. return this.value[kConnected] === 0 && this.value[kSize] === 0
  9. ? undefined
  10. : this.value
  11. }
  12. }
  13. class CompatFinalizer {
  14. constructor (finalizer) {
  15. this.finalizer = finalizer
  16. }
  17. register (dispatcher, key) {
  18. if (dispatcher.on) {
  19. dispatcher.on('disconnect', () => {
  20. if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
  21. this.finalizer(key)
  22. }
  23. })
  24. }
  25. }
  26. unregister (key) {}
  27. }
  28. module.exports = function () {
  29. // FIXME: remove workaround when the Node bug is backported to v18
  30. // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
  31. if (process.env.NODE_V8_COVERAGE && process.version.startsWith('v18')) {
  32. process._rawDebug('Using compatibility WeakRef and FinalizationRegistry')
  33. return {
  34. WeakRef: CompatWeakRef,
  35. FinalizationRegistry: CompatFinalizer
  36. }
  37. }
  38. return { WeakRef, FinalizationRegistry }
  39. }