splunk-events
Advanced tools
Comparing version 1.6.1 to 1.7.0
@@ -10,2 +10,6 @@ # Changelog | ||
## [1.7.0] - 2021-10-28 | ||
### Changed | ||
- Separate debounce and exponential backoff into `Strategy` classes. | ||
## [1.6.1] - 2021-10-26 | ||
@@ -12,0 +16,0 @@ ### Fixed |
/*! | ||
* splunk-events v1.6.1 | ||
* splunk-events v1.7.0 | ||
* Copyright (c) VTEX | ||
@@ -104,2 +104,104 @@ * Released under the MIT License. | ||
var DEFAULT_DEBOUNCE_TIME = 2000; | ||
var DebounceStrategy = /** @class */ (function () { | ||
function DebounceStrategy(_a) { | ||
var _this = this; | ||
var _b = _a.debounceTime, debounceTime = _b === void 0 ? DEFAULT_DEBOUNCE_TIME : _b, autoRetryFlush = _a.autoRetryFlush, sendEvents = _a.sendEvents; | ||
this.pendingEvents = []; | ||
this.events = []; | ||
this.isSendingEvents = false; | ||
this.flushPending = false; | ||
this.flushImpl = function () { | ||
if (_this.isSendingEvents) { | ||
_this.flushPending = true; | ||
return; | ||
} | ||
_this.pendingEvents = Array.from(_this.events); | ||
_this.events = []; | ||
_this.isSendingEvents = true; | ||
_this.sendEvents(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (!_this.flushPending) { | ||
return; | ||
} | ||
_this.flushPending = false; | ||
return _this.flushImpl(); | ||
})["catch"](function () { | ||
_this.events = _this.events.concat(_this.pendingEvents); | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (_this.autoRetryFlush) { | ||
_this.flushEvents(); | ||
} | ||
}); | ||
}; | ||
this.flushEvents = debounce(this.flushImpl, debounceTime); | ||
this.autoRetryFlush = autoRetryFlush; | ||
this.sendEvents = sendEvents; | ||
} | ||
DebounceStrategy.prototype.abort = function () { | ||
this.flushEvents.clear(); | ||
}; | ||
DebounceStrategy.prototype.addEvent = function (event) { | ||
this.events.push(event); | ||
}; | ||
return DebounceStrategy; | ||
}()); | ||
var DEFAULT_EXPONENTIAL_BACKOFF_LIMIT = 60000; | ||
var ExponentialBackoffStrategy = /** @class */ (function () { | ||
function ExponentialBackoffStrategy(_a) { | ||
var sendEvents = _a.sendEvents, _b = _a.exponentialBackoffLimit, exponentialBackoffLimit = _b === void 0 ? DEFAULT_EXPONENTIAL_BACKOFF_LIMIT : _b, maxNumberOfRetries = _a.maxNumberOfRetries; | ||
this.isBackoffInProgress = false; | ||
this.maxNumberOfRetries = Infinity; | ||
this.events = []; | ||
this.pendingEvents = []; | ||
this.sendEvents = sendEvents; | ||
this.exponentialBackoffLimit = exponentialBackoffLimit; | ||
this.maxNumberOfRetries = maxNumberOfRetries !== null && maxNumberOfRetries !== void 0 ? maxNumberOfRetries : this.maxNumberOfRetries; | ||
} | ||
ExponentialBackoffStrategy.prototype.addEvent = function (event) { | ||
this.events.push(event); | ||
}; | ||
ExponentialBackoffStrategy.prototype.flushEvents = function () { | ||
var _this = this; | ||
if (this.isBackoffInProgress) { | ||
return Promise.resolve(); | ||
} | ||
this.isBackoffInProgress = true; | ||
var backoffMultiplier = 2; | ||
var executeFlush = function (depth) { | ||
if (depth === void 0) { depth = 0; } | ||
_this.pendingEvents = _this.pendingEvents.concat(_this.events); | ||
_this.events = []; | ||
return _this.sendEvents(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isBackoffInProgress = false; | ||
if (_this.events.length > 0) { | ||
return _this.flushEvents(); | ||
} | ||
return Promise.resolve(); | ||
})["catch"](function () { | ||
var waitTime = Math.pow(backoffMultiplier, depth) * 1000; | ||
if (depth > _this.maxNumberOfRetries) { | ||
_this.events = []; | ||
_this.isBackoffInProgress = false; | ||
return; | ||
} | ||
return new Promise(function (resolve, reject) { | ||
setTimeout(function () { | ||
executeFlush(depth + 1) | ||
.then(resolve, reject)["catch"](reject); | ||
}, Math.min(waitTime, _this.exponentialBackoffLimit)); | ||
}); | ||
}); | ||
}; | ||
return executeFlush(); | ||
}; | ||
return ExponentialBackoffStrategy; | ||
}()); | ||
function fetchRequest(context) { | ||
@@ -120,4 +222,3 @@ if ((typeof window !== 'undefined' && typeof window.fetch !== 'function') || | ||
var DEFAULT_EXPONENTIAL_BACKOFF_LIMIT = 60000; | ||
var DEFAULT_DEBOUNCE_TIME = 2000; | ||
var DEFAULT_USE_EXPONENTIAL_BACKOFF = false; | ||
var SplunkEvents = /** @class */ (function () { | ||
@@ -128,19 +229,11 @@ function SplunkEvents(config) { | ||
this.autoFlush = true; | ||
this.autoRetryFlush = true; | ||
this.debounceTime = DEFAULT_DEBOUNCE_TIME; | ||
this.debug = false; | ||
this.events = []; | ||
this.host = '-'; | ||
this.injectAdditionalInfo = false; | ||
this.injectTimestamp = false; | ||
this.isSendingEvents = false; | ||
this.path = '/services/collector/event'; | ||
this.pendingEvents = []; | ||
this.shouldParseEventData = true; | ||
this.source = 'log'; | ||
this.flushPending = false; | ||
this.useExponentialBackoff = false; | ||
this.exponentialBackoffLimit = DEFAULT_EXPONENTIAL_BACKOFF_LIMIT; | ||
this.isBackoffInProgress = false; | ||
this.maxNumberOfRetries = Infinity; | ||
this.configured = false; | ||
this.flushStrategy = null; | ||
/** | ||
@@ -171,2 +264,5 @@ * Logs an event to Splunk. | ||
if (account === void 0) { account = ''; } | ||
if (_this.flushStrategy == null) { | ||
throw new Error('SplunkEvents instance is not configured properly'); | ||
} | ||
_this.validateEvent(eventData); | ||
@@ -182,20 +278,8 @@ var eventObj = __assign(__assign({ level: level, | ||
var data = __assign(__assign({ sourcetype: _this.source, host: _this.host }, (_this.injectTimestamp && { time: +new Date() })), { event: event }); | ||
_this.events.push(data); | ||
_this.flushStrategy.addEvent(data); | ||
if (_this.autoFlush) { | ||
_this.flushEvents(); | ||
_this.flushStrategy.flushEvents(); | ||
} | ||
}; | ||
/** | ||
* Internal flush that contains the logic for debouncing or | ||
* backing off exponentially. | ||
*/ | ||
this.flushEvents = function () { | ||
if (_this.useExponentialBackoff) { | ||
_this._backoffFlush(); | ||
} | ||
else { | ||
_this.debouncedFlush(); | ||
} | ||
}; | ||
/** | ||
* Flushes pending events into one single request. | ||
@@ -206,108 +290,52 @@ * | ||
*/ | ||
this.flush = function (events) { | ||
if (events === void 0) { events = _this.events; } | ||
return __awaiter(_this, void 0, void 0, function () { | ||
var splunkBatchedFormattedEvents; | ||
var _this = this; | ||
var _a; | ||
return __generator(this, function (_b) { | ||
this.validateConfig(); | ||
if (events.length === 0) { | ||
return [2 /*return*/]; | ||
} | ||
if (this.debug) { | ||
console.log("sending " + events.length + " events to splunk"); | ||
} | ||
splunkBatchedFormattedEvents = this.formatEventsForSplunkBatch(events); | ||
return [2 /*return*/, this.request({ | ||
url: "" + this.endpoint + this.path, | ||
method: 'POST', | ||
data: splunkBatchedFormattedEvents, | ||
headers: (_a = this.headers) !== null && _a !== void 0 ? _a : {}, | ||
responseType: 'json', | ||
}) | ||
.then(function () { | ||
if (_this.debug) { | ||
console.log(events.length + " events successfuly sent to splunk"); | ||
} | ||
})["catch"](function (e) { | ||
if (_this.debug) { | ||
console.warn('Error sending events to splunk.', e); | ||
} | ||
throw e; | ||
})]; | ||
}); | ||
}); | ||
}; | ||
this._backoffFlush = function () { | ||
if (_this.isBackoffInProgress) { | ||
return Promise.resolve(); | ||
} | ||
_this.isBackoffInProgress = true; | ||
var backoffMultiplier = 2; | ||
var executeFlush = function (depth) { | ||
if (depth === void 0) { depth = 0; } | ||
_this.pendingEvents = _this.pendingEvents.concat(_this.events); | ||
_this.events = []; | ||
return _this.flush(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isBackoffInProgress = false; | ||
if (_this.events.length > 0) { | ||
return _this._backoffFlush(); | ||
} | ||
return Promise.resolve(); | ||
})["catch"](function () { | ||
var waitTime = Math.pow(backoffMultiplier, depth) * 1000; | ||
if (depth > _this.maxNumberOfRetries) { | ||
_this.events = []; | ||
_this.isBackoffInProgress = false; | ||
return; | ||
} | ||
return new Promise(function (resolve, reject) { | ||
setTimeout(function () { | ||
executeFlush(depth + 1) | ||
.then(resolve, reject)["catch"](reject); | ||
}, Math.min(waitTime, _this.exponentialBackoffLimit)); | ||
}); | ||
}); | ||
}; | ||
return executeFlush(); | ||
}; | ||
this._debouncedFlush = function () { | ||
if (_this.isSendingEvents) { | ||
_this.flushPending = true; | ||
return; | ||
} | ||
_this.pendingEvents = Array.from(_this.events); | ||
_this.events = []; | ||
_this.isSendingEvents = true; | ||
_this.flush(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (!_this.flushPending) { | ||
return; | ||
this.flush = function (events) { return __awaiter(_this, void 0, void 0, function () { | ||
var splunkBatchedFormattedEvents; | ||
var _this = this; | ||
var _a; | ||
return __generator(this, function (_b) { | ||
this.validateConfig(); | ||
if (!events) { | ||
this.flushStrategy.flushEvents(); | ||
return [2 /*return*/]; | ||
} | ||
_this.flushPending = false; | ||
return _this._debouncedFlush(); | ||
})["catch"](function () { | ||
_this.events = _this.events.concat(_this.pendingEvents); | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (_this.autoRetryFlush) { | ||
_this.flushEvents(); | ||
if (events.length === 0) { | ||
return [2 /*return*/]; | ||
} | ||
if (this.debug) { | ||
console.log("sending " + events.length + " events to splunk"); | ||
} | ||
splunkBatchedFormattedEvents = this.formatEventsForSplunkBatch(events); | ||
return [2 /*return*/, this.request({ | ||
url: "" + this.endpoint + this.path, | ||
method: 'POST', | ||
data: splunkBatchedFormattedEvents, | ||
headers: (_a = this.headers) !== null && _a !== void 0 ? _a : {}, | ||
responseType: 'json', | ||
}) | ||
.then(function () { | ||
if (_this.debug) { | ||
console.log(events.length + " events successfuly sent to splunk"); | ||
} | ||
})["catch"](function (e) { | ||
if (_this.debug) { | ||
console.warn('Error sending events to splunk.', e); | ||
} | ||
throw e; | ||
})]; | ||
}); | ||
}; | ||
this.debouncedFlush = debounce(this._debouncedFlush, this.debounceTime); | ||
if (config) { | ||
this.config(config); | ||
}); }; | ||
if (!config) { | ||
return; | ||
} | ||
this.config(config); | ||
} | ||
/** | ||
* Configure (or reconfigure) this Splunk Event instance. | ||
* Configure this Splunk Event instance. | ||
*/ | ||
SplunkEvents.prototype.config = function (config) { | ||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t; | ||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; | ||
if (this.configured) { | ||
return; | ||
} | ||
this.configured = true; | ||
this.endpoint = (_a = config === null || config === void 0 ? void 0 : config.endpoint) !== null && _a !== void 0 ? _a : this.endpoint; // required | ||
@@ -317,28 +345,34 @@ this.token = (_b = config === null || config === void 0 ? void 0 : config.token) !== null && _b !== void 0 ? _b : this.endpoint; // required | ||
(_d = (_c = config === null || config === void 0 ? void 0 : config.injectAditionalInfo) !== null && _c !== void 0 ? _c : config === null || config === void 0 ? void 0 : config.injectAdditionalInfo) !== null && _d !== void 0 ? _d : this.injectAdditionalInfo; | ||
this.useExponentialBackoff = | ||
(_e = config === null || config === void 0 ? void 0 : config.useExponentialBackoff) !== null && _e !== void 0 ? _e : this.useExponentialBackoff; | ||
this.exponentialBackoffLimit = | ||
(_f = config === null || config === void 0 ? void 0 : config.exponentialBackoffLimit) !== null && _f !== void 0 ? _f : this.exponentialBackoffLimit; | ||
this.autoFlush = this.useExponentialBackoff | ||
? // should always be true when using exponential backoff strategy | ||
true | ||
: (_g = config === null || config === void 0 ? void 0 : config.autoFlush) !== null && _g !== void 0 ? _g : this.autoFlush; | ||
this.autoRetryFlush = (_h = config === null || config === void 0 ? void 0 : config.autoRetryFlush) !== null && _h !== void 0 ? _h : this.autoRetryFlush; | ||
this.source = (_j = config === null || config === void 0 ? void 0 : config.source) !== null && _j !== void 0 ? _j : this.source; | ||
this.path = (_k = config === null || config === void 0 ? void 0 : config.path) !== null && _k !== void 0 ? _k : this.path; | ||
this.host = (_l = config === null || config === void 0 ? void 0 : config.host) !== null && _l !== void 0 ? _l : this.host; | ||
this.debug = (_m = config === null || config === void 0 ? void 0 : config.debug) !== null && _m !== void 0 ? _m : this.debug; | ||
var prevDebounceTime = this.debounceTime; | ||
this.debounceTime = (_o = config === null || config === void 0 ? void 0 : config.debounceTime) !== null && _o !== void 0 ? _o : this.debounceTime; | ||
if (this.debounceTime !== prevDebounceTime) { | ||
this.debouncedFlush.clear(); | ||
this.debouncedFlush = debounce(this._debouncedFlush, this.debounceTime); | ||
this.autoFlush = (_e = config === null || config === void 0 ? void 0 : config.autoFlush) !== null && _e !== void 0 ? _e : this.autoFlush; | ||
this.source = (_f = config === null || config === void 0 ? void 0 : config.source) !== null && _f !== void 0 ? _f : this.source; | ||
this.path = (_g = config === null || config === void 0 ? void 0 : config.path) !== null && _g !== void 0 ? _g : this.path; | ||
this.host = (_h = config === null || config === void 0 ? void 0 : config.host) !== null && _h !== void 0 ? _h : this.host; | ||
this.debug = (_j = config === null || config === void 0 ? void 0 : config.debug) !== null && _j !== void 0 ? _j : this.debug; | ||
this._requestImpl = (_k = config === null || config === void 0 ? void 0 : config.request) !== null && _k !== void 0 ? _k : this._requestImpl; | ||
this.injectTimestamp = (_l = config === null || config === void 0 ? void 0 : config.injectTimestamp) !== null && _l !== void 0 ? _l : this.injectTimestamp; | ||
this.shouldParseEventData = | ||
(_m = config === null || config === void 0 ? void 0 : config.shouldParseEventData) !== null && _m !== void 0 ? _m : this.shouldParseEventData; | ||
this.headers = __assign({ Authorization: "Splunk " + this.token, 'Content-Type': 'application/json' }, ((_o = config === null || config === void 0 ? void 0 : config.headers) !== null && _o !== void 0 ? _o : {})); | ||
var useExponentialBackoff = (_p = config === null || config === void 0 ? void 0 : config.useExponentialBackoff) !== null && _p !== void 0 ? _p : DEFAULT_USE_EXPONENTIAL_BACKOFF; | ||
// Exponential backoff configurations | ||
var exponentialBackoffLimit = config === null || config === void 0 ? void 0 : config.exponentialBackoffLimit; | ||
var maxNumberOfRetries = config === null || config === void 0 ? void 0 : config.maxNumberOfRetries; | ||
// Debounce configurations | ||
var debounceTime = config === null || config === void 0 ? void 0 : config.debounceTime; | ||
var autoRetryFlush = (_q = config === null || config === void 0 ? void 0 : config.autoRetryFlush) !== null && _q !== void 0 ? _q : true; | ||
if (useExponentialBackoff) { | ||
this.autoFlush = true; | ||
this.flushStrategy = new ExponentialBackoffStrategy({ | ||
sendEvents: this.flush, | ||
exponentialBackoffLimit: exponentialBackoffLimit, | ||
maxNumberOfRetries: maxNumberOfRetries, | ||
}); | ||
} | ||
this._requestImpl = (_p = config === null || config === void 0 ? void 0 : config.request) !== null && _p !== void 0 ? _p : this._requestImpl; | ||
this.injectTimestamp = (_q = config === null || config === void 0 ? void 0 : config.injectTimestamp) !== null && _q !== void 0 ? _q : this.injectTimestamp; | ||
this.shouldParseEventData = | ||
(_r = config === null || config === void 0 ? void 0 : config.shouldParseEventData) !== null && _r !== void 0 ? _r : this.shouldParseEventData; | ||
this.maxNumberOfRetries = | ||
(_s = config === null || config === void 0 ? void 0 : config.maxNumberOfRetries) !== null && _s !== void 0 ? _s : this.maxNumberOfRetries; | ||
this.headers = __assign({ Authorization: "Splunk " + this.token, 'Content-Type': 'application/json' }, ((_t = config === null || config === void 0 ? void 0 : config.headers) !== null && _t !== void 0 ? _t : {})); | ||
else { | ||
this.flushStrategy = new DebounceStrategy({ | ||
sendEvents: this.flush, | ||
debounceTime: debounceTime, | ||
autoRetryFlush: autoRetryFlush, | ||
}); | ||
} | ||
}; | ||
@@ -408,2 +442,5 @@ /** | ||
} | ||
if (this.flushStrategy == null) { | ||
throw new Error('Instance must be configured (either by constructor or calling config method) before flushing events'); | ||
} | ||
}; | ||
@@ -410,0 +447,0 @@ return SplunkEvents; |
/*! | ||
* splunk-events v1.6.1 | ||
* splunk-events v1.7.0 | ||
* Copyright (c) VTEX | ||
@@ -20,3 +20,3 @@ * Released under the MIT License. | ||
***************************************************************************** */ | ||
var n=function(){return(n=Object.assign||function(n){for(var e,t=1,o=arguments.length;t<o;t++)for(var i in e=arguments[t])Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n}).apply(this,arguments)};function e(n,e,t,o){return new(t||(t=Promise))((function(i,s){function u(n){try{l(o.next(n))}catch(n){s(n)}}function r(n){try{l(o.throw(n))}catch(n){s(n)}}function l(n){var e;n.done?i(n.value):(e=n.value,e instanceof t?e:new t((function(n){n(e)}))).then(u,r)}l((o=o.apply(n,e||[])).next())}))}function t(n,e){var t,o,i,s,u={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:r(0),throw:r(1),return:r(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function r(s){return function(r){return function(s){if(t)throw new TypeError("Generator is already executing.");for(;u;)try{if(t=1,o&&(i=2&s[0]?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return u.label++,{value:s[1],done:!1};case 5:u.label++,o=s[1],s=[0];continue;case 7:s=u.ops.pop(),u.trys.pop();continue;default:if(!(i=u.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){u=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){u.label=s[1];break}if(6===s[0]&&u.label<i[1]){u.label=i[1],i=s;break}if(i&&u.label<i[2]){u.label=i[2],u.ops.push(s);break}i[2]&&u.ops.pop(),u.trys.pop();continue}s=e.call(n,u)}catch(n){s=[6,n],o=0}finally{t=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,r])}}}function o(n,e){void 0===e&&(e=100);var t=null,o=null,i=function(){for(var i=[],s=0;s<arguments.length;s++)i[s]=arguments[s];return t&&(clearTimeout(t),t=null),new Promise((function(s,u){o=u,t=setTimeout((function(){var e=n.apply(void 0,i);null!=e&&e.then(s).catch(u)}),e)}))};return i.clear=function(){t&&(clearTimeout(t),null==o||o(),t=null)},i}function i(e){return"undefined"!=typeof window&&"function"!=typeof window.fetch||"undefined"!=typeof global&&"function"!=typeof global.fetch?(console.log("Error, using fetchRequest without fetch object"),Promise.resolve(null)):fetch(e.url,n(n({},e),{body:e.data})).then((function(n){return"json"===e.responseType?n.json():n}))}var s=function(){function s(s){var u=this;this._requestImpl=i,this.autoFlush=!0,this.autoRetryFlush=!0,this.debounceTime=2e3,this.debug=!1,this.events=[],this.host="-",this.injectAdditionalInfo=!1,this.injectTimestamp=!1,this.isSendingEvents=!1,this.path="/services/collector/event",this.pendingEvents=[],this.shouldParseEventData=!0,this.source="log",this.flushPending=!1,this.useExponentialBackoff=!1,this.exponentialBackoffLimit=6e4,this.isBackoffInProgress=!1,this.maxNumberOfRetries=1/0,this.logEvent=function(e,t,o,i,s,r){void 0===r&&(r=""),u.validateEvent(s);var l=n(n({level:e,type:t,workflowType:o,workflowInstance:i,account:r},s),u.injectAdditionalInfo?u.getAdditionalInfo():{}),a=u.shouldParseEventData?u.parseEventData(l):l,h=n(n({sourcetype:u.source,host:u.host},u.injectTimestamp&&{time:+new Date}),{event:a});u.events.push(h),u.autoFlush&&u.flushEvents()},this.flushEvents=function(){u.useExponentialBackoff?u._backoffFlush():u.debouncedFlush()},this.flush=function(n){return void 0===n&&(n=u.events),e(u,void 0,void 0,(function(){var e,o,i=this;return t(this,(function(t){return this.validateConfig(),0===n.length?[2]:(this.debug&&console.log("sending "+n.length+" events to splunk"),e=this.formatEventsForSplunkBatch(n),[2,this.request({url:""+this.endpoint+this.path,method:"POST",data:e,headers:null!==(o=this.headers)&&void 0!==o?o:{},responseType:"json"}).then((function(){i.debug&&console.log(n.length+" events successfuly sent to splunk")})).catch((function(n){throw i.debug&&console.warn("Error sending events to splunk.",n),n}))])}))}))},this._backoffFlush=function(){if(u.isBackoffInProgress)return Promise.resolve();u.isBackoffInProgress=!0;var n=function(e){return void 0===e&&(e=0),u.pendingEvents=u.pendingEvents.concat(u.events),u.events=[],u.flush(u.pendingEvents).then((function(){return u.pendingEvents=[],u.isBackoffInProgress=!1,u.events.length>0?u._backoffFlush():Promise.resolve()})).catch((function(){var t=1e3*Math.pow(2,e);return e>u.maxNumberOfRetries?(u.events=[],void(u.isBackoffInProgress=!1)):new Promise((function(o,i){setTimeout((function(){n(e+1).then(o,i).catch(i)}),Math.min(t,u.exponentialBackoffLimit))}))}))};return n()},this._debouncedFlush=function(){u.isSendingEvents?u.flushPending=!0:(u.pendingEvents=Array.from(u.events),u.events=[],u.isSendingEvents=!0,u.flush(u.pendingEvents).then((function(){if(u.pendingEvents=[],u.isSendingEvents=!1,u.flushPending)return u.flushPending=!1,u._debouncedFlush()})).catch((function(){u.events=u.events.concat(u.pendingEvents),u.pendingEvents=[],u.isSendingEvents=!1,u.autoRetryFlush&&u.flushEvents()})))},this.debouncedFlush=o(this._debouncedFlush,this.debounceTime),s&&this.config(s)}return s.prototype.config=function(e){var t,i,s,u,r,l,a,h,c,f,d,v,p,g,b,m,y,E;this.endpoint=null!==(t=null==e?void 0:e.endpoint)&&void 0!==t?t:this.endpoint,this.token=null!==(i=null==e?void 0:e.token)&&void 0!==i?i:this.endpoint,this.injectAdditionalInfo=null!==(u=null!==(s=null==e?void 0:e.injectAditionalInfo)&&void 0!==s?s:null==e?void 0:e.injectAdditionalInfo)&&void 0!==u?u:this.injectAdditionalInfo,this.useExponentialBackoff=null!==(r=null==e?void 0:e.useExponentialBackoff)&&void 0!==r?r:this.useExponentialBackoff,this.exponentialBackoffLimit=null!==(l=null==e?void 0:e.exponentialBackoffLimit)&&void 0!==l?l:this.exponentialBackoffLimit,this.autoFlush=!!this.useExponentialBackoff||(null!==(a=null==e?void 0:e.autoFlush)&&void 0!==a?a:this.autoFlush),this.autoRetryFlush=null!==(h=null==e?void 0:e.autoRetryFlush)&&void 0!==h?h:this.autoRetryFlush,this.source=null!==(c=null==e?void 0:e.source)&&void 0!==c?c:this.source,this.path=null!==(f=null==e?void 0:e.path)&&void 0!==f?f:this.path,this.host=null!==(d=null==e?void 0:e.host)&&void 0!==d?d:this.host,this.debug=null!==(v=null==e?void 0:e.debug)&&void 0!==v?v:this.debug;var w=this.debounceTime;this.debounceTime=null!==(p=null==e?void 0:e.debounceTime)&&void 0!==p?p:this.debounceTime,this.debounceTime!==w&&(this.debouncedFlush.clear(),this.debouncedFlush=o(this._debouncedFlush,this.debounceTime)),this._requestImpl=null!==(g=null==e?void 0:e.request)&&void 0!==g?g:this._requestImpl,this.injectTimestamp=null!==(b=null==e?void 0:e.injectTimestamp)&&void 0!==b?b:this.injectTimestamp,this.shouldParseEventData=null!==(m=null==e?void 0:e.shouldParseEventData)&&void 0!==m?m:this.shouldParseEventData,this.maxNumberOfRetries=null!==(y=null==e?void 0:e.maxNumberOfRetries)&&void 0!==y?y:this.maxNumberOfRetries,this.headers=n({Authorization:"Splunk "+this.token,"Content-Type":"application/json"},null!==(E=null==e?void 0:e.headers)&&void 0!==E?E:{})},s.prototype.request=function(n){return this._requestImpl(n)},s.prototype.parseEventData=function(n){var e="";for(var t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&null!=n[t]){var o=n[t];switch(typeof o){case"string":e+=t+'="'+o.replace(/"/g,"")+'" ';break;case"boolean":case"number":e+=t+"="+o+" ";break;default:throw new Error("Event property must be string, number or boolean")}}return e},s.prototype.validateEvent=function(n){if(null===n)throw new Error("Event must not be null");if(void 0===n)throw new Error("Event must not be undefined");if("object"!=typeof n)throw new Error("Event must be an object")},s.prototype.getAdditionalInfo=function(){if("undefined"==typeof navigator||"undefined"==typeof window)return"";var n=window.screen,e=window.location;return{additional_info:navigator.userAgent.replace(/,/g,";")+","+(navigator.browserLanguage||navigator.language)+","+navigator.platform+","+(n.availWidth||"-")+","+(n.availHeight||"-")+","+e.hostname+","+e.pathname+","+e.protocol.replace(":","")+","+(e.hash||"-")}},s.prototype.formatEventsForSplunkBatch=function(n){return n.map((function(n){return JSON.stringify(n)})).join("\n")},s.prototype.validateConfig=function(){if(null==this.token)throw new Error("Token must not be null nor undefined");if(null==this.endpoint)throw new Error("Endpoint must not be null nor undefined")},s}();export default s; | ||
var t=function(){return(t=Object.assign||function(t){for(var n,e=1,i=arguments.length;e<i;e++)for(var o in n=arguments[e])Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o]);return t}).apply(this,arguments)};function n(t,n,e,i){return new(e||(e=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function u(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var n;t.done?o(t.value):(n=t.value,n instanceof e?n:new e((function(t){t(n)}))).then(r,u)}l((i=i.apply(t,n||[])).next())}))}function e(t,n){var e,i,o,s,r={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function u(s){return function(u){return function(s){if(e)throw new TypeError("Generator is already executing.");for(;r;)try{if(e=1,i&&(o=2&s[0]?i.return:s[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,s[1])).done)return o;switch(i=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return r.label++,{value:s[1],done:!1};case 5:r.label++,i=s[1],s=[0];continue;case 7:s=r.ops.pop(),r.trys.pop();continue;default:if(!(o=r.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){r=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){r.label=s[1];break}if(6===s[0]&&r.label<o[1]){r.label=o[1],o=s;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(s);break}o[2]&&r.ops.pop(),r.trys.pop();continue}s=n.call(t,r)}catch(t){s=[6,t],i=0}finally{e=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}var i=function(){function t(t){var n=this,e=t.debounceTime,i=void 0===e?2e3:e,o=t.autoRetryFlush,s=t.sendEvents;this.pendingEvents=[],this.events=[],this.isSendingEvents=!1,this.flushPending=!1,this.flushImpl=function(){n.isSendingEvents?n.flushPending=!0:(n.pendingEvents=Array.from(n.events),n.events=[],n.isSendingEvents=!0,n.sendEvents(n.pendingEvents).then((function(){if(n.pendingEvents=[],n.isSendingEvents=!1,n.flushPending)return n.flushPending=!1,n.flushImpl()})).catch((function(){n.events=n.events.concat(n.pendingEvents),n.pendingEvents=[],n.isSendingEvents=!1,n.autoRetryFlush&&n.flushEvents()})))},this.flushEvents=function(t,n){void 0===n&&(n=100);var e=null,i=null,o=function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];return e&&(clearTimeout(e),e=null),new Promise((function(s,r){i=r,e=setTimeout((function(){var n=t.apply(void 0,o);null!=n&&n.then(s).catch(r)}),n)}))};return o.clear=function(){e&&(clearTimeout(e),null==i||i(),e=null)},o}(this.flushImpl,i),this.autoRetryFlush=o,this.sendEvents=s}return t.prototype.abort=function(){this.flushEvents.clear()},t.prototype.addEvent=function(t){this.events.push(t)},t}(),o=function(){function t(t){var n=t.sendEvents,e=t.exponentialBackoffLimit,i=void 0===e?6e4:e,o=t.maxNumberOfRetries;this.isBackoffInProgress=!1,this.maxNumberOfRetries=1/0,this.events=[],this.pendingEvents=[],this.sendEvents=n,this.exponentialBackoffLimit=i,this.maxNumberOfRetries=null!=o?o:this.maxNumberOfRetries}return t.prototype.addEvent=function(t){this.events.push(t)},t.prototype.flushEvents=function(){var t=this;if(this.isBackoffInProgress)return Promise.resolve();this.isBackoffInProgress=!0;var n=function(e){return void 0===e&&(e=0),t.pendingEvents=t.pendingEvents.concat(t.events),t.events=[],t.sendEvents(t.pendingEvents).then((function(){return t.pendingEvents=[],t.isBackoffInProgress=!1,t.events.length>0?t.flushEvents():Promise.resolve()})).catch((function(){var i=1e3*Math.pow(2,e);return e>t.maxNumberOfRetries?(t.events=[],void(t.isBackoffInProgress=!1)):new Promise((function(o,s){setTimeout((function(){n(e+1).then(o,s).catch(s)}),Math.min(i,t.exponentialBackoffLimit))}))}))};return n()},t}();function s(n){return"undefined"!=typeof window&&"function"!=typeof window.fetch||"undefined"!=typeof global&&"function"!=typeof global.fetch?(console.log("Error, using fetchRequest without fetch object"),Promise.resolve(null)):fetch(n.url,t(t({},n),{body:n.data})).then((function(t){return"json"===n.responseType?t.json():t}))}var r=function(){function r(i){var o=this;this._requestImpl=s,this.autoFlush=!0,this.debug=!1,this.host="-",this.injectAdditionalInfo=!1,this.injectTimestamp=!1,this.path="/services/collector/event",this.shouldParseEventData=!0,this.source="log",this.configured=!1,this.flushStrategy=null,this.logEvent=function(n,e,i,s,r,u){if(void 0===u&&(u=""),null==o.flushStrategy)throw new Error("SplunkEvents instance is not configured properly");o.validateEvent(r);var l=t(t({level:n,type:e,workflowType:i,workflowInstance:s,account:u},r),o.injectAdditionalInfo?o.getAdditionalInfo():{}),a=o.shouldParseEventData?o.parseEventData(l):l,h=t(t({sourcetype:o.source,host:o.host},o.injectTimestamp&&{time:+new Date}),{event:a});o.flushStrategy.addEvent(h),o.autoFlush&&o.flushStrategy.flushEvents()},this.flush=function(t){return n(o,void 0,void 0,(function(){var n,i,o=this;return e(this,(function(e){return this.validateConfig(),t?0===t.length?[2]:(this.debug&&console.log("sending "+t.length+" events to splunk"),n=this.formatEventsForSplunkBatch(t),[2,this.request({url:""+this.endpoint+this.path,method:"POST",data:n,headers:null!==(i=this.headers)&&void 0!==i?i:{},responseType:"json"}).then((function(){o.debug&&console.log(t.length+" events successfuly sent to splunk")})).catch((function(t){throw o.debug&&console.warn("Error sending events to splunk.",t),t}))]):(this.flushStrategy.flushEvents(),[2])}))}))},i&&this.config(i)}return r.prototype.config=function(n){var e,s,r,u,l,a,h,f,c,d,v,p,g,m,y;if(!this.configured){this.configured=!0,this.endpoint=null!==(e=null==n?void 0:n.endpoint)&&void 0!==e?e:this.endpoint,this.token=null!==(s=null==n?void 0:n.token)&&void 0!==s?s:this.endpoint,this.injectAdditionalInfo=null!==(u=null!==(r=null==n?void 0:n.injectAditionalInfo)&&void 0!==r?r:null==n?void 0:n.injectAdditionalInfo)&&void 0!==u?u:this.injectAdditionalInfo,this.autoFlush=null!==(l=null==n?void 0:n.autoFlush)&&void 0!==l?l:this.autoFlush,this.source=null!==(a=null==n?void 0:n.source)&&void 0!==a?a:this.source,this.path=null!==(h=null==n?void 0:n.path)&&void 0!==h?h:this.path,this.host=null!==(f=null==n?void 0:n.host)&&void 0!==f?f:this.host,this.debug=null!==(c=null==n?void 0:n.debug)&&void 0!==c?c:this.debug,this._requestImpl=null!==(d=null==n?void 0:n.request)&&void 0!==d?d:this._requestImpl,this.injectTimestamp=null!==(v=null==n?void 0:n.injectTimestamp)&&void 0!==v?v:this.injectTimestamp,this.shouldParseEventData=null!==(p=null==n?void 0:n.shouldParseEventData)&&void 0!==p?p:this.shouldParseEventData,this.headers=t({Authorization:"Splunk "+this.token,"Content-Type":"application/json"},null!==(g=null==n?void 0:n.headers)&&void 0!==g?g:{});var E=null!==(m=null==n?void 0:n.useExponentialBackoff)&&void 0!==m&&m,b=null==n?void 0:n.exponentialBackoffLimit,w=null==n?void 0:n.maxNumberOfRetries,k=null==n?void 0:n.debounceTime,P=null===(y=null==n?void 0:n.autoRetryFlush)||void 0===y||y;E?(this.autoFlush=!0,this.flushStrategy=new o({sendEvents:this.flush,exponentialBackoffLimit:b,maxNumberOfRetries:w})):this.flushStrategy=new i({sendEvents:this.flush,debounceTime:k,autoRetryFlush:P})}},r.prototype.request=function(t){return this._requestImpl(t)},r.prototype.parseEventData=function(t){var n="";for(var e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&null!=t[e]){var i=t[e];switch(typeof i){case"string":n+=e+'="'+i.replace(/"/g,"")+'" ';break;case"boolean":case"number":n+=e+"="+i+" ";break;default:throw new Error("Event property must be string, number or boolean")}}return n},r.prototype.validateEvent=function(t){if(null===t)throw new Error("Event must not be null");if(void 0===t)throw new Error("Event must not be undefined");if("object"!=typeof t)throw new Error("Event must be an object")},r.prototype.getAdditionalInfo=function(){if("undefined"==typeof navigator||"undefined"==typeof window)return"";var t=window.screen,n=window.location;return{additional_info:navigator.userAgent.replace(/,/g,";")+","+(navigator.browserLanguage||navigator.language)+","+navigator.platform+","+(t.availWidth||"-")+","+(t.availHeight||"-")+","+n.hostname+","+n.pathname+","+n.protocol.replace(":","")+","+(n.hash||"-")}},r.prototype.formatEventsForSplunkBatch=function(t){return t.map((function(t){return JSON.stringify(t)})).join("\n")},r.prototype.validateConfig=function(){if(null==this.token)throw new Error("Token must not be null nor undefined");if(null==this.endpoint)throw new Error("Endpoint must not be null nor undefined");if(null==this.flushStrategy)throw new Error("Instance must be configured (either by constructor or calling config method) before flushing events")},r}();export default r; | ||
//# sourceMappingURL=splunk-events.esm.min.js.map |
/*! | ||
* splunk-events v1.6.1 | ||
* splunk-events v1.7.0 | ||
* Copyright (c) VTEX | ||
@@ -106,2 +106,104 @@ * Released under the MIT License. | ||
var DEFAULT_DEBOUNCE_TIME = 2000; | ||
var DebounceStrategy = /** @class */ (function () { | ||
function DebounceStrategy(_a) { | ||
var _this = this; | ||
var _b = _a.debounceTime, debounceTime = _b === void 0 ? DEFAULT_DEBOUNCE_TIME : _b, autoRetryFlush = _a.autoRetryFlush, sendEvents = _a.sendEvents; | ||
this.pendingEvents = []; | ||
this.events = []; | ||
this.isSendingEvents = false; | ||
this.flushPending = false; | ||
this.flushImpl = function () { | ||
if (_this.isSendingEvents) { | ||
_this.flushPending = true; | ||
return; | ||
} | ||
_this.pendingEvents = Array.from(_this.events); | ||
_this.events = []; | ||
_this.isSendingEvents = true; | ||
_this.sendEvents(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (!_this.flushPending) { | ||
return; | ||
} | ||
_this.flushPending = false; | ||
return _this.flushImpl(); | ||
})["catch"](function () { | ||
_this.events = _this.events.concat(_this.pendingEvents); | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (_this.autoRetryFlush) { | ||
_this.flushEvents(); | ||
} | ||
}); | ||
}; | ||
this.flushEvents = debounce(this.flushImpl, debounceTime); | ||
this.autoRetryFlush = autoRetryFlush; | ||
this.sendEvents = sendEvents; | ||
} | ||
DebounceStrategy.prototype.abort = function () { | ||
this.flushEvents.clear(); | ||
}; | ||
DebounceStrategy.prototype.addEvent = function (event) { | ||
this.events.push(event); | ||
}; | ||
return DebounceStrategy; | ||
}()); | ||
var DEFAULT_EXPONENTIAL_BACKOFF_LIMIT = 60000; | ||
var ExponentialBackoffStrategy = /** @class */ (function () { | ||
function ExponentialBackoffStrategy(_a) { | ||
var sendEvents = _a.sendEvents, _b = _a.exponentialBackoffLimit, exponentialBackoffLimit = _b === void 0 ? DEFAULT_EXPONENTIAL_BACKOFF_LIMIT : _b, maxNumberOfRetries = _a.maxNumberOfRetries; | ||
this.isBackoffInProgress = false; | ||
this.maxNumberOfRetries = Infinity; | ||
this.events = []; | ||
this.pendingEvents = []; | ||
this.sendEvents = sendEvents; | ||
this.exponentialBackoffLimit = exponentialBackoffLimit; | ||
this.maxNumberOfRetries = maxNumberOfRetries !== null && maxNumberOfRetries !== void 0 ? maxNumberOfRetries : this.maxNumberOfRetries; | ||
} | ||
ExponentialBackoffStrategy.prototype.addEvent = function (event) { | ||
this.events.push(event); | ||
}; | ||
ExponentialBackoffStrategy.prototype.flushEvents = function () { | ||
var _this = this; | ||
if (this.isBackoffInProgress) { | ||
return Promise.resolve(); | ||
} | ||
this.isBackoffInProgress = true; | ||
var backoffMultiplier = 2; | ||
var executeFlush = function (depth) { | ||
if (depth === void 0) { depth = 0; } | ||
_this.pendingEvents = _this.pendingEvents.concat(_this.events); | ||
_this.events = []; | ||
return _this.sendEvents(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isBackoffInProgress = false; | ||
if (_this.events.length > 0) { | ||
return _this.flushEvents(); | ||
} | ||
return Promise.resolve(); | ||
})["catch"](function () { | ||
var waitTime = Math.pow(backoffMultiplier, depth) * 1000; | ||
if (depth > _this.maxNumberOfRetries) { | ||
_this.events = []; | ||
_this.isBackoffInProgress = false; | ||
return; | ||
} | ||
return new Promise(function (resolve, reject) { | ||
setTimeout(function () { | ||
executeFlush(depth + 1) | ||
.then(resolve, reject)["catch"](reject); | ||
}, Math.min(waitTime, _this.exponentialBackoffLimit)); | ||
}); | ||
}); | ||
}; | ||
return executeFlush(); | ||
}; | ||
return ExponentialBackoffStrategy; | ||
}()); | ||
function fetchRequest(context) { | ||
@@ -122,4 +224,3 @@ if ((typeof window !== 'undefined' && typeof window.fetch !== 'function') || | ||
var DEFAULT_EXPONENTIAL_BACKOFF_LIMIT = 60000; | ||
var DEFAULT_DEBOUNCE_TIME = 2000; | ||
var DEFAULT_USE_EXPONENTIAL_BACKOFF = false; | ||
var SplunkEvents = /** @class */ (function () { | ||
@@ -130,19 +231,11 @@ function SplunkEvents(config) { | ||
this.autoFlush = true; | ||
this.autoRetryFlush = true; | ||
this.debounceTime = DEFAULT_DEBOUNCE_TIME; | ||
this.debug = false; | ||
this.events = []; | ||
this.host = '-'; | ||
this.injectAdditionalInfo = false; | ||
this.injectTimestamp = false; | ||
this.isSendingEvents = false; | ||
this.path = '/services/collector/event'; | ||
this.pendingEvents = []; | ||
this.shouldParseEventData = true; | ||
this.source = 'log'; | ||
this.flushPending = false; | ||
this.useExponentialBackoff = false; | ||
this.exponentialBackoffLimit = DEFAULT_EXPONENTIAL_BACKOFF_LIMIT; | ||
this.isBackoffInProgress = false; | ||
this.maxNumberOfRetries = Infinity; | ||
this.configured = false; | ||
this.flushStrategy = null; | ||
/** | ||
@@ -173,2 +266,5 @@ * Logs an event to Splunk. | ||
if (account === void 0) { account = ''; } | ||
if (_this.flushStrategy == null) { | ||
throw new Error('SplunkEvents instance is not configured properly'); | ||
} | ||
_this.validateEvent(eventData); | ||
@@ -184,20 +280,8 @@ var eventObj = __assign(__assign({ level: level, | ||
var data = __assign(__assign({ sourcetype: _this.source, host: _this.host }, (_this.injectTimestamp && { time: +new Date() })), { event: event }); | ||
_this.events.push(data); | ||
_this.flushStrategy.addEvent(data); | ||
if (_this.autoFlush) { | ||
_this.flushEvents(); | ||
_this.flushStrategy.flushEvents(); | ||
} | ||
}; | ||
/** | ||
* Internal flush that contains the logic for debouncing or | ||
* backing off exponentially. | ||
*/ | ||
this.flushEvents = function () { | ||
if (_this.useExponentialBackoff) { | ||
_this._backoffFlush(); | ||
} | ||
else { | ||
_this.debouncedFlush(); | ||
} | ||
}; | ||
/** | ||
* Flushes pending events into one single request. | ||
@@ -208,108 +292,52 @@ * | ||
*/ | ||
this.flush = function (events) { | ||
if (events === void 0) { events = _this.events; } | ||
return __awaiter(_this, void 0, void 0, function () { | ||
var splunkBatchedFormattedEvents; | ||
var _this = this; | ||
var _a; | ||
return __generator(this, function (_b) { | ||
this.validateConfig(); | ||
if (events.length === 0) { | ||
return [2 /*return*/]; | ||
} | ||
if (this.debug) { | ||
console.log("sending " + events.length + " events to splunk"); | ||
} | ||
splunkBatchedFormattedEvents = this.formatEventsForSplunkBatch(events); | ||
return [2 /*return*/, this.request({ | ||
url: "" + this.endpoint + this.path, | ||
method: 'POST', | ||
data: splunkBatchedFormattedEvents, | ||
headers: (_a = this.headers) !== null && _a !== void 0 ? _a : {}, | ||
responseType: 'json', | ||
}) | ||
.then(function () { | ||
if (_this.debug) { | ||
console.log(events.length + " events successfuly sent to splunk"); | ||
} | ||
})["catch"](function (e) { | ||
if (_this.debug) { | ||
console.warn('Error sending events to splunk.', e); | ||
} | ||
throw e; | ||
})]; | ||
}); | ||
}); | ||
}; | ||
this._backoffFlush = function () { | ||
if (_this.isBackoffInProgress) { | ||
return Promise.resolve(); | ||
} | ||
_this.isBackoffInProgress = true; | ||
var backoffMultiplier = 2; | ||
var executeFlush = function (depth) { | ||
if (depth === void 0) { depth = 0; } | ||
_this.pendingEvents = _this.pendingEvents.concat(_this.events); | ||
_this.events = []; | ||
return _this.flush(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isBackoffInProgress = false; | ||
if (_this.events.length > 0) { | ||
return _this._backoffFlush(); | ||
} | ||
return Promise.resolve(); | ||
})["catch"](function () { | ||
var waitTime = Math.pow(backoffMultiplier, depth) * 1000; | ||
if (depth > _this.maxNumberOfRetries) { | ||
_this.events = []; | ||
_this.isBackoffInProgress = false; | ||
return; | ||
} | ||
return new Promise(function (resolve, reject) { | ||
setTimeout(function () { | ||
executeFlush(depth + 1) | ||
.then(resolve, reject)["catch"](reject); | ||
}, Math.min(waitTime, _this.exponentialBackoffLimit)); | ||
}); | ||
}); | ||
}; | ||
return executeFlush(); | ||
}; | ||
this._debouncedFlush = function () { | ||
if (_this.isSendingEvents) { | ||
_this.flushPending = true; | ||
return; | ||
} | ||
_this.pendingEvents = Array.from(_this.events); | ||
_this.events = []; | ||
_this.isSendingEvents = true; | ||
_this.flush(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (!_this.flushPending) { | ||
return; | ||
this.flush = function (events) { return __awaiter(_this, void 0, void 0, function () { | ||
var splunkBatchedFormattedEvents; | ||
var _this = this; | ||
var _a; | ||
return __generator(this, function (_b) { | ||
this.validateConfig(); | ||
if (!events) { | ||
this.flushStrategy.flushEvents(); | ||
return [2 /*return*/]; | ||
} | ||
_this.flushPending = false; | ||
return _this._debouncedFlush(); | ||
})["catch"](function () { | ||
_this.events = _this.events.concat(_this.pendingEvents); | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (_this.autoRetryFlush) { | ||
_this.flushEvents(); | ||
if (events.length === 0) { | ||
return [2 /*return*/]; | ||
} | ||
if (this.debug) { | ||
console.log("sending " + events.length + " events to splunk"); | ||
} | ||
splunkBatchedFormattedEvents = this.formatEventsForSplunkBatch(events); | ||
return [2 /*return*/, this.request({ | ||
url: "" + this.endpoint + this.path, | ||
method: 'POST', | ||
data: splunkBatchedFormattedEvents, | ||
headers: (_a = this.headers) !== null && _a !== void 0 ? _a : {}, | ||
responseType: 'json', | ||
}) | ||
.then(function () { | ||
if (_this.debug) { | ||
console.log(events.length + " events successfuly sent to splunk"); | ||
} | ||
})["catch"](function (e) { | ||
if (_this.debug) { | ||
console.warn('Error sending events to splunk.', e); | ||
} | ||
throw e; | ||
})]; | ||
}); | ||
}; | ||
this.debouncedFlush = debounce(this._debouncedFlush, this.debounceTime); | ||
if (config) { | ||
this.config(config); | ||
}); }; | ||
if (!config) { | ||
return; | ||
} | ||
this.config(config); | ||
} | ||
/** | ||
* Configure (or reconfigure) this Splunk Event instance. | ||
* Configure this Splunk Event instance. | ||
*/ | ||
SplunkEvents.prototype.config = function (config) { | ||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t; | ||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; | ||
if (this.configured) { | ||
return; | ||
} | ||
this.configured = true; | ||
this.endpoint = (_a = config === null || config === void 0 ? void 0 : config.endpoint) !== null && _a !== void 0 ? _a : this.endpoint; // required | ||
@@ -319,28 +347,34 @@ this.token = (_b = config === null || config === void 0 ? void 0 : config.token) !== null && _b !== void 0 ? _b : this.endpoint; // required | ||
(_d = (_c = config === null || config === void 0 ? void 0 : config.injectAditionalInfo) !== null && _c !== void 0 ? _c : config === null || config === void 0 ? void 0 : config.injectAdditionalInfo) !== null && _d !== void 0 ? _d : this.injectAdditionalInfo; | ||
this.useExponentialBackoff = | ||
(_e = config === null || config === void 0 ? void 0 : config.useExponentialBackoff) !== null && _e !== void 0 ? _e : this.useExponentialBackoff; | ||
this.exponentialBackoffLimit = | ||
(_f = config === null || config === void 0 ? void 0 : config.exponentialBackoffLimit) !== null && _f !== void 0 ? _f : this.exponentialBackoffLimit; | ||
this.autoFlush = this.useExponentialBackoff | ||
? // should always be true when using exponential backoff strategy | ||
true | ||
: (_g = config === null || config === void 0 ? void 0 : config.autoFlush) !== null && _g !== void 0 ? _g : this.autoFlush; | ||
this.autoRetryFlush = (_h = config === null || config === void 0 ? void 0 : config.autoRetryFlush) !== null && _h !== void 0 ? _h : this.autoRetryFlush; | ||
this.source = (_j = config === null || config === void 0 ? void 0 : config.source) !== null && _j !== void 0 ? _j : this.source; | ||
this.path = (_k = config === null || config === void 0 ? void 0 : config.path) !== null && _k !== void 0 ? _k : this.path; | ||
this.host = (_l = config === null || config === void 0 ? void 0 : config.host) !== null && _l !== void 0 ? _l : this.host; | ||
this.debug = (_m = config === null || config === void 0 ? void 0 : config.debug) !== null && _m !== void 0 ? _m : this.debug; | ||
var prevDebounceTime = this.debounceTime; | ||
this.debounceTime = (_o = config === null || config === void 0 ? void 0 : config.debounceTime) !== null && _o !== void 0 ? _o : this.debounceTime; | ||
if (this.debounceTime !== prevDebounceTime) { | ||
this.debouncedFlush.clear(); | ||
this.debouncedFlush = debounce(this._debouncedFlush, this.debounceTime); | ||
this.autoFlush = (_e = config === null || config === void 0 ? void 0 : config.autoFlush) !== null && _e !== void 0 ? _e : this.autoFlush; | ||
this.source = (_f = config === null || config === void 0 ? void 0 : config.source) !== null && _f !== void 0 ? _f : this.source; | ||
this.path = (_g = config === null || config === void 0 ? void 0 : config.path) !== null && _g !== void 0 ? _g : this.path; | ||
this.host = (_h = config === null || config === void 0 ? void 0 : config.host) !== null && _h !== void 0 ? _h : this.host; | ||
this.debug = (_j = config === null || config === void 0 ? void 0 : config.debug) !== null && _j !== void 0 ? _j : this.debug; | ||
this._requestImpl = (_k = config === null || config === void 0 ? void 0 : config.request) !== null && _k !== void 0 ? _k : this._requestImpl; | ||
this.injectTimestamp = (_l = config === null || config === void 0 ? void 0 : config.injectTimestamp) !== null && _l !== void 0 ? _l : this.injectTimestamp; | ||
this.shouldParseEventData = | ||
(_m = config === null || config === void 0 ? void 0 : config.shouldParseEventData) !== null && _m !== void 0 ? _m : this.shouldParseEventData; | ||
this.headers = __assign({ Authorization: "Splunk " + this.token, 'Content-Type': 'application/json' }, ((_o = config === null || config === void 0 ? void 0 : config.headers) !== null && _o !== void 0 ? _o : {})); | ||
var useExponentialBackoff = (_p = config === null || config === void 0 ? void 0 : config.useExponentialBackoff) !== null && _p !== void 0 ? _p : DEFAULT_USE_EXPONENTIAL_BACKOFF; | ||
// Exponential backoff configurations | ||
var exponentialBackoffLimit = config === null || config === void 0 ? void 0 : config.exponentialBackoffLimit; | ||
var maxNumberOfRetries = config === null || config === void 0 ? void 0 : config.maxNumberOfRetries; | ||
// Debounce configurations | ||
var debounceTime = config === null || config === void 0 ? void 0 : config.debounceTime; | ||
var autoRetryFlush = (_q = config === null || config === void 0 ? void 0 : config.autoRetryFlush) !== null && _q !== void 0 ? _q : true; | ||
if (useExponentialBackoff) { | ||
this.autoFlush = true; | ||
this.flushStrategy = new ExponentialBackoffStrategy({ | ||
sendEvents: this.flush, | ||
exponentialBackoffLimit: exponentialBackoffLimit, | ||
maxNumberOfRetries: maxNumberOfRetries, | ||
}); | ||
} | ||
this._requestImpl = (_p = config === null || config === void 0 ? void 0 : config.request) !== null && _p !== void 0 ? _p : this._requestImpl; | ||
this.injectTimestamp = (_q = config === null || config === void 0 ? void 0 : config.injectTimestamp) !== null && _q !== void 0 ? _q : this.injectTimestamp; | ||
this.shouldParseEventData = | ||
(_r = config === null || config === void 0 ? void 0 : config.shouldParseEventData) !== null && _r !== void 0 ? _r : this.shouldParseEventData; | ||
this.maxNumberOfRetries = | ||
(_s = config === null || config === void 0 ? void 0 : config.maxNumberOfRetries) !== null && _s !== void 0 ? _s : this.maxNumberOfRetries; | ||
this.headers = __assign({ Authorization: "Splunk " + this.token, 'Content-Type': 'application/json' }, ((_t = config === null || config === void 0 ? void 0 : config.headers) !== null && _t !== void 0 ? _t : {})); | ||
else { | ||
this.flushStrategy = new DebounceStrategy({ | ||
sendEvents: this.flush, | ||
debounceTime: debounceTime, | ||
autoRetryFlush: autoRetryFlush, | ||
}); | ||
} | ||
}; | ||
@@ -410,2 +444,5 @@ /** | ||
} | ||
if (this.flushStrategy == null) { | ||
throw new Error('Instance must be configured (either by constructor or calling config method) before flushing events'); | ||
} | ||
}; | ||
@@ -412,0 +449,0 @@ return SplunkEvents; |
/*! | ||
* splunk-events v1.6.1 | ||
* splunk-events v1.7.0 | ||
* Copyright (c) VTEX | ||
@@ -20,3 +20,3 @@ * Released under the MIT License. | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */var n=function(){return(n=Object.assign||function(n){for(var e,t=1,o=arguments.length;t<o;t++)for(var i in e=arguments[t])Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n}).apply(this,arguments)};function e(n,e,t,o){return new(t||(t=Promise))((function(i,s){function u(n){try{l(o.next(n))}catch(n){s(n)}}function r(n){try{l(o.throw(n))}catch(n){s(n)}}function l(n){var e;n.done?i(n.value):(e=n.value,e instanceof t?e:new t((function(n){n(e)}))).then(u,r)}l((o=o.apply(n,e||[])).next())}))}function t(n,e){var t,o,i,s,u={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:r(0),throw:r(1),return:r(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function r(s){return function(r){return function(s){if(t)throw new TypeError("Generator is already executing.");for(;u;)try{if(t=1,o&&(i=2&s[0]?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return u.label++,{value:s[1],done:!1};case 5:u.label++,o=s[1],s=[0];continue;case 7:s=u.ops.pop(),u.trys.pop();continue;default:if(!(i=u.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){u=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){u.label=s[1];break}if(6===s[0]&&u.label<i[1]){u.label=i[1],i=s;break}if(i&&u.label<i[2]){u.label=i[2],u.ops.push(s);break}i[2]&&u.ops.pop(),u.trys.pop();continue}s=e.call(n,u)}catch(n){s=[6,n],o=0}finally{t=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,r])}}}function o(n,e){void 0===e&&(e=100);var t=null,o=null,i=function(){for(var i=[],s=0;s<arguments.length;s++)i[s]=arguments[s];return t&&(clearTimeout(t),t=null),new Promise((function(s,u){o=u,t=setTimeout((function(){var e=n.apply(void 0,i);null!=e&&e.then(s).catch(u)}),e)}))};return i.clear=function(){t&&(clearTimeout(t),null==o||o(),t=null)},i}function i(e){return"undefined"!=typeof window&&"function"!=typeof window.fetch||"undefined"!=typeof global&&"function"!=typeof global.fetch?(console.log("Error, using fetchRequest without fetch object"),Promise.resolve(null)):fetch(e.url,n(n({},e),{body:e.data})).then((function(n){return"json"===e.responseType?n.json():n}))}var s=function(){function s(s){var u=this;this._requestImpl=i,this.autoFlush=!0,this.autoRetryFlush=!0,this.debounceTime=2e3,this.debug=!1,this.events=[],this.host="-",this.injectAdditionalInfo=!1,this.injectTimestamp=!1,this.isSendingEvents=!1,this.path="/services/collector/event",this.pendingEvents=[],this.shouldParseEventData=!0,this.source="log",this.flushPending=!1,this.useExponentialBackoff=!1,this.exponentialBackoffLimit=6e4,this.isBackoffInProgress=!1,this.maxNumberOfRetries=1/0,this.logEvent=function(e,t,o,i,s,r){void 0===r&&(r=""),u.validateEvent(s);var l=n(n({level:e,type:t,workflowType:o,workflowInstance:i,account:r},s),u.injectAdditionalInfo?u.getAdditionalInfo():{}),a=u.shouldParseEventData?u.parseEventData(l):l,h=n(n({sourcetype:u.source,host:u.host},u.injectTimestamp&&{time:+new Date}),{event:a});u.events.push(h),u.autoFlush&&u.flushEvents()},this.flushEvents=function(){u.useExponentialBackoff?u._backoffFlush():u.debouncedFlush()},this.flush=function(n){return void 0===n&&(n=u.events),e(u,void 0,void 0,(function(){var e,o,i=this;return t(this,(function(t){return this.validateConfig(),0===n.length?[2]:(this.debug&&console.log("sending "+n.length+" events to splunk"),e=this.formatEventsForSplunkBatch(n),[2,this.request({url:""+this.endpoint+this.path,method:"POST",data:e,headers:null!==(o=this.headers)&&void 0!==o?o:{},responseType:"json"}).then((function(){i.debug&&console.log(n.length+" events successfuly sent to splunk")})).catch((function(n){throw i.debug&&console.warn("Error sending events to splunk.",n),n}))])}))}))},this._backoffFlush=function(){if(u.isBackoffInProgress)return Promise.resolve();u.isBackoffInProgress=!0;var n=function(e){return void 0===e&&(e=0),u.pendingEvents=u.pendingEvents.concat(u.events),u.events=[],u.flush(u.pendingEvents).then((function(){return u.pendingEvents=[],u.isBackoffInProgress=!1,u.events.length>0?u._backoffFlush():Promise.resolve()})).catch((function(){var t=1e3*Math.pow(2,e);return e>u.maxNumberOfRetries?(u.events=[],void(u.isBackoffInProgress=!1)):new Promise((function(o,i){setTimeout((function(){n(e+1).then(o,i).catch(i)}),Math.min(t,u.exponentialBackoffLimit))}))}))};return n()},this._debouncedFlush=function(){u.isSendingEvents?u.flushPending=!0:(u.pendingEvents=Array.from(u.events),u.events=[],u.isSendingEvents=!0,u.flush(u.pendingEvents).then((function(){if(u.pendingEvents=[],u.isSendingEvents=!1,u.flushPending)return u.flushPending=!1,u._debouncedFlush()})).catch((function(){u.events=u.events.concat(u.pendingEvents),u.pendingEvents=[],u.isSendingEvents=!1,u.autoRetryFlush&&u.flushEvents()})))},this.debouncedFlush=o(this._debouncedFlush,this.debounceTime),s&&this.config(s)}return s.prototype.config=function(e){var t,i,s,u,r,l,a,h,c,f,d,v,p,g,m,b,y,E;this.endpoint=null!==(t=null==e?void 0:e.endpoint)&&void 0!==t?t:this.endpoint,this.token=null!==(i=null==e?void 0:e.token)&&void 0!==i?i:this.endpoint,this.injectAdditionalInfo=null!==(u=null!==(s=null==e?void 0:e.injectAditionalInfo)&&void 0!==s?s:null==e?void 0:e.injectAdditionalInfo)&&void 0!==u?u:this.injectAdditionalInfo,this.useExponentialBackoff=null!==(r=null==e?void 0:e.useExponentialBackoff)&&void 0!==r?r:this.useExponentialBackoff,this.exponentialBackoffLimit=null!==(l=null==e?void 0:e.exponentialBackoffLimit)&&void 0!==l?l:this.exponentialBackoffLimit,this.autoFlush=!!this.useExponentialBackoff||(null!==(a=null==e?void 0:e.autoFlush)&&void 0!==a?a:this.autoFlush),this.autoRetryFlush=null!==(h=null==e?void 0:e.autoRetryFlush)&&void 0!==h?h:this.autoRetryFlush,this.source=null!==(c=null==e?void 0:e.source)&&void 0!==c?c:this.source,this.path=null!==(f=null==e?void 0:e.path)&&void 0!==f?f:this.path,this.host=null!==(d=null==e?void 0:e.host)&&void 0!==d?d:this.host,this.debug=null!==(v=null==e?void 0:e.debug)&&void 0!==v?v:this.debug;var w=this.debounceTime;this.debounceTime=null!==(p=null==e?void 0:e.debounceTime)&&void 0!==p?p:this.debounceTime,this.debounceTime!==w&&(this.debouncedFlush.clear(),this.debouncedFlush=o(this._debouncedFlush,this.debounceTime)),this._requestImpl=null!==(g=null==e?void 0:e.request)&&void 0!==g?g:this._requestImpl,this.injectTimestamp=null!==(m=null==e?void 0:e.injectTimestamp)&&void 0!==m?m:this.injectTimestamp,this.shouldParseEventData=null!==(b=null==e?void 0:e.shouldParseEventData)&&void 0!==b?b:this.shouldParseEventData,this.maxNumberOfRetries=null!==(y=null==e?void 0:e.maxNumberOfRetries)&&void 0!==y?y:this.maxNumberOfRetries,this.headers=n({Authorization:"Splunk "+this.token,"Content-Type":"application/json"},null!==(E=null==e?void 0:e.headers)&&void 0!==E?E:{})},s.prototype.request=function(n){return this._requestImpl(n)},s.prototype.parseEventData=function(n){var e="";for(var t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&null!=n[t]){var o=n[t];switch(typeof o){case"string":e+=t+'="'+o.replace(/"/g,"")+'" ';break;case"boolean":case"number":e+=t+"="+o+" ";break;default:throw new Error("Event property must be string, number or boolean")}}return e},s.prototype.validateEvent=function(n){if(null===n)throw new Error("Event must not be null");if(void 0===n)throw new Error("Event must not be undefined");if("object"!=typeof n)throw new Error("Event must be an object")},s.prototype.getAdditionalInfo=function(){if("undefined"==typeof navigator||"undefined"==typeof window)return"";var n=window.screen,e=window.location;return{additional_info:navigator.userAgent.replace(/,/g,";")+","+(navigator.browserLanguage||navigator.language)+","+navigator.platform+","+(n.availWidth||"-")+","+(n.availHeight||"-")+","+e.hostname+","+e.pathname+","+e.protocol.replace(":","")+","+(e.hash||"-")}},s.prototype.formatEventsForSplunkBatch=function(n){return n.map((function(n){return JSON.stringify(n)})).join("\n")},s.prototype.validateConfig=function(){if(null==this.token)throw new Error("Token must not be null nor undefined");if(null==this.endpoint)throw new Error("Endpoint must not be null nor undefined")},s}();module.exports=s; | ||
***************************************************************************** */var t=function(){return(t=Object.assign||function(t){for(var n,e=1,i=arguments.length;e<i;e++)for(var o in n=arguments[e])Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o]);return t}).apply(this,arguments)};function n(t,n,e,i){return new(e||(e=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function u(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var n;t.done?o(t.value):(n=t.value,n instanceof e?n:new e((function(t){t(n)}))).then(r,u)}l((i=i.apply(t,n||[])).next())}))}function e(t,n){var e,i,o,s,r={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function u(s){return function(u){return function(s){if(e)throw new TypeError("Generator is already executing.");for(;r;)try{if(e=1,i&&(o=2&s[0]?i.return:s[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,s[1])).done)return o;switch(i=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return r.label++,{value:s[1],done:!1};case 5:r.label++,i=s[1],s=[0];continue;case 7:s=r.ops.pop(),r.trys.pop();continue;default:if(!(o=r.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){r=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){r.label=s[1];break}if(6===s[0]&&r.label<o[1]){r.label=o[1],o=s;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(s);break}o[2]&&r.ops.pop(),r.trys.pop();continue}s=n.call(t,r)}catch(t){s=[6,t],i=0}finally{e=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}var i=function(){function t(t){var n=this,e=t.debounceTime,i=void 0===e?2e3:e,o=t.autoRetryFlush,s=t.sendEvents;this.pendingEvents=[],this.events=[],this.isSendingEvents=!1,this.flushPending=!1,this.flushImpl=function(){n.isSendingEvents?n.flushPending=!0:(n.pendingEvents=Array.from(n.events),n.events=[],n.isSendingEvents=!0,n.sendEvents(n.pendingEvents).then((function(){if(n.pendingEvents=[],n.isSendingEvents=!1,n.flushPending)return n.flushPending=!1,n.flushImpl()})).catch((function(){n.events=n.events.concat(n.pendingEvents),n.pendingEvents=[],n.isSendingEvents=!1,n.autoRetryFlush&&n.flushEvents()})))},this.flushEvents=function(t,n){void 0===n&&(n=100);var e=null,i=null,o=function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];return e&&(clearTimeout(e),e=null),new Promise((function(s,r){i=r,e=setTimeout((function(){var n=t.apply(void 0,o);null!=n&&n.then(s).catch(r)}),n)}))};return o.clear=function(){e&&(clearTimeout(e),null==i||i(),e=null)},o}(this.flushImpl,i),this.autoRetryFlush=o,this.sendEvents=s}return t.prototype.abort=function(){this.flushEvents.clear()},t.prototype.addEvent=function(t){this.events.push(t)},t}(),o=function(){function t(t){var n=t.sendEvents,e=t.exponentialBackoffLimit,i=void 0===e?6e4:e,o=t.maxNumberOfRetries;this.isBackoffInProgress=!1,this.maxNumberOfRetries=1/0,this.events=[],this.pendingEvents=[],this.sendEvents=n,this.exponentialBackoffLimit=i,this.maxNumberOfRetries=null!=o?o:this.maxNumberOfRetries}return t.prototype.addEvent=function(t){this.events.push(t)},t.prototype.flushEvents=function(){var t=this;if(this.isBackoffInProgress)return Promise.resolve();this.isBackoffInProgress=!0;var n=function(e){return void 0===e&&(e=0),t.pendingEvents=t.pendingEvents.concat(t.events),t.events=[],t.sendEvents(t.pendingEvents).then((function(){return t.pendingEvents=[],t.isBackoffInProgress=!1,t.events.length>0?t.flushEvents():Promise.resolve()})).catch((function(){var i=1e3*Math.pow(2,e);return e>t.maxNumberOfRetries?(t.events=[],void(t.isBackoffInProgress=!1)):new Promise((function(o,s){setTimeout((function(){n(e+1).then(o,s).catch(s)}),Math.min(i,t.exponentialBackoffLimit))}))}))};return n()},t}();function s(n){return"undefined"!=typeof window&&"function"!=typeof window.fetch||"undefined"!=typeof global&&"function"!=typeof global.fetch?(console.log("Error, using fetchRequest without fetch object"),Promise.resolve(null)):fetch(n.url,t(t({},n),{body:n.data})).then((function(t){return"json"===n.responseType?t.json():t}))}var r=function(){function r(i){var o=this;this._requestImpl=s,this.autoFlush=!0,this.debug=!1,this.host="-",this.injectAdditionalInfo=!1,this.injectTimestamp=!1,this.path="/services/collector/event",this.shouldParseEventData=!0,this.source="log",this.configured=!1,this.flushStrategy=null,this.logEvent=function(n,e,i,s,r,u){if(void 0===u&&(u=""),null==o.flushStrategy)throw new Error("SplunkEvents instance is not configured properly");o.validateEvent(r);var l=t(t({level:n,type:e,workflowType:i,workflowInstance:s,account:u},r),o.injectAdditionalInfo?o.getAdditionalInfo():{}),a=o.shouldParseEventData?o.parseEventData(l):l,h=t(t({sourcetype:o.source,host:o.host},o.injectTimestamp&&{time:+new Date}),{event:a});o.flushStrategy.addEvent(h),o.autoFlush&&o.flushStrategy.flushEvents()},this.flush=function(t){return n(o,void 0,void 0,(function(){var n,i,o=this;return e(this,(function(e){return this.validateConfig(),t?0===t.length?[2]:(this.debug&&console.log("sending "+t.length+" events to splunk"),n=this.formatEventsForSplunkBatch(t),[2,this.request({url:""+this.endpoint+this.path,method:"POST",data:n,headers:null!==(i=this.headers)&&void 0!==i?i:{},responseType:"json"}).then((function(){o.debug&&console.log(t.length+" events successfuly sent to splunk")})).catch((function(t){throw o.debug&&console.warn("Error sending events to splunk.",t),t}))]):(this.flushStrategy.flushEvents(),[2])}))}))},i&&this.config(i)}return r.prototype.config=function(n){var e,s,r,u,l,a,h,f,c,d,v,p,g,m,y;if(!this.configured){this.configured=!0,this.endpoint=null!==(e=null==n?void 0:n.endpoint)&&void 0!==e?e:this.endpoint,this.token=null!==(s=null==n?void 0:n.token)&&void 0!==s?s:this.endpoint,this.injectAdditionalInfo=null!==(u=null!==(r=null==n?void 0:n.injectAditionalInfo)&&void 0!==r?r:null==n?void 0:n.injectAdditionalInfo)&&void 0!==u?u:this.injectAdditionalInfo,this.autoFlush=null!==(l=null==n?void 0:n.autoFlush)&&void 0!==l?l:this.autoFlush,this.source=null!==(a=null==n?void 0:n.source)&&void 0!==a?a:this.source,this.path=null!==(h=null==n?void 0:n.path)&&void 0!==h?h:this.path,this.host=null!==(f=null==n?void 0:n.host)&&void 0!==f?f:this.host,this.debug=null!==(c=null==n?void 0:n.debug)&&void 0!==c?c:this.debug,this._requestImpl=null!==(d=null==n?void 0:n.request)&&void 0!==d?d:this._requestImpl,this.injectTimestamp=null!==(v=null==n?void 0:n.injectTimestamp)&&void 0!==v?v:this.injectTimestamp,this.shouldParseEventData=null!==(p=null==n?void 0:n.shouldParseEventData)&&void 0!==p?p:this.shouldParseEventData,this.headers=t({Authorization:"Splunk "+this.token,"Content-Type":"application/json"},null!==(g=null==n?void 0:n.headers)&&void 0!==g?g:{});var E=null!==(m=null==n?void 0:n.useExponentialBackoff)&&void 0!==m&&m,b=null==n?void 0:n.exponentialBackoffLimit,w=null==n?void 0:n.maxNumberOfRetries,k=null==n?void 0:n.debounceTime,P=null===(y=null==n?void 0:n.autoRetryFlush)||void 0===y||y;E?(this.autoFlush=!0,this.flushStrategy=new o({sendEvents:this.flush,exponentialBackoffLimit:b,maxNumberOfRetries:w})):this.flushStrategy=new i({sendEvents:this.flush,debounceTime:k,autoRetryFlush:P})}},r.prototype.request=function(t){return this._requestImpl(t)},r.prototype.parseEventData=function(t){var n="";for(var e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&null!=t[e]){var i=t[e];switch(typeof i){case"string":n+=e+'="'+i.replace(/"/g,"")+'" ';break;case"boolean":case"number":n+=e+"="+i+" ";break;default:throw new Error("Event property must be string, number or boolean")}}return n},r.prototype.validateEvent=function(t){if(null===t)throw new Error("Event must not be null");if(void 0===t)throw new Error("Event must not be undefined");if("object"!=typeof t)throw new Error("Event must be an object")},r.prototype.getAdditionalInfo=function(){if("undefined"==typeof navigator||"undefined"==typeof window)return"";var t=window.screen,n=window.location;return{additional_info:navigator.userAgent.replace(/,/g,";")+","+(navigator.browserLanguage||navigator.language)+","+navigator.platform+","+(t.availWidth||"-")+","+(t.availHeight||"-")+","+n.hostname+","+n.pathname+","+n.protocol.replace(":","")+","+(n.hash||"-")}},r.prototype.formatEventsForSplunkBatch=function(t){return t.map((function(t){return JSON.stringify(t)})).join("\n")},r.prototype.validateConfig=function(){if(null==this.token)throw new Error("Token must not be null nor undefined");if(null==this.endpoint)throw new Error("Endpoint must not be null nor undefined");if(null==this.flushStrategy)throw new Error("Instance must be configured (either by constructor or calling config method) before flushing events")},r}();module.exports=r; | ||
//# sourceMappingURL=splunk-events.min.js.map |
/*! | ||
* splunk-events v1.6.1 | ||
* splunk-events v1.7.0 | ||
* Copyright (c) VTEX | ||
@@ -110,2 +110,104 @@ * Released under the MIT License. | ||
var DEFAULT_DEBOUNCE_TIME = 2000; | ||
var DebounceStrategy = /** @class */ (function () { | ||
function DebounceStrategy(_a) { | ||
var _this = this; | ||
var _b = _a.debounceTime, debounceTime = _b === void 0 ? DEFAULT_DEBOUNCE_TIME : _b, autoRetryFlush = _a.autoRetryFlush, sendEvents = _a.sendEvents; | ||
this.pendingEvents = []; | ||
this.events = []; | ||
this.isSendingEvents = false; | ||
this.flushPending = false; | ||
this.flushImpl = function () { | ||
if (_this.isSendingEvents) { | ||
_this.flushPending = true; | ||
return; | ||
} | ||
_this.pendingEvents = Array.from(_this.events); | ||
_this.events = []; | ||
_this.isSendingEvents = true; | ||
_this.sendEvents(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (!_this.flushPending) { | ||
return; | ||
} | ||
_this.flushPending = false; | ||
return _this.flushImpl(); | ||
})["catch"](function () { | ||
_this.events = _this.events.concat(_this.pendingEvents); | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (_this.autoRetryFlush) { | ||
_this.flushEvents(); | ||
} | ||
}); | ||
}; | ||
this.flushEvents = debounce(this.flushImpl, debounceTime); | ||
this.autoRetryFlush = autoRetryFlush; | ||
this.sendEvents = sendEvents; | ||
} | ||
DebounceStrategy.prototype.abort = function () { | ||
this.flushEvents.clear(); | ||
}; | ||
DebounceStrategy.prototype.addEvent = function (event) { | ||
this.events.push(event); | ||
}; | ||
return DebounceStrategy; | ||
}()); | ||
var DEFAULT_EXPONENTIAL_BACKOFF_LIMIT = 60000; | ||
var ExponentialBackoffStrategy = /** @class */ (function () { | ||
function ExponentialBackoffStrategy(_a) { | ||
var sendEvents = _a.sendEvents, _b = _a.exponentialBackoffLimit, exponentialBackoffLimit = _b === void 0 ? DEFAULT_EXPONENTIAL_BACKOFF_LIMIT : _b, maxNumberOfRetries = _a.maxNumberOfRetries; | ||
this.isBackoffInProgress = false; | ||
this.maxNumberOfRetries = Infinity; | ||
this.events = []; | ||
this.pendingEvents = []; | ||
this.sendEvents = sendEvents; | ||
this.exponentialBackoffLimit = exponentialBackoffLimit; | ||
this.maxNumberOfRetries = maxNumberOfRetries !== null && maxNumberOfRetries !== void 0 ? maxNumberOfRetries : this.maxNumberOfRetries; | ||
} | ||
ExponentialBackoffStrategy.prototype.addEvent = function (event) { | ||
this.events.push(event); | ||
}; | ||
ExponentialBackoffStrategy.prototype.flushEvents = function () { | ||
var _this = this; | ||
if (this.isBackoffInProgress) { | ||
return Promise.resolve(); | ||
} | ||
this.isBackoffInProgress = true; | ||
var backoffMultiplier = 2; | ||
var executeFlush = function (depth) { | ||
if (depth === void 0) { depth = 0; } | ||
_this.pendingEvents = _this.pendingEvents.concat(_this.events); | ||
_this.events = []; | ||
return _this.sendEvents(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isBackoffInProgress = false; | ||
if (_this.events.length > 0) { | ||
return _this.flushEvents(); | ||
} | ||
return Promise.resolve(); | ||
})["catch"](function () { | ||
var waitTime = Math.pow(backoffMultiplier, depth) * 1000; | ||
if (depth > _this.maxNumberOfRetries) { | ||
_this.events = []; | ||
_this.isBackoffInProgress = false; | ||
return; | ||
} | ||
return new Promise(function (resolve, reject) { | ||
setTimeout(function () { | ||
executeFlush(depth + 1) | ||
.then(resolve, reject)["catch"](reject); | ||
}, Math.min(waitTime, _this.exponentialBackoffLimit)); | ||
}); | ||
}); | ||
}; | ||
return executeFlush(); | ||
}; | ||
return ExponentialBackoffStrategy; | ||
}()); | ||
function fetchRequest(context) { | ||
@@ -126,4 +228,3 @@ if ((typeof window !== 'undefined' && typeof window.fetch !== 'function') || | ||
var DEFAULT_EXPONENTIAL_BACKOFF_LIMIT = 60000; | ||
var DEFAULT_DEBOUNCE_TIME = 2000; | ||
var DEFAULT_USE_EXPONENTIAL_BACKOFF = false; | ||
var SplunkEvents = /** @class */ (function () { | ||
@@ -134,19 +235,11 @@ function SplunkEvents(config) { | ||
this.autoFlush = true; | ||
this.autoRetryFlush = true; | ||
this.debounceTime = DEFAULT_DEBOUNCE_TIME; | ||
this.debug = false; | ||
this.events = []; | ||
this.host = '-'; | ||
this.injectAdditionalInfo = false; | ||
this.injectTimestamp = false; | ||
this.isSendingEvents = false; | ||
this.path = '/services/collector/event'; | ||
this.pendingEvents = []; | ||
this.shouldParseEventData = true; | ||
this.source = 'log'; | ||
this.flushPending = false; | ||
this.useExponentialBackoff = false; | ||
this.exponentialBackoffLimit = DEFAULT_EXPONENTIAL_BACKOFF_LIMIT; | ||
this.isBackoffInProgress = false; | ||
this.maxNumberOfRetries = Infinity; | ||
this.configured = false; | ||
this.flushStrategy = null; | ||
/** | ||
@@ -177,2 +270,5 @@ * Logs an event to Splunk. | ||
if (account === void 0) { account = ''; } | ||
if (_this.flushStrategy == null) { | ||
throw new Error('SplunkEvents instance is not configured properly'); | ||
} | ||
_this.validateEvent(eventData); | ||
@@ -188,20 +284,8 @@ var eventObj = __assign(__assign({ level: level, | ||
var data = __assign(__assign({ sourcetype: _this.source, host: _this.host }, (_this.injectTimestamp && { time: +new Date() })), { event: event }); | ||
_this.events.push(data); | ||
_this.flushStrategy.addEvent(data); | ||
if (_this.autoFlush) { | ||
_this.flushEvents(); | ||
_this.flushStrategy.flushEvents(); | ||
} | ||
}; | ||
/** | ||
* Internal flush that contains the logic for debouncing or | ||
* backing off exponentially. | ||
*/ | ||
this.flushEvents = function () { | ||
if (_this.useExponentialBackoff) { | ||
_this._backoffFlush(); | ||
} | ||
else { | ||
_this.debouncedFlush(); | ||
} | ||
}; | ||
/** | ||
* Flushes pending events into one single request. | ||
@@ -212,108 +296,52 @@ * | ||
*/ | ||
this.flush = function (events) { | ||
if (events === void 0) { events = _this.events; } | ||
return __awaiter(_this, void 0, void 0, function () { | ||
var splunkBatchedFormattedEvents; | ||
var _this = this; | ||
var _a; | ||
return __generator(this, function (_b) { | ||
this.validateConfig(); | ||
if (events.length === 0) { | ||
return [2 /*return*/]; | ||
} | ||
if (this.debug) { | ||
console.log("sending " + events.length + " events to splunk"); | ||
} | ||
splunkBatchedFormattedEvents = this.formatEventsForSplunkBatch(events); | ||
return [2 /*return*/, this.request({ | ||
url: "" + this.endpoint + this.path, | ||
method: 'POST', | ||
data: splunkBatchedFormattedEvents, | ||
headers: (_a = this.headers) !== null && _a !== void 0 ? _a : {}, | ||
responseType: 'json', | ||
}) | ||
.then(function () { | ||
if (_this.debug) { | ||
console.log(events.length + " events successfuly sent to splunk"); | ||
} | ||
})["catch"](function (e) { | ||
if (_this.debug) { | ||
console.warn('Error sending events to splunk.', e); | ||
} | ||
throw e; | ||
})]; | ||
}); | ||
}); | ||
}; | ||
this._backoffFlush = function () { | ||
if (_this.isBackoffInProgress) { | ||
return Promise.resolve(); | ||
} | ||
_this.isBackoffInProgress = true; | ||
var backoffMultiplier = 2; | ||
var executeFlush = function (depth) { | ||
if (depth === void 0) { depth = 0; } | ||
_this.pendingEvents = _this.pendingEvents.concat(_this.events); | ||
_this.events = []; | ||
return _this.flush(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isBackoffInProgress = false; | ||
if (_this.events.length > 0) { | ||
return _this._backoffFlush(); | ||
} | ||
return Promise.resolve(); | ||
})["catch"](function () { | ||
var waitTime = Math.pow(backoffMultiplier, depth) * 1000; | ||
if (depth > _this.maxNumberOfRetries) { | ||
_this.events = []; | ||
_this.isBackoffInProgress = false; | ||
return; | ||
} | ||
return new Promise(function (resolve, reject) { | ||
setTimeout(function () { | ||
executeFlush(depth + 1) | ||
.then(resolve, reject)["catch"](reject); | ||
}, Math.min(waitTime, _this.exponentialBackoffLimit)); | ||
}); | ||
}); | ||
}; | ||
return executeFlush(); | ||
}; | ||
this._debouncedFlush = function () { | ||
if (_this.isSendingEvents) { | ||
_this.flushPending = true; | ||
return; | ||
} | ||
_this.pendingEvents = Array.from(_this.events); | ||
_this.events = []; | ||
_this.isSendingEvents = true; | ||
_this.flush(_this.pendingEvents) | ||
.then(function () { | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (!_this.flushPending) { | ||
return; | ||
this.flush = function (events) { return __awaiter(_this, void 0, void 0, function () { | ||
var splunkBatchedFormattedEvents; | ||
var _this = this; | ||
var _a; | ||
return __generator(this, function (_b) { | ||
this.validateConfig(); | ||
if (!events) { | ||
this.flushStrategy.flushEvents(); | ||
return [2 /*return*/]; | ||
} | ||
_this.flushPending = false; | ||
return _this._debouncedFlush(); | ||
})["catch"](function () { | ||
_this.events = _this.events.concat(_this.pendingEvents); | ||
_this.pendingEvents = []; | ||
_this.isSendingEvents = false; | ||
if (_this.autoRetryFlush) { | ||
_this.flushEvents(); | ||
if (events.length === 0) { | ||
return [2 /*return*/]; | ||
} | ||
if (this.debug) { | ||
console.log("sending " + events.length + " events to splunk"); | ||
} | ||
splunkBatchedFormattedEvents = this.formatEventsForSplunkBatch(events); | ||
return [2 /*return*/, this.request({ | ||
url: "" + this.endpoint + this.path, | ||
method: 'POST', | ||
data: splunkBatchedFormattedEvents, | ||
headers: (_a = this.headers) !== null && _a !== void 0 ? _a : {}, | ||
responseType: 'json', | ||
}) | ||
.then(function () { | ||
if (_this.debug) { | ||
console.log(events.length + " events successfuly sent to splunk"); | ||
} | ||
})["catch"](function (e) { | ||
if (_this.debug) { | ||
console.warn('Error sending events to splunk.', e); | ||
} | ||
throw e; | ||
})]; | ||
}); | ||
}; | ||
this.debouncedFlush = debounce(this._debouncedFlush, this.debounceTime); | ||
if (config) { | ||
this.config(config); | ||
}); }; | ||
if (!config) { | ||
return; | ||
} | ||
this.config(config); | ||
} | ||
/** | ||
* Configure (or reconfigure) this Splunk Event instance. | ||
* Configure this Splunk Event instance. | ||
*/ | ||
SplunkEvents.prototype.config = function (config) { | ||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t; | ||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; | ||
if (this.configured) { | ||
return; | ||
} | ||
this.configured = true; | ||
this.endpoint = (_a = config === null || config === void 0 ? void 0 : config.endpoint) !== null && _a !== void 0 ? _a : this.endpoint; // required | ||
@@ -323,28 +351,34 @@ this.token = (_b = config === null || config === void 0 ? void 0 : config.token) !== null && _b !== void 0 ? _b : this.endpoint; // required | ||
(_d = (_c = config === null || config === void 0 ? void 0 : config.injectAditionalInfo) !== null && _c !== void 0 ? _c : config === null || config === void 0 ? void 0 : config.injectAdditionalInfo) !== null && _d !== void 0 ? _d : this.injectAdditionalInfo; | ||
this.useExponentialBackoff = | ||
(_e = config === null || config === void 0 ? void 0 : config.useExponentialBackoff) !== null && _e !== void 0 ? _e : this.useExponentialBackoff; | ||
this.exponentialBackoffLimit = | ||
(_f = config === null || config === void 0 ? void 0 : config.exponentialBackoffLimit) !== null && _f !== void 0 ? _f : this.exponentialBackoffLimit; | ||
this.autoFlush = this.useExponentialBackoff | ||
? // should always be true when using exponential backoff strategy | ||
true | ||
: (_g = config === null || config === void 0 ? void 0 : config.autoFlush) !== null && _g !== void 0 ? _g : this.autoFlush; | ||
this.autoRetryFlush = (_h = config === null || config === void 0 ? void 0 : config.autoRetryFlush) !== null && _h !== void 0 ? _h : this.autoRetryFlush; | ||
this.source = (_j = config === null || config === void 0 ? void 0 : config.source) !== null && _j !== void 0 ? _j : this.source; | ||
this.path = (_k = config === null || config === void 0 ? void 0 : config.path) !== null && _k !== void 0 ? _k : this.path; | ||
this.host = (_l = config === null || config === void 0 ? void 0 : config.host) !== null && _l !== void 0 ? _l : this.host; | ||
this.debug = (_m = config === null || config === void 0 ? void 0 : config.debug) !== null && _m !== void 0 ? _m : this.debug; | ||
var prevDebounceTime = this.debounceTime; | ||
this.debounceTime = (_o = config === null || config === void 0 ? void 0 : config.debounceTime) !== null && _o !== void 0 ? _o : this.debounceTime; | ||
if (this.debounceTime !== prevDebounceTime) { | ||
this.debouncedFlush.clear(); | ||
this.debouncedFlush = debounce(this._debouncedFlush, this.debounceTime); | ||
this.autoFlush = (_e = config === null || config === void 0 ? void 0 : config.autoFlush) !== null && _e !== void 0 ? _e : this.autoFlush; | ||
this.source = (_f = config === null || config === void 0 ? void 0 : config.source) !== null && _f !== void 0 ? _f : this.source; | ||
this.path = (_g = config === null || config === void 0 ? void 0 : config.path) !== null && _g !== void 0 ? _g : this.path; | ||
this.host = (_h = config === null || config === void 0 ? void 0 : config.host) !== null && _h !== void 0 ? _h : this.host; | ||
this.debug = (_j = config === null || config === void 0 ? void 0 : config.debug) !== null && _j !== void 0 ? _j : this.debug; | ||
this._requestImpl = (_k = config === null || config === void 0 ? void 0 : config.request) !== null && _k !== void 0 ? _k : this._requestImpl; | ||
this.injectTimestamp = (_l = config === null || config === void 0 ? void 0 : config.injectTimestamp) !== null && _l !== void 0 ? _l : this.injectTimestamp; | ||
this.shouldParseEventData = | ||
(_m = config === null || config === void 0 ? void 0 : config.shouldParseEventData) !== null && _m !== void 0 ? _m : this.shouldParseEventData; | ||
this.headers = __assign({ Authorization: "Splunk " + this.token, 'Content-Type': 'application/json' }, ((_o = config === null || config === void 0 ? void 0 : config.headers) !== null && _o !== void 0 ? _o : {})); | ||
var useExponentialBackoff = (_p = config === null || config === void 0 ? void 0 : config.useExponentialBackoff) !== null && _p !== void 0 ? _p : DEFAULT_USE_EXPONENTIAL_BACKOFF; | ||
// Exponential backoff configurations | ||
var exponentialBackoffLimit = config === null || config === void 0 ? void 0 : config.exponentialBackoffLimit; | ||
var maxNumberOfRetries = config === null || config === void 0 ? void 0 : config.maxNumberOfRetries; | ||
// Debounce configurations | ||
var debounceTime = config === null || config === void 0 ? void 0 : config.debounceTime; | ||
var autoRetryFlush = (_q = config === null || config === void 0 ? void 0 : config.autoRetryFlush) !== null && _q !== void 0 ? _q : true; | ||
if (useExponentialBackoff) { | ||
this.autoFlush = true; | ||
this.flushStrategy = new ExponentialBackoffStrategy({ | ||
sendEvents: this.flush, | ||
exponentialBackoffLimit: exponentialBackoffLimit, | ||
maxNumberOfRetries: maxNumberOfRetries, | ||
}); | ||
} | ||
this._requestImpl = (_p = config === null || config === void 0 ? void 0 : config.request) !== null && _p !== void 0 ? _p : this._requestImpl; | ||
this.injectTimestamp = (_q = config === null || config === void 0 ? void 0 : config.injectTimestamp) !== null && _q !== void 0 ? _q : this.injectTimestamp; | ||
this.shouldParseEventData = | ||
(_r = config === null || config === void 0 ? void 0 : config.shouldParseEventData) !== null && _r !== void 0 ? _r : this.shouldParseEventData; | ||
this.maxNumberOfRetries = | ||
(_s = config === null || config === void 0 ? void 0 : config.maxNumberOfRetries) !== null && _s !== void 0 ? _s : this.maxNumberOfRetries; | ||
this.headers = __assign({ Authorization: "Splunk " + this.token, 'Content-Type': 'application/json' }, ((_t = config === null || config === void 0 ? void 0 : config.headers) !== null && _t !== void 0 ? _t : {})); | ||
else { | ||
this.flushStrategy = new DebounceStrategy({ | ||
sendEvents: this.flush, | ||
debounceTime: debounceTime, | ||
autoRetryFlush: autoRetryFlush, | ||
}); | ||
} | ||
}; | ||
@@ -414,2 +448,5 @@ /** | ||
} | ||
if (this.flushStrategy == null) { | ||
throw new Error('Instance must be configured (either by constructor or calling config method) before flushing events'); | ||
} | ||
}; | ||
@@ -416,0 +453,0 @@ return SplunkEvents; |
/*! | ||
* splunk-events v1.6.1 | ||
* splunk-events v1.7.0 | ||
* Copyright (c) VTEX | ||
* Released under the MIT License. | ||
*/ | ||
!function(n,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(n="undefined"!=typeof globalThis?globalThis:n||self).SplunkEvents=e()}(this,(function(){"use strict"; | ||
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(t="undefined"!=typeof globalThis?globalThis:t||self).SplunkEvents=n()}(this,(function(){"use strict"; | ||
/*! ***************************************************************************** | ||
@@ -20,3 +20,3 @@ Copyright (c) Microsoft Corporation. | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */var n=function(){return(n=Object.assign||function(n){for(var e,t=1,o=arguments.length;t<o;t++)for(var i in e=arguments[t])Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n}).apply(this,arguments)};function e(n,e,t,o){return new(t||(t=Promise))((function(i,s){function u(n){try{l(o.next(n))}catch(n){s(n)}}function r(n){try{l(o.throw(n))}catch(n){s(n)}}function l(n){var e;n.done?i(n.value):(e=n.value,e instanceof t?e:new t((function(n){n(e)}))).then(u,r)}l((o=o.apply(n,e||[])).next())}))}function t(n,e){var t,o,i,s,u={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:r(0),throw:r(1),return:r(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function r(s){return function(r){return function(s){if(t)throw new TypeError("Generator is already executing.");for(;u;)try{if(t=1,o&&(i=2&s[0]?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return u.label++,{value:s[1],done:!1};case 5:u.label++,o=s[1],s=[0];continue;case 7:s=u.ops.pop(),u.trys.pop();continue;default:if(!(i=u.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){u=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){u.label=s[1];break}if(6===s[0]&&u.label<i[1]){u.label=i[1],i=s;break}if(i&&u.label<i[2]){u.label=i[2],u.ops.push(s);break}i[2]&&u.ops.pop(),u.trys.pop();continue}s=e.call(n,u)}catch(n){s=[6,n],o=0}finally{t=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,r])}}}function o(n,e){void 0===e&&(e=100);var t=null,o=null,i=function(){for(var i=[],s=0;s<arguments.length;s++)i[s]=arguments[s];return t&&(clearTimeout(t),t=null),new Promise((function(s,u){o=u,t=setTimeout((function(){var e=n.apply(void 0,i);null!=e&&e.then(s).catch(u)}),e)}))};return i.clear=function(){t&&(clearTimeout(t),null==o||o(),t=null)},i}function i(e){return"undefined"!=typeof window&&"function"!=typeof window.fetch||"undefined"!=typeof global&&"function"!=typeof global.fetch?(console.log("Error, using fetchRequest without fetch object"),Promise.resolve(null)):fetch(e.url,n(n({},e),{body:e.data})).then((function(n){return"json"===e.responseType?n.json():n}))}return function(){function s(s){var u=this;this._requestImpl=i,this.autoFlush=!0,this.autoRetryFlush=!0,this.debounceTime=2e3,this.debug=!1,this.events=[],this.host="-",this.injectAdditionalInfo=!1,this.injectTimestamp=!1,this.isSendingEvents=!1,this.path="/services/collector/event",this.pendingEvents=[],this.shouldParseEventData=!0,this.source="log",this.flushPending=!1,this.useExponentialBackoff=!1,this.exponentialBackoffLimit=6e4,this.isBackoffInProgress=!1,this.maxNumberOfRetries=1/0,this.logEvent=function(e,t,o,i,s,r){void 0===r&&(r=""),u.validateEvent(s);var l=n(n({level:e,type:t,workflowType:o,workflowInstance:i,account:r},s),u.injectAdditionalInfo?u.getAdditionalInfo():{}),a=u.shouldParseEventData?u.parseEventData(l):l,h=n(n({sourcetype:u.source,host:u.host},u.injectTimestamp&&{time:+new Date}),{event:a});u.events.push(h),u.autoFlush&&u.flushEvents()},this.flushEvents=function(){u.useExponentialBackoff?u._backoffFlush():u.debouncedFlush()},this.flush=function(n){return void 0===n&&(n=u.events),e(u,void 0,void 0,(function(){var e,o,i=this;return t(this,(function(t){return this.validateConfig(),0===n.length?[2]:(this.debug&&console.log("sending "+n.length+" events to splunk"),e=this.formatEventsForSplunkBatch(n),[2,this.request({url:""+this.endpoint+this.path,method:"POST",data:e,headers:null!==(o=this.headers)&&void 0!==o?o:{},responseType:"json"}).then((function(){i.debug&&console.log(n.length+" events successfuly sent to splunk")})).catch((function(n){throw i.debug&&console.warn("Error sending events to splunk.",n),n}))])}))}))},this._backoffFlush=function(){if(u.isBackoffInProgress)return Promise.resolve();u.isBackoffInProgress=!0;var n=function(e){return void 0===e&&(e=0),u.pendingEvents=u.pendingEvents.concat(u.events),u.events=[],u.flush(u.pendingEvents).then((function(){return u.pendingEvents=[],u.isBackoffInProgress=!1,u.events.length>0?u._backoffFlush():Promise.resolve()})).catch((function(){var t=1e3*Math.pow(2,e);return e>u.maxNumberOfRetries?(u.events=[],void(u.isBackoffInProgress=!1)):new Promise((function(o,i){setTimeout((function(){n(e+1).then(o,i).catch(i)}),Math.min(t,u.exponentialBackoffLimit))}))}))};return n()},this._debouncedFlush=function(){u.isSendingEvents?u.flushPending=!0:(u.pendingEvents=Array.from(u.events),u.events=[],u.isSendingEvents=!0,u.flush(u.pendingEvents).then((function(){if(u.pendingEvents=[],u.isSendingEvents=!1,u.flushPending)return u.flushPending=!1,u._debouncedFlush()})).catch((function(){u.events=u.events.concat(u.pendingEvents),u.pendingEvents=[],u.isSendingEvents=!1,u.autoRetryFlush&&u.flushEvents()})))},this.debouncedFlush=o(this._debouncedFlush,this.debounceTime),s&&this.config(s)}return s.prototype.config=function(e){var t,i,s,u,r,l,a,h,c,f,d,v,p,g,b,m,y,E;this.endpoint=null!==(t=null==e?void 0:e.endpoint)&&void 0!==t?t:this.endpoint,this.token=null!==(i=null==e?void 0:e.token)&&void 0!==i?i:this.endpoint,this.injectAdditionalInfo=null!==(u=null!==(s=null==e?void 0:e.injectAditionalInfo)&&void 0!==s?s:null==e?void 0:e.injectAdditionalInfo)&&void 0!==u?u:this.injectAdditionalInfo,this.useExponentialBackoff=null!==(r=null==e?void 0:e.useExponentialBackoff)&&void 0!==r?r:this.useExponentialBackoff,this.exponentialBackoffLimit=null!==(l=null==e?void 0:e.exponentialBackoffLimit)&&void 0!==l?l:this.exponentialBackoffLimit,this.autoFlush=!!this.useExponentialBackoff||(null!==(a=null==e?void 0:e.autoFlush)&&void 0!==a?a:this.autoFlush),this.autoRetryFlush=null!==(h=null==e?void 0:e.autoRetryFlush)&&void 0!==h?h:this.autoRetryFlush,this.source=null!==(c=null==e?void 0:e.source)&&void 0!==c?c:this.source,this.path=null!==(f=null==e?void 0:e.path)&&void 0!==f?f:this.path,this.host=null!==(d=null==e?void 0:e.host)&&void 0!==d?d:this.host,this.debug=null!==(v=null==e?void 0:e.debug)&&void 0!==v?v:this.debug;var w=this.debounceTime;this.debounceTime=null!==(p=null==e?void 0:e.debounceTime)&&void 0!==p?p:this.debounceTime,this.debounceTime!==w&&(this.debouncedFlush.clear(),this.debouncedFlush=o(this._debouncedFlush,this.debounceTime)),this._requestImpl=null!==(g=null==e?void 0:e.request)&&void 0!==g?g:this._requestImpl,this.injectTimestamp=null!==(b=null==e?void 0:e.injectTimestamp)&&void 0!==b?b:this.injectTimestamp,this.shouldParseEventData=null!==(m=null==e?void 0:e.shouldParseEventData)&&void 0!==m?m:this.shouldParseEventData,this.maxNumberOfRetries=null!==(y=null==e?void 0:e.maxNumberOfRetries)&&void 0!==y?y:this.maxNumberOfRetries,this.headers=n({Authorization:"Splunk "+this.token,"Content-Type":"application/json"},null!==(E=null==e?void 0:e.headers)&&void 0!==E?E:{})},s.prototype.request=function(n){return this._requestImpl(n)},s.prototype.parseEventData=function(n){var e="";for(var t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&null!=n[t]){var o=n[t];switch(typeof o){case"string":e+=t+'="'+o.replace(/"/g,"")+'" ';break;case"boolean":case"number":e+=t+"="+o+" ";break;default:throw new Error("Event property must be string, number or boolean")}}return e},s.prototype.validateEvent=function(n){if(null===n)throw new Error("Event must not be null");if(void 0===n)throw new Error("Event must not be undefined");if("object"!=typeof n)throw new Error("Event must be an object")},s.prototype.getAdditionalInfo=function(){if("undefined"==typeof navigator||"undefined"==typeof window)return"";var n=window.screen,e=window.location;return{additional_info:navigator.userAgent.replace(/,/g,";")+","+(navigator.browserLanguage||navigator.language)+","+navigator.platform+","+(n.availWidth||"-")+","+(n.availHeight||"-")+","+e.hostname+","+e.pathname+","+e.protocol.replace(":","")+","+(e.hash||"-")}},s.prototype.formatEventsForSplunkBatch=function(n){return n.map((function(n){return JSON.stringify(n)})).join("\n")},s.prototype.validateConfig=function(){if(null==this.token)throw new Error("Token must not be null nor undefined");if(null==this.endpoint)throw new Error("Endpoint must not be null nor undefined")},s}()})); | ||
***************************************************************************** */var t=function(){return(t=Object.assign||function(t){for(var n,e=1,i=arguments.length;e<i;e++)for(var o in n=arguments[e])Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o]);return t}).apply(this,arguments)};function n(t,n,e,i){return new(e||(e=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function u(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var n;t.done?o(t.value):(n=t.value,n instanceof e?n:new e((function(t){t(n)}))).then(r,u)}l((i=i.apply(t,n||[])).next())}))}function e(t,n){var e,i,o,s,r={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function u(s){return function(u){return function(s){if(e)throw new TypeError("Generator is already executing.");for(;r;)try{if(e=1,i&&(o=2&s[0]?i.return:s[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,s[1])).done)return o;switch(i=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return r.label++,{value:s[1],done:!1};case 5:r.label++,i=s[1],s=[0];continue;case 7:s=r.ops.pop(),r.trys.pop();continue;default:if(!(o=r.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){r=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){r.label=s[1];break}if(6===s[0]&&r.label<o[1]){r.label=o[1],o=s;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(s);break}o[2]&&r.ops.pop(),r.trys.pop();continue}s=n.call(t,r)}catch(t){s=[6,t],i=0}finally{e=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}var i=function(){function t(t){var n=this,e=t.debounceTime,i=void 0===e?2e3:e,o=t.autoRetryFlush,s=t.sendEvents;this.pendingEvents=[],this.events=[],this.isSendingEvents=!1,this.flushPending=!1,this.flushImpl=function(){n.isSendingEvents?n.flushPending=!0:(n.pendingEvents=Array.from(n.events),n.events=[],n.isSendingEvents=!0,n.sendEvents(n.pendingEvents).then((function(){if(n.pendingEvents=[],n.isSendingEvents=!1,n.flushPending)return n.flushPending=!1,n.flushImpl()})).catch((function(){n.events=n.events.concat(n.pendingEvents),n.pendingEvents=[],n.isSendingEvents=!1,n.autoRetryFlush&&n.flushEvents()})))},this.flushEvents=function(t,n){void 0===n&&(n=100);var e=null,i=null,o=function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];return e&&(clearTimeout(e),e=null),new Promise((function(s,r){i=r,e=setTimeout((function(){var n=t.apply(void 0,o);null!=n&&n.then(s).catch(r)}),n)}))};return o.clear=function(){e&&(clearTimeout(e),null==i||i(),e=null)},o}(this.flushImpl,i),this.autoRetryFlush=o,this.sendEvents=s}return t.prototype.abort=function(){this.flushEvents.clear()},t.prototype.addEvent=function(t){this.events.push(t)},t}(),o=function(){function t(t){var n=t.sendEvents,e=t.exponentialBackoffLimit,i=void 0===e?6e4:e,o=t.maxNumberOfRetries;this.isBackoffInProgress=!1,this.maxNumberOfRetries=1/0,this.events=[],this.pendingEvents=[],this.sendEvents=n,this.exponentialBackoffLimit=i,this.maxNumberOfRetries=null!=o?o:this.maxNumberOfRetries}return t.prototype.addEvent=function(t){this.events.push(t)},t.prototype.flushEvents=function(){var t=this;if(this.isBackoffInProgress)return Promise.resolve();this.isBackoffInProgress=!0;var n=function(e){return void 0===e&&(e=0),t.pendingEvents=t.pendingEvents.concat(t.events),t.events=[],t.sendEvents(t.pendingEvents).then((function(){return t.pendingEvents=[],t.isBackoffInProgress=!1,t.events.length>0?t.flushEvents():Promise.resolve()})).catch((function(){var i=1e3*Math.pow(2,e);return e>t.maxNumberOfRetries?(t.events=[],void(t.isBackoffInProgress=!1)):new Promise((function(o,s){setTimeout((function(){n(e+1).then(o,s).catch(s)}),Math.min(i,t.exponentialBackoffLimit))}))}))};return n()},t}();function s(n){return"undefined"!=typeof window&&"function"!=typeof window.fetch||"undefined"!=typeof global&&"function"!=typeof global.fetch?(console.log("Error, using fetchRequest without fetch object"),Promise.resolve(null)):fetch(n.url,t(t({},n),{body:n.data})).then((function(t){return"json"===n.responseType?t.json():t}))}return function(){function r(i){var o=this;this._requestImpl=s,this.autoFlush=!0,this.debug=!1,this.host="-",this.injectAdditionalInfo=!1,this.injectTimestamp=!1,this.path="/services/collector/event",this.shouldParseEventData=!0,this.source="log",this.configured=!1,this.flushStrategy=null,this.logEvent=function(n,e,i,s,r,u){if(void 0===u&&(u=""),null==o.flushStrategy)throw new Error("SplunkEvents instance is not configured properly");o.validateEvent(r);var l=t(t({level:n,type:e,workflowType:i,workflowInstance:s,account:u},r),o.injectAdditionalInfo?o.getAdditionalInfo():{}),a=o.shouldParseEventData?o.parseEventData(l):l,h=t(t({sourcetype:o.source,host:o.host},o.injectTimestamp&&{time:+new Date}),{event:a});o.flushStrategy.addEvent(h),o.autoFlush&&o.flushStrategy.flushEvents()},this.flush=function(t){return n(o,void 0,void 0,(function(){var n,i,o=this;return e(this,(function(e){return this.validateConfig(),t?0===t.length?[2]:(this.debug&&console.log("sending "+t.length+" events to splunk"),n=this.formatEventsForSplunkBatch(t),[2,this.request({url:""+this.endpoint+this.path,method:"POST",data:n,headers:null!==(i=this.headers)&&void 0!==i?i:{},responseType:"json"}).then((function(){o.debug&&console.log(t.length+" events successfuly sent to splunk")})).catch((function(t){throw o.debug&&console.warn("Error sending events to splunk.",t),t}))]):(this.flushStrategy.flushEvents(),[2])}))}))},i&&this.config(i)}return r.prototype.config=function(n){var e,s,r,u,l,a,h,f,c,d,v,p,g,m,y;if(!this.configured){this.configured=!0,this.endpoint=null!==(e=null==n?void 0:n.endpoint)&&void 0!==e?e:this.endpoint,this.token=null!==(s=null==n?void 0:n.token)&&void 0!==s?s:this.endpoint,this.injectAdditionalInfo=null!==(u=null!==(r=null==n?void 0:n.injectAditionalInfo)&&void 0!==r?r:null==n?void 0:n.injectAdditionalInfo)&&void 0!==u?u:this.injectAdditionalInfo,this.autoFlush=null!==(l=null==n?void 0:n.autoFlush)&&void 0!==l?l:this.autoFlush,this.source=null!==(a=null==n?void 0:n.source)&&void 0!==a?a:this.source,this.path=null!==(h=null==n?void 0:n.path)&&void 0!==h?h:this.path,this.host=null!==(f=null==n?void 0:n.host)&&void 0!==f?f:this.host,this.debug=null!==(c=null==n?void 0:n.debug)&&void 0!==c?c:this.debug,this._requestImpl=null!==(d=null==n?void 0:n.request)&&void 0!==d?d:this._requestImpl,this.injectTimestamp=null!==(v=null==n?void 0:n.injectTimestamp)&&void 0!==v?v:this.injectTimestamp,this.shouldParseEventData=null!==(p=null==n?void 0:n.shouldParseEventData)&&void 0!==p?p:this.shouldParseEventData,this.headers=t({Authorization:"Splunk "+this.token,"Content-Type":"application/json"},null!==(g=null==n?void 0:n.headers)&&void 0!==g?g:{});var E=null!==(m=null==n?void 0:n.useExponentialBackoff)&&void 0!==m&&m,b=null==n?void 0:n.exponentialBackoffLimit,w=null==n?void 0:n.maxNumberOfRetries,k=null==n?void 0:n.debounceTime,j=null===(y=null==n?void 0:n.autoRetryFlush)||void 0===y||y;E?(this.autoFlush=!0,this.flushStrategy=new o({sendEvents:this.flush,exponentialBackoffLimit:b,maxNumberOfRetries:w})):this.flushStrategy=new i({sendEvents:this.flush,debounceTime:k,autoRetryFlush:j})}},r.prototype.request=function(t){return this._requestImpl(t)},r.prototype.parseEventData=function(t){var n="";for(var e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&null!=t[e]){var i=t[e];switch(typeof i){case"string":n+=e+'="'+i.replace(/"/g,"")+'" ';break;case"boolean":case"number":n+=e+"="+i+" ";break;default:throw new Error("Event property must be string, number or boolean")}}return n},r.prototype.validateEvent=function(t){if(null===t)throw new Error("Event must not be null");if(void 0===t)throw new Error("Event must not be undefined");if("object"!=typeof t)throw new Error("Event must be an object")},r.prototype.getAdditionalInfo=function(){if("undefined"==typeof navigator||"undefined"==typeof window)return"";var t=window.screen,n=window.location;return{additional_info:navigator.userAgent.replace(/,/g,";")+","+(navigator.browserLanguage||navigator.language)+","+navigator.platform+","+(t.availWidth||"-")+","+(t.availHeight||"-")+","+n.hostname+","+n.pathname+","+n.protocol.replace(":","")+","+(n.hash||"-")}},r.prototype.formatEventsForSplunkBatch=function(t){return t.map((function(t){return JSON.stringify(t)})).join("\n")},r.prototype.validateConfig=function(){if(null==this.token)throw new Error("Token must not be null nor undefined");if(null==this.endpoint)throw new Error("Endpoint must not be null nor undefined");if(null==this.flushStrategy)throw new Error("Instance must be configured (either by constructor or calling config method) before flushing events")},r}()})); | ||
//# sourceMappingURL=splunk-events.umd.min.js.map |
{ | ||
"name": "splunk-events", | ||
"version": "1.6.1", | ||
"version": "1.7.0", | ||
"description": "Javascript lib to create Splunk Logs via HTTP", | ||
@@ -5,0 +5,0 @@ "main": "lib/splunk-events.min.js", |
@@ -30,6 +30,6 @@ import SplunkEvents from '../splunk-events' | ||
expect( | ||
// @ts-expect-error: events is private but we want to | ||
// assert on it anyway without making it public | ||
splunkEvents.events | ||
).toStrictEqual([]) | ||
// @ts-expect-error: private property | ||
splunkEvents.flushStrategy | ||
).toBeNull() | ||
splunkEvents.config({ | ||
@@ -39,5 +39,6 @@ endpoint: 'endpoint', | ||
}) | ||
expect( | ||
// @ts-expect-error: same as above | ||
splunkEvents.events | ||
// @ts-expect-error: private property | ||
splunkEvents.flushStrategy.events | ||
).toStrictEqual([]) | ||
@@ -95,2 +96,72 @@ }) | ||
it('should use request function passed in config', async () => { | ||
const request = jest.fn().mockReturnValue(Promise.resolve({})) | ||
splunkEvents.config({ | ||
endpoint: '/splunk', | ||
token: 'splunk-token-123', | ||
request, | ||
}) | ||
splunkEvents.logEvent('debug', 'info', 'request', 'defaultRequestImpl', { | ||
doesMyRequestSucceed: true, | ||
}) | ||
jest.runAllTimers() | ||
await flushPromises() | ||
expect(request).toHaveBeenCalledTimes(1) | ||
expect(request).toHaveBeenLastCalledWith( | ||
expect.objectContaining({ | ||
data: expect.stringContaining('doesMyRequestSucceed=true'), | ||
}) | ||
) | ||
}) | ||
it('should default to fetchRequest in case request is not configured', async () => { | ||
const requestMock = jest.requireMock('../request').fetchRequest as jest.Mock | ||
splunkEvents.config({ | ||
endpoint: '/splunk', | ||
token: 'splunk-token-123', | ||
}) | ||
splunkEvents.logEvent('debug', 'info', 'request', 'defaultRequestImpl', { | ||
doesDefaultRequestWork: true, | ||
}) | ||
jest.runAllTimers() | ||
expect(requestMock).toHaveBeenCalledTimes(1) | ||
expect(requestMock).toHaveBeenLastCalledWith( | ||
expect.objectContaining({ | ||
data: expect.stringContaining('doesDefaultRequestWork=true'), | ||
}) | ||
) | ||
}) | ||
it('should be able to receive config in constructor', () => { | ||
const mySplunkLogger = new SplunkEvents({ | ||
endpoint: '/splunk', | ||
token: 'my-splunk-token-123', | ||
}) | ||
const requestSpy = jest | ||
.spyOn(SplunkEvents.prototype, 'request') | ||
.mockImplementation(() => Promise.resolve(null)) | ||
mySplunkLogger.logEvent('debug', 'info', 'checkout', 'finish-purchase', { | ||
orderFormId: '1234abc', | ||
}) | ||
jest.runAllTimers() | ||
expect(requestSpy).toHaveBeenCalledTimes(1) | ||
expect(requestSpy).toHaveBeenLastCalledWith( | ||
expect.objectContaining({ | ||
data: expect.stringContaining('orderFormId=\\"1234abc\\"'), | ||
}) | ||
) | ||
}) | ||
describe('Debounce strategy', () => { | ||
@@ -160,41 +231,2 @@ it('should only make one request if called in timeout range', async () => { | ||
it('should update debounce time', async () => { | ||
splunkEvents.config({ | ||
endpoint: '/splunk', | ||
token: 'splunk-token-123', | ||
debounceTime: 1 * SECOND, | ||
}) | ||
const requestSpy = jest | ||
.spyOn(SplunkEvents.prototype, 'request') | ||
.mockImplementation(() => Promise.resolve(null)) | ||
splunkEvents.logEvent('debug', 'info', 'checkout', 'add-to-cart', { | ||
itemId: '320', | ||
}) | ||
expect(requestSpy).toHaveBeenCalledTimes(0) | ||
jest.advanceTimersByTime(1 * SECOND) | ||
await flushPromises() | ||
expect(requestSpy).toHaveBeenCalledTimes(1) | ||
splunkEvents.config({ debounceTime: 2 * SECOND }) | ||
splunkEvents.logEvent('debug', 'info', 'checkout', 'update-item', { | ||
index: 0, | ||
quantity: 10, | ||
}) | ||
jest.advanceTimersByTime(1 * SECOND) | ||
await flushPromises() | ||
expect(requestSpy).toHaveBeenCalledTimes(1) | ||
jest.advanceTimersByTime(1 * SECOND) | ||
await flushPromises() | ||
expect(requestSpy).toHaveBeenCalledTimes(2) | ||
}) | ||
it('should use configured debounce time when a request fails', async () => { | ||
@@ -236,73 +268,15 @@ const requestMock = jest.fn(() => Promise.resolve({} as Response)) | ||
it('should use request function passed in config', async () => { | ||
const request = jest.fn().mockReturnValue(Promise.resolve({})) | ||
splunkEvents.config({ | ||
endpoint: '/splunk', | ||
token: 'splunk-token-123', | ||
request, | ||
}) | ||
splunkEvents.logEvent('debug', 'info', 'request', 'defaultRequestImpl', { | ||
doesMyRequestSucceed: true, | ||
}) | ||
jest.runAllTimers() | ||
await flushPromises() | ||
expect(request).toHaveBeenCalledTimes(1) | ||
expect(request).toHaveBeenLastCalledWith( | ||
expect.objectContaining({ | ||
data: expect.stringContaining('doesMyRequestSucceed=true'), | ||
describe('Exponential backoff', () => { | ||
it('should automatically enable auto flush', () => { | ||
splunkEvents.config({ | ||
useExponentialBackoff: true, | ||
autoFlush: false, | ||
}) | ||
) | ||
}) | ||
it('should default to fetchRequest in case request is not configured', async () => { | ||
const requestMock = jest.requireMock('../request').fetchRequest as jest.Mock | ||
splunkEvents.config({ | ||
endpoint: '/splunk', | ||
token: 'splunk-token-123', | ||
expect( | ||
// @ts-expect-error: private property | ||
splunkEvents.autoFlush | ||
).toBe(true) | ||
}) | ||
splunkEvents.logEvent('debug', 'info', 'request', 'defaultRequestImpl', { | ||
doesDefaultRequestWork: true, | ||
}) | ||
jest.runAllTimers() | ||
expect(requestMock).toHaveBeenCalledTimes(1) | ||
expect(requestMock).toHaveBeenLastCalledWith( | ||
expect.objectContaining({ | ||
data: expect.stringContaining('doesDefaultRequestWork=true'), | ||
}) | ||
) | ||
}) | ||
it('should be able to receive config in constructor', () => { | ||
const mySplunkLogger = new SplunkEvents({ | ||
endpoint: '/splunk', | ||
token: 'my-splunk-token-123', | ||
}) | ||
const requestSpy = jest | ||
.spyOn(SplunkEvents.prototype, 'request') | ||
.mockImplementation(() => Promise.resolve(null)) | ||
mySplunkLogger.logEvent('debug', 'info', 'checkout', 'finish-purchase', { | ||
orderFormId: '1234abc', | ||
}) | ||
jest.runAllTimers() | ||
expect(requestSpy).toHaveBeenCalledTimes(1) | ||
expect(requestSpy).toHaveBeenLastCalledWith( | ||
expect.objectContaining({ | ||
data: expect.stringContaining('orderFormId=\\"1234abc\\"'), | ||
}) | ||
) | ||
}) | ||
describe('Exponential backoff', () => { | ||
it('should correctly backoff exponentially', async () => { | ||
@@ -459,3 +433,3 @@ const requestMock = jest | ||
// @ts-expect-error: asserting on private property | ||
splunkEvents.isBackoffInProgress | ||
splunkEvents.flushStrategy.isBackoffInProgress | ||
).toBe(true) | ||
@@ -462,0 +436,0 @@ |
@@ -0,5 +1,10 @@ | ||
export interface DebouncedFn { | ||
(): void | ||
clear(): void | ||
} | ||
export default function debounce<T>( | ||
func: (...args: T[]) => void | Promise<void>, | ||
wait = 100 | ||
) { | ||
): DebouncedFn { | ||
let timeout: NodeJS.Timeout | null = null | ||
@@ -6,0 +11,0 @@ let cancel: (() => void) | null = null |
@@ -1,3 +0,5 @@ | ||
import debounce from './debounce' | ||
import { DebounceStrategy } from './debounceStrategy' | ||
import { ExponentialBackoffStrategy } from './exponentialBackoffStrategy' | ||
import { FetchContext, fetchRequest } from './request' | ||
import type { EventData, SplunkEvent, Strategy } from './strategy' | ||
@@ -95,14 +97,4 @@ export { FetchContext } | ||
type EventData = Record<string, string | number | boolean> | ||
const DEFAULT_USE_EXPONENTIAL_BACKOFF = false | ||
interface SplunkEvent { | ||
host: string | ||
sourcetype: string | ||
time?: number | ||
event: EventData | string | ||
} | ||
const DEFAULT_EXPONENTIAL_BACKOFF_LIMIT = 60_000 | ||
const DEFAULT_DEBOUNCE_TIME = 2_000 | ||
export default class SplunkEvents { | ||
@@ -114,8 +106,4 @@ private _requestImpl: ( | ||
private autoFlush = true | ||
private autoRetryFlush = true | ||
private debounceTime = DEFAULT_DEBOUNCE_TIME | ||
private debouncedFlush: { (): Promise<void>; clear(): void } | ||
private debug = false | ||
private endpoint?: string | ||
private events: SplunkEvent[] = [] | ||
private headers?: HeadersInit | ||
@@ -125,26 +113,29 @@ private host = '-' | ||
private injectTimestamp = false | ||
private isSendingEvents = false | ||
private path = '/services/collector/event' | ||
private pendingEvents: SplunkEvent[] = [] | ||
private shouldParseEventData = true | ||
private source = 'log' | ||
private token?: string | ||
private flushPending = false | ||
private useExponentialBackoff = false | ||
private exponentialBackoffLimit = DEFAULT_EXPONENTIAL_BACKOFF_LIMIT | ||
private isBackoffInProgress = false | ||
private maxNumberOfRetries = Infinity | ||
private configured = false | ||
private flushStrategy: Strategy | null = null | ||
constructor(config?: Config) { | ||
this.debouncedFlush = debounce(this._debouncedFlush, this.debounceTime) | ||
if (!config) { | ||
return | ||
} | ||
if (config) { | ||
this.config(config) | ||
} | ||
this.config(config) | ||
} | ||
/** | ||
* Configure (or reconfigure) this Splunk Event instance. | ||
* Configure this Splunk Event instance. | ||
*/ | ||
public config(config: Partial<Config>) { | ||
if (this.configured) { | ||
return | ||
} | ||
this.configured = true | ||
this.endpoint = config?.endpoint ?? this.endpoint // required | ||
@@ -156,11 +147,5 @@ this.token = config?.token ?? this.endpoint // required | ||
this.injectAdditionalInfo | ||
this.useExponentialBackoff = | ||
config?.useExponentialBackoff ?? this.useExponentialBackoff | ||
this.exponentialBackoffLimit = | ||
config?.exponentialBackoffLimit ?? this.exponentialBackoffLimit | ||
this.autoFlush = this.useExponentialBackoff | ||
? // should always be true when using exponential backoff strategy | ||
true | ||
: config?.autoFlush ?? this.autoFlush | ||
this.autoRetryFlush = config?.autoRetryFlush ?? this.autoRetryFlush | ||
this.autoFlush = config?.autoFlush ?? this.autoFlush | ||
this.source = config?.source ?? this.source | ||
@@ -171,17 +156,8 @@ this.path = config?.path ?? this.path | ||
const prevDebounceTime = this.debounceTime | ||
this._requestImpl = config?.request ?? this._requestImpl | ||
this.debounceTime = config?.debounceTime ?? this.debounceTime | ||
if (this.debounceTime !== prevDebounceTime) { | ||
this.debouncedFlush.clear() | ||
this.debouncedFlush = debounce(this._debouncedFlush, this.debounceTime) | ||
} | ||
this._requestImpl = config?.request ?? this._requestImpl | ||
this.injectTimestamp = config?.injectTimestamp ?? this.injectTimestamp | ||
this.shouldParseEventData = | ||
config?.shouldParseEventData ?? this.shouldParseEventData | ||
this.maxNumberOfRetries = | ||
config?.maxNumberOfRetries ?? this.maxNumberOfRetries | ||
this.headers = { | ||
@@ -192,2 +168,29 @@ Authorization: `Splunk ${this.token}`, | ||
} | ||
const useExponentialBackoff = | ||
config?.useExponentialBackoff ?? DEFAULT_USE_EXPONENTIAL_BACKOFF | ||
// Exponential backoff configurations | ||
const exponentialBackoffLimit = config?.exponentialBackoffLimit | ||
const maxNumberOfRetries = config?.maxNumberOfRetries | ||
// Debounce configurations | ||
const debounceTime = config?.debounceTime | ||
const autoRetryFlush = config?.autoRetryFlush ?? true | ||
if (useExponentialBackoff) { | ||
this.autoFlush = true | ||
this.flushStrategy = new ExponentialBackoffStrategy({ | ||
sendEvents: this.flush, | ||
exponentialBackoffLimit, | ||
maxNumberOfRetries, | ||
}) | ||
} else { | ||
this.flushStrategy = new DebounceStrategy({ | ||
sendEvents: this.flush, | ||
debounceTime, | ||
autoRetryFlush, | ||
}) | ||
} | ||
} | ||
@@ -226,2 +229,6 @@ | ||
) => { | ||
if (this.flushStrategy == null) { | ||
throw new Error('SplunkEvents instance is not configured properly') | ||
} | ||
this.validateEvent(eventData) | ||
@@ -250,6 +257,6 @@ | ||
this.events.push(data) | ||
this.flushStrategy.addEvent(data) | ||
if (this.autoFlush) { | ||
this.flushEvents() | ||
this.flushStrategy.flushEvents() | ||
} | ||
@@ -334,14 +341,2 @@ } | ||
/** | ||
* Internal flush that contains the logic for debouncing or | ||
* backing off exponentially. | ||
*/ | ||
private flushEvents = () => { | ||
if (this.useExponentialBackoff) { | ||
this._backoffFlush() | ||
} else { | ||
this.debouncedFlush() | ||
} | ||
} | ||
/** | ||
* Flushes pending events into one single request. | ||
@@ -352,5 +347,11 @@ * | ||
*/ | ||
public flush = async (events = this.events): Promise<void> => { | ||
public flush = async (events?: SplunkEvent[]): Promise<void> => { | ||
this.validateConfig() | ||
if (!events) { | ||
this.flushStrategy!.flushEvents() | ||
return | ||
} | ||
if (events.length === 0) { | ||
@@ -387,85 +388,2 @@ return | ||
private _backoffFlush = (): Promise<void> => { | ||
if (this.isBackoffInProgress) { | ||
return Promise.resolve() | ||
} | ||
this.isBackoffInProgress = true | ||
const backoffMultiplier = 2 | ||
const executeFlush = (depth = 0): Promise<void> => { | ||
this.pendingEvents = this.pendingEvents.concat(this.events) | ||
this.events = [] | ||
return this.flush(this.pendingEvents) | ||
.then(() => { | ||
this.pendingEvents = [] | ||
this.isBackoffInProgress = false | ||
if (this.events.length > 0) { | ||
return this._backoffFlush() | ||
} | ||
return Promise.resolve() | ||
}) | ||
.catch(() => { | ||
const waitTime = backoffMultiplier ** depth * 1_000 | ||
if (depth > this.maxNumberOfRetries) { | ||
this.events = [] | ||
this.isBackoffInProgress = false | ||
return | ||
} | ||
return new Promise((resolve, reject) => { | ||
setTimeout(() => { | ||
executeFlush(depth + 1) | ||
.then(resolve, reject) | ||
.catch(reject) | ||
}, Math.min(waitTime, this.exponentialBackoffLimit)) | ||
}) | ||
}) | ||
} | ||
return executeFlush() | ||
} | ||
private _debouncedFlush = () => { | ||
if (this.isSendingEvents) { | ||
this.flushPending = true | ||
return | ||
} | ||
this.pendingEvents = Array.from(this.events) | ||
this.events = [] | ||
this.isSendingEvents = true | ||
this.flush(this.pendingEvents) | ||
.then(() => { | ||
this.pendingEvents = [] | ||
this.isSendingEvents = false | ||
if (!this.flushPending) { | ||
return | ||
} | ||
this.flushPending = false | ||
return this._debouncedFlush() | ||
}) | ||
.catch(() => { | ||
this.events = this.events.concat(this.pendingEvents) | ||
this.pendingEvents = [] | ||
this.isSendingEvents = false | ||
if (this.autoRetryFlush) { | ||
this.flushEvents() | ||
} | ||
}) | ||
} | ||
private formatEventsForSplunkBatch(events: SplunkEvent[]) { | ||
@@ -483,3 +401,9 @@ return events.map((event) => JSON.stringify(event)).join('\n') | ||
} | ||
if (this.flushStrategy == null) { | ||
throw new Error( | ||
'Instance must be configured (either by constructor or calling config method) before flushing events' | ||
) | ||
} | ||
} | ||
} |
@@ -1,5 +0,6 @@ | ||
export default function debounce<T>(func: (...args: T[]) => void | Promise<void>, wait?: number): { | ||
(...args: T[]): Promise<void>; | ||
export interface DebouncedFn { | ||
(): void; | ||
clear(): void; | ||
}; | ||
} | ||
export default function debounce<T>(func: (...args: T[]) => void | Promise<void>, wait?: number): DebouncedFn; | ||
//# sourceMappingURL=debounce.d.ts.map |
import { FetchContext } from './request'; | ||
import type { EventData, SplunkEvent } from './strategy'; | ||
export { FetchContext }; | ||
@@ -91,18 +92,7 @@ export interface Config { | ||
} | ||
declare type EventData = Record<string, string | number | boolean>; | ||
interface SplunkEvent { | ||
host: string; | ||
sourcetype: string; | ||
time?: number; | ||
event: EventData | string; | ||
} | ||
export default class SplunkEvents { | ||
private _requestImpl; | ||
private autoFlush; | ||
private autoRetryFlush; | ||
private debounceTime; | ||
private debouncedFlush; | ||
private debug; | ||
private endpoint?; | ||
private events; | ||
private headers?; | ||
@@ -112,16 +102,11 @@ private host; | ||
private injectTimestamp; | ||
private isSendingEvents; | ||
private path; | ||
private pendingEvents; | ||
private shouldParseEventData; | ||
private source; | ||
private token?; | ||
private flushPending; | ||
private useExponentialBackoff; | ||
private exponentialBackoffLimit; | ||
private isBackoffInProgress; | ||
private maxNumberOfRetries; | ||
private configured; | ||
private flushStrategy; | ||
constructor(config?: Config); | ||
/** | ||
* Configure (or reconfigure) this Splunk Event instance. | ||
* Configure this Splunk Event instance. | ||
*/ | ||
@@ -164,7 +149,2 @@ config(config: Partial<Config>): void; | ||
/** | ||
* Internal flush that contains the logic for debouncing or | ||
* backing off exponentially. | ||
*/ | ||
private flushEvents; | ||
/** | ||
* Flushes pending events into one single request. | ||
@@ -175,5 +155,3 @@ * | ||
*/ | ||
flush: (events?: SplunkEvent[]) => Promise<void>; | ||
private _backoffFlush; | ||
private _debouncedFlush; | ||
flush: (events?: SplunkEvent[] | undefined) => Promise<void>; | ||
private formatEventsForSplunkBatch; | ||
@@ -180,0 +158,0 @@ private validateConfig; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
299768
35
2558