index.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /*
  2. * Copyright (c) 2015-present, Vitaly Tomilov
  3. *
  4. * See the LICENSE file at the top-level directory of this distribution
  5. * for licensing information.
  6. *
  7. * Removal or modification of this copyright notice is prohibited.
  8. */
  9. const npm = {
  10. path: require('path'),
  11. util: require('util'),
  12. patterns: require('../patterns')
  13. };
  14. ////////////////////////////////////////////
  15. // Simpler check for null/undefined;
  16. function isNull(value) {
  17. return value === null || value === undefined;
  18. }
  19. ////////////////////////////////////////////////////////
  20. // Verifies parameter for being a non-empty text string;
  21. function isText(txt) {
  22. return txt && typeof txt === 'string' && /\S/.test(txt);
  23. }
  24. ///////////////////////////////////////////////////////////
  25. // Approximates the environment as being for development.
  26. //
  27. // Proper configuration is having NODE_ENV = 'development', but this
  28. // method only checks for 'dev' being present, and regardless of the case.
  29. function isDev() {
  30. const env = global.process.env.NODE_ENV || '';
  31. return env.toLowerCase().indexOf('dev') !== -1;
  32. }
  33. /////////////////////////////////////////////
  34. // Adds properties from source to the target,
  35. // making them read-only and enumerable.
  36. function addReadProperties(target, source) {
  37. for (const p in source) {
  38. addReadProp(target, p, source[p]);
  39. }
  40. }
  41. ///////////////////////////////////////////////////////
  42. // Adds a read-only, non-deletable enumerable property.
  43. function addReadProp(obj, name, value, hidden) {
  44. Object.defineProperty(obj, name, {
  45. value,
  46. configurable: false,
  47. enumerable: !hidden,
  48. writable: false
  49. });
  50. }
  51. //////////////////////////////////////////////////////////////
  52. // Converts a connection string or object into its safe copy:
  53. // if password is present, it is masked with symbol '#'.
  54. function getSafeConnection(cn) {
  55. const maskPassword = cs => cs.replace(/:(?![/])([^@]+)/, (_, m) => ':' + new Array(m.length + 1).join('#'));
  56. if (typeof cn === 'object') {
  57. const copy = Object.assign({}, cn);
  58. if (typeof copy.password === 'string') {
  59. copy.password = copy.password.replace(/./g, '#');
  60. }
  61. if (typeof copy.connectionString === 'string') {
  62. copy.connectionString = maskPassword(copy.connectionString);
  63. }
  64. return copy;
  65. }
  66. return maskPassword(cn);
  67. }
  68. ///////////////////////////////////////////
  69. // Returns a space gap for console output;
  70. function messageGap(level) {
  71. return ' '.repeat(level * 4);
  72. }
  73. /////////////////////////////////////////
  74. // Provides platform-neutral inheritance;
  75. function inherits(child, parent) {
  76. child.prototype.__proto__ = parent.prototype;
  77. }
  78. // istanbul ignore next
  79. function getLocalStack(startIdx, maxLines) {
  80. // from the call stack, we take up to maximum lines,
  81. // starting with specified line index:
  82. startIdx = startIdx || 0;
  83. const endIdx = maxLines > 0 ? startIdx + maxLines : undefined;
  84. return new Error().stack
  85. .split('\n')
  86. .filter(line => line.match(/\(.+\)/))
  87. .slice(startIdx, endIdx)
  88. .join('\n');
  89. }
  90. //////////////////////////////
  91. // Internal error container;
  92. function InternalError(error) {
  93. this.error = error;
  94. }
  95. /////////////////////////////////////////////////////////////////
  96. // Parses a property name, and gets its name from the object,
  97. // if the property exists. Returns object {valid, has, target, value}:
  98. // - valid - true/false, whether the syntax is valid
  99. // - has - a flag that property exists; set when 'valid' = true
  100. // - target - the target object that contains the property; set when 'has' = true
  101. // - value - the value; set when 'has' = true
  102. function getIfHas(obj, prop) {
  103. const result = {valid: true};
  104. if (prop.indexOf('.') === -1) {
  105. result.has = prop in obj;
  106. result.target = obj;
  107. if (result.has) {
  108. result.value = obj[prop];
  109. }
  110. } else {
  111. const names = prop.split('.');
  112. let missing, target;
  113. for (let i = 0; i < names.length; i++) {
  114. const n = names[i];
  115. if (!n) {
  116. result.valid = false;
  117. return result;
  118. }
  119. if (!missing && hasProperty(obj, n)) {
  120. target = obj;
  121. obj = obj[n];
  122. } else {
  123. missing = true;
  124. }
  125. }
  126. result.has = !missing;
  127. if (result.has) {
  128. result.target = target;
  129. result.value = obj;
  130. }
  131. }
  132. return result;
  133. }
  134. /////////////////////////////////////////////////////////////////////////
  135. // Checks if the property exists in the object or value or its prototype;
  136. function hasProperty(value, prop) {
  137. return (value && typeof value === 'object' && prop in value) ||
  138. value !== null && value !== undefined && value[prop] !== undefined;
  139. }
  140. ////////////////////////////////////////////////////////
  141. // Adds prototype inspection
  142. function addInspection(type, cb) {
  143. type.prototype[npm.util.inspect.custom] = cb;
  144. }
  145. /////////////////////////////////////////////////////////////////////////////////////////
  146. // Identifies a general connectivity error, after which no more queries can be executed.
  147. // This is for detecting when to skip executing ROLLBACK for a failed transaction.
  148. function isConnectivityError(err) {
  149. const code = err && typeof err.code === 'string' && err.code;
  150. const cls = code && code.substring(0, 2); // Error Class
  151. // istanbul ignore next (we cannot test-cover all error cases):
  152. return code === 'ECONNRESET' || (cls === '08' && code !== '08P01') || (cls === '57' && code !== '57014');
  153. // Code 'ECONNRESET' - Connectivity issue handled by the driver.
  154. // Class 08 - Connection Exception (except for 08P01, for protocol violation).
  155. // Class 57 - Operator Intervention (except for 57014, for cancelled queries).
  156. //
  157. // ERROR CODES: https://www.postgresql.org/docs/9.6/static/errcodes-appendix.html
  158. }
  159. ///////////////////////////////////////////////////////////////
  160. // Does JSON.stringify, with support for BigInt (irreversible)
  161. function toJson(data) {
  162. if (data !== undefined) {
  163. return JSON.stringify(data, (_, v) => typeof v === 'bigint' ? `${v}#bigint` : v)
  164. .replace(/"(-?\d+)#bigint"/g, (_, a) => a);
  165. }
  166. }
  167. const exp = {
  168. toJson,
  169. getIfHas,
  170. addInspection,
  171. InternalError,
  172. getLocalStack,
  173. isText,
  174. isNull,
  175. isDev,
  176. addReadProp,
  177. addReadProperties,
  178. getSafeConnection,
  179. messageGap,
  180. inherits,
  181. isConnectivityError
  182. };
  183. const mainFile = process.argv[1];
  184. // istanbul ignore next
  185. exp.startDir = mainFile ? npm.path.dirname(mainFile) : process.cwd();
  186. module.exports = exp;