UNPKG

45.8 kBJavaScriptView Raw
1// config.js (c) 2010-2020 Loren West and other contributors
2// May be freely distributed under the MIT license.
3// For further details and documentation:
4// http://lorenwest.github.com/node-config
5
6// Dependencies
7var deferConfig = require('../defer').deferConfig,
8 DeferredConfig = require('../defer').DeferredConfig,
9 RawConfig = require('../raw').RawConfig,
10 Parser = require('../parser'),
11 Utils = require('util'),
12 Path = require('path'),
13 FileSystem = require('fs');
14
15// Static members
16var DEFAULT_CLONE_DEPTH = 20,
17 NODE_CONFIG, CONFIG_DIR, RUNTIME_JSON_FILENAME, NODE_ENV, APP_INSTANCE,
18 HOST, HOSTNAME, ALLOW_CONFIG_MUTATIONS, CONFIG_SKIP_GITCRYPT,
19 NODE_CONFIG_PARSER,
20 env = {},
21 privateUtil = {},
22 deprecationWarnings = {},
23 configSources = [], // Configuration sources - array of {name, original, parsed}
24 checkMutability = true, // Check for mutability/immutability on first get
25 gitCryptTestRegex = /^.GITCRYPT/; // regular expression to test for gitcrypt files.
26
27/**
28 * <p>Application Configurations</p>
29 *
30 * <p>
31 * The config module exports a singleton object representing all
32 * configurations for this application deployment.
33 * </p>
34 *
35 * <p>
36 * Application configurations are stored in files within the config directory
37 * of your application. The default configuration file is loaded, followed
38 * by files specific to the deployment type (development, testing, staging,
39 * production, etc.).
40 * </p>
41 *
42 * <p>
43 * For example, with the following config/default.yaml file:
44 * </p>
45 *
46 * <pre>
47 * ...
48 * customer:
49 * &nbsp;&nbsp;initialCredit: 500
50 * &nbsp;&nbsp;db:
51 * &nbsp;&nbsp;&nbsp;&nbsp;name: customer
52 * &nbsp;&nbsp;&nbsp;&nbsp;port: 5984
53 * ...
54 * </pre>
55 *
56 * <p>
57 * The following code loads the customer section into the CONFIG variable:
58 * <p>
59 *
60 * <pre>
61 * var CONFIG = require('config').customer;
62 * ...
63 * newCustomer.creditLimit = CONFIG.initialCredit;
64 * database.open(CONFIG.db.name, CONFIG.db.port);
65 * ...
66 * </pre>
67 *
68 * @module config
69 * @class Config
70 */
71
72/**
73 * <p>Get the configuration object.</p>
74 *
75 * <p>
76 * The configuration object is a shared singleton object within the application,
77 * attained by calling require('config').
78 * </p>
79 *
80 * <p>
81 * Usually you'll specify a CONFIG variable at the top of your .js file
82 * for file/module scope. If you want the root of the object, you can do this:
83 * </p>
84 * <pre>
85 * var CONFIG = require('config');
86 * </pre>
87 *
88 * <p>
89 * Sometimes you only care about a specific sub-object within the CONFIG
90 * object. In that case you could do this at the top of your file:
91 * </p>
92 * <pre>
93 * var CONFIG = require('config').customer;
94 * or
95 * var CUSTOMER_CONFIG = require('config').customer;
96 * </pre>
97 *
98 * <script type="text/javascript">
99 * document.getElementById("showProtected").style.display = "block";
100 * </script>
101 *
102 * @method constructor
103 * @return CONFIG {object} - The top level configuration object
104 */
105var Config = function() {
106 var t = this;
107
108 // Bind all utility functions to this
109 for (var fnName in util) {
110 if (typeof util[fnName] === 'function') {
111 util[fnName] = util[fnName].bind(t);
112 }
113 }
114
115 // Merge configurations into this
116 util.extendDeep(t, util.loadFileConfigs());
117 util.attachProtoDeep(t);
118
119 // Perform strictness checks and possibly throw an exception.
120 util.runStrictnessChecks(t);
121};
122
123/**
124 * Utilities are under the util namespace vs. at the top level
125 */
126var util = Config.prototype.util = {};
127
128/**
129 * Underlying get mechanism
130 *
131 * @private
132 * @method getImpl
133 * @param object {object} - Object to get the property for
134 * @param property {string|string[]} - The property name to get (as an array or '.' delimited string)
135 * @return value {*} - Property value, including undefined if not defined.
136 */
137var getImpl= function(object, property) {
138 var t = this,
139 elems = Array.isArray(property) ? property : property.split('.'),
140 name = elems[0],
141 value = object[name];
142 if (elems.length <= 1) {
143 return value;
144 }
145 // Note that typeof null === 'object'
146 if (value === null || typeof value !== 'object') {
147 return undefined;
148 }
149 return getImpl(value, elems.slice(1));
150};
151
152/**
153 * <p>Get a configuration value</p>
154 *
155 * <p>
156 * This will return the specified property value, throwing an exception if the
157 * configuration isn't defined. It is used to assure configurations are defined
158 * before being used, and to prevent typos.
159 * </p>
160 *
161 * @method get
162 * @param property {string} - The configuration property to get. Can include '.' sub-properties.
163 * @return value {*} - The property value
164 */
165Config.prototype.get = function(property) {
166 if(property === null || property === undefined){
167 throw new Error("Calling config.get with null or undefined argument");
168 }
169
170 // Make configurations immutable after first get (unless disabled)
171 if (checkMutability) {
172 if (!util.initParam('ALLOW_CONFIG_MUTATIONS', false)) {
173 util.makeImmutable(config);
174 }
175 checkMutability = false;
176 }
177 var t = this,
178 value = getImpl(t, property);
179
180 // Produce an exception if the property doesn't exist
181 if (value === undefined) {
182 throw new Error('Configuration property "' + property + '" is not defined');
183 }
184
185 // Return the value
186 return value;
187};
188
189/**
190 * Test that a configuration parameter exists
191 *
192 * <pre>
193 * var config = require('config');
194 * if (config.has('customer.dbName')) {
195 * console.log('Customer database name: ' + config.customer.dbName);
196 * }
197 * </pre>
198 *
199 * @method has
200 * @param property {string} - The configuration property to test. Can include '.' sub-properties.
201 * @return isPresent {boolean} - True if the property is defined, false if not defined.
202 */
203Config.prototype.has = function(property) {
204 // While get() throws an exception for undefined input, has() is designed to test validity, so false is appropriate
205 if(property === null || property === undefined){
206 return false;
207 }
208 var t = this;
209 return (getImpl(t, property) !== undefined);
210};
211
212/**
213 * <p>
214 * Set default configurations for a node.js module.
215 * </p>
216 *
217 * <p>
218 * This allows module developers to attach their configurations onto the
219 * default configuration object so they can be configured by the consumers
220 * of the module.
221 * </p>
222 *
223 * <p>Using the function within your module:</p>
224 * <pre>
225 * var CONFIG = require("config");
226 * CONFIG.util.setModuleDefaults("MyModule", {
227 * &nbsp;&nbsp;templateName: "t-50",
228 * &nbsp;&nbsp;colorScheme: "green"
229 * });
230 * <br>
231 * // Template name may be overridden by application config files
232 * console.log("Template: " + CONFIG.MyModule.templateName);
233 * </pre>
234 *
235 * <p>
236 * The above example results in a "MyModule" element of the configuration
237 * object, containing an object with the specified default values.
238 * </p>
239 *
240 * @method setModuleDefaults
241 * @param moduleName {string} - Name of your module.
242 * @param defaultProperties {object} - The default module configuration.
243 * @return moduleConfig {object} - The module level configuration object.
244 */
245util.setModuleDefaults = function (moduleName, defaultProperties) {
246
247 // Copy the properties into a new object
248 var t = this,
249 moduleConfig = util.cloneDeep(defaultProperties);
250
251 // Set module defaults into the first sources element
252 if (configSources.length === 0 || configSources[0].name !== 'Module Defaults') {
253 configSources.splice(0, 0, {
254 name: 'Module Defaults',
255 parsed: {}
256 });
257 }
258 util.setPath(configSources[0].parsed, moduleName.split('.'), {});
259 util.extendDeep(getImpl(configSources[0].parsed, moduleName), defaultProperties);
260
261 // Create a top level config for this module if it doesn't exist
262 util.setPath(t, moduleName.split('.'), getImpl(t, moduleName) || {});
263
264 // Extend local configurations into the module config
265 util.extendDeep(moduleConfig, getImpl(t, moduleName));
266
267 // Merge the extended configs without replacing the original
268 util.extendDeep(getImpl(t, moduleName), moduleConfig);
269
270 // reset the mutability check for "config.get" method.
271 // we are not making t[moduleName] immutable immediately,
272 // since there might be more modifications before the first config.get
273 if (!util.initParam('ALLOW_CONFIG_MUTATIONS', false)) {
274 checkMutability = true;
275 }
276
277 // Attach handlers & watchers onto the module config object
278 return util.attachProtoDeep(getImpl(t, moduleName));
279};
280
281/**
282 * <p>Make a configuration property hidden so it doesn't appear when enumerating
283 * elements of the object.</p>
284 *
285 * <p>
286 * The property still exists and can be read from and written to, but it won't
287 * show up in for ... in loops, Object.keys(), or JSON.stringify() type methods.
288 * </p>
289 *
290 * <p>
291 * If the property already exists, it will be made hidden. Otherwise it will
292 * be created as a hidden property with the specified value.
293 * </p>
294 *
295 * <p><i>
296 * This method was built for hiding configuration values, but it can be applied
297 * to <u>any</u> javascript object.
298 * </i></p>
299 *
300 * <p>Example:</p>
301 * <pre>
302 * var CONFIG = require('config');
303 * ...
304 *
305 * // Hide the Amazon S3 credentials
306 * CONFIG.util.makeHidden(CONFIG.amazonS3, 'access_id');
307 * CONFIG.util.makeHidden(CONFIG.amazonS3, 'secret_key');
308 * </pre>
309 *
310 * @method makeHidden
311 * @param object {object} - The object to make a hidden property into.
312 * @param property {string} - The name of the property to make hidden.
313 * @param value {*} - (optional) Set the property value to this (otherwise leave alone)
314 * @return object {object} - The original object is returned - for chaining.
315 */
316util.makeHidden = function(object, property, value) {
317
318 // If the new value isn't specified, just mark the property as hidden
319 if (typeof value === 'undefined') {
320 Object.defineProperty(object, property, {
321 enumerable : false
322 });
323 }
324 // Otherwise set the value and mark it as hidden
325 else {
326 Object.defineProperty(object, property, {
327 value : value,
328 enumerable : false
329 });
330 }
331
332 return object;
333}
334
335/**
336 * <p>Make a javascript object property immutable (assuring it cannot be changed
337 * from the current value).</p>
338 * <p>
339 * If the specified property is an object, all attributes of that object are
340 * made immutable, including properties of contained objects, recursively.
341 * If a property name isn't supplied, all properties of the object are made
342 * immutable.
343 * </p>
344 * <p>
345 *
346 * </p>
347 * <p>
348 * New properties can be added to the object and those properties will not be
349 * immutable unless this method is called on those new properties.
350 * </p>
351 * <p>
352 * This operation cannot be undone.
353 * </p>
354 *
355 * <p>Example:</p>
356 * <pre>
357 * var config = require('config');
358 * var myObject = {hello:'world'};
359 * config.util.makeImmutable(myObject);
360 * </pre>
361 *
362 * @method makeImmutable
363 * @param object {object} - The object to specify immutable properties for
364 * @param [property] {string | [string]} - The name of the property (or array of names) to make immutable.
365 * If not provided, all owned properties of the object are made immutable.
366 * @param [value] {* | [*]} - Property value (or array of values) to set
367 * the property to before making immutable. Only used when setting a single
368 * property. Retained for backward compatibility.
369 * @return object {object} - The original object is returned - for chaining.
370 */
371util.makeImmutable = function(object, property, value) {
372 var properties = null;
373
374 // Backwards compatibility mode where property/value can be specified
375 if (typeof property === 'string') {
376 return Object.defineProperty(object, property, {
377 value : (typeof value === 'undefined') ? object[property] : value,
378 writable : false,
379 configurable: false
380 });
381 }
382
383 // Get the list of properties to work with
384 if (Array.isArray(property)) {
385 properties = property;
386 }
387 else {
388 properties = Object.keys(object);
389 }
390
391 // Process each property
392 for (var i = 0; i < properties.length; i++) {
393 var propertyName = properties[i],
394 value = object[propertyName];
395
396 if (value instanceof RawConfig) {
397 Object.defineProperty(object, propertyName, {
398 value: value.resolve(),
399 writable: false,
400 configurable: false
401 });
402 } else if (Array.isArray(value)) {
403 // Ensure object items of this array are also immutable.
404 value.forEach((item, index) => { if (util.isObject(item) || Array.isArray(item)) util.makeImmutable(item) })
405
406 Object.defineProperty(object, propertyName, {
407 value: Object.freeze(value)
408 });
409 } else {
410 Object.defineProperty(object, propertyName, {
411 value: value,
412 writable : false,
413 configurable: false
414 });
415
416 // Ensure new properties can not be added.
417 Object.preventExtensions(object)
418
419 // Call recursively if an object.
420 if (util.isObject(value)) {
421 util.makeImmutable(value);
422 }
423 }
424 }
425
426 return object;
427};
428
429/**
430 * Return the sources for the configurations
431 *
432 * <p>
433 * All sources for configurations are stored in an array of objects containing
434 * the source name (usually the filename), the original source (as a string),
435 * and the parsed source as an object.
436 * </p>
437 *
438 * @method getConfigSources
439 * @return configSources {Array[Object]} - An array of objects containing
440 * name, original, and parsed elements
441 */
442util.getConfigSources = function() {
443 var t = this;
444 return configSources.slice(0);
445};
446
447/**
448 * Load the individual file configurations.
449 *
450 * <p>
451 * This method builds a map of filename to the configuration object defined
452 * by the file. The search order is:
453 * </p>
454 *
455 * <pre>
456 * default.EXT
457 * (deployment).EXT
458 * (hostname).EXT
459 * (hostname)-(deployment).EXT
460 * local.EXT
461 * local-(deployment).EXT
462 * runtime.json
463 * </pre>
464 *
465 * <p>
466 * EXT can be yml, yaml, coffee, iced, json, cson or js signifying the file type.
467 * yaml (and yml) is in YAML format, coffee is a coffee-script, iced is iced-coffee-script,
468 * json is in JSON format, cson is in CSON format, properties is in .properties format
469 * (http://en.wikipedia.org/wiki/.properties), and js is a javascript executable file that is
470 * require()'d with module.exports being the config object.
471 * </p>
472 *
473 * <p>
474 * hostname is the $HOST environment variable (or --HOST command line parameter)
475 * if set, otherwise the $HOSTNAME environment variable (or --HOSTNAME command
476 * line parameter) if set, otherwise the hostname found from
477 * require('os').hostname().
478 * </p>
479 *
480 * <p>
481 * Once a hostname is found, everything from the first period ('.') onwards
482 * is removed. For example, abc.example.com becomes abc
483 * </p>
484 *
485 * <p>
486 * (deployment) is the deployment type, found in the $NODE_ENV environment
487 * variable (which can be overriden by using $NODE_CONFIG_ENV
488 * environment variable). Defaults to 'development'.
489 * </p>
490 *
491 * <p>
492 * The runtime.json file contains configuration changes made at runtime either
493 * manually, or by the application setting a configuration value.
494 * </p>
495 *
496 * <p>
497 * If the $NODE_APP_INSTANCE environment variable (or --NODE_APP_INSTANCE
498 * command line parameter) is set, then files with this appendage will be loaded.
499 * See the Multiple Application Instances section of the main documentaion page
500 * for more information.
501 * </p>
502 *
503 * @protected
504 * @method loadFileConfigs
505 * @return config {Object} The configuration object
506 */
507util.loadFileConfigs = function(configDir) {
508
509 // Initialize
510 var t = this,
511 config = {};
512
513 // Initialize parameters from command line, environment, or default
514 NODE_ENV = util.initParam('NODE_ENV', 'development');
515
516 // Override, NODE_ENV if NODE_CONFIG_ENV is specified.
517 NODE_ENV = util.initParam('NODE_CONFIG_ENV', NODE_ENV);
518
519 // Split files name, for loading multiple files.
520 NODE_ENV = NODE_ENV.split(',');
521
522 CONFIG_DIR = configDir || util.initParam('NODE_CONFIG_DIR', Path.join( process.cwd(), 'config') );
523 if (CONFIG_DIR.indexOf('.') === 0) {
524 CONFIG_DIR = Path.join(process.cwd() , CONFIG_DIR);
525 }
526
527 APP_INSTANCE = util.initParam('NODE_APP_INSTANCE');
528 HOST = util.initParam('HOST');
529 HOSTNAME = util.initParam('HOSTNAME');
530 CONFIG_SKIP_GITCRYPT = util.initParam('CONFIG_SKIP_GITCRYPT');
531
532 // This is for backward compatibility
533 RUNTIME_JSON_FILENAME = util.initParam('NODE_CONFIG_RUNTIME_JSON', Path.join(CONFIG_DIR , 'runtime.json') );
534
535 NODE_CONFIG_PARSER = util.initParam('NODE_CONFIG_PARSER');
536 if (NODE_CONFIG_PARSER) {
537 try {
538 var parserModule = Path.isAbsolute(NODE_CONFIG_PARSER)
539 ? NODE_CONFIG_PARSER
540 : Path.join(CONFIG_DIR, NODE_CONFIG_PARSER);
541 Parser = require(parserModule);
542 }
543 catch (e) {
544 console.warn('Failed to load config parser from ' + NODE_CONFIG_PARSER);
545 console.log(e);
546 }
547 }
548
549 // Determine the host name from the OS module, $HOST, or $HOSTNAME
550 // Remove any . appendages, and default to null if not set
551 try {
552 var hostName = HOST || HOSTNAME;
553
554 if (!hostName) {
555 var OS = require('os');
556 hostName = OS.hostname();
557 }
558 } catch (e) {
559 hostName = '';
560 }
561
562 // Store the hostname that won.
563 env.HOSTNAME = hostName;
564
565 // Read each file in turn
566 var baseNames = ['default'].concat(NODE_ENV);
567
568 // #236: Also add full hostname when they are different.
569 if (hostName) {
570 var firstDomain = hostName.split('.')[0];
571
572 NODE_ENV.forEach(function(env) {
573 // Backward compatibility
574 baseNames.push(firstDomain, firstDomain + '-' + env);
575
576 // Add full hostname when it is not the same
577 if (hostName !== firstDomain) {
578 baseNames.push(hostName, hostName + '-' + env);
579 }
580 });
581 }
582
583 NODE_ENV.forEach(function(env) {
584 baseNames.push('local', 'local-' + env);
585 });
586
587 var allowedFiles = {};
588 var resolutionIndex = 1;
589 var extNames = Parser.getFilesOrder();
590 baseNames.forEach(function(baseName) {
591 extNames.forEach(function(extName) {
592 allowedFiles[baseName + '.' + extName] = resolutionIndex++;
593 if (APP_INSTANCE) {
594 allowedFiles[baseName + '-' + APP_INSTANCE + '.' + extName] = resolutionIndex++;
595 }
596 });
597 });
598
599 var locatedFiles = util.locateMatchingFiles(CONFIG_DIR, allowedFiles);
600 locatedFiles.forEach(function(fullFilename) {
601 var configObj = util.parseFile(fullFilename);
602 if (configObj) {
603 util.extendDeep(config, configObj);
604 }
605 });
606
607 // Override configurations from the $NODE_CONFIG environment variable
608 // NODE_CONFIG only applies to the base config
609 if (!configDir) {
610 var envConfig = {};
611 if (process.env.NODE_CONFIG) {
612 try {
613 envConfig = JSON.parse(process.env.NODE_CONFIG);
614 } catch(e) {
615 console.error('The $NODE_CONFIG environment variable is malformed JSON');
616 }
617 util.extendDeep(config, envConfig);
618 configSources.push({
619 name: "$NODE_CONFIG",
620 parsed: envConfig,
621 });
622 }
623
624 // Override configurations from the --NODE_CONFIG command line
625 var cmdLineConfig = util.getCmdLineArg('NODE_CONFIG');
626 if (cmdLineConfig) {
627 try {
628 cmdLineConfig = JSON.parse(cmdLineConfig);
629 } catch(e) {
630 console.error('The --NODE_CONFIG={json} command line argument is malformed JSON');
631 }
632 util.extendDeep(config, cmdLineConfig);
633 configSources.push({
634 name: "--NODE_CONFIG argument",
635 parsed: cmdLineConfig,
636 });
637 }
638
639 // Place the mixed NODE_CONFIG into the environment
640 env['NODE_CONFIG'] = JSON.stringify(util.extendDeep(envConfig, cmdLineConfig, {}));
641 }
642
643 // Override with environment variables if there is a custom-environment-variables.EXT mapping file
644 var customEnvVars = util.getCustomEnvVars(CONFIG_DIR, extNames);
645 util.extendDeep(config, customEnvVars);
646
647 // Extend the original config with the contents of runtime.json (backwards compatibility)
648 var runtimeJson = util.parseFile(RUNTIME_JSON_FILENAME) || {};
649 util.extendDeep(config, runtimeJson);
650
651 util.resolveDeferredConfigs(config);
652
653 // Return the configuration object
654 return config;
655};
656
657/**
658 * Return a list of fullFilenames who exists in allowedFiles
659 * Ordered according to allowedFiles argument specifications
660 *
661 * @protected
662 * @method locateMatchingFiles
663 * @param configDirs {string} the config dir, or multiple dirs separated by a column (:)
664 * @param allowedFiles {object} an object. keys and supported filenames
665 * and values are the position in the resolution order
666 * @returns {string[]} fullFilenames - path + filename
667 */
668util.locateMatchingFiles = function(configDirs, allowedFiles) {
669 return configDirs.split(Path.delimiter)
670 .reduce(function(files, configDir) {
671 if (configDir) {
672 try {
673 FileSystem.readdirSync(configDir).forEach(function(file) {
674 if (allowedFiles[file]) {
675 files.push([allowedFiles[file], Path.join(configDir, file)]);
676 }
677 });
678 }
679 catch(e) {}
680 return files;
681 }
682 }, [])
683 .sort(function(a, b) { return a[0] - b[0]; })
684 .map(function(file) { return file[1]; });
685};
686
687// Using basic recursion pattern, find all the deferred values and resolve them.
688util.resolveDeferredConfigs = function (config) {
689 var deferred = [];
690
691 function _iterate (prop) {
692
693 // We put the properties we are going to look it in an array to keep the order predictable
694 var propsToSort = [];
695
696 // First step is to put the properties of interest in an array
697 for (var property in prop) {
698 if (prop.hasOwnProperty(property) && prop[property] != null) {
699 propsToSort.push(property);
700 }
701 }
702
703 // Second step is to iterate of the elements in a predictable (sorted) order
704 propsToSort.sort().forEach(function (property) {
705 if (prop[property].constructor === Object) {
706 _iterate(prop[property]);
707 } else if (prop[property].constructor === Array) {
708 for (var i = 0; i < prop[property].length; i++) {
709 if (prop[property][i] instanceof DeferredConfig) {
710 deferred.push(prop[property][i].prepare(config, prop[property], i));
711 }
712 else {
713 _iterate(prop[property][i]);
714 }
715 }
716 } else {
717 if (prop[property] instanceof DeferredConfig) {
718 deferred.push(prop[property].prepare(config, prop, property));
719 }
720 // else: Nothing to do. Keep the property how it is.
721 }
722 });
723 }
724
725 _iterate(config);
726
727 deferred.forEach(function (defer) { defer.resolve(); });
728};
729
730/**
731 * Parse and return the specified configuration file.
732 *
733 * If the file exists in the application config directory, it will
734 * parse and return it as a JavaScript object.
735 *
736 * The file extension determines the parser to use.
737 *
738 * .js = File to run that has a module.exports containing the config object
739 * .coffee = File to run that has a module.exports with coffee-script containing the config object
740 * .iced = File to run that has a module.exports with iced-coffee-script containing the config object
741 * All other supported file types (yaml, toml, json, cson, hjson, json5, properties, xml)
742 * are parsed with util.parseString.
743 *
744 * If the file doesn't exist, a null will be returned. If the file can't be
745 * parsed, an exception will be thrown.
746 *
747 * This method performs synchronous file operations, and should not be called
748 * after synchronous module loading.
749 *
750 * @protected
751 * @method parseFile
752 * @param fullFilename {string} The full file path and name
753 * @return configObject {object|null} The configuration object parsed from the file
754 */
755util.parseFile = function(fullFilename) {
756 var t = this, // Initialize
757 configObject = null,
758 fileContent = null,
759 stat = null;
760
761 // Note that all methods here are the Sync versions. This is appropriate during
762 // module loading (which is a synchronous operation), but not thereafter.
763
764 try {
765 // Try loading the file.
766 fileContent = FileSystem.readFileSync(fullFilename, 'utf-8');
767 fileContent = fileContent.replace(/^\uFEFF/, '');
768 }
769 catch (e2) {
770 if (e2.code !== 'ENOENT') {
771 throw new Error('Config file ' + fullFilename + ' cannot be read. Error code is: '+e2.code
772 +'. Error message is: '+e2.message);
773 }
774 return null; // file doesn't exists
775 }
776
777 // Parse the file based on extension
778 try {
779
780 // skip if it's a gitcrypt file and CONFIG_SKIP_GITCRYPT is true
781 if (CONFIG_SKIP_GITCRYPT) {
782 if (gitCryptTestRegex.test(fileContent)) {
783 console.error('WARNING: ' + fullFilename + ' is a git-crypt file and CONFIG_SKIP_GITCRYPT is set. skipping.');
784 return null;
785 }
786 }
787
788 configObject = Parser.parse(fullFilename, fileContent);
789 }
790 catch (e3) {
791 if (gitCryptTestRegex.test(fileContent)) {
792 console.error('ERROR: ' + fullFilename + ' is a git-crypt file and CONFIG_SKIP_GITCRYPT is not set.');
793 }
794 throw new Error("Cannot parse config file: '" + fullFilename + "': " + e3);
795 }
796
797 // Keep track of this configuration sources, including empty ones
798 if (typeof configObject === 'object') {
799 configSources.push({
800 name: fullFilename,
801 original: fileContent,
802 parsed: configObject,
803 });
804 }
805
806 return configObject;
807};
808
809/**
810 * Parse and return the specied string with the specified format.
811 *
812 * The format determines the parser to use.
813 *
814 * json = File is parsed using JSON.parse()
815 * yaml (or yml) = Parsed with a YAML parser
816 * toml = Parsed with a TOML parser
817 * cson = Parsed with a CSON parser
818 * hjson = Parsed with a HJSON parser
819 * json5 = Parsed with a JSON5 parser
820 * properties = Parsed with the 'properties' node package
821 * xml = Parsed with a XML parser
822 *
823 * If the file doesn't exist, a null will be returned. If the file can't be
824 * parsed, an exception will be thrown.
825 *
826 * This method performs synchronous file operations, and should not be called
827 * after synchronous module loading.
828 *
829 * @protected
830 * @method parseString
831 * @param content {string} The full content
832 * @param format {string} The format to be parsed
833 * @return {configObject} The configuration object parsed from the string
834 */
835util.parseString = function (content, format) {
836 var parser = Parser.getParser(format);
837 if (typeof parser === 'function') {
838 return parser(null, content);
839 }
840};
841
842/**
843 * Attach the Config class prototype to all config objects recursively.
844 *
845 * <p>
846 * This allows you to do anything with CONFIG sub-objects as you can do with
847 * the top-level CONFIG object. It's so you can do this:
848 * </p>
849 *
850 * <pre>
851 * var CUST_CONFIG = require('config').Customer;
852 * CUST_CONFIG.get(...)
853 * </pre>
854 *
855 * @protected
856 * @method attachProtoDeep
857 * @param toObject
858 * @param depth
859 * @return toObject
860 */
861util.attachProtoDeep = function(toObject, depth) {
862 if (toObject instanceof RawConfig) {
863 return toObject;
864 }
865
866 // Recursion detection
867 var t = this;
868 depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth);
869 if (depth < 0) {
870 return toObject;
871 }
872
873 // Adding Config.prototype methods directly to toObject as hidden properties
874 // because adding to toObject.__proto__ exposes the function in toObject
875 for (var fnName in Config.prototype) {
876 if (!toObject[fnName]) {
877 util.makeHidden(toObject, fnName, Config.prototype[fnName]);
878 }
879 }
880
881 // Add prototypes to sub-objects
882 for (var prop in toObject) {
883 if (util.isObject(toObject[prop])) {
884 util.attachProtoDeep(toObject[prop], depth - 1);
885 }
886 }
887
888 // Return the original object
889 return toObject;
890};
891
892/**
893 * Return a deep copy of the specified object.
894 *
895 * This returns a new object with all elements copied from the specified
896 * object. Deep copies are made of objects and arrays so you can do anything
897 * with the returned object without affecting the input object.
898 *
899 * @protected
900 * @method cloneDeep
901 * @param parent {object} The original object to copy from
902 * @param [depth=20] {Integer} Maximum depth (default 20)
903 * @return {object} A new object with the elements copied from the copyFrom object
904 *
905 * This method is copied from https://github.com/pvorb/node-clone/blob/17eea36140d61d97a9954c53417d0e04a00525d9/clone.js
906 *
907 * Copyright © 2011-2014 Paul Vorbach and contributors.
908 * Permission is hereby granted, free of charge, to any person obtaining a copy
909 * of this software and associated documentation files (the “Software”), to deal
910 * in the Software without restriction, including without limitation the rights
911 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
912 * of the Software, and to permit persons to whom the Software is furnished to do so,
913 * subject to the following conditions: The above copyright notice and this permission
914 * notice shall be included in all copies or substantial portions of the Software.
915 */
916util.cloneDeep = function cloneDeep(parent, depth, circular, prototype) {
917 // maintain two arrays for circular references, where corresponding parents
918 // and children have the same index
919 var allParents = [];
920 var allChildren = [];
921
922 var useBuffer = typeof Buffer != 'undefined';
923
924 if (typeof circular === 'undefined')
925 circular = true;
926
927 if (typeof depth === 'undefined')
928 depth = 20;
929
930 // recurse this function so we don't reset allParents and allChildren
931 function _clone(parent, depth) {
932 // cloning null always returns null
933 if (parent === null)
934 return null;
935
936 if (depth === 0)
937 return parent;
938
939 var child;
940 if (typeof parent != 'object') {
941 return parent;
942 }
943
944 if (Utils.isArray(parent)) {
945 child = [];
946 } else if (Utils.isRegExp(parent)) {
947 child = new RegExp(parent.source, util.getRegExpFlags(parent));
948 if (parent.lastIndex) child.lastIndex = parent.lastIndex;
949 } else if (Utils.isDate(parent)) {
950 child = new Date(parent.getTime());
951 } else if (useBuffer && Buffer.isBuffer(parent)) {
952 child = new Buffer(parent.length);
953 parent.copy(child);
954 return child;
955 } else {
956 if (typeof prototype === 'undefined') child = Object.create(Object.getPrototypeOf(parent));
957 else child = Object.create(prototype);
958 }
959
960 if (circular) {
961 var index = allParents.indexOf(parent);
962
963 if (index != -1) {
964 return allChildren[index];
965 }
966 allParents.push(parent);
967 allChildren.push(child);
968 }
969
970 for (var i in parent) {
971 var propDescriptor = Object.getOwnPropertyDescriptor(parent,i);
972 var hasGetter = ((propDescriptor !== undefined) && (propDescriptor.get !== undefined));
973
974 if (hasGetter){
975 Object.defineProperty(child,i,propDescriptor);
976 } else if (util.isPromise(parent[i])) {
977 child[i] = parent[i];
978 } else {
979 child[i] = _clone(parent[i], depth - 1);
980 }
981 }
982
983 return child;
984 }
985
986 return _clone(parent, depth);
987};
988
989/**
990 * Set objects given a path as a string list
991 *
992 * @protected
993 * @method setPath
994 * @param object {object} - Object to set the property on
995 * @param path {array[string]} - Array path to the property
996 * @param value {*} - value to set, ignoring null
997 */
998util.setPath = function (object, path, value) {
999 var nextKey = null;
1000 if (value === null || path.length === 0) {
1001 return;
1002 }
1003 else if (path.length === 1) { // no more keys to make, so set the value
1004 object[path.shift()] = value;
1005 }
1006 else {
1007 nextKey = path.shift();
1008 if (!object.hasOwnProperty(nextKey)) {
1009 object[nextKey] = {};
1010 }
1011 util.setPath(object[nextKey], path, value);
1012 }
1013};
1014
1015/**
1016 * Create a new object patterned after substitutionMap, where:
1017 * 1. Terminal string values in substitutionMap are used as keys
1018 * 2. To look up values in a key-value store, variables
1019 * 3. And parent keys are created as necessary to retain the structure of substitutionMap.
1020 *
1021 * @protected
1022 * @method substituteDeep
1023 * @param substitionMap {object} - an object whose terminal (non-subobject) values are strings
1024 * @param variables {object[string:value]} - usually process.env, a flat object used to transform
1025 * terminal values in a copy of substititionMap.
1026 * @returns {object} - deep copy of substitutionMap with only those paths whose terminal values
1027 * corresponded to a key in `variables`
1028 */
1029util.substituteDeep = function (substitutionMap, variables) {
1030 var result = {};
1031
1032 function _substituteVars(map, vars, pathTo) {
1033 for (var prop in map) {
1034 var value = map[prop];
1035 if (typeof(value) === 'string') { // We found a leaf variable name
1036 if (vars[value] !== undefined) { // if the vars provide a value set the value in the result map
1037 util.setPath(result, pathTo.concat(prop), vars[value]);
1038 }
1039 }
1040 else if (util.isObject(value)) { // work on the subtree, giving it a clone of the pathTo
1041 if ('__name' in value && '__format' in value && vars[value.__name] !== undefined) {
1042 try {
1043 var parsedValue = util.parseString(vars[value.__name], value.__format);
1044 } catch(err) {
1045 err.message = '__format parser error in ' + value.__name + ': ' + err.message;
1046 throw err;
1047 }
1048 util.setPath(result, pathTo.concat(prop), parsedValue);
1049 } else {
1050 _substituteVars(value, vars, pathTo.concat(prop));
1051 }
1052 }
1053 else {
1054 msg = "Illegal key type for substitution map at " + pathTo.join('.') + ': ' + typeof(value);
1055 throw Error(msg);
1056 }
1057 }
1058 }
1059
1060 _substituteVars(substitutionMap, variables, []);
1061 return result;
1062
1063};
1064
1065/* Map environment variables into the configuration if a mapping file,
1066 * `custom-environment-variables.EXT` exists.
1067 *
1068 * @protected
1069 * @method getCustomEnvVars
1070 * @param CONFIG_DIR {string} - the passsed configuration directory
1071 * @param extNames {Array[string]} - acceptable configuration file extension names.
1072 * @returns {object} - mapped environment variables or {} if there are none
1073 */
1074util.getCustomEnvVars = function (CONFIG_DIR, extNames) {
1075 var result = {};
1076 var resolutionIndex = 1;
1077 var allowedFiles = {};
1078 extNames.forEach(function (extName) {
1079 allowedFiles['custom-environment-variables' + '.' + extName] = resolutionIndex++;
1080 });
1081 var locatedFiles = util.locateMatchingFiles(CONFIG_DIR, allowedFiles);
1082 locatedFiles.forEach(function (fullFilename) {
1083 var configObj = util.parseFile(fullFilename);
1084 if (configObj) {
1085 var environmentSubstitutions = util.substituteDeep(configObj, process.env);
1086 util.extendDeep(result, environmentSubstitutions);
1087 }
1088 });
1089 return result;
1090};
1091
1092/**
1093 * Return true if two objects have equal contents.
1094 *
1095 * @protected
1096 * @method equalsDeep
1097 * @param object1 {object} The object to compare from
1098 * @param object2 {object} The object to compare with
1099 * @param depth {integer} An optional depth to prevent recursion. Default: 20.
1100 * @return {boolean} True if both objects have equivalent contents
1101 */
1102util.equalsDeep = function(object1, object2, depth) {
1103
1104 // Recursion detection
1105 var t = this;
1106 depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth);
1107 if (depth < 0) {
1108 return {};
1109 }
1110
1111 // Fast comparisons
1112 if (!object1 || !object2) {
1113 return false;
1114 }
1115 if (object1 === object2) {
1116 return true;
1117 }
1118 if (typeof(object1) != 'object' || typeof(object2) != 'object') {
1119 return false;
1120 }
1121
1122 // They must have the same keys. If their length isn't the same
1123 // then they're not equal. If the keys aren't the same, the value
1124 // comparisons will fail.
1125 if (Object.keys(object1).length != Object.keys(object2).length) {
1126 return false;
1127 }
1128
1129 // Compare the values
1130 for (var prop in object1) {
1131
1132 // Call recursively if an object or array
1133 if (object1[prop] && typeof(object1[prop]) === 'object') {
1134 if (!util.equalsDeep(object1[prop], object2[prop], depth - 1)) {
1135 return false;
1136 }
1137 }
1138 else {
1139 if (object1[prop] !== object2[prop]) {
1140 return false;
1141 }
1142 }
1143 }
1144
1145 // Test passed.
1146 return true;
1147};
1148
1149/**
1150 * Returns an object containing all elements that differ between two objects.
1151 * <p>
1152 * This method was designed to be used to create the runtime.json file
1153 * contents, but can be used to get the diffs between any two Javascript objects.
1154 * </p>
1155 * <p>
1156 * It works best when object2 originated by deep copying object1, then
1157 * changes were made to object2, and you want an object that would give you
1158 * the changes made to object1 which resulted in object2.
1159 * </p>
1160 *
1161 * @protected
1162 * @method diffDeep
1163 * @param object1 {object} The base object to compare to
1164 * @param object2 {object} The object to compare with
1165 * @param depth {integer} An optional depth to prevent recursion. Default: 20.
1166 * @return {object} A differential object, which if extended onto object1 would
1167 * result in object2.
1168 */
1169util.diffDeep = function(object1, object2, depth) {
1170
1171 // Recursion detection
1172 var t = this, diff = {};
1173 depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth);
1174 if (depth < 0) {
1175 return {};
1176 }
1177
1178 // Process each element from object2, adding any element that's different
1179 // from object 1.
1180 for (var parm in object2) {
1181 var value1 = object1[parm];
1182 var value2 = object2[parm];
1183 if (value1 && value2 && util.isObject(value2)) {
1184 if (!(util.equalsDeep(value1, value2))) {
1185 diff[parm] = util.diffDeep(value1, value2, depth - 1);
1186 }
1187 }
1188 else if (Array.isArray(value1) && Array.isArray(value2)) {
1189 if(!util.equalsDeep(value1, value2)) {
1190 diff[parm] = value2;
1191 }
1192 }
1193 else if (value1 !== value2){
1194 diff[parm] = value2;
1195 }
1196 }
1197
1198 // Return the diff object
1199 return diff;
1200
1201};
1202
1203/**
1204 * Extend an object, and any object it contains.
1205 *
1206 * This does not replace deep objects, but dives into them
1207 * replacing individual elements instead.
1208 *
1209 * @protected
1210 * @method extendDeep
1211 * @param mergeInto {object} The object to merge into
1212 * @param mergeFrom... {object...} - Any number of objects to merge from
1213 * @param depth {integer} An optional depth to prevent recursion. Default: 20.
1214 * @return {object} The altered mergeInto object is returned
1215 */
1216util.extendDeep = function(mergeInto) {
1217
1218 // Initialize
1219 var t = this;
1220 var vargs = Array.prototype.slice.call(arguments, 1);
1221 var depth = vargs.pop();
1222 if (typeof(depth) != 'number') {
1223 vargs.push(depth);
1224 depth = DEFAULT_CLONE_DEPTH;
1225 }
1226
1227 // Recursion detection
1228 if (depth < 0) {
1229 return mergeInto;
1230 }
1231
1232 // Cycle through each object to extend
1233 vargs.forEach(function(mergeFrom) {
1234
1235 // Cycle through each element of the object to merge from
1236 for (var prop in mergeFrom) {
1237
1238 // save original value in deferred elements
1239 var fromIsDeferredFunc = mergeFrom[prop] instanceof DeferredConfig;
1240 var isDeferredFunc = mergeInto[prop] instanceof DeferredConfig;
1241
1242 if (fromIsDeferredFunc && mergeInto.hasOwnProperty(prop)) {
1243 mergeFrom[prop]._original = isDeferredFunc ? mergeInto[prop]._original : mergeInto[prop];
1244 }
1245 // Extend recursively if both elements are objects and target is not really a deferred function
1246 if (mergeFrom[prop] instanceof Date) {
1247 mergeInto[prop] = mergeFrom[prop];
1248 } if (mergeFrom[prop] instanceof RegExp) {
1249 mergeInto[prop] = mergeFrom[prop];
1250 } else if (util.isObject(mergeInto[prop]) && util.isObject(mergeFrom[prop]) && !isDeferredFunc) {
1251 util.extendDeep(mergeInto[prop], mergeFrom[prop], depth - 1);
1252 }
1253 else if (util.isPromise(mergeFrom[prop])) {
1254 mergeInto[prop] = mergeFrom[prop];
1255 }
1256 // Copy recursively if the mergeFrom element is an object (or array or fn)
1257 else if (mergeFrom[prop] && typeof mergeFrom[prop] === 'object') {
1258 mergeInto[prop] = util.cloneDeep(mergeFrom[prop], depth -1);
1259 }
1260
1261 // Copy property descriptor otherwise, preserving accessors
1262 else if (Object.getOwnPropertyDescriptor(Object(mergeFrom), prop)){
1263 Object.defineProperty(mergeInto, prop, Object.getOwnPropertyDescriptor(Object(mergeFrom), prop));
1264 } else {
1265 mergeInto[prop] = mergeFrom[prop];
1266 }
1267 }
1268 });
1269
1270 // Chain
1271 return mergeInto;
1272
1273};
1274
1275/**
1276 * Is the specified argument a regular javascript object?
1277 *
1278 * The argument is an object if it's a JS object, but not an array.
1279 *
1280 * @protected
1281 * @method isObject
1282 * @param obj {*} An argument of any type.
1283 * @return {boolean} TRUE if the arg is an object, FALSE if not
1284 */
1285util.isObject = function(obj) {
1286 return (obj !== null) && (typeof obj === 'object') && !(Array.isArray(obj));
1287};
1288
1289/**
1290 * Is the specified argument a javascript promise?
1291 *
1292 * @protected
1293 * @method isPromise
1294 * @param obj {*} An argument of any type.
1295 * @returns {boolean}
1296 */
1297util.isPromise = function(obj) {
1298 return Object.prototype.toString.call(obj) === '[object Promise]';
1299};
1300
1301/**
1302 * <p>Initialize a parameter from the command line or process environment</p>
1303 *
1304 * <p>
1305 * This method looks for the parameter from the command line in the format
1306 * --PARAMETER=VALUE, then from the process environment, then from the
1307 * default specified as an argument.
1308 * </p>
1309 *
1310 * @method initParam
1311 * @param paramName {String} Name of the parameter
1312 * @param [defaultValue] {Any} Default value of the parameter
1313 * @return {Any} The found value, or default value
1314 */
1315util.initParam = function (paramName, defaultValue) {
1316 var t = this;
1317
1318 // Record and return the value
1319 var value = util.getCmdLineArg(paramName) || process.env[paramName] || defaultValue;
1320 env[paramName] = value;
1321 return value;
1322}
1323
1324/**
1325 * <p>Get Command Line Arguments</p>
1326 *
1327 * <p>
1328 * This method allows you to retrieve the value of the specified command line argument.
1329 * </p>
1330 *
1331 * <p>
1332 * The argument is case sensitive, and must be of the form '--ARG_NAME=value'
1333 * </p>
1334 *
1335 * @method getCmdLineArg
1336 * @param searchFor {String} The argument name to search for
1337 * @return {*} false if the argument was not found, the argument value if found
1338 */
1339util.getCmdLineArg = function (searchFor) {
1340 var cmdLineArgs = process.argv.slice(2, process.argv.length),
1341 argName = '--' + searchFor + '=';
1342
1343 for (var argvIt = 0; argvIt < cmdLineArgs.length; argvIt++) {
1344 if (cmdLineArgs[argvIt].indexOf(argName) === 0) {
1345 return cmdLineArgs[argvIt].substr(argName.length);
1346 }
1347 }
1348
1349 return false;
1350}
1351
1352/**
1353 * <p>Get a Config Environment Variable Value</p>
1354 *
1355 * <p>
1356 * This method returns the value of the specified config environment variable,
1357 * including any defaults or overrides.
1358 * </p>
1359 *
1360 * @method getEnv
1361 * @param varName {String} The environment variable name
1362 * @return {String} The value of the environment variable
1363 */
1364util.getEnv = function (varName) {
1365 return env[varName];
1366}
1367
1368
1369
1370/**
1371 * Returns a string of flags for regular expression `re`.
1372 *
1373 * @param {RegExp} re Regular expression
1374 * @returns {string} Flags
1375 */
1376util.getRegExpFlags = function (re) {
1377 var flags = '';
1378 re.global && (flags += 'g');
1379 re.ignoreCase && (flags += 'i');
1380 re.multiline && (flags += 'm');
1381 return flags;
1382};
1383
1384/**
1385 * Returns a new deep copy of the current config object, or any part of the config if provided.
1386 *
1387 * @param {Object} config The part of the config to copy and serialize. Omit this argument to return the entire config.
1388 * @returns {Object} The cloned config or part of the config
1389 */
1390util.toObject = function(config) {
1391 return JSON.parse(JSON.stringify(config || this));
1392};
1393
1394// Run strictness checks on NODE_ENV and NODE_APP_INSTANCE and throw an error if there's a problem.
1395util.runStrictnessChecks = function (config) {
1396 var sources = config.util.getConfigSources();
1397
1398 var sourceFilenames = sources.map(function (src) {
1399 return Path.basename(src.name);
1400 });
1401
1402 NODE_ENV.forEach(function(env) {
1403 // Throw an exception if there's no explicit config file for NODE_ENV
1404 var anyFilesMatchEnv = sourceFilenames.some(function (filename) {
1405 return filename.match(env);
1406 });
1407 // development is special-cased because it's the default value
1408 if (env && (env !== 'development') && !anyFilesMatchEnv) {
1409 _warnOrThrow("NODE_ENV value of '"+env+"' did not match any deployment config file names.");
1410 }
1411 // Throw if NODE_ENV matches' default' or 'local'
1412 if ((env === 'default') || (env === 'local')) {
1413 _warnOrThrow("NODE_ENV value of '"+env+"' is ambiguous.");
1414 }
1415 });
1416
1417 // Throw an exception if there's no explict config file for NODE_APP_INSTANCE
1418 var anyFilesMatchInstance = sourceFilenames.some(function (filename) {
1419 return filename.match(APP_INSTANCE);
1420 });
1421 if (APP_INSTANCE && !anyFilesMatchInstance) {
1422 _warnOrThrow("NODE_APP_INSTANCE value of '"+APP_INSTANCE+"' did not match any instance config file names.");
1423 }
1424
1425 function _warnOrThrow (msg) {
1426 var beStrict = process.env.NODE_CONFIG_STRICT_MODE;
1427 var prefix = beStrict ? 'FATAL: ' : 'WARNING: ';
1428 var seeURL = 'See https://github.com/lorenwest/node-config/wiki/Strict-Mode';
1429
1430 console.error(prefix+msg);
1431 console.error(prefix+seeURL);
1432
1433 // Accept 1 and true as truthy values. When set via process.env, Node.js casts them to strings.
1434 if (["true", "1"].indexOf(beStrict) >= 0) {
1435 throw new Error(prefix+msg+' '+seeURL);
1436 }
1437 }
1438};
1439
1440// Instantiate and export the configuration
1441var config = module.exports = new Config();
1442
1443// copy methods to util for backwards compatibility
1444util.stripComments = Parser.stripComments;
1445util.stripYamlComments = Parser.stripYamlComments;
1446
1447// Produce warnings if the configuration is empty
1448var showWarnings = !(util.initParam('SUPPRESS_NO_CONFIG_WARNING'));
1449if (showWarnings && Object.keys(config).length === 0) {
1450 console.error('WARNING: No configurations found in configuration directory:' +CONFIG_DIR);
1451 console.error('WARNING: To disable this warning set SUPPRESS_NO_CONFIG_WARNING in the environment.');
1452}