deprecate.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict'
  2. let deprecationHandler = null
  3. function warnOnce (oldName, newName) {
  4. let warned = false
  5. const msg = newName
  6. ? `'${oldName}' is deprecated and will be removed. Please use '${newName}' instead.`
  7. : `'${oldName}' is deprecated and will be removed.`
  8. return () => {
  9. if (!warned && !process.noDeprecation) {
  10. warned = true
  11. deprecate.log(msg)
  12. }
  13. }
  14. }
  15. const deprecate = {
  16. setHandler: (handler) => { deprecationHandler = handler },
  17. getHandler: () => deprecationHandler,
  18. warn: (oldName, newName) => {
  19. return deprecate.log(`'${oldName}' is deprecated. Use '${newName}' instead.`)
  20. },
  21. log: (message) => {
  22. if (typeof deprecationHandler === 'function') {
  23. deprecationHandler(message)
  24. } else if (process.throwDeprecation) {
  25. throw new Error(message)
  26. } else if (process.traceDeprecation) {
  27. return console.trace(message)
  28. } else {
  29. return console.warn(`(electron) ${message}`)
  30. }
  31. },
  32. event: (emitter, oldName, newName) => {
  33. const warn = newName.startsWith('-') /* internal event */
  34. ? warnOnce(`${oldName} event`)
  35. : warnOnce(`${oldName} event`, `${newName} event`)
  36. return emitter.on(newName, function (...args) {
  37. if (this.listenerCount(oldName) !== 0) {
  38. warn()
  39. this.emit(oldName, ...args)
  40. }
  41. })
  42. },
  43. removeProperty: (o, removedName) => {
  44. // if the property's already been removed, warn about it
  45. if (!(removedName in o)) {
  46. deprecate.log(`Unable to remove property '${removedName}' from an object that lacks it.`)
  47. }
  48. // wrap the deprecated property in an accessor to warn
  49. const warn = warnOnce(removedName)
  50. let val = o[removedName]
  51. return Object.defineProperty(o, removedName, {
  52. configurable: true,
  53. get: () => {
  54. warn()
  55. return val
  56. },
  57. set: newVal => {
  58. warn()
  59. val = newVal
  60. }
  61. })
  62. },
  63. renameProperty: (o, oldName, newName) => {
  64. const warn = warnOnce(oldName, newName)
  65. // if the new property isn't there yet,
  66. // inject it and warn about it
  67. if ((oldName in o) && !(newName in o)) {
  68. warn()
  69. o[newName] = o[oldName]
  70. }
  71. // wrap the deprecated property in an accessor to warn
  72. // and redirect to the new property
  73. return Object.defineProperty(o, oldName, {
  74. get: () => {
  75. warn()
  76. return o[newName]
  77. },
  78. set: value => {
  79. warn()
  80. o[newName] = value
  81. }
  82. })
  83. }
  84. }
  85. module.exports = deprecate