-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig.js
318 lines (294 loc) · 10.9 KB
/
config.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/**
* @license
* MOST Web Framework 2.0 Codename Blueshift
* Copyright (c) 2017, THEMOST LP All rights reserved
*
* Use of this source code is governed by an BSD-3-Clause license that can be
* found in the LICENSE file at https://themost.io/license
*/
///
var _ = require('lodash');
var Symbol = require('symbol');
var LangUtils = require("./utils").LangUtils;
var Args = require('./utils').Args;
var TraceUtils = require('./utils').TraceUtils;
var PathUtils = require('./utils').PathUtils;
var AbstractClassError = require('./errors').AbstractClassError;
var configProperty = Symbol('config');
var currentConfiguration = Symbol('current');
var configPathProperty = Symbol('configurationPath');
var executionPathProperty = Symbol('executionPath');
var strategiesProperty = Symbol('strategies');
/**
* @class Represents an application configuration
* @param {string=} configPath
* @property {*} settings
* @constructor
*/
function ConfigurationBase(configPath) {
//init strategies
this[strategiesProperty] = { };
this[configPathProperty] = configPath || PathUtils.join(process.cwd(),'config');
TraceUtils.debug('Initializing configuration under %s.', this[configPathProperty]);
this[executionPathProperty] = PathUtils.join(this[configPathProperty],'..');
TraceUtils.debug('Setting execution path under %s.', this[executionPathProperty]);
//load default module loader strategy
this.useStrategy(ModuleLoaderStrategy, DefaultModuleLoaderStrategy);
//get configuration source
var configSourcePath;
try {
var env = 'production';
//node.js mode
if (process && process.env) {
env = process.env['NODE_ENV'] || 'production';
}
//browser mode
else if (window && window.env) {
env = window.env['BROWSER_ENV'] || 'production';
}
configSourcePath = PathUtils.join(this[configPathProperty], 'app.' + env + '.json');
TraceUtils.debug('Validating environment configuration source on %s.', configSourcePath);
this[configProperty] = require(configSourcePath);
}
catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
TraceUtils.log('The environment specific configuration cannot be found or is inaccessible.');
try {
configSourcePath = PathUtils.join(this[configPathProperty], 'app.json');
TraceUtils.debug('Validating application configuration source on %s.', configSourcePath);
this[configProperty] = require(configSourcePath);
}
catch(err) {
if (err.code === 'MODULE_NOT_FOUND') {
TraceUtils.log('The default application configuration cannot be found or is inaccessible.');
}
else {
TraceUtils.error('An error occurred while trying to open default application configuration.');
TraceUtils.error(err);
}
TraceUtils.debug('Initializing empty configuration');
this[configProperty] = { };
}
}
else {
TraceUtils.error('An error occurred while trying to open application configuration.');
TraceUtils.error(err);
//load default configuration
this[configProperty] = { };
}
}
//initialize settings object
this[configProperty]['settings'] = this[configProperty]['settings'] || { };
/**
* @name ConfigurationBase#settings
* @type {*}
*/
Object.defineProperty(this, 'settings',{
get: function() {
return this[configProperty]['settings'];
},
enumerable:true,
configurable:false});
}
//noinspection JSUnusedGlobalSymbols
/**
* Returns the configuration source object
* @returns {*}
*/
ConfigurationBase.prototype.getSource = function() {
return this[configProperty];
};
//noinspection JSUnusedGlobalSymbols
/**
* Returns the source configuration object based on the given path (e.g. settings.auth.cookieName or settings/auth/cookieName)
* @param {string} p - A string which represents an object path
* @returns {Object|Array}
*/
ConfigurationBase.prototype.getSourceAt = function(p) {
return _.at(this[configProperty],p.replace(/\//g,'.'))[0];
};
//noinspection JSUnusedGlobalSymbols
/**
* Returns a boolean which indicates whether the specified object path exists or not (e.g. settings.auth.cookieName or settings/auth/cookieName)
* @param {string} p - A string which represents an object path
* @returns {boolean}
*/
ConfigurationBase.prototype.hasSourceAt = function(p) {
return _.isObject(_.at(this[configProperty],p.replace(/\//g,'.'))[0]);
};
//noinspection JSUnusedGlobalSymbols
/**
* Sets the config value to the specified object path (e.g. settings.auth.cookieName or settings/auth/cookieName)
* @param {string} p - A string which represents an object path
* @param {*} value
* @returns {Object}
*/
ConfigurationBase.prototype.setSourceAt = function(p, value) {
return _.set(this[configProperty], p.replace(/\//g,'.'), value);
};
//noinspection JSUnusedGlobalSymbols
/**
* Sets the current execution path
* @param {string} p
* @returns ConfigurationBase
*/
ConfigurationBase.prototype.setExecutionPath = function(p) {
this[executionPathProperty] = p;
return this;
};
/**
* Gets the current execution path
* @returns {string}
*/
ConfigurationBase.prototype.getExecutionPath = function() {
return this[executionPathProperty];
};
/**
* Gets the current configuration path
* @returns {string}
*/
ConfigurationBase.prototype.getConfigurationPath = function() {
return this[configPathProperty];
};
/**
* Register a configuration strategy
* @param {Function} strategyBaseCtor
* @param {Function=} strategyCtor
* @returns ConfigurationBase
*/
ConfigurationBase.prototype.useStrategy = function(strategyBaseCtor, strategyCtor) {
Args.notFunction(strategyBaseCtor,"Configuration strategy constructor");
if (typeof strategyCtor === 'undefined') {
this[strategiesProperty]["$".concat(strategyBaseCtor.name)] = new strategyBaseCtor(this);
return this;
}
Args.notFunction(strategyCtor,"Strategy constructor");
this[strategiesProperty]["$".concat(strategyBaseCtor.name)] = new strategyCtor(this);
return this;
};
//noinspection JSUnusedGlobalSymbols
/**
* Gets a configuration strategy
* @param {Function} strategyBaseCtor
*/
ConfigurationBase.prototype.getStrategy = function(strategyBaseCtor) {
Args.notFunction(strategyBaseCtor,"Configuration strategy constructor");
return this[strategiesProperty]["$".concat(strategyBaseCtor.name)];
};
/**
* Gets a configuration strategy
* @param {Function} strategyBaseCtor
*/
ConfigurationBase.prototype.hasStrategy = function(strategyBaseCtor) {
Args.notFunction(strategyBaseCtor,"Configuration strategy constructor");
return typeof this[strategiesProperty]["$".concat(strategyBaseCtor.name)] !== 'undefined';
};
/**
* Gets the current configuration
* @returns ConfigurationBase - An instance of DataConfiguration class which represents the current data configuration
*/
ConfigurationBase.getCurrent = function() {
if (_.isNil(ConfigurationBase[currentConfiguration])) {
ConfigurationBase[currentConfiguration] = new ConfigurationBase();
}
return ConfigurationBase[currentConfiguration];
};
/**
* Sets the current configuration
* @param {ConfigurationBase} configuration
* @returns ConfigurationBase - An instance of ApplicationConfiguration class which represents the current configuration
*/
ConfigurationBase.setCurrent = function(configuration) {
if (configuration instanceof ConfigurationBase) {
if (!configuration.hasStrategy(ModuleLoaderStrategy)) {
configuration.useStrategy(ModuleLoaderStrategy, DefaultModuleLoaderStrategy);
}
ConfigurationBase[currentConfiguration] = configuration;
return ConfigurationBase[currentConfiguration];
}
throw new TypeError('Invalid argument. Expected an instance of DataConfiguration class.');
};
/**
* @class
* @param {ConfigurationBase} config
* @constructor
* @abstract
*/
function ConfigurationStrategy(config) {
Args.check(this.constructor.name !== ConfigurationStrategy, new AbstractClassError());
Args.notNull(config, 'Configuration');
this[configProperty] = config;
}
/**
* @returns {ConfigurationBase}
*/
ConfigurationStrategy.prototype.getConfiguration = function() {
return this[configProperty];
};
/**
* @class
* @constructor
* @param {ConfigurationBase} config
* @extends ConfigurationStrategy
*/
function ModuleLoaderStrategy(config) {
ModuleLoaderStrategy.super_.bind(this)(config);
}
LangUtils.inherits(ModuleLoaderStrategy, ConfigurationStrategy);
ModuleLoaderStrategy.prototype.require = function(modulePath) {
Args.notEmpty(modulePath,'Module Path');
if (!/^.\//i.test(modulePath)) {
if (require.resolve && require.resolve.paths) {
/**
* get require paths collection
* @type string[]
*/
var paths = require.resolve.paths(modulePath);
//get execution
var path1 = this.getConfiguration().getExecutionPath();
//loop directories to parent (like classic require)
while (path1) {
//if path does not exist in paths collection
if (paths.indexOf(PathUtils.join(path1,'node_modules'))<0) {
//add it
paths.push(PathUtils.join(path1,'node_modules'));
//and check the next path which is going to be resolved
if (path1 === PathUtils.join(path1,'..')) {
//if it is the same with the current path break loop
break;
}
//otherwise get parent path
path1 = PathUtils.join(path1,'..');
}
else {
//path already exists in paths collection, so break loop
break;
}
}
var finalModulePath = require.resolve(modulePath, {
paths:paths
});
return require(finalModulePath);
}
else {
return require(modulePath);
}
}
return require(PathUtils.join(this.getConfiguration().getExecutionPath(),modulePath));
};
/**
* @class
* @constructor
* @param {ConfigurationBase} config
* @extends ModuleLoaderStrategy
*/
function DefaultModuleLoaderStrategy(config) {
DefaultModuleLoaderStrategy.super_.bind(this)(config);
}
LangUtils.inherits(DefaultModuleLoaderStrategy, ModuleLoaderStrategy);
if (typeof exports !== 'undefined') {
module.exports.ConfigurationBase = ConfigurationBase;
module.exports.ConfigurationStrategy = ConfigurationStrategy;
module.exports.ModuleLoaderStrategy = ModuleLoaderStrategy;
module.exports.DefaultModuleLoaderStrategy = DefaultModuleLoaderStrategy;
}