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