forked from hughsk/envify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom.js
106 lines (90 loc) · 2.95 KB
/
custom.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
var acorn = require('acorn-node')
, dash = require('dash-ast')
, msplice = require('multisplice')
, through = require('through2')
var processEnvPattern = /\bprocess\.env\b/
function equalNodes(a, b) {
if (a.type !== b.type) return false
switch (a.type) {
case 'Literal': return a.value === b.value
case 'Identifier': return a.name === b.name
case 'MemberExpression': return a.computed === b.computed && equalNodes(a.object, b.object) && equalNodes(a.property, b.property)
}
return false
}
module.exports = function(rootEnv) {
rootEnv = rootEnv || process.env || {}
return function envify(file, argv) {
if (/\.json$/.test(file)) return through()
var buffer = []
argv = argv || {}
return through(write, flush)
function write(data, enc, cb) {
buffer.push(data)
cb()
}
function transform(source, envs) {
var args = [].concat(envs[0]._ || []).concat(envs[1]._ || [])
var purge = args.indexOf('purge') !== -1
var replacements = []
function match(node) {
return (
node.type === 'MemberExpression'
&& node.object.type === 'MemberExpression'
&& node.object.computed === false
&& node.object.object.type === 'Identifier'
&& node.object.object.name === 'process'
&& node.object.property.type === 'Identifier'
&& node.object.property.name === 'env'
&& (node.computed ? node.property.type === 'Literal' : node.property.type === 'Identifier')
)
}
var ast = acorn.parse(source)
dash(ast, { leave: function(node) {
if (match(node)) {
var key = node.property.name || node.property.value
for (var i = 0; i < envs.length; i++) {
var value = envs[i][key]
if (value !== undefined) {
replacements.push({ node: node, value: JSON.stringify(value) })
return
}
}
if (purge) {
replacements.push({ node: node, value: 'undefined' })
}
} else if (node.type === 'AssignmentExpression') {
for (var i = 0; i < replacements.length; ++i) {
if (equalNodes(replacements[i].node, node.left)) {
replacements.splice(i, 1)
}
}
}
} })
var splicer = msplice(source)
if (replacements.length > 0) {
replacements.sort(function (a, b) {
return b.start - a.start
})
for (var i = 0; i < replacements.length; i++) {
var r = replacements[i]
splicer.splice(r.node.start, r.node.end, r.value)
}
}
return splicer.toString()
}
function flush(cb) {
var source = buffer.join('')
if (processEnvPattern.test(source)) {
try {
source = transform(source, [argv, rootEnv])
} catch(err) {
return this.emit('error', err)
}
}
this.push(source)
this.push(null)
cb()
}
}
}