index.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict";
  2. import * as esprima from 'esprima';
  3. import * as escodegen from 'escodegen';
  4. import { IProgramNode } from './src/interfaces/nodes/IProgramNode';
  5. import { Obfuscator } from './src/Obfuscator';
  6. export class JavaScriptObfuscator {
  7. /**
  8. * @type any
  9. */
  10. private static defaultOptions: any = {
  11. compact: true,
  12. debugProtection: false,
  13. debugProtectionInterval: false,
  14. disableConsoleOutput: true,
  15. rotateUnicodeArray: true
  16. };
  17. /**
  18. * @type any
  19. */
  20. private static escodegenParams: any = {
  21. verbatim: 'x-verbatim-property'
  22. };
  23. /**
  24. * @param sourceCode
  25. * @param customOptions
  26. */
  27. public static obfuscate (sourceCode: string, customOptions: any): string {
  28. let astTree: IProgramNode = esprima.parse(sourceCode),
  29. options: any = Object.assign(JavaScriptObfuscator.defaultOptions, customOptions),
  30. obfuscator: Obfuscator = new Obfuscator(options);
  31. obfuscator.obfuscateNode(astTree);
  32. return JavaScriptObfuscator.generateCode(astTree, options);
  33. }
  34. /**
  35. * @param astTree
  36. * @param options
  37. */
  38. private static generateCode (astTree: IProgramNode, options: any): string {
  39. let escodegenParams: any = Object.assign({}, JavaScriptObfuscator.escodegenParams);
  40. if (options.hasOwnProperty('compact')) {
  41. escodegenParams.format = {};
  42. escodegenParams.format.compact = options.compact;
  43. }
  44. return escodegen.generate(astTree, escodegenParams);
  45. }
  46. }