# 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

    4623x

    4623x

    680870x

    680870x
    602575x

    78295x

    27041x
    27041x

    27041x

     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: string): string {
            const obfuscatedIdentifierName: string|undefined = this.namesMap.get(`${nodeValue}-${nodeIdentifier}`);

            if (!obfuscatedIdentifierName) {
                return nodeValue;
            }

            return obfuscatedIdentifierName;
        }

        /**
         * Store all identifiers names as keys in given `namesMap` with random names as value.
         * Reserved names will be ignored.
         *
         * @param nodeName
         * @param nodeIdentifier
         */
        public storeNames (nodeName: string, nodeIdentifier: string): void {
            Eif (!this.isReservedName(nodeName)) {
                this.namesMap.set(`${nodeName}-${nodeIdentifier}`, RandomGeneratorUtils.getRandomVariableName());
            }
        }

        /**
         * @param name
         * @returns {boolean}
         */
        private isReservedName (name: string): boolean {
            return this.options.reservedNames
                .some((reservedName: string) => {
                    return new RegExp(reservedName, 'g').test(name);
                });
        }
    }