JavaScriptObfuscatorMemory.spec.ts 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { assert } from 'chai';
  2. import { readFileAsString } from '../helpers/readFileAsString';
  3. import { JavaScriptObfuscator } from '../../src/JavaScriptObfuscatorFacade';
  4. const heapValueToMB = (value: number) => Math.round(value / 1024 / 1024 * 100) / 100;
  5. describe('JavaScriptObfuscator memory', function () {
  6. const iterationsCount: number = 500;
  7. const gcDiffThreshold: number = 10;
  8. const allowedHeapDiffThreshold: number = 40;
  9. this.timeout(100000);
  10. describe('memory: heap usage', () => {
  11. it('should keep heap usage without memory leaks', () => {
  12. const sourceCode: string = readFileAsString('./test/fixtures/sample.js');
  13. const maxHeapUsed: number[] = [];
  14. let prevHeapUsed: number | null = null;
  15. for (let i: number = 0; i < iterationsCount; i++) {
  16. JavaScriptObfuscator.obfuscate(
  17. sourceCode,
  18. {
  19. compact: true,
  20. controlFlowFlattening: true,
  21. controlFlowFlatteningThreshold: 0.75,
  22. deadCodeInjection: true,
  23. deadCodeInjectionThreshold: 0.4,
  24. debugProtection: false,
  25. debugProtectionInterval: false,
  26. disableConsoleOutput: true,
  27. identifierNamesGenerator: 'mangled',
  28. log: false,
  29. renameGlobals: false,
  30. rotateStringArray: true,
  31. selfDefending: true,
  32. shuffleStringArray: true,
  33. splitStrings: true,
  34. splitStringsChunkLength: 2,
  35. stringArray: true,
  36. stringArrayEncoding: 'base64',
  37. stringArrayThreshold: 0.75,
  38. transformObjectKeys: true,
  39. unicodeEscapeSequence: false
  40. }
  41. );
  42. const heap = process.memoryUsage();
  43. const heapUsed: number = heapValueToMB(heap.heapUsed);
  44. const gcDiff: number = (prevHeapUsed ?? heapUsed) - heapUsed;
  45. if (prevHeapUsed && gcDiff > gcDiffThreshold) {
  46. maxHeapUsed.push(prevHeapUsed);
  47. }
  48. prevHeapUsed = heapUsed;
  49. }
  50. const sortedMaxHeapUsed: number[] = [...maxHeapUsed].sort((a: number, b: number) => a - b);
  51. const firstMaxHeapMBUsed: number = sortedMaxHeapUsed[0];
  52. const lastMaxHeapMbUsed: number = sortedMaxHeapUsed[sortedMaxHeapUsed.length - 1];
  53. const diff: number = lastMaxHeapMbUsed - firstMaxHeapMBUsed;
  54. assert.closeTo(diff, 0, allowedHeapDiffThreshold);
  55. });
  56. });
  57. });