This repository has been archived by the owner on Jun 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
212 lines (163 loc) · 5.56 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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"use strict"
/* eslint no-unused-vars: ["warn", {"args": "after-used"}] */
/* eslint no-console: 0 */
/* eslint max-depth: 0 */
const _ = require("underscore")
const fs = require("fs")
const path = require("path")
const qs = require("qs")
const yaml = require("js-yaml")
const duration = require("iso8601-duration")
const callsites = require("callsites")
let singleValue = null
const getNodeEnv = () => process.env.NODE_ENV || "development"
// Woraround duration.default.pattern issue
const durationPattern = new RegExp(
`^${duration.default.pattern.toString().slice(1, -1)}$`
)
const dtPattern =
/^\d{4}-\d\d-\d\d(T\d\d:\d\d(:\d\d(\.\d\d\d)?([+-]\d{4}|Z)?)?)?$/
function replicate(destination, source) {
if (destination === undefined || destination === source)
return source
if (_.isObject(destination) && !_.isArray(destination))
for (const attr in source)
if (_.chain(source).keys().contains(attr).value())
destination[attr] = replicate(destination[attr], source[attr])
return destination
}
function parseEnvValue(resource, isQs = false) {
if (isQs && typeof resource === "string")
try { resource = JSON.parse(resource) }
catch(_err) {}
try {
switch (typeof resource) {
//------------------------------------------------------------------------
case "string":
switch (true) {
case resource.trim() === "": // empty string
break
case resource.startsWith("raw:"): // raw string
resource = resource.slice(4)
break
case resource.startsWith("env:"): // parse envvar
resource = parseEnvValue(process.env[resource.slice(4)], true)
break
case durationPattern.test(resource): // ISO-8601 duration
resource = duration.toSeconds(duration.parse(resource)) * 1000
break
case /^\w+(\[\w*\])?=([^&]*)?(&\w+(\[\w*\])?=([^&]*)?)*$/
.test(resource):
resource = _.chain(qs.parse(resource))
.map((v, k) => [ k, parseEnvValue(v, true) ])
.filter(pair => pair[1] !== undefined)
.object()
.value()
resource = singleValue(_.isEmpty(resource) ? undefined : resource)
break
case /^\/.+\/[gimuy]*$/.test(resource):
{
let flags
if (!resource.endsWith("/")) {
flags = _.last(resource.split("/"))
resource = resource.replace(/^(\/.+\/)[gimuy]+$/, "$1")
}
resource = new RegExp(resource.slice(1, -1), flags)
}
break
case dtPattern.test(resource): // ISO-8601 date/time
try {
const date = new Date(resource)
if (date.toJSON() !== null)
resource = date
} catch(_e) {}
break
// TODO: nested keys
default:
// Take what you got
break
}
break
//------------------------------------------------------------------------
case "object":
switch (true) {
case _.isEmpty(resource):
// null, empty arrays, empty objects: do nothing
break
case Array.isArray(resource):
resource = resource.map(e => parseEnvValue(e, isQs))
break
/*
* Other cases go here
*/
default:
resource = _.chain(resource)
.map((v, k) => [ k, parseEnvValue(v, isQs) ])
.object()
.value()
}
break
/*------------------------------------------------------------------------
* case other type:
* goes here
*/
//------------------------------------------------------------------------
default:
// Take what you got
break
}
} catch(err) {
console.error(err)
}
return resource
}
function expandKeys(obj) {
if (!_.isObject(obj))
return obj
for (const [ key, value ] of _.pairs(obj))
if (key.indexOf(".") > 0) {
const [ outer, ...rest ] = key.split(".")
const inner = rest.join(".")
if (_.isObject(obj[outer])) {
obj[outer][inner] = value
delete obj[key]
} else if (_.isUndefined(obj[outer])) {
obj[outer] = { [inner]: value }
delete obj[key]
}
}
for (const value of _.values(obj))
expandKeys(value)
return obj
}
function loadModule(fname) {
if (!fname.startsWith("/")) {
const base = path.dirname(callsites()[2].getFileName())
fname = path.join(base, fname)
}
if (fname.endsWith(".json"))
return require(fname)
else if (fname.endsWith(".yaml") || fname.endsWith(".yml"))
return yaml.safeLoad(fs.readFileSync(fname, "utf8"))
else
throw new Error(`invalid file ${fname}`)
}
singleValue = value =>
(
(_.keys(value).length === 1)
&& _.chain(value).values().first().value() === ""
) ? parseEnvValue(_.chain(value).keys().first().value())
: value
module.exports = (config, nodeEnv) => {
if (_.isString(config))
config = loadModule(config)
nodeEnv = nodeEnv || getNodeEnv()
config = parseEnvValue(expandKeys(_.clone(config)))
const { defaults, development } = config
let current = _.isUndefined(config[nodeEnv]) ? development : config[nodeEnv]
current = _.isUndefined(current) ? development : current
current = _.isUndefined(current) ? defaults : current
if (current !== defaults)
current = replicate(current, defaults)
return current
}