All files / src SourceMapCorrector.ts

100% Statements 22/22
100% Branches 11/11
100% Functions 1/1
100% Lines 22/22
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99        1x   1x 1x   1x                                                             14x 14x   14x 14x             14x                   14x 10x     4x       1x   1x       3x 1x   1x     2x     2x             14x 1x     13x      
import { IObfuscationResult } from "./interfaces/IObfuscationResult";
 
import { TSourceMapMode } from "./types/TSourceMapMode";
 
import { SourceMapMode } from "./enums/SourceMapMode";
 
import { ObfuscationResult } from "./ObfuscationResult";
import { Utils } from "./Utils";
 
export class SourceMapCorrector {
    /**
     * @type {string}
     */
    private obfuscatedCode: string;
 
    /**
     * @type {string}
     */
    private sourceMap: string;
 
    /**
     * @type {TSourceMapMode}
     */
    private sourceMapMode: TSourceMapMode;
 
    /**
     * @type {string}
     */
    private sourceMapUrl: string;
 
    /**
     * @param obfuscationResult
     * @param sourceMapUrl
     * @param sourceMapMode
     */
    constructor (
        obfuscationResult: IObfuscationResult,
        sourceMapUrl: string,
        sourceMapMode: TSourceMapMode
    ) {
        this.obfuscatedCode = obfuscationResult.getObfuscatedCode();
        this.sourceMap = obfuscationResult.getSourceMap();
 
        this.sourceMapUrl = sourceMapUrl;
        this.sourceMapMode = sourceMapMode;
    }
 
    /**
     * @returns {ObfuscationResult}
     */
    public correct (): IObfuscationResult {
        return new ObfuscationResult(
            this.correctObfuscatedCode(),
            this.correctSourceMap()
        );
    }
 
    /**
     * @returns {string}
     */
    private correctObfuscatedCode (): string {
        if (!this.sourceMap) {
            return this.obfuscatedCode;
        }
 
        let sourceMappingUrl: string = '//# sourceMappingURL=';
 
        switch (this.sourceMapMode) {
            case SourceMapMode.Inline:
                sourceMappingUrl += `data:application/json;base64,${Utils.btoa(this.sourceMapUrl || this.sourceMap, false)}`;
 
                break;
 
            case SourceMapMode.Separate:
            default:
                if (this.sourceMapUrl) {
                    sourceMappingUrl += this.sourceMapUrl;
 
                    break;
                }
 
                return this.obfuscatedCode;
        }
 
        return `${this.obfuscatedCode}\n${sourceMappingUrl}`;
    };
 
    /**
     * @returns {string}
     */
    private correctSourceMap (): string {
        if (this.sourceMapMode === SourceMapMode.Inline) {
            return '';
        }
 
        return this.sourceMap;
    }
}