1 |
3a515b92
|
cagy
|
'use strict';
|
2 |
|
|
|
3 |
|
|
var jsTokens = require('js-tokens').default;
|
4 |
|
|
|
5 |
|
|
var processEnvRe = /\bprocess\.env\.[_$a-zA-Z][$\w]+\b/;
|
6 |
|
|
var spaceOrCommentRe = /^(?:\s|\/[/*])/;
|
7 |
|
|
|
8 |
|
|
function replace(src, envs) {
|
9 |
|
|
if (!processEnvRe.test(src)) {
|
10 |
|
|
return src;
|
11 |
|
|
}
|
12 |
|
|
|
13 |
|
|
var out = [];
|
14 |
|
|
var purge = envs.some(function(env) {
|
15 |
|
|
return env._ && env._.indexOf('purge') !== -1;
|
16 |
|
|
});
|
17 |
|
|
|
18 |
|
|
jsTokens.lastIndex = 0
|
19 |
|
|
var parts = src.match(jsTokens);
|
20 |
|
|
|
21 |
|
|
for (var i = 0; i < parts.length; i++) {
|
22 |
|
|
if (parts[i ] === 'process' &&
|
23 |
|
|
parts[i + 1] === '.' &&
|
24 |
|
|
parts[i + 2] === 'env' &&
|
25 |
|
|
parts[i + 3] === '.') {
|
26 |
|
|
var prevCodeToken = getAdjacentCodeToken(-1, parts, i);
|
27 |
|
|
var nextCodeToken = getAdjacentCodeToken(1, parts, i + 4);
|
28 |
|
|
var replacement = getReplacementString(envs, parts[i + 4], purge);
|
29 |
|
|
if (prevCodeToken !== '.' &&
|
30 |
|
|
nextCodeToken !== '.' &&
|
31 |
|
|
nextCodeToken !== '=' &&
|
32 |
|
|
typeof replacement === 'string') {
|
33 |
|
|
out.push(replacement);
|
34 |
|
|
i += 4;
|
35 |
|
|
continue;
|
36 |
|
|
}
|
37 |
|
|
}
|
38 |
|
|
out.push(parts[i]);
|
39 |
|
|
}
|
40 |
|
|
|
41 |
|
|
return out.join('');
|
42 |
|
|
}
|
43 |
|
|
|
44 |
|
|
function getAdjacentCodeToken(dir, parts, i) {
|
45 |
|
|
while (true) {
|
46 |
|
|
var part = parts[i += dir];
|
47 |
|
|
if (!spaceOrCommentRe.test(part)) {
|
48 |
|
|
return part;
|
49 |
|
|
}
|
50 |
|
|
}
|
51 |
|
|
}
|
52 |
|
|
|
53 |
|
|
function getReplacementString(envs, name, purge) {
|
54 |
|
|
for (var j = 0; j < envs.length; j++) {
|
55 |
|
|
var env = envs[j];
|
56 |
|
|
if (typeof env[name] !== 'undefined') {
|
57 |
|
|
return JSON.stringify(env[name]);
|
58 |
|
|
}
|
59 |
|
|
}
|
60 |
|
|
if (purge) {
|
61 |
|
|
return 'undefined';
|
62 |
|
|
}
|
63 |
|
|
}
|
64 |
|
|
|
65 |
|
|
module.exports = replace;
|