UNPKG

@browser-bunyan/server-stream

Version:

Bunyan stream for batching and sending log records to a server

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