bootstrap.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. const Path = require('path')
  2. const sinon = require('sinon')
  3. require('./common_bootstrap')
  4. /*
  5. * Global stubs
  6. */
  7. const globalStubsSandbox = sinon.createSandbox()
  8. const globalStubs = {
  9. logger: {
  10. debug: globalStubsSandbox.stub(),
  11. info: globalStubsSandbox.stub(),
  12. log: globalStubsSandbox.stub(),
  13. warn: globalStubsSandbox.stub(),
  14. err: globalStubsSandbox.stub(),
  15. error: globalStubsSandbox.stub(),
  16. fatal: globalStubsSandbox.stub(),
  17. },
  18. }
  19. /*
  20. * Sandboxed module configuration
  21. */
  22. const SandboxedModule = require('sandboxed-module')
  23. SandboxedModule.configure({
  24. ignoreMissing: true,
  25. requires: getSandboxedModuleRequires(),
  26. globals: {
  27. AbortController,
  28. AbortSignal,
  29. Buffer,
  30. Promise,
  31. console,
  32. process,
  33. URL,
  34. TextEncoder,
  35. TextDecoder,
  36. },
  37. sourceTransformers: {
  38. removeNodePrefix: function (source) {
  39. return source.replace(/require\(['"]node:/g, "require('")
  40. },
  41. },
  42. })
  43. function getSandboxedModuleRequires() {
  44. const requires = {
  45. '@overleaf/logger': globalStubs.logger,
  46. }
  47. const internalModules = [
  48. '../../app/src/Features/Errors/Errors',
  49. '../../app/src/Features/Helpers/Mongo',
  50. ]
  51. const externalLibs = [
  52. 'async',
  53. 'bull',
  54. 'json2csv',
  55. 'lodash',
  56. 'marked',
  57. 'moment',
  58. '@overleaf/o-error',
  59. 'sanitize-html',
  60. 'sshpk',
  61. 'xml2js',
  62. 'mongodb',
  63. 'mongodb-legacy',
  64. ]
  65. for (const modulePath of internalModules) {
  66. requires[Path.resolve(__dirname, modulePath)] = require(modulePath)
  67. }
  68. for (const lib of externalLibs) {
  69. requires[lib] = require(lib)
  70. }
  71. return requires
  72. }
  73. /*
  74. * Mocha hooks
  75. */
  76. // sandboxed-module somehow registers every fake module it creates in this
  77. // module's children array, which uses quite a big amount of memory. We'll take
  78. // a copy of the module children array and restore it after each test so that
  79. // the garbage collector has a chance to reclaim the fake modules.
  80. let initialModuleChildren
  81. exports.mochaHooks = {
  82. beforeAll() {
  83. // Record initial module children
  84. initialModuleChildren = module.children.slice()
  85. },
  86. beforeEach() {
  87. // Install logger stub
  88. this.logger = globalStubs.logger
  89. },
  90. afterEach() {
  91. // Delete leaking sandboxed modules
  92. module.children = initialModuleChildren.slice()
  93. // Reset global stubs
  94. globalStubsSandbox.reset()
  95. // Restore other stubs
  96. sinon.restore()
  97. },
  98. }