Reporter.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import util from "./util.js"
  2. export default class Reporter extends EventEmitter {
  3. constructor() {
  4. super();
  5. this._header= {}
  6. this._body= {}
  7. this._queue= []
  8. this._disabled= !1
  9. this._interval= null
  10. this._reportUrl= null
  11. this.isDocumentLoaded =()=>document.readyState === "complete";
  12. this._header.logModuleId = REPORT_MODULE_TYPE,
  13. this._header.url = location.href,
  14. this._header.enviroment = ENV,
  15. this._header.networkType = window.navigator.connection ? window.navigator.connection.type : "unknown",
  16. this._interval = window.setInterval(()=>{
  17. this._flushReport()
  18. }
  19. , 10 * 1e3)
  20. }
  21. disable() {
  22. this._disabled = !0,
  23. this._interval && window.clearInterval(this._interval)
  24. }
  25. updateHeader(e) {
  26. Object.assign(this._header, e)
  27. }
  28. updateBody(e) {
  29. Object.assign(this._body, e)
  30. }
  31. updateReportUrl(e) {
  32. this._reportUrl = e
  33. }
  34. report(e, t, r) {
  35. if (this._disabled)
  36. return;
  37. r || (r = {});
  38. const {immediate: n, sampleRate: o} = r;
  39. if (o && o > Math.random())
  40. return;
  41. this.updateBody({
  42. logTime: util.getFormattedDate(new Date),
  43. logTimestamp: Date.now()
  44. });
  45. const a = s=>{
  46. const l = oe(le(oe({}, this._body), {
  47. type: e
  48. }), s);
  49. this._queue.push(l),
  50. e === "measurement" && this.emit("report", s)
  51. }
  52. ;
  53. Array.isArray(t) ? t.forEach(s=>a(s)) : a(t),
  54. (n || this._queue.length >= REPORT_NUM_PER_REQUEST) && this._flushReport()
  55. }
  56. _flushReport() {
  57. if (this._disabled || !this._queue.length || !this.isDocumentLoaded())
  58. return;
  59. const e = {
  60. header: this._header,
  61. body: this._queue.splice(0, REPORT_NUM_PER_REQUEST)
  62. };
  63. this._post(e)
  64. }
  65. _post(e) {
  66. const t = this._reportUrl || REPORT_URL.DEV;
  67. // return new Promise((r,n)=>{
  68. // const o = new XMLHttpRequest;
  69. // o.open("POST", t),
  70. // o.setRequestHeader("Content-Type", "application/json");
  71. // try {
  72. // o.send(JSON.stringify(e))
  73. // } catch (a) {
  74. // console.error(a)
  75. // }
  76. // o.addEventListener("readystatechange", ()=>{
  77. // if (o.readyState == 4)
  78. // return o.status == 200 ? r(o) : n("Unable to send log")
  79. // }
  80. // )
  81. // }
  82. // )
  83. }
  84. }
  85. const reporter = new Reporter();
  86. export { reporter };