All files / src/node-transformers/node-obfuscators/replacers IdentifierReplacer.ts

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