UNPKG

@browser-bunyan/server-stream

Version:

Bunyan stream for batching and sending log records to a server

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