ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

decache.ts 1.9 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Thanks: https://github.com/dwyl/decache
  2. // We reuse this file to also uncache plugin base path
  3. import { Module } from 'module'
  4. import { extname } from 'path'
  5. function decachePlugin (require: NodeRequire, libraryPath: string) {
  6. const moduleName = find(require, libraryPath)
  7. if (!moduleName) return
  8. searchCache(require, moduleName, function (mod) {
  9. delete require.cache[mod.id]
  10. removeCachedPath(mod.path)
  11. })
  12. }
  13. function decacheModule (require: NodeRequire, name: string) {
  14. const moduleName = find(require, name)
  15. if (!moduleName) return
  16. searchCache(require, moduleName, function (mod) {
  17. delete require.cache[mod.id]
  18. removeCachedPath(mod.path)
  19. })
  20. }
  21. // ---------------------------------------------------------------------------
  22. export {
  23. decacheModule,
  24. decachePlugin
  25. }
  26. // ---------------------------------------------------------------------------
  27. function find (require: NodeRequire, moduleName: string) {
  28. try {
  29. return require.resolve(moduleName)
  30. } catch {
  31. return ''
  32. }
  33. }
  34. function searchCache (require: NodeRequire, moduleName: string, callback: (current: NodeModule) => void) {
  35. const resolvedModule = require.resolve(moduleName)
  36. let mod: NodeModule
  37. const visited = {}
  38. if (resolvedModule && ((mod = require.cache[resolvedModule]) !== undefined)) {
  39. // Recursively go over the results
  40. (function run (current) {
  41. visited[current.id] = true
  42. current.children.forEach(function (child) {
  43. if (extname(child.filename) !== '.node' && !visited[child.id]) {
  44. run(child)
  45. }
  46. })
  47. // Call the specified callback providing the
  48. // found module
  49. callback(current)
  50. })(mod)
  51. }
  52. };
  53. function removeCachedPath (pluginPath: string) {
  54. const pathCache = (Module as any)._pathCache as { [ id: string ]: string[] }
  55. Object.keys(pathCache).forEach(function (cacheKey) {
  56. if (cacheKey.includes(pluginPath)) {
  57. delete pathCache[cacheKey]
  58. }
  59. })
  60. }