@browser-bunyan/server-stream
Version:
Bunyan stream for batching and sending log records to a server
3 lines (2 loc) • 2.08 kB
JavaScript
var t="undefined"!=typeof window?window.navigator.userAgent:"no-window",e=/bot|crawler|spider|crawling/i.test(t);exports.ServerStream=/*#__PURE__*/function(){function r(t){var e=this;void 0===t&&(t={});var o=t.method,n=void 0===o?"PUT":o,i=t.url,s=void 0===i?"/log":i,d=t.throttleInterval,u=void 0===d?3e3:d,a=t.withCredentials,c=void 0!==a&&a,l=t.onError,h=t.flushOnClose,w=void 0!==h&&h,f=t.writeCondition;this.writeCondition=void 0===f?r.defaultWriteCondition:f,this.records={},this.start({method:n,url:s,throttleInterval:u,withCredentials:c,onError:l}),w&&void 0!==window.fetch&&window.addEventListener("beforeunload",function(){e.currentThrottleTimeout&&window.clearTimeout(e.currentThrottleTimeout);var t=e.recordsAsArray();t.length&&window.fetch(s,{method:n,body:JSON.stringify(t),headers:{"Content-Type":"application/json"},credentials:c?"include":"same-origin",mode:"cors",keepalive:!0})},!1)}var o=r.prototype;return o.start=function(t){var e=this,r=t.method,o=t.url,n=t.throttleInterval,i=t.withCredentials,s=t.onError;!function t(){e.currentThrottleTimeout=setTimeout(function(){var n=e.recordsAsArray();if(n.length){var d=new XMLHttpRequest;d.onreadystatechange=function(){d.readyState===XMLHttpRequest.DONE&&(d.status>=400&&("function"==typeof s?s.call(e,n,d):console.warn("Browser Bunyan: A server log write failed")),e.records={},t())},d.open(r,o),d.setRequestHeader("Content-Type","application/json"),d.withCredentials=i,d.send(JSON.stringify(n))}else t()},n)}()},o.stop=function(){var t=this;setTimeout(function(){t.currentThrottleTimeout&&(clearTimeout(t.currentThrottleTimeout),t.currentThrottleTimeout=null)},1)},o.write=function(e){e.url="undefined"!=typeof window&&window.location.href,e.userAgent=t,this.currentThrottleTimeout&&this.writeCondition(e)&&(this.records[e.msg]?this.records[e.msg].count++:(e.count=1,this.records[e.msg]=e))},o.recordsAsArray=function(){var t=this;return Object.keys(this.records).map(function(e){return t.records[e]})},r.defaultWriteCondition=function(){return window.navigator.onLine&&!e},r}();
//# sourceMappingURL=index.js.map