forked from javascript-obfuscator/javascript-obfuscator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEscapeSequenceEncoder.ts
More file actions
52 lines (41 loc) · 1.6 KB
/
EscapeSequenceEncoder.ts
File metadata and controls
52 lines (41 loc) · 1.6 KB
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
import { injectable } from 'inversify';
import { IEscapeSequenceEncoder } from '../interfaces/utils/IEscapeSequenceEncoder';
@injectable()
export class EscapeSequenceEncoder implements IEscapeSequenceEncoder {
/**
* @type {Map<string, string>}
*/
private readonly stringsCache: Map <string, string> = new Map();
/**
* @param {string} string
* @param {boolean} encodeAllSymbols
* @returns {string}
*/
public encode (string: string, encodeAllSymbols: boolean): string {
const cacheKey: string = `${string}-${String(encodeAllSymbols)}`;
if (this.stringsCache.has(cacheKey)) {
return <string>this.stringsCache.get(cacheKey);
}
const radix: number = 16;
const replaceRegExp: RegExp = new RegExp('[\\s\\S]', 'g');
const escapeSequenceRegExp: RegExp = new RegExp('[\'\"\\\\\\s]');
const regExp: RegExp = new RegExp('[\\x00-\\x7F]');
let prefix: string,
template: string;
const result: string = string.replace(replaceRegExp, (character: string): string => {
if (!encodeAllSymbols && !escapeSequenceRegExp.exec(character)) {
return character;
}
if (regExp.exec(character)) {
prefix = '\\x';
template = '00';
} else {
prefix = '\\u';
template = '0000';
}
return `${prefix}${(template + character.charCodeAt(0).toString(radix)).slice(-template.length)}`;
});
this.stringsCache.set(cacheKey, result);
return result;
}
}