forked from javascript-obfuscator/webpack-obfuscator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
115 lines (96 loc) · 3.71 KB
/
index.ts
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
"use strict";
import { Compiler } from 'webpack';
const JavaScriptObfuscator = require('javascript-obfuscator');
const RawSource = require("webpack-sources").RawSource;
const SourceMapSource = require("webpack-sources").SourceMapSource;
const multimatch = require('multimatch');
const transferSourceMap = require("multi-stage-sourcemap").transfer;
type TObject = {[key: string]: any};
class WebpackObfuscator {
/**
* @type {TObject}
*/
public options: TObject = {};
/**
* @type {string}
*/
public excludes: string[];
/**
* @param {TObject} options
* @param {string | string[]} excludes
*/
constructor (options: TObject, excludes: string|string[]) {
this.options = options || {};
this.excludes = typeof excludes === 'string' ? [excludes] : excludes || [];
}
/**
* @param {Compiler} compiler
*/
public apply (compiler: Compiler): void {
compiler.plugin('compilation', (compilation: any) => {
compilation.plugin("optimize-chunk-assets", (chunks: any[], callback: () => void) => {
let files = [];
chunks.forEach((chunk) => {
chunk['files'].forEach((file) => {
files.push(file);
});
});
compilation.additionalChunkAssets.forEach((file) => {
files.push(file);
});
files.forEach((file) => {
if (!/\.js($|\?)/i.test(file) || this.shouldExclude(file, this.excludes)) {
return;
}
let asset = compilation.assets[file],
input, inputSourceMap;
if (this.options.sourceMap !== false) {
if (asset.sourceAndMap) {
let sourceAndMap = asset.sourceAndMap();
inputSourceMap = sourceAndMap.map;
input = sourceAndMap.source;
} else {
inputSourceMap = asset.map();
input = asset.source();
}
if (inputSourceMap) {
this.options.sourceMap = true;
}
} else {
input = asset.source();
}
let obfuscationResult: any = JavaScriptObfuscator.obfuscate(
input,
this.options
);
if (this.options.sourceMap) {
let obfuscationSourceMap: any = obfuscationResult.getSourceMap(),
transferredSourceMap: any = transferSourceMap({
fromSourceMap: obfuscationSourceMap,
toSourceMap: inputSourceMap
});
compilation.assets[file] = new SourceMapSource(
obfuscationResult.toString(),
file,
JSON.parse(transferredSourceMap),
asset.source(),
inputSourceMap
);
} else {
compilation.assets[file] = new RawSource(obfuscationResult.toString());
}
});
callback();
});
});
}
/**
* @param filePath
* @param excludes
* @returns {boolean}
*/
private shouldExclude (filePath: string, excludes: string[]): boolean {
return multimatch(filePath, excludes).length > 0
}
}
module.exports = WebpackObfuscator;