index.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const url_1 = require("url");
  4. const lodash_1 = require("./lodash");
  5. exports.defaults = lodash_1.defaults;
  6. exports.noop = lodash_1.noop;
  7. exports.flatten = lodash_1.flatten;
  8. const debug_1 = require("./debug");
  9. exports.Debug = debug_1.default;
  10. const TLSProfiles_1 = require("../constants/TLSProfiles");
  11. /**
  12. * Test if two buffers are equal
  13. *
  14. * @export
  15. * @param {Buffer} a
  16. * @param {Buffer} b
  17. * @returns {boolean} Whether the two buffers are equal
  18. */
  19. function bufferEqual(a, b) {
  20. if (typeof a.equals === "function") {
  21. return a.equals(b);
  22. }
  23. if (a.length !== b.length) {
  24. return false;
  25. }
  26. for (let i = 0; i < a.length; ++i) {
  27. if (a[i] !== b[i]) {
  28. return false;
  29. }
  30. }
  31. return true;
  32. }
  33. exports.bufferEqual = bufferEqual;
  34. /**
  35. * Convert a buffer to string, supports buffer array
  36. *
  37. * @param {*} value - The input value
  38. * @param {string} encoding - string encoding
  39. * @return {*} The result
  40. * @example
  41. * ```js
  42. * var input = [Buffer.from('foo'), [Buffer.from('bar')]]
  43. * var res = convertBufferToString(input, 'utf8')
  44. * expect(res).to.eql(['foo', ['bar']])
  45. * ```
  46. * @private
  47. */
  48. function convertBufferToString(value, encoding) {
  49. if (value instanceof Buffer) {
  50. return value.toString(encoding);
  51. }
  52. if (Array.isArray(value)) {
  53. const length = value.length;
  54. const res = Array(length);
  55. for (let i = 0; i < length; ++i) {
  56. res[i] =
  57. value[i] instanceof Buffer && encoding === "utf8"
  58. ? value[i].toString()
  59. : convertBufferToString(value[i], encoding);
  60. }
  61. return res;
  62. }
  63. return value;
  64. }
  65. exports.convertBufferToString = convertBufferToString;
  66. /**
  67. * Convert a list of results to node-style
  68. *
  69. * @param {Array} arr - The input value
  70. * @return {Array} The output value
  71. * @example
  72. * ```js
  73. * var input = ['a', 'b', new Error('c'), 'd']
  74. * var output = exports.wrapMultiResult(input)
  75. * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd'])
  76. * ```
  77. * @private
  78. */
  79. function wrapMultiResult(arr) {
  80. // When using WATCH/EXEC transactions, the EXEC will return
  81. // a null instead of an array
  82. if (!arr) {
  83. return null;
  84. }
  85. const result = [];
  86. const length = arr.length;
  87. for (let i = 0; i < length; ++i) {
  88. const item = arr[i];
  89. if (item instanceof Error) {
  90. result.push([item]);
  91. }
  92. else {
  93. result.push([null, item]);
  94. }
  95. }
  96. return result;
  97. }
  98. exports.wrapMultiResult = wrapMultiResult;
  99. /**
  100. * Detect if the argument is a int
  101. *
  102. * @param {string} value
  103. * @return {boolean} Whether the value is a int
  104. * @example
  105. * ```js
  106. * > isInt('123')
  107. * true
  108. * > isInt('123.3')
  109. * false
  110. * > isInt('1x')
  111. * false
  112. * > isInt(123)
  113. * true
  114. * > isInt(true)
  115. * false
  116. * ```
  117. * @private
  118. */
  119. function isInt(value) {
  120. const x = parseFloat(value);
  121. return !isNaN(value) && (x | 0) === x;
  122. }
  123. exports.isInt = isInt;
  124. /**
  125. * Pack an array to an Object
  126. *
  127. * @param {array} array
  128. * @return {object}
  129. * @example
  130. * ```js
  131. * > packObject(['a', 'b', 'c', 'd'])
  132. * { a: 'b', c: 'd' }
  133. * ```
  134. */
  135. function packObject(array) {
  136. const result = {};
  137. const length = array.length;
  138. for (let i = 1; i < length; i += 2) {
  139. result[array[i - 1]] = array[i];
  140. }
  141. return result;
  142. }
  143. exports.packObject = packObject;
  144. /**
  145. * Return a callback with timeout
  146. *
  147. * @param {function} callback
  148. * @param {number} timeout
  149. * @return {function}
  150. */
  151. function timeout(callback, timeout) {
  152. let timer;
  153. const run = function () {
  154. if (timer) {
  155. clearTimeout(timer);
  156. timer = null;
  157. callback.apply(this, arguments);
  158. }
  159. };
  160. timer = setTimeout(run, timeout, new Error("timeout"));
  161. return run;
  162. }
  163. exports.timeout = timeout;
  164. /**
  165. * Convert an object to an array
  166. *
  167. * @param {object} obj
  168. * @return {array}
  169. * @example
  170. * ```js
  171. * > convertObjectToArray({ a: '1' })
  172. * ['a', '1']
  173. * ```
  174. */
  175. function convertObjectToArray(obj) {
  176. const result = [];
  177. const keys = Object.keys(obj); // Object.entries requires node 7+
  178. for (let i = 0, l = keys.length; i < l; i++) {
  179. result.push(keys[i], obj[keys[i]]);
  180. }
  181. return result;
  182. }
  183. exports.convertObjectToArray = convertObjectToArray;
  184. /**
  185. * Convert a map to an array
  186. *
  187. * @param {Map} map
  188. * @return {array}
  189. * @example
  190. * ```js
  191. * > convertMapToArray(new Map([[1, '2']]))
  192. * [1, '2']
  193. * ```
  194. */
  195. function convertMapToArray(map) {
  196. const result = [];
  197. let pos = 0;
  198. map.forEach(function (value, key) {
  199. result[pos] = key;
  200. result[pos + 1] = value;
  201. pos += 2;
  202. });
  203. return result;
  204. }
  205. exports.convertMapToArray = convertMapToArray;
  206. /**
  207. * Convert a non-string arg to a string
  208. *
  209. * @param {*} arg
  210. * @return {string}
  211. */
  212. function toArg(arg) {
  213. if (arg === null || typeof arg === "undefined") {
  214. return "";
  215. }
  216. return String(arg);
  217. }
  218. exports.toArg = toArg;
  219. /**
  220. * Optimize error stack
  221. *
  222. * @param {Error} error - actually error
  223. * @param {string} friendlyStack - the stack that more meaningful
  224. * @param {string} filterPath - only show stacks with the specified path
  225. */
  226. function optimizeErrorStack(error, friendlyStack, filterPath) {
  227. const stacks = friendlyStack.split("\n");
  228. let lines = "";
  229. let i;
  230. for (i = 1; i < stacks.length; ++i) {
  231. if (stacks[i].indexOf(filterPath) === -1) {
  232. break;
  233. }
  234. }
  235. for (let j = i; j < stacks.length; ++j) {
  236. lines += "\n" + stacks[j];
  237. }
  238. const pos = error.stack.indexOf("\n");
  239. error.stack = error.stack.slice(0, pos) + lines;
  240. return error;
  241. }
  242. exports.optimizeErrorStack = optimizeErrorStack;
  243. /**
  244. * Parse the redis protocol url
  245. *
  246. * @param {string} url - the redis protocol url
  247. * @return {Object}
  248. */
  249. function parseURL(url) {
  250. if (isInt(url)) {
  251. return { port: url };
  252. }
  253. let parsed = url_1.parse(url, true, true);
  254. if (!parsed.slashes && url[0] !== "/") {
  255. url = "//" + url;
  256. parsed = url_1.parse(url, true, true);
  257. }
  258. const options = parsed.query || {};
  259. const allowUsernameInURI = options.allowUsernameInURI && options.allowUsernameInURI !== "false";
  260. delete options.allowUsernameInURI;
  261. const result = {};
  262. if (parsed.auth) {
  263. const index = parsed.auth.indexOf(":");
  264. if (allowUsernameInURI) {
  265. result.username =
  266. index === -1 ? parsed.auth : parsed.auth.slice(0, index);
  267. }
  268. result.password = index === -1 ? "" : parsed.auth.slice(index + 1);
  269. }
  270. if (parsed.pathname) {
  271. if (parsed.protocol === "redis:" || parsed.protocol === "rediss:") {
  272. if (parsed.pathname.length > 1) {
  273. result.db = parsed.pathname.slice(1);
  274. }
  275. }
  276. else {
  277. result.path = parsed.pathname;
  278. }
  279. }
  280. if (parsed.host) {
  281. result.host = parsed.hostname;
  282. }
  283. if (parsed.port) {
  284. result.port = parsed.port;
  285. }
  286. lodash_1.defaults(result, options);
  287. return result;
  288. }
  289. exports.parseURL = parseURL;
  290. /**
  291. * Resolve TLS profile shortcut in connection options
  292. *
  293. * @param {Object} options - the redis connection options
  294. * @return {Object}
  295. */
  296. function resolveTLSProfile(options) {
  297. let tls = options === null || options === void 0 ? void 0 : options.tls;
  298. if (typeof tls === "string")
  299. tls = { profile: tls };
  300. const profile = TLSProfiles_1.default[tls === null || tls === void 0 ? void 0 : tls.profile];
  301. if (profile) {
  302. tls = Object.assign({}, profile, tls);
  303. delete tls.profile;
  304. options = Object.assign({}, options, { tls });
  305. }
  306. return options;
  307. }
  308. exports.resolveTLSProfile = resolveTLSProfile;
  309. /**
  310. * Get a random element from `array`
  311. *
  312. * @export
  313. * @template T
  314. * @param {T[]} array the array
  315. * @param {number} [from=0] start index
  316. * @returns {T}
  317. */
  318. function sample(array, from = 0) {
  319. const length = array.length;
  320. if (from >= length) {
  321. return;
  322. }
  323. return array[from + Math.floor(Math.random() * (length - from))];
  324. }
  325. exports.sample = sample;
  326. /**
  327. * Shuffle the array using the Fisher-Yates Shuffle.
  328. * This method will mutate the original array.
  329. *
  330. * @export
  331. * @template T
  332. * @param {T[]} array
  333. * @returns {T[]}
  334. */
  335. function shuffle(array) {
  336. let counter = array.length;
  337. // While there are elements in the array
  338. while (counter > 0) {
  339. // Pick a random index
  340. const index = Math.floor(Math.random() * counter);
  341. // Decrease counter by 1
  342. counter--;
  343. // And swap the last element with it
  344. [array[counter], array[index]] = [array[index], array[counter]];
  345. }
  346. return array;
  347. }
  348. exports.shuffle = shuffle;
  349. /**
  350. * Error message for connection being disconnected
  351. */
  352. exports.CONNECTION_CLOSED_ERROR_MSG = "Connection is closed.";
  353. function zipMap(keys, values) {
  354. const map = new Map();
  355. keys.forEach((key, index) => {
  356. map.set(key, values[index]);
  357. });
  358. return map;
  359. }
  360. exports.zipMap = zipMap;