ConditionalCommentNodeGuard.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { injectable } from 'inversify';
  2. import * as ESTree from 'estree';
  3. import { INodeGuard } from '../interfaces/node-guards/INodeGuard';
  4. @injectable()
  5. export class ConditionalCommentNodeGuard implements INodeGuard {
  6. /**
  7. * @type {RegExp}
  8. */
  9. private static readonly obfuscationEnableCommentRegExp: RegExp = new RegExp('javascript-obfuscator *: *enable');
  10. /**
  11. * @type {RegExp}
  12. */
  13. private static readonly obfuscationDisableCommentRegExp: RegExp = new RegExp('javascript-obfuscator *: *disable');
  14. /**
  15. * @type {boolean}
  16. */
  17. private obfuscationEnabledForCurrentNode: boolean = true;
  18. /**
  19. * @type {boolean}
  20. */
  21. private obfuscationEnabledForNextNode: boolean | null = null;
  22. /**
  23. * @returns {boolean}
  24. * @param node
  25. */
  26. public check (node: ESTree.Node): boolean {
  27. if (this.obfuscationEnabledForNextNode) {
  28. this.obfuscationEnabledForCurrentNode = this.obfuscationEnabledForNextNode;
  29. this.obfuscationEnabledForNextNode = null;
  30. }
  31. if (!node.leadingComments && !node.trailingComments) {
  32. return this.obfuscationEnabledForCurrentNode;
  33. }
  34. const leadingComments: ESTree.Comment[] | undefined = node.leadingComments;
  35. const trailingComments: ESTree.Comment[] | undefined = node.trailingComments;
  36. if (leadingComments) {
  37. this.obfuscationEnabledForCurrentNode = this.checkComments(leadingComments);
  38. }
  39. if (trailingComments) {
  40. this.obfuscationEnabledForNextNode = this.checkComments(trailingComments);
  41. }
  42. return this.obfuscationEnabledForCurrentNode;
  43. }
  44. /**
  45. * @param {Comment[]} comments
  46. * @returns {boolean}
  47. */
  48. private checkComments (comments: ESTree.Comment[]): boolean {
  49. const commentsLength: number = comments.length;
  50. let obfuscationEnabled: boolean = this.obfuscationEnabledForCurrentNode;
  51. for (let i: number = 0; i < commentsLength; i++) {
  52. const comment: ESTree.Comment = comments[i];
  53. if (ConditionalCommentNodeGuard.obfuscationEnableCommentRegExp.test(comment.value)) {
  54. obfuscationEnabled = true;
  55. continue;
  56. }
  57. if (ConditionalCommentNodeGuard.obfuscationDisableCommentRegExp.test(comment.value)) {
  58. obfuscationEnabled = false;
  59. }
  60. }
  61. return obfuscationEnabled;
  62. }
  63. }