IdentifierReplacer.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { injectable, inject } from 'inversify';
  2. import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers';
  3. import { IObfuscatorReplacerWithStorage } from '../../../interfaces/node-transformers/IObfuscatorReplacerWithStorage';
  4. import { IOptions } from '../../../interfaces/options/IOptions';
  5. import { AbstractReplacer } from './AbstractReplacer';
  6. import { RandomGeneratorUtils } from '../../../utils/RandomGeneratorUtils';
  7. @injectable()
  8. export class IdentifierReplacer extends AbstractReplacer implements IObfuscatorReplacerWithStorage {
  9. /**
  10. * @type {Map<string, string>}
  11. */
  12. private readonly namesMap: Map<string, string> = new Map();
  13. /**
  14. * @param options
  15. */
  16. constructor (
  17. @inject(ServiceIdentifiers.IOptions) options: IOptions
  18. ) {
  19. super(options);
  20. }
  21. /**
  22. * @param nodeValue
  23. * @param nodeIdentifier
  24. * @returns {string}
  25. */
  26. public replace (nodeValue: string, nodeIdentifier: string): string {
  27. const mapKey: string = `${nodeValue}-${nodeIdentifier}`;
  28. if (!this.namesMap.has(mapKey)) {
  29. return nodeValue;
  30. }
  31. return <string>this.namesMap.get(mapKey);
  32. }
  33. /**
  34. * Store all identifiers names as keys in given `namesMap` with random names as value.
  35. * Reserved names will be ignored.
  36. *
  37. * @param nodeName
  38. * @param nodeIdentifier
  39. */
  40. public storeNames (nodeName: string, nodeIdentifier: string): void {
  41. if (!this.isReservedName(nodeName)) {
  42. this.namesMap.set(`${nodeName}-${nodeIdentifier}`, RandomGeneratorUtils.getRandomVariableName());
  43. }
  44. }
  45. /**
  46. * @param name
  47. * @returns {boolean}
  48. */
  49. private isReservedName (name: string): boolean {
  50. return this.options.reservedNames
  51. .some((reservedName: string) => {
  52. return new RegExp(reservedName, 'g').test(name);
  53. });
  54. }
  55. }