index.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. private static defaultOptions: any = {
  8. compact: true,
  9. rotateUnicodeArray: true
  10. };
  11. /**
  12. * @type any
  13. */
  14. private static escodegenParams: any = {
  15. verbatim: 'x-verbatim-property'
  16. };
  17. /**
  18. * @param sourceCode
  19. * @param customOptions
  20. */
  21. public static obfuscate (sourceCode: string, customOptions: any): string {
  22. let astTree: IProgramNode = esprima.parse(sourceCode),
  23. options: any = Object.assign(JavaScriptObfuscator.defaultOptions, customOptions),
  24. obfuscator: Obfuscator = new Obfuscator(options);
  25. obfuscator.obfuscateNode(astTree);
  26. return JavaScriptObfuscator.generateCode(astTree, options);
  27. }
  28. /**
  29. * @param astTree
  30. * @param options
  31. */
  32. private static generateCode (astTree: IProgramNode, options: any): string {
  33. let escodegenParams: any = Object.assign({}, JavaScriptObfuscator.escodegenParams);
  34. if (options.hasOwnProperty('compact')) {
  35. escodegenParams.format = {};
  36. escodegenParams.format.compact = options.compact;
  37. }
  38. return escodegen.generate(astTree, escodegenParams);
  39. }
  40. }
  41. module.exports = JavaScriptObfuscator;