This repository has been archived by the owner on Jun 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
90 lines (71 loc) · 2.28 KB
/
index.js
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
'use strict';
function injectDefaultOptions(options) {
options = options || {};
options.prefix = options.prefix || '#{';
options.suffix = options.suffix || '}';
options.configFile = options.configFile || process.cwd() + '/config.json';
options.preserveUnknownTokens = options.preserveUnknownTokens || false;
options.delimiter = options.delimiter || '.';
if (options.configFile) {
try {
options.tokens = require(options.configFile);
} catch (e) { }
}
options.tokens = options.tokens || options.global || {};
return options;
}
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
function getTokenValue(tokens, tokenName, delimiter) {
var tmpTokens = tokens;
if (tokens.hasOwnProperty(tokenName)) {
return tokens[tokenName];
}
var tokenNameParts = tokenName.split(delimiter);
for (var i = 0; i < tokenNameParts.length; i++) {
if (tmpTokens.hasOwnProperty(tokenNameParts[i])) {
tmpTokens = tmpTokens[tokenNameParts[i]];
} else {
return null;
}
}
return tmpTokens;
}
function replace(target, options) {
options = injectDefaultOptions(options);
var regexPattern = `${ escapeRegExp(options.prefix) }(.+?)${ escapeRegExp(options.suffix)}`;
var includeRegExp = new RegExp(regexPattern, 'g');
var isObject = false;
var text;
if (typeof target === 'object') {
text = JSON.stringify(target);
isObject = true;
} else if ( typeof target === 'string') {
text = target;
} else {
text = target.toString();
}
var retVal = text;
var regExpResult;
while (regExpResult = includeRegExp.exec(text)) {
var fullMatch = regExpResult[0];
var tokenName = regExpResult[1];
var tokenValue = getTokenValue(options.tokens, tokenName, options.delimiter);
if (tokenValue === null && !options.preserveUnknownTokens) {
tokenValue = '';
}
if (tokenValue !== null) {
if (typeof tokenValue === 'object') {
tokenValue = JSON.stringify(tokenValue);
} else if (typeof tokenValue === 'string') {
if (tokenValue.indexOf('"') > -1) {
tokenValue = tokenValue.replace(/"/g, '\\"');
}
}
retVal = retVal.replace(fullMatch, tokenValue);
}
}
return isObject ? JSON.parse(retVal) : retVal;
}
module.exports = replace;