splat.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. 'use strict';
  2. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  3. function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
  4. function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  5. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  6. function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
  7. function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
  8. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
  9. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
  11. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
  13. function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  14. var util = require('util');
  15. var _require = require('triple-beam'),
  16. SPLAT = _require.SPLAT;
  17. /**
  18. * Captures the number of format (i.e. %s strings) in a given string.
  19. * Based on `util.format`, see Node.js source:
  20. * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230
  21. * @type {RegExp}
  22. */
  23. var formatRegExp = /%[scdjifoO%]/g;
  24. /**
  25. * Captures the number of escaped % signs in a format string (i.e. %s strings).
  26. * @type {RegExp}
  27. */
  28. var escapedPercent = /%%/g;
  29. var Splatter = /*#__PURE__*/function () {
  30. function Splatter(opts) {
  31. _classCallCheck(this, Splatter);
  32. this.options = opts;
  33. }
  34. /**
  35. * Check to see if tokens <= splat.length, assign { splat, meta } into the
  36. * `info` accordingly, and write to this instance.
  37. *
  38. * @param {Info} info Logform info message.
  39. * @param {String[]} tokens Set of string interpolation tokens.
  40. * @returns {Info} Modified info message
  41. * @private
  42. */
  43. _createClass(Splatter, [{
  44. key: "_splat",
  45. value: function _splat(info, tokens) {
  46. var msg = info.message;
  47. var splat = info[SPLAT] || info.splat || [];
  48. var percents = msg.match(escapedPercent);
  49. var escapes = percents && percents.length || 0;
  50. // The expected splat is the number of tokens minus the number of escapes
  51. // e.g.
  52. // - { expectedSplat: 3 } '%d %s %j'
  53. // - { expectedSplat: 5 } '[%s] %d%% %d%% %s %j'
  54. //
  55. // Any "meta" will be arugments in addition to the expected splat size
  56. // regardless of type. e.g.
  57. //
  58. // logger.log('info', '%d%% %s %j', 100, 'wow', { such: 'js' }, { thisIsMeta: true });
  59. // would result in splat of four (4), but only three (3) are expected. Therefore:
  60. //
  61. // extraSplat = 3 - 4 = -1
  62. // metas = [100, 'wow', { such: 'js' }, { thisIsMeta: true }].splice(-1, -1 * -1);
  63. // splat = [100, 'wow', { such: 'js' }]
  64. var expectedSplat = tokens.length - escapes;
  65. var extraSplat = expectedSplat - splat.length;
  66. var metas = extraSplat < 0 ? splat.splice(extraSplat, -1 * extraSplat) : [];
  67. // Now that { splat } has been separated from any potential { meta }. we
  68. // can assign this to the `info` object and write it to our format stream.
  69. // If the additional metas are **NOT** objects or **LACK** enumerable properties
  70. // you are going to have a bad time.
  71. var metalen = metas.length;
  72. if (metalen) {
  73. for (var i = 0; i < metalen; i++) {
  74. Object.assign(info, metas[i]);
  75. }
  76. }
  77. info.message = util.format.apply(util, [msg].concat(_toConsumableArray(splat)));
  78. return info;
  79. }
  80. /**
  81. * Transforms the `info` message by using `util.format` to complete
  82. * any `info.message` provided it has string interpolation tokens.
  83. * If no tokens exist then `info` is immutable.
  84. *
  85. * @param {Info} info Logform info message.
  86. * @param {Object} opts Options for this instance.
  87. * @returns {Info} Modified info message
  88. */
  89. }, {
  90. key: "transform",
  91. value: function transform(info) {
  92. var msg = info.message;
  93. var splat = info[SPLAT] || info.splat;
  94. // No need to process anything if splat is undefined
  95. if (!splat || !splat.length) {
  96. return info;
  97. }
  98. // Extract tokens, if none available default to empty array to
  99. // ensure consistancy in expected results
  100. var tokens = msg && msg.match && msg.match(formatRegExp);
  101. // This condition will take care of inputs with info[SPLAT]
  102. // but no tokens present
  103. if (!tokens && (splat || splat.length)) {
  104. var metas = splat.length > 1 ? splat.splice(0) : splat;
  105. // Now that { splat } has been separated from any potential { meta }. we
  106. // can assign this to the `info` object and write it to our format stream.
  107. // If the additional metas are **NOT** objects or **LACK** enumerable properties
  108. // you are going to have a bad time.
  109. var metalen = metas.length;
  110. if (metalen) {
  111. for (var i = 0; i < metalen; i++) {
  112. Object.assign(info, metas[i]);
  113. }
  114. }
  115. return info;
  116. }
  117. if (tokens) {
  118. return this._splat(info, tokens);
  119. }
  120. return info;
  121. }
  122. }]);
  123. return Splatter;
  124. }();
  125. /*
  126. * function splat (info)
  127. * Returns a new instance of the splat format TransformStream
  128. * which performs string interpolation from `info` objects. This was
  129. * previously exposed implicitly in `winston < 3.0.0`.
  130. */
  131. module.exports = function (opts) {
  132. return new Splatter(opts);
  133. };