index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. 'use strict';
  2. var has = Object.prototype.hasOwnProperty;
  3. /**
  4. * Gather environment variables from various locations.
  5. *
  6. * @param {Object} environment The default environment variables.
  7. * @returns {Object} environment.
  8. * @api public
  9. */
  10. function env(environment) {
  11. environment = environment || {};
  12. if ('object' === typeof process && 'object' === typeof process.env) {
  13. env.merge(environment, process.env);
  14. }
  15. if ('undefined' !== typeof window) {
  16. if ('string' === window.name && window.name.length) {
  17. env.merge(environment, env.parse(window.name));
  18. }
  19. if (window.localStorage) {
  20. try { env.merge(environment, env.parse(window.localStorage.env || window.localStorage.debug)); }
  21. catch (e) {}
  22. }
  23. if (
  24. 'object' === typeof window.location
  25. && 'string' === typeof window.location.hash
  26. && window.location.hash.length
  27. ) {
  28. env.merge(environment, env.parse(window.location.hash.charAt(0) === '#'
  29. ? window.location.hash.slice(1)
  30. : window.location.hash
  31. ));
  32. }
  33. }
  34. //
  35. // Also add lower case variants to the object for easy access.
  36. //
  37. var key, lower;
  38. for (key in environment) {
  39. lower = key.toLowerCase();
  40. if (!(lower in environment)) {
  41. environment[lower] = environment[key];
  42. }
  43. }
  44. return environment;
  45. }
  46. /**
  47. * A poor man's merge utility.
  48. *
  49. * @param {Object} base Object where the add object is merged in.
  50. * @param {Object} add Object that needs to be added to the base object.
  51. * @returns {Object} base
  52. * @api private
  53. */
  54. env.merge = function merge(base, add) {
  55. for (var key in add) {
  56. if (has.call(add, key)) {
  57. base[key] = add[key];
  58. }
  59. }
  60. return base;
  61. };
  62. /**
  63. * A poor man's query string parser.
  64. *
  65. * @param {String} query The query string that needs to be parsed.
  66. * @returns {Object} Key value mapped query string.
  67. * @api private
  68. */
  69. env.parse = function parse(query) {
  70. var parser = /([^=?&]+)=([^&]*)/g
  71. , result = {}
  72. , part;
  73. if (!query) return result;
  74. for (;
  75. part = parser.exec(query);
  76. result[decodeURIComponent(part[1])] = decodeURIComponent(part[2])
  77. );
  78. return result.env || result;
  79. };
  80. //
  81. // Expose the module
  82. //
  83. module.exports = env;