@sanseng/liveavatar-js-sdk-skywalking 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -20,35 +20,474 @@
20
20
  !function(){var e,t,r={"./src/index.ts":function(){function e(){return Math.random()}function t(e){return e>=10?"".concat(e):"0".concat(e)}function r(e){var r,n=new Date;return {year:t(n.getFullYear()),month:t(n.getMonth()+1),day:t(n.getDate()),hours:t(n.getHours()),minutes:t(n.getMinutes()),seconds:t(n.getSeconds()),miSeconds:(r=n.getMilliseconds(),"0000".concat(r).slice(-3))}}function n(){var e={browser:"",browserVersion:"",os:"",osVersion:"",UA:navigator.userAgent};return function(e){var t=navigator.userAgent,r={Chrome:/Chrome/,IE:/MSIE/,Firefox:/Firefox/,Opera:/Presto/,Safari:/Version\/([\d.]+).*Safari/,360:/360SE/,QQBrowser:/QQ/};for(var n in r)r[n].test(t)&&(e.browser=n,"Chrome"===n?e.browserVersion=t.split("Chrome/")[1].split(" ")[0]:"IE"===n?e.browserVersion=t.split("MSIE ")[1].split(" ")[1]:"Firefox"===n?e.browserVersion=t.split("Firefox/")[1]:"Opera"===n?e.browserVersion=t.split("Version/")[1]:"Safari"===n?e.browserVersion=t.split("Version/")[1].split(" ")[0]:"360"===n?e.browserVersion="":"QQBrowser"===n&&(e.browserVersion=t.split("Version/")[1].split(" ")[0]));}(e),function(e){var t=navigator.userAgent,r={iPhone:/iPhone/,iPad:/iPad/,Android:/Android/,Windows:/Windows/,Mac:/Macintosh/};for(var n in r)r[n].test(t)&&(e.os=n,"Windows"===n?e.osVersion=t.split("Windows NT ")[1].split(";")[0]:"Mac"===n?e.osVersion=t.split("Mac OS X ")[1].split(")")[0]:"iPhone"===n?e.osVersion=t.split("iPhone OS ")[1].split(" ")[0]:"iPad"===n?e.osVersion=t.split("iPad; CPU OS ")[1].split(" ")[0]:"Android"===n&&(e.osVersion=t.split("Android ")[1].split(";")[0]));}(e),e}function o(e){return e.replace(/(\d+)|./g,(function(e,t){return t?"*":e}))}function i(e){return e>0?Math.floor(e):0}var a,c,s;!function(e){e.AJAX_ERROR="ajax",e.FETCH_ERROR="fetch",e.RESOURCE_ERROR="resource",e.VUE_ERROR="vue",e.PROMISE_ERROR="promise",e.JS_ERROR="js",e.WHITE_SCREEN_ERROR="whiteScreen",e.UNKNOWN_ERROR="unknown";}(a||(a={})),function(e){e.INFO="Info",e.WARNING="Warning",e.ERROR="Error";}(c||(c={})),function(e){e.ERROR="/browser/errorELKLog",e.ERRORS="/browser/errorELKLogs",e.PERF="/browser/perfData",e.SEGMENT="/v3/segment",e.SEGMENTS="/v3/segments",e.SLOW_INTERACTIONS="/browser/perfData";}(s||(s={}));var u,l="Http",f="Exit";!function(e){e[e.OPENED=1]="OPENED",e[e.DONE=4]="DONE";}(u||(u={}));var p=10001,h="<browser>",d=2048,v="--- FETCH ERROR START: ",y="FETCH ERROR START END ---";var g={getLogTime:function(){var e=r(),t=e.year,n=e.month,o=e.day,i=e.hours,a=e.minutes,c=e.seconds,s=e.miSeconds;return "".concat(t,"-").concat(n,"-").concat(o," ").concat(i,":").concat(a,":").concat(c,".").concat(s)}},m=function(){return m=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},m.apply(this,arguments)},w=navigator.userAgent.toLowerCase();var b={getUserid:function(){var e=document.cookie,t="";if(0!==e.length)for(var r=e.split(";"),n=0;n<r.length;n++){var o=r[n].split("="),i=o[0],a=o[1];"userid"===i.trim()&&(t=a.trim());}return t||function(){var e=w.indexOf("userid/");if(e>-1)return w.substr(e+7).split(" ")[0].replace(/^-/,"")}()}},E=b=m(m({},b),g),R=function(){return R=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},R.apply(this,arguments)};function S(e,t){if(["SLOW_INTERACTIONS"].indexOf(e)>-1)return function(e){if(!e)return "";var t=Array.isArray(e)?e:[e],r="";return t.forEach((function(e){r+="".concat(JSON.stringify(e),"\n");})),r}(t);if(-1===["ERRORS","ERROR"].indexOf(e))return JSON.stringify(t);var r="",i=E.getUserid(),a=n(),c=[];return t.forEach((function(e){var t=e.category,n=e.logtime;if("ajax"===t)c.push(n);else if("promise"===t&&c.indexOf(n)>-1)return;var s=e.stack;if(s)try{"string"!=typeof s&&(s=JSON.stringify(s));var u=s.match(/(?:([^\s\(]+)\s*\()?\s*(https?:\/\/[^:\s]+(?:\/[^:\s]*)*):(\d+):(\d+)\)?/);u&&u[0]&&(s=s.split(u[0])[0]+u[0],e.stack=s);}catch(e){}if(i&&(e.userid=i),(e=R(R({},e),a)).pagePath){var l=o(e.pagePath),f=e.pagePath.startsWith("/")?"":"/";e.pagePath.startsWith("http")?e.groupedPagePath=e.pagePath:e.groupedPagePath=location.origin+f+l;}r+="".concat(JSON.stringify(e),"\n");})),r}var T=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},O=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},k=function(){function e(e,t,r){switch(this.url="",this.type="",this.hook=void 0,r&&(this.hook=r),this.type=e,e){case "ERROR":this.url=t+s.ERROR;break;case "ERRORS":this.url=t+s.ERRORS;break;case "SEGMENT":this.url=t+s.SEGMENT;break;case "SEGMENTS":this.url=t+s.SEGMENTS;break;case "PERF":this.url=t+s.PERF;break;case "SLOW_INTERACTIONS":this.url=t+s.SLOW_INTERACTIONS;}if(t.includes("//apm.myhexin.com/apm-web/")){var n="isZip=0";"ERRORS"===e?this.url+="?appId=skywalking-log&".concat(n):"PERF"===e&&(this.url+="?appId=skywalking-perf-log&".concat(n));}}return e.prototype.send=function(e){return T(this,void 0,void 0,(function(){var t,r;return O(this,(function(n){switch(n.label){case 0:return this.url?this.hook?[4,this.hook({type:this.type,url:this.url,data:e})]:[3,2]:[2];case 1:if(!n.sent())return [2];n.label=2;case 2:return (t=new XMLHttpRequest).open("post",this.url,true),t.setRequestHeader("Content-Type","application/json"),t.onreadystatechange=function(){4===t.readyState&&t.status<400&&console.log("Report successfully");},r=S(this.type,e),t.send(r),[2]}}))}))},e}();function I(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var r=16*e()|0;return ("x"===t?r:3&r|8).toString(16)}))}var x=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},P=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}};var _,C=location.host,L="v1.1.27",A=function(e,t){ void 0===t&&(t=[]);var r,n={uniqueId:window.ELK_WHITESCREEN_TRACEID||I(),collector:"",service:"",serviceVersion:"",group:"",subGroup:"",pagePath:"",domain:C,sdkVersion:L};return (r=["collector","service","serviceVersion","group","subGroup","pagePath","reportHook","pageKey"],t.forEach((function(e){ -1===r.indexOf(e)&&r.push(e);})),r).forEach((function(t){var r;if("pagePath"!==t||e[t])n[t]="reportHook"===t?(null===(r=e.hooks)||void 0===r?void 0:r.reportHook)||e.reportHook:e[t];else {var o=location.pathname,i=location.hash,a="";o&&"/"!==o&&(a+=o),i&&(a+=o?i:i.replace("#","")),n[t]=a||"/";}})),n.logtime=E.getLogTime(),n},H=function(e,t){var r=t,n=e.extraMsg;return n&&("function"==typeof n&&(n=n()),r="".concat(r," -(").concat(n,")")),r},q=function(e,t){return x(void 0,void 0,void 0,(function(){var r,n;return P(this,(function(o){switch(o.label){case 0:if("function"!=typeof(r=(null===(n=e.hooks)||void 0===n?void 0:n.filterHook)||e.filterHook))return [3,4];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,r(t)];case 2:return [2,o.sent()];case 3:return o.sent(),[2,true];case 4:return [2,true]}}))}))},M=function(){function e(){}return e.prototype.getPerfTiming=function(e){try{return this._returnPerfData(e)}catch(e){throw e}},e.prototype._returnPerfData=function(e){var t=function(){if(window.performance&&window.performance.timing)return window.performance.timing}();if(t){var r={redirectTime:void 0!==t.navigationStart?i(t.fetchStart-t.navigationStart):void 0!==t.redirectEnd?i(t.redirectEnd-t.redirectStart):0,dnsTime:i(t.domainLookupEnd-t.domainLookupStart),tcpTime:i(t.connectEnd-t.connectStart),ttfbTime:i(t.responseStart-t.requestStart),transTime:i(t.responseEnd-t.responseStart),domAnalysisTime:i(t.domContentLoadedEventStart-t.domLoading),fptTime:i(t.responseEnd-t.fetchStart),domReadyTime:i(t.domContentLoadedEventEnd-t.fetchStart),resTime:i(t.loadEventStart-t.domContentLoadedEventEnd),loadPageTime:i(t.loadEventEnd-t.fetchStart),sslTime:"https:"===location.protocol&&t.secureConnectionStart>0?i(t.connectEnd-t.secureConnectionStart):void 0,ttlTime:i(t.domInteractive-t.fetchStart),firstPackTime:i(t.responseStart-t.domainLookupStart),sdkVersion:L};if(e){var n=["script","link","img"],o=[];performance.getEntries().forEach((function(e,t){if(t){var r=e.name,i=e.initiatorType,a=e.transferSize,c=e.responseEnd,s=e.startTime;if(-1!==n.indexOf(i)){var u=Math.round(c-s),l=r.split("/").pop().replace(/^;/,"");o.push({name:l,type:i,size:a,time:u});}}})),r.entries=o;}return r}console.log("your browser do not support performance");},e}(),D=M,j=-1,N=function(e){addEventListener("pageshow",(function(t){t.persisted&&(j=t.timeStamp,e(t));}),true);},U=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},F=function(){var e=U();return e&&e.activationStart||0},G=function(e,t){var r=U(),n="navigate";return j>=0?n="back-forward-cache":r&&(document.prerendering||F()>0?n="prerender":document.wasDiscarded?n="restore":r.type&&(n=r.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:n}},W=function(e,t,r){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var n=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries());}));}));return n.observe(Object.assign({type:e,buffered:!0},r||{})),n}}catch(e){}},V=function(e,t,r,n){var o,i;return function(a){t.value>=0&&(a||n)&&((i=t.value-(o||0))||void 0===o)&&(o=t.value,t.delta=i,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,r),e(t));}},B=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}));},Q=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e();}));},K=function(e){var t=false;return function(){t||(e(),t=true);}},J=-1,X=function(){return "hidden"!==document.visibilityState||document.prerendering?1/0:0},z=function(e){"hidden"===document.visibilityState&&J>-1&&(J="visibilitychange"===e.type?e.timeStamp:0,Z());},Y=function(){addEventListener("visibilitychange",z,true),addEventListener("prerenderingchange",z,true);},Z=function(){removeEventListener("visibilitychange",z,true),removeEventListener("prerenderingchange",z,true);},$=function(){return J<0&&(J=X(),Y(),N((function(){setTimeout((function(){J=X(),Y();}),0);}))),{get firstHiddenTime(){return J}}},ee=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),true):e();},te=[1800,3e3],re=function(e,t){t=t||{},ee((function(){var r,n=$(),o=G("FCP"),i=W("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(i.disconnect(),e.startTime<n.firstHiddenTime&&(o.value=Math.max(e.startTime-F(),0),o.entries.push(e),r(true)));}));}));i&&(r=V(e,o,te,t.reportAllChanges),N((function(n){o=G("FCP"),r=V(e,o,te,t.reportAllChanges),B((function(){o.value=performance.now()-n.timeStamp,r(true);}));})));}));},ne=[.1,.25],oe=0,ie=1/0,ae=0,ce=function(e){e.forEach((function(e){e.interactionId&&(ie=Math.min(ie,e.interactionId),ae=Math.max(ae,e.interactionId),oe=ae?(ae-ie)/7+1:0);}));},se=function(){return _?oe:performance.interactionCount||0},ue=function(){"interactionCount"in performance||_||(_=W("event",ce,{type:"event",buffered:true,durationThreshold:0}));},le=[],fe=new Map,pe=0,he=[],de=function(e){if(he.forEach((function(t){return t(e)})),e.interactionId||"first-input"===e.entryType){var t=le[le.length-1],r=fe.get(e.interactionId);if(r||le.length<10||e.duration>t.latency){if(r)e.duration>r.latency?(r.entries=[e],r.latency=e.duration):e.duration===r.latency&&e.startTime===r.entries[0].startTime&&r.entries.push(e);else {var n={id:e.interactionId,latency:e.duration,entries:[e]};fe.set(n.id,n),le.push(n);}le.sort((function(e,t){return t.latency-e.latency})),le.length>10&&le.splice(10).forEach((function(e){return fe.delete(e.id)}));}}},ve=function(e){var t=self.requestIdleCallback||self.setTimeout,r=-1;return e=K(e),"hidden"===document.visibilityState?e():(r=t(e),Q(e)),r},ye=[200,500],ge=function(e,t){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(t=t||{},ee((function(){var r;ue();var n,o=G("INP"),i=function(e){ve((function(){e.forEach(de);var t=function(){var e=Math.min(le.length-1,Math.floor((se()-pe)/50));return le[e]}();t&&t.latency!==o.value&&(o.value=t.latency,o.entries=t.entries,n());}));},a=W("event",i,{durationThreshold:null!==(r=t.durationThreshold)&&void 0!==r?r:40});n=V(e,o,ye,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:true}),Q((function(){i(a.takeRecords()),n(true);})),N((function(){pe=se(),le.length=0,fe.clear(),o=G("INP"),n=V(e,o,ye,t.reportAllChanges);})));})));},me=[800,1800],we=function e(t){document.prerendering?ee((function(){return e(t)})):"complete"!==document.readyState?addEventListener("load",(function(){return e(t)}),true):setTimeout(t,0);},be=function(e,t){t=t||{};var r=G("TTFB"),n=V(e,r,me,t.reportAllChanges);we((function(){var o=U();o&&(r.value=Math.max(o.responseStart-F(),0),r.entries=[o],n(true),N((function(){r=G("TTFB",0),(n=V(e,r,me,t.reportAllChanges))(true);})));}));},Ee=(function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,t||[])).next());}))}),Re=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},Se=function(){function e(){}return e.prototype.createMetricPromise=function(e,t){return void 0===t&&(t=3e3),new Promise((function(r){var n=setTimeout((function(){return r(void 0)}),t),o=false,i=function(e){o||(o=true,clearTimeout(n),r(e));};try{e(i);}catch(e){i(void 0);}}))},e.prototype.getFCP=function(){return Ee(this,void 0,void 0,(function(){return Re(this,(function(e){return [2,this.createMetricPromise((function(e){re((function(t){return e(t.value)}));}))]}))}))},e.prototype.getTTFB=function(){return Ee(this,void 0,void 0,(function(){return Re(this,(function(e){return [2,this.createMetricPromise((function(e){be((function(t){return e(t.value)}));}))]}))}))},e.prototype.getCLS=function(){return Ee(this,void 0,void 0,(function(){return Re(this,(function(e){return [2,new Promise((function(e){var t;try{!function(e,t){t=t||{},re(K((function(){var r,n=G("CLS",0),o=0,i=[],a=function(e){e.forEach((function(e){if(!e.hadRecentInput){var t=i[0],r=i[i.length-1];o&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(o+=e.value,i.push(e)):(o=e.value,i=[e]);}})),o>n.value&&(n.value=o,n.entries=i,r());},c=W("layout-shift",a);c&&(r=V(e,n,ne,t.reportAllChanges),Q((function(){a(c.takeRecords()),r(!0);})),N((function(){o=0,n=G("CLS",0),r=V(e,n,ne,t.reportAllChanges),B((function(){return r()}));})),setTimeout(r,0));})));}((function(e){t=Math.round(1e4*e.value)/1e4;}),{reportAllChanges:!0});}catch(t){return void e(void 0)}setTimeout((function(){e(null!=t?t:0);}),5e3);}))]}))}))},e.prototype.getINP=function(){return Ee(this,void 0,void 0,(function(){return Re(this,(function(e){return [2,new Promise((function(e){var t;try{ge((function(e){t=e.value;}),{reportAllChanges:!0});}catch(t){return void e(void 0)}setTimeout((function(){e(t);}),5e3);}))]}))}))},e.prototype.getLCP=function(){return Ee(this,void 0,void 0,(function(){return Re(this,(function(e){return [2,new Promise((function(e){var t,r,n=false,o=0,i=function(t){n||(n=true,e(t));};try{var a=new PerformanceObserver((function(e){for(var t=0,r=e.getEntries();t<r.length;t++){var n=r[t];o=n.startTime;}}));a.observe({type:"largest-contentful-paint",buffered:!0});var c=function(){"hidden"===document.visibilityState&&(document.removeEventListener("visibilitychange",c),a.disconnect(),i(o||void 0));};r=function(){t.forEach((function(e){return document.removeEventListener(e,r)})),a.disconnect(),i(o||void 0);},(t=["click","keydown","touchstart"]).forEach((function(e){return document.addEventListener(e,r,{once:!0})})),document.addEventListener("visibilitychange",c),setTimeout((function(){n||(document.removeEventListener("visibilitychange",c),a.disconnect(),i(o||void 0));}),5e3);}catch(e){i(void 0);}}))]}))}))},e.prototype._roundToInteger=function(e){return e?Math.round(e):e},e.prototype.getNewPerf=function(){return Ee(this,void 0,void 0,(function(){var e,t,r,n,o,i,a;return Re(this,(function(c){switch(c.label){case 0:return e=[this.getFCP(),this.getLCP(),this.getTTFB(),this.getCLS(),this.getINP()],[4,Promise.all(e)];case 1:return t=c.sent(),r=t[0],n=t[1],o=t[2],i=t[3],a=t[4],r=this._roundToInteger(r),n=this._roundToInteger(n),o=this._roundToInteger(o),a=this._roundToInteger(a),[2,{fcpTime:r,lcpTime:n,ttfbTime:o,clsScore:i,inpTime:a}]}}))}))},e}();var Te,Oe=Se,ke=function(e,t){return window.getComputedStyle?window.getComputedStyle(e,null)[t]:e.currentStyle[t]};!function(e){e[e.SVG=2]="SVG",e[e.IMG=2]="IMG",e[e.CANVAS=4]="CANVAS",e[e.OBJECT=4]="OBJECT",e[e.EMBED=4]="EMBED",e[e.VIDEO=4]="VIDEO";}(Te||(Te={}));var Ie=performance.now(),xe=["SCRIPT","STYLE","META","HEAD","LINK"],Pe=window.innerWidth,_e=window.innerHeight,Ce=function(){function e(){this.fmpTime=0,this.statusCollector=[],this.flag=true,this.observer=null,this.callbackCount=0,this.entries={},performance&&performance.getEntries?this.initObserver():console.log("your browser do not support performance.getEntries");}return e.prototype.getFirstSnapShot=function(){var e=performance.now(),t=document.body;t&&this.setTag(t,this.callbackCount),this.statusCollector.push({time:e});},e.prototype.initObserver=function(){var e=this;this.getFirstSnapShot(),this.observer=new MutationObserver((function(){e.callbackCount+=1;var t=performance.now(),r=document.body;r&&e.setTag(r,e.callbackCount),e.statusCollector.push({time:t});})),this.observer.observe(document,{childList:true,subtree:true}),"complete"===document.readyState?this.calculateFinalScore():window.addEventListener("load",(function(){e.calculateFinalScore();}),false);},e.prototype.calculateFinalScore=function(){var e=this;if(window.MutationEvent&&this.flag)if(this.checkNeedCancel(Ie)){this.observer.disconnect(),this.flag=false;for(var t=null,r=0,n=this.getTreeScore(document.body).dpss;r<n.length;r++){var o=n[r];t&&t.st?t.st<o.st&&(t=o):t=o;}if(performance.getEntries().forEach((function(t){e.entries[t.name]=t.responseEnd;})),!t)return false;var i=this.filterResult(t.els),a=this.getFmpTime(i);this.fmpTime=a;}else setTimeout((function(){e.calculateFinalScore();}),500);},e.prototype.getFmpTime=function(e){var t=0;try{for(var r=0,n=e;r<n.length;r++){var o=n[r],i=0;if(1===o.weight){var a=parseInt(o.ele.getAttribute("fmp_c"),10);i=this.statusCollector[a].time;}else if(2===o.weight)if("IMG"===o.ele.tagName)i=this.entries[o.ele.src];else if("SVG"===o.ele.tagName){a=parseInt(o.ele.getAttribute("fmp_c"),10);i=this.statusCollector[a].time;}else {var c=ke(o.ele,"background-image").match(/url\(\"(.*?)\"\)/),s=void 0;c&&c[1]&&(s=c[1]),(null==s?void 0:s.indexOf("http"))>-1&&(s=location.protocol+(c&&c[1]||"-")),i=this.entries[s];}else if(4===o.weight)if("CANVAS"===o.ele.tagName){a=parseInt(o.ele.getAttribute("fmp_c"),10);i=this.statusCollector[a]&&this.statusCollector[a].time;}else "VIDEO"===o.ele.tagName&&((i=this.entries[o.ele.src])||(i=this.entries[o.ele.poster]));"number"!=typeof i&&(i=0),t<i&&(t=i);}}catch(e){console.warn(e);}return t},e.prototype.filterResult=function(e){if(1===e.length)return e;var t=0;e.forEach((function(e){t+=e.st;}));var r=t/e.length;return e.filter((function(e){return e.st>r}))},e.prototype.checkNeedCancel=function(e){var t=performance.now()-e,r=this.statusCollector.length>0?this.statusCollector[this.statusCollector.length-1].time:0;return t>3e3||t-r>1e3},e.prototype.getTreeScore=function(e){if(!e)return {};for(var t=[],r=0,n=e.children;r<n.length;r++){var o=n[r];if(o.getAttribute("fmp_c")){var i=this.getTreeScore(o);i.st&&t.push(i);}}return this.calcaulteGrades(e,t)},e.prototype.calcaulteGrades=function(e,t){var r=e.getBoundingClientRect(),n=r.width,o=r.height,i=r.left,a=r.top,c=true;(_e<a||Pe<i)&&(c=false);var s=0;t.forEach((function(e){s+=e.st;}));var u=Number(Te[e.tagName])||1;1===u&&ke(e,"background-image")&&"initial"!==ke(e,"background-image")&&"none"!==ke(e,"background-image")&&(u=Te.IMG);var l=c?n*o*u:0,f=[{ele:e,st:l,weight:u}],p=e,h=this.calculateAreaParent(e);if(s>l*h||0===h){l=s,f=[];for(var d=0,v=t;d<v.length;d++){var y=v[d];f=f.concat(y.els);}}return {dpss:t,st:l,els:f,root:p}},e.prototype.calculateAreaParent=function(e){var t=e.getBoundingClientRect(),r=t.left,n=t.right,o=t.top,i=t.bottom,a=t.width,c=t.height,s=Pe,u=_e,l=n-r+(s-0)-(Math.max(n,s)-Math.min(r,0)),f=i-o+(u-0)-(Math.max(i,u)-Math.min(o,0));return l<=0||f<=0?0:l*f/(a*c)},e.prototype.setTag=function(e,t){var r=e.tagName;if(-1===xe.indexOf(r)){var n=e.children;if(n&&n.length>0)for(var o=n.length-1;o>=0;o--){var i=n[o];if(!(null!==i.getAttribute("fmp_c"))){var a=i.getBoundingClientRect(),c=a.left,s=a.top,u=a.width,l=a.height;if(_e<s||Pe<c||0===u||0===l)continue;i.setAttribute("fmp_c","".concat(t));}this.setTag(i,t);}}},e}(),Le=Ce,Ae=function(){return Ae=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},Ae.apply(this,arguments)},He=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},qe=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},Me=new(function(){function e(){this.timer=null,this.customPerfDetail={},this.perfConfig={perfDetail:{}};}return e.prototype.recordPerf=function(e){return He(this,void 0,void 0,(function(){var t,r,i,a,c=this;return qe(this,(function(s){return t=e.options,r=e.uniqueId,i=e.customPerf,a=void 0===i?{}:i,this.timer?(this.customPerfDetail=Ae(Ae({},this.customPerfDetail),a),clearTimeout(this.timer)):this.customPerfDetail=Ae(Ae({},this.customPerfDetail),a),this.timer=setTimeout((function(){return He(c,void 0,void 0,(function(){var e,i,a,c,s,u,l,f,p,h,d,v,y,g,m,w,b,R;return qe(this,(function(S){switch(S.label){case 0:e=new D,this.perfConfig.perfDetail=e.getPerfTiming(t.perfEntries),t.useFmp&&(i=new Le,this.perfConfig.perfDetail.fmpTime=parseInt(String((null==i?void 0:i.fmpTime)||0),10)),S.label=1;case 1:return S.trys.push([1,3,,4]),[4,(new Oe).getNewPerf()];case 2:return c=S.sent(),a=Ae(Ae(Ae({},this.perfConfig.perfDetail),c),this.customPerfDetail),[3,4];case 3:return S.sent(),[3,4];case 4:return s=t.pagePath,u=t.group,l=t.subGroup,f=t.service,p=t.serviceVersion,(h=s)||(h=location.href.replace(location.origin,"")||"/"),d=E.getLogTime(),v=n(),y=Ae(Ae(Ae({},a),{pagePath:h,group:u,subGroup:l,service:f,serviceVersion:p,logtime:d}),v),(g=E.getUserid())&&(y.userid=g),r&&(y.uniqueId=r),s&&(m=o(s),w=s.startsWith("/")?"":"/",s.startsWith("http")?y.groupedPagePath=s:y.groupedPagePath=location.origin+w+m),b=(null===(R=t.hooks)||void 0===R?void 0:R.reportHook)||t.reportHook,[4,new k("PERF",t.collector,b).send(y)];case 5:return S.sent(),this.clearPerf(),[2]}}))}))}),t.sendPerfTime||6e3),[2]}))}))},e.prototype.clearPerf=function(){window.performance&&window.performance.clearResourceTimings&&(window.performance.clearResourceTimings(),this.perfConfig={perfDetail:{}},this.customPerfDetail={},clearTimeout(this.timer));},e}()),De=10240;function je(e,t,r){if(void 0===t&&(t=De),e)try{var n=e;if("string"==typeof e)n=e;else if(e instanceof FormData){var o={};try{for(var i=(u=e.entries()).next();!i.done;){var a=i.value,c=a[0];(f=a[1])instanceof File?o[c]="[File: ".concat(f.name,", size: ").concat(f.size,"]"):o[c]=f,i=u.next();}}catch(e){o._error="[FormData parsing failed]";}n=JSON.stringify(o);}else if(e instanceof URLSearchParams){var s={};try{var u;for(i=(u=e.entries()).next();!i.done;){var l=i.value,f=(c=l[0],l[1]);s[c]=f,i=u.next();}}catch(e){s._error="[URLSearchParams parsing failed]";}n=JSON.stringify(s);}else n=e instanceof ArrayBuffer?"[Binary data, size: ".concat(e.byteLength,"]"):e instanceof Uint8Array?"[Binary data, size: ".concat(e.length,"]"):JSON.stringify(e);if(r&&"function"==typeof r)try{var p=r("string"==typeof n?JSON.parse(n):n);n="string"==typeof p?p:JSON.stringify(p);}catch(e){}return "string"==typeof n&&n.length>t?n.substring(0,t)+"... [truncated]":"string"==typeof n?n:JSON.stringify(n)}catch(e){return "[Error processing request body]"}}function Ne(e){if(e)try{var t={};if(e instanceof Headers)try{for(var r=e.entries(),n=r.next();!n.done;){var o=n.value,i=o[0],a=o[1];i.toLowerCase().includes("content-type")||i.toLowerCase().includes("user-agent")||i.toLowerCase().includes("authorization")||i.toLowerCase().includes("cookie")||i.toLowerCase().includes("token")||i.toLowerCase().includes("sw8")||(t[i]=a),n=r.next();}}catch(e){t._error="[Headers parsing failed]";}else if("object"==typeof e)for(var c=0,s=Object.entries(e);c<s.length;c++){var u=s[c];i=u[0],a=u[1];i.toLowerCase().includes("content-type")||i.toLowerCase().includes("user-agent")||i.toLowerCase().includes("authorization")||i.toLowerCase().includes("cookie")||i.toLowerCase().includes("token")||i.toLowerCase().includes("sw8")||(t[i]=String(a));}return Object.keys(t).length>0?t:void 0}catch(e){return}}function Ue(e){return Boolean(e.collectRequestParams)}var Fe=function(){return Fe=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},Fe.apply(this,arguments)},Ge=function(e){return window.btoa(e)};function We(e,t){var r=window.XMLHttpRequest,n=XMLHttpRequest.prototype.send,o=XMLHttpRequest.prototype.open;function i(e){var t=new CustomEvent(e,{detail:this});window.dispatchEvent(t);}r.getRequestConfig=[],window.XMLHttpRequest=function(){var t=new r;return t.addEventListener("readystatechange",(function(){i.call(this,"xhrReadyStateChange");}),false),t.open=function(e,t,r,n,i){return this.getRequestConfig=arguments,o.apply(this,arguments)},t.send=function(t){var r;return Ue(e)&&t&&(this.requestBody=je(t,e.maxRequestBodySize,null===(r=e.hooks)||void 0===r?void 0:r.requestParamsHook)),n.apply(this,arguments)},t};var a=[];window.addEventListener("xhrReadyStateChange",(function(r){var n,o={traceId:"",service:e.service+h,spans:[],serviceInstance:e.serviceVersion,traceSegmentId:""},i=r.detail.readyState,c=r.detail.getRequestConfig,d=c[1],v={};0===c[1].indexOf("http://")||0===c[1].indexOf("https://")?v=new URL(c[1]):0===c[1].indexOf("//")?v=new URL("".concat(window.location.protocol).concat(c[1])):(v=new URL(window.location.href)).pathname=c[1];if((!(null===(n=e.noTraceUrls)||void 0===n?void 0:n.length)||!e.noTraceUrls.some((function(e){if("string"==typeof e){if(e===d)return true}else if(e instanceof RegExp&&e.test(d))return true})))&&(!([s.ERROR,s.ERRORS,s.PERF,s.SEGMENTS].indexOf(v.pathname)>-1)||e.traceSDKInternal)){if(i===u.OPENED){var y=I(),g=I();a.push({event:r.detail,startTime:(new Date).getTime(),traceId:y,traceSegmentId:g});var m=window.ELK_WHITESCREEN_TRACEID||String(Ge(y)),w=String(Ge(g)),b=String(Ge(o.service)),E=String(Ge(o.serviceInstance)),R=String(Ge(e.pagePath)),S=String(Ge(v.host)),T=o.spans.length,O="".concat(1,"-").concat(m,"-").concat(w,"-").concat(T,"-").concat(b,"-").concat(E,"-").concat(R,"-").concat(S);r.detail.setRequestHeader("sw8",O),sessionStorage.setItem("current-sw-traceId",m);}if(i===u.DONE){for(var k=(new Date).getTime(),x=0;x<a.length;x++)if(a[x].event.readyState===u.DONE){var P={};a[x].event.status&&(P=new URL(a[x].event.responseURL));var _={operationName:e.pagePath,startTime:a[x].startTime,endTime:k,spanId:o.spans.length,spanLayer:l,spanType:f,isError:0===r.detail.status||r.detail.status>=400,parentSpanId:o.spans.length-1,componentId:p,peer:P.host,tags:e.detailMode?[{key:"http.method",value:c[0]},{key:"url",value:a[x].event.responseURL}]:void 0};(o=Fe(Fe({},o),{traceId:a[x].traceId,traceSegmentId:a[x].traceSegmentId})).spans.push(_),a.splice(x,1);}t.push(o);}}}));}var Ve=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},Be=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}};var Qe=function(){function e(e,t){ void 0===e&&(e=100),this.slowInteractions=[],this.observer=null,this.isSupported=false,this.maxQueueSize=100,this.interactionMap=new Map,this.allowedEventTypes=["pointerup","click","keyup"],this.threshold=e,this.onQueueFull=t,this.isSupported=this.checkBrowserSupport();}return e.prototype.checkBrowserSupport=function(){if("undefined"==typeof window)return false;if(!("PerformanceObserver"in window))return false;try{var e=PerformanceObserver.supportedEntryTypes;if(!e||!e.includes("event"))return !1}catch(e){return false}return true},e.prototype.isSupportedBrowser=function(){return this.isSupported},e.prototype.start=function(){var e=this;if(!this.isSupported)return this.slowInteractions;try{this.observer=new PerformanceObserver((function(t){try{e.handlePerformanceEntries(t.getEntries());}catch(e){}})),this.observer.observe({type:"event",buffered:!0});}catch(e){}return this.slowInteractions},e.prototype.stop=function(){this.observer&&(this.observer.disconnect(),this.observer=null);},e.prototype.handlePerformanceEntries=function(e){for(var t=0,r=e;t<r.length;t++){var n=r[t];"interactionId"in n&&n.interactionId&&n.interactionId>0?this.processWithInteractionId(n):this.allowedEventTypes.includes(n.name)&&this.processWithoutInteractionId(n);}},e.prototype.processWithInteractionId=function(e){var t=e.interactionId,r=this.interactionMap.get(t);if(r)e.duration>r.sintDuration&&(r.sintDuration=Math.round(e.duration),r.sintEventType=e.name,r.sintTimestamp=this.getEventTimestamp(e),r.sintTargetClass=this.getTargetClass(e),r.sintTargetTag=this.getTargetTag(e),r.logtime=E.getLogTime());else if(e.duration>this.threshold){var n=this.createInteraction(e,t);this.interactionMap.set(t,n),this.addToQueue(n);}},e.prototype.processWithoutInteractionId=function(e){if(e.duration>this.threshold){var t=this.createInteraction(e);this.addToQueue(t);}},e.prototype.createInteraction=function(e,t){return {logtime:E.getLogTime(),sintTimestamp:this.getEventTimestamp(e),sintDuration:Math.round(e.duration),sintEventType:e.name,sintTargetClass:this.getTargetClass(e),sintTargetTag:this.getTargetTag(e),sintThreshold:this.threshold,sintInteractionId:t}},e.prototype.getEventTimestamp=function(e){try{var t=window.performance,r=t&&t.timeOrigin||t&&t.timing&&t.timing.navigationStart||0;if(r)return Math.round(r+e.startTime)}catch(e){}return Date.now()},e.prototype.addToQueue=function(e){if(this.slowInteractions.length>=this.maxQueueSize)if(this.onQueueFull)this.onQueueFull();else {var t=this.slowInteractions.shift();t.sintInteractionId&&this.interactionMap.delete(t.sintInteractionId);}this.slowInteractions.push(e);},e.prototype.getTargetClass=function(e){try{var t=e.target;if(t&&t.className){if("string"==typeof t.className)return t.className;if(t.className&&"object"==typeof t.className)return t.className.baseVal||""}return ""}catch(e){return ""}},e.prototype.getTargetTag=function(e){try{var t=e.target;return t&&t.tagName?t.tagName.toLowerCase():""}catch(e){return ""}},e.prototype.getSlowInteractions=function(){return this.slowInteractions},e.prototype.clearQueue=function(){this.slowInteractions=[],this.interactionMap.clear();},e}(),Ke=function(){return Ke=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},Ke.apply(this,arguments)},Je=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},Xe=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},ze=function(){function e(e,t){ void 0===e&&(e=100),void 0===t&&(t=3e4);var r=this;this.reportTimer=null,this.options=null,this.unloadListenerAdded=false,this.unloadHandler=null,this.handleQueueFull=function(){r.options&&(r.reportSlowInteractions(),r.reportTimer&&(clearInterval(r.reportTimer),r.reportTimer=null),r.startPeriodicReporting());},this.threshold=e,this.reportInterval=t,this.collector=new Qe(e,this.handleQueueFull);}return e.prototype.start=function(e){e&&(this.options=e);var t=this.collector.start();return this.options&&this.collector.isSupportedBrowser()&&(this.startPeriodicReporting(),this.setupUnloadReporting()),t},e.prototype.startPeriodicReporting=function(){var e=this;this.reportTimer&&clearInterval(this.reportTimer),this.reportTimer=setInterval((function(){e.reportSlowInteractions();}),this.reportInterval);},e.prototype.setupUnloadReporting=function(){var e=this;this.unloadListenerAdded||(this.unloadHandler=function(){e.reportSlowInteractions(true);},window.addEventListener("beforeunload",this.unloadHandler),window.addEventListener("pagehide",this.unloadHandler),this.unloadListenerAdded=true);},e.prototype.reportSlowInteractions=function(e){return Je(this,void 0,void 0,(function(){var e,t,r,o,i,a,c,s,u,l,f,p,h,d;return Xe(this,(function(v){switch(v.label){case 0:if(0===(e=this.collector.getSlowInteractions()).length)return [2];t=e.slice(),this.collector.clearQueue(),v.label=1;case 1:return v.trys.push([1,3,,4]),r=this.options,o=r.group,i=r.subGroup,a=r.service,c=r.serviceVersion,s=r.pagePath,u=r.collector,l=r.hooks,f=E.getUserid(),p=n(),h=t.map((function(e){return Ke(Ke(Ke(Ke({group:o,subGroup:i,service:a,serviceVersion:c,pagePath:s||location.href},e||{}),{sdkVersion:"v1.1.27"}),f?{userid:f}:{}),p)})),d=null==l?void 0:l.reportHook,[4,new k("SLOW_INTERACTIONS",u,d).send(h)];case 2:return v.sent(),[3,4];case 3:return v.sent(),[3,4];case 4:return [2]}}))}))},e.prototype.stop=function(){this.collector.stop(),this.reportTimer&&(clearInterval(this.reportTimer),this.reportTimer=null),this.unloadListenerAdded&&this.unloadHandler&&(window.removeEventListener("beforeunload",this.unloadHandler),window.removeEventListener("pagehide",this.unloadHandler),this.unloadListenerAdded=false,this.unloadHandler=null);},e.prototype.getSlowInteractions=function(){return this.collector.getSlowInteractions()},e.prototype.clearQueue=function(){this.collector.clearQueue();},e.prototype.getConfig=function(){return {threshold:this.threshold,reportInterval:this.reportInterval,queueSize:this.collector.getSlowInteractions().length}},e}(),Ye=null;var Ze,$e=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},et=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},tt=new(function(){function e(){this.queues=[],this.collector="",this.hook=void 0,this.isLock=false;}return e.prototype.addTask=function(e,t,r){this.queues.push(e),this.collector=t,this.hook=r;},e.prototype.fireTasks=function(){return $e(this,void 0,void 0,(function(){return et(this,(function(e){switch(e.label){case 0:return this.queues&&this.queues.length?[4,new k("ERRORS",this.collector,this.hook).send(this.queues)]:[2];case 1:return e.sent(),this.queues=[],[2]}}))}))},e.prototype.finallyFireTasks=function(){var e=this;this.isLock||(this.isLock=true,window.onbeforeunload=function(){e.queues.length&&new k("ERRORS",e.collector,e.hook).send(e.queues);});},e}()),rt=false,nt=function(){function e(){this.logInfo={uniqueId:"",category:a.UNKNOWN_ERROR,service:"",serviceVersion:"",group:"",subGroup:"",pagePath:"",grade:c.INFO,errorUrl:"",line:0,col:0,message:"",firstReportedError:false,collector:"",reportHook:void 0};}return e.prototype.traceInfo=function(e){rt||this.logInfo.category!==a.JS_ERROR||(rt=true,this.logInfo.firstReportedError=true);var t=this.logInfo,r=t.collector,n=t.reportHook;delete this.logInfo.collector,tt.addTask(this.logInfo,r,n),tt.finallyFireTasks(),setTimeout((function(){tt.fireTasks();}),e||3e4);},e}(),ot=(Ze=function(e,t){return Ze=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);},Ze(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e;}Ze(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r);}),it=function(){return it=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},it.apply(this,arguments)},at=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},ct=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},st=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ot(t,e),t.prototype.handleErrors=function(e){var t=this,r=window.onerror;window.onerror=function(n,o,i,s,u){return at(t,void 0,void 0,(function(){var t,l;return ct(this,(function(f){switch(f.label){case 0:return r&&r(n,o,i,s,u),n=H(e,n),t={category:a.JS_ERROR,grade:c.ERROR,errorUrl:o,line:i,col:s,message:n,stack:u&&u.stack||""},[4,q(e,t)];case 1:return f.sent()?(l=A(e,[]),this.logInfo=it(it({},l),t),this.traceInfo(e.sendErrorTime),[2]):[2]}}))}))};},t}(nt),ut=new st,lt=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t;}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n);}}(),ft=function(){return ft=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},ft.apply(this,arguments)},pt=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},ht=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},dt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return lt(t,e),t.prototype.handleErrors=function(e){var t=this;window.addEventListener("unhandledrejection",(function(r){return pt(t,void 0,void 0,(function(){var t,n,o,i,s,u,l,f,p,h;return ht(this,(function(d){switch(d.label){case 0:if(!r||!r.reason)return [2];if(null===(h=null==r?void 0:r.reason)||void 0===h?void 0:h.request)return [2];t="",d.label=1;case 1:return d.trys.push([1,3,,4]),r.reason.config&&r.reason.config.url&&(t=r.reason.config.url),n=r.reason.message||"",n=H(e,n),o=r.reason.stack||"",i={category:a.PROMISE_ERROR,grade:c.ERROR,errorUrl:t||location.href,message:n,stack:o},o.includes(v)&&o.includes(y)&&(s=o.split(y),u=s[0],l=s[1],u=u.replace(v,""),i.category=a.FETCH_ERROR,i.stack=l,i.traceId=u),[4,q(e,i)];case 2:return d.sent()?(f=A(e,[]),this.logInfo=ft(ft({},f),i),this.traceInfo(e.sendErrorTime),[3,4]):[2];case 3:return p=d.sent(),console.log(p),[3,4];case 4:return [2]}}))}))}));},t}(nt),vt=new dt,yt=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t;}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n);}}(),gt=function(){return gt=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},gt.apply(this,arguments)},mt=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},wt=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},bt=400,Et=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return yt(t,e),t.prototype.handleWeblogError=function(e,t){if(!e.includes("//cbasspider.10jqka.com.cn"))return t;return gt(gt({},t),{group:"weblog",service:"weblog",subGroup:"weblog"})},t.prototype.isApmApi=function(e,t,r){var n,o,i,a,c;return !(!e||!e.toString().includes(r))||(!!(null===(i=null===(o=null===(n=null==t?void 0:t.target)||void 0===n?void 0:n.getRequestConfig)||void 0===o?void 0:o[1])||void 0===i?void 0:i.includes(r))||!!(null===(c=null===(a=null==t?void 0:t.target)||void 0===a?void 0:a.pageSpyRequestUrl)||void 0===c?void 0:c.includes(r)))},t.prototype.shouldReportRequest=function(e,t){var r;if(e)return true;var n=null===(r=null==t?void 0:t.currentTarget)||void 0===r?void 0:r.status;return n>=bt||0===n},t.prototype.handleError=function(e){var r=this;if(window.XMLHttpRequest)if(t.isInterceptorRegistered)console.warn("[SkyWalking] AjaxErrors interceptor already registered, skipping duplicate registration");else {t.isInterceptorRegistered=true;var n=window.XMLHttpRequest.prototype,o=n.open,i=n.send,s=n.setRequestHeader,u=o,l=i,f=s,p=new WeakMap,h=new WeakMap,v=function(t){var n=t.start,o=t.xhr;return function(t){return mt(r,void 0,void 0,(function(){var r,i,s,u,l,f,h,v,y,g,m,w,b,E,R,S,T,O,k,I,x,P,_,C,L,M,D,j,N,U;return wt(this,(function(F){switch(F.label){case 0:r=Date.now(),s=(i=r-n)>=e.maxReqCostTime,u=t.type,F.label=1;case 1:if(F.trys.push([1,3,,4]),!this.shouldReportRequest(s,t))return [2];if(l=p.get(o)||{},f=l.url,h=l.method,v=l.headers,y=l.body,g=e.collector,this.isApmApi(f,t,g))return [2];if(m="error"===(null==t?void 0:t.type)&&0===(null===(M=null==t?void 0:t.currentTarget)||void 0===M?void 0:M.status),w=t.currentTarget.status,b=void 0,"timeout"===u?(b="net::timeout (status: ".concat(w,")"),(null===(D=null==t?void 0:t.target)||void 0===D?void 0:D.timeout)&&(b+=", ajax timeout: ".concat(t.target.timeout))):s?b="net::slowRequest (status: ".concat(w,"), maxReqCostTime: ").concat(e.maxReqCostTime):m?(b="net::CORS_ERROR (possible causes: CORS, network failure, timeout)",f&&(b+=", URL: ".concat(f.toString()))):b=w>=bt?"net::REQUEST_ERROR(status: ".concat(w,")"):"net::ERR_EMPTY(status: ".concat(w,")"),(null==(E=t.target.response)?void 0:E.length)>d&&(E=E.replace(/\s/g,"")).length>d&&(E="".concat(E.slice(0,d),"...(").concat(w,")")),R="接口响应正常",s&&(R="慢请求"),("load"!==u||w>=bt)&&(S=f||"unknown URL",R=m?"CORS Error: ".concat(S):w>=bt?"Request failed with status code ".concat(w,", URL: ").concat(S):t.target.response||b,R=H(e,R)),T=f||(null===(N=null===(j=t.target)||void 0===j?void 0:j.getRequestConfig)||void 0===N?void 0:N[1])||(null===(U=t.target)||void 0===U?void 0:U.responseURL)||"",O={},Ue(e)&&(h&&(O.reqMethod=h),(k=Ne(v))&&(O.reqHeaders=k),y&&(O.reqBody=y),"GET"===h&&T))try{(I=new URL(T,window.location.origin)).search&&(x={},I.searchParams.forEach((function(e,t){x[t]=e;})),Object.keys(x).length>0&&(O.reqQuery=x));}catch(e){}return P=gt({category:a.AJAX_ERROR,grade:c.ERROR,errorUrl:T,message:R,reqErrType:u,stack:b},O),(s||"timeout"===u)&&(P.slowRequest=i),"load"!==u&&(P.stack=t.target.response||b),[4,q(e,P)];case 2:return F.sent()?(_=A(e,[]),_=this.handleWeblogError(T,_),this.logInfo=gt(gt({},_),P),C=sessionStorage.getItem("current-sw-traceId"),sessionStorage.removeItem("current-sw-traceId"),C&&(this.logInfo.traceId=C),this.traceInfo(e.sendErrorTime),[3,4]):[2];case 3:return L=F.sent(),console.log(L),[3,4];case 4:return [2]}}))}))}};XMLHttpRequest.prototype.open=function(e,t){p.set(this,{url:t,method:e,headers:{},body:void 0});try{if("function"==typeof u)return u.apply(this,arguments)}catch(e){return console.error("XHR open error:",e),o.apply(this,arguments)}},XMLHttpRequest.prototype.setRequestHeader=function(t,r){if(Ue(e)){var n=p.get(this)||{},o=gt({},n.headers||{});o[t]=r,p.set(this,gt(gt({},n),{headers:o}));}try{if("function"==typeof f)return f.apply(this,arguments)}catch(e){return console.error("XHR setRequestHeader error:",e),s.apply(this,arguments)}},XMLHttpRequest.prototype.send=function(t){var r,n=Date.now(),o=this;if(Ue(e)&&t){var a=p.get(this)||{};p.set(this,gt(gt({},a),{body:je(t,e.maxRequestBodySize,null===(r=e.hooks)||void 0===r?void 0:r.requestParamsHook)}));}if(this.addEventListener){var c=h.get(this);c&&(c.load&&this.removeEventListener("load",c.load),c.error&&this.removeEventListener("error",c.error),c.abort&&this.removeEventListener("abort",c.abort),c.timeout&&this.removeEventListener("timeout",c.timeout));var s={load:v({start:n,xhr:o}),error:v({start:n,xhr:o}),abort:v({start:n,xhr:o}),timeout:v({start:n,xhr:o})};this.addEventListener("load",s.load),this.addEventListener("error",s.error),this.addEventListener("abort",s.abort),this.addEventListener("timeout",s.timeout),h.set(this,s);}else {var u=this.onreadystatechange;this.onreadystatechange=function(e){u&&u.apply(this,arguments),4===this.readyState&&v({start:n,xhr:o})(e);};}try{if("function"==typeof l)return l.apply(this,arguments)}catch(e){return console.error("XHR send error:",e),i.apply(this,arguments)}};}},t.isInterceptorRegistered=false,t}(nt),Rt=new Et;function St(e){var t,r="";return e instanceof Request?(r=e.url,t=new URL(e.url)):0===(r=e.toString()).indexOf("http://")||0===r.indexOf("https://")?t=new URL(r):0===r.indexOf("//")?t=new URL("".concat(window.location.protocol).concat(r)):(t=new URL(window.location.href)).pathname=r,{url:t,originUrl:r}}var Tt=function(){function e(){this.contexts=new Map,this.requestCounter=0;}return e.prototype.setContext=function(e,t){this.contexts.set(e,t),this.cleanupExpiredContexts();},e.prototype.getContext=function(e){return this.contexts.get(e)},e.prototype.removeContext=function(e){this.contexts.delete(e);},e.prototype.generateRequestId=function(){return this.requestCounter++,"fetch_".concat(Date.now(),"_").concat(this.requestCounter)},e.prototype.findContextByUrl=function(e,t){ void 0===t&&(t=5e3);for(var r,n=Date.now(),o=1/0,i=Array.from(this.contexts.values()),a=0;a<i.length;a++){var c=i[a],s=n-c.startTime;s<=t&&c.url===e&&s<o&&(r=c,o=s);}return r},e.prototype.cleanupExpiredContexts=function(){for(var e=Date.now(),t=Array.from(this.contexts.entries()),r=0;r<t.length;r++){var n=t[r],o=n[0];e-n[1].startTime>3e4&&this.contexts.delete(o);}},e.prototype.getContextCount=function(){return this.contexts.size},e.prototype.clear=function(){this.contexts.clear(),this.requestCounter=0;},e}(),Ot=new Tt,kt=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t;}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n);}}(),It=function(){return It=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},It.apply(this,arguments)},xt=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},Pt=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},_t=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return kt(t,e),t.prototype.handleWeblogError=function(e,t){if(!e.includes("//cbasspider.10jqka.com.cn"))return t;return It(It({},t),{group:"weblog",service:"weblog",subGroup:"weblog"})},t.prototype.shouldReportRequest=function(e){return !(null==e?void 0:e.ok)&&(0===e.status||e.status>=400)},t.prototype.handleError=function(e){var r=this;if(window.fetch)if(t.isInterceptorRegistered)console.warn("[SkyWalking] FetchErrors interceptor already registered, skipping duplicate registration");else {t.isInterceptorRegistered=true;var n=window.fetch;window.fetch=function(t,o){return xt(r,void 0,void 0,(function(){var r,i,u,l,f,p,h,d,v,y,g,m,w,b,E,R,S,T,O,k,I,x,P,_,C;return Pt(this,(function(L){switch(L.label){case 0:r={},L.label=1;case 1:if(L.trys.push([1,5,,10]),t instanceof Request)return [2,n(t,o)];if(i=St(t),b=i.url,u=i.originUrl,l=function(e,t,r){var n;if((null===(n=r.noTraceUrls)||void 0===n?void 0:n.length)&&r.noTraceUrls.some((function(e){return "string"==typeof e?e===t:e instanceof RegExp&&e.test(t)})))return {shouldSkip:true,isSDKInternal:false,isAPMApi:false,reason:"url in noTraceUrls list"};var o=[s.ERROR,s.ERRORS,s.PERF,s.SEGMENTS].indexOf(e.pathname)>-1;return o&&!r.traceSDKInternal?{shouldSkip:true,isSDKInternal:true,isAPMApi:false,reason:"SDK internal request"}:e.href.includes(r.collector)?{shouldSkip:true,isSDKInternal:false,isAPMApi:true,reason:"APM API request"}:{shouldSkip:false,isSDKInternal:o,isAPMApi:false}}(b,u,{noTraceUrls:e.noTraceUrls,collector:e.collector,traceSDKInternal:e.traceSDKInternal}),l.shouldSkip)return [2,n(t,o)];if(Ue(e)&&(f=(null==o?void 0:o.method)||"GET",r.reqMethod=f,o&&(r.reqHeaders=Ne(o.headers),r.reqBody=je(o.body,e.maxRequestBodySize,null===(P=e.hooks)||void 0===P?void 0:P.requestParamsHook)),"GET"===f))try{(p=new URL(b,window.location.origin)).search?(h={},p.searchParams.forEach((function(e,t){h[t]=e;})),Object.keys(h).length>0&&(r.reqQuery=h)):null===(C=null===(_=t.toString())||void 0===_?void 0:_.split("?")[1])||void 0===C||C.split("&").forEach((function(e){var t=e.split("="),n=t[0],o=t[1];r.reqQuery||(r.reqQuery={}),r.reqQuery[n]=o;}));}catch(e){}return [4,n(t,o)];case 2:return d=L.sent(),this.shouldReportRequest(d)?(v="",S="Interface response is normal",y=d.status,R=d.url||b.href,0===y?(v="net::CORS_ERROR (possible causes: CORS, network failure, timeout)",S="CORS Error URL: ".concat(R)):y>=400&&(v="net::REQUEST_ERROR(status: ".concat(y,")"),S="Request failed with status code ".concat(y,", URL: ").concat(R)),g=It({category:a.FETCH_ERROR,grade:c.ERROR,errorUrl:d.url||b.href,message:H(e,S),stack:v,reqErrType:"error"},r),e.noErrorPaths&&e.noErrorPaths.length>0&&e.noErrorPaths.some((function(e){return "string"==typeof e?g.errorUrl.indexOf(e)>-1:e instanceof RegExp&&e.test(g.errorUrl)}))?(console.log("The Fetch error was filtered out by noErrorPaths: ".concat(g.errorUrl)),[2,d.clone()]):[4,q(e,g)]):[3,4];case 3:if(!L.sent())return [2,d.clone()];k=A(e,[]),k=this.handleWeblogError(g.errorUrl,k),this.logInfo=It(It({},k),g);try{(null==(I=Ot.findContextByUrl(b.href))?void 0:I.traceId)?this.logInfo.traceId=I.traceId:(m=sessionStorage.getItem("current-sw-traceId"))&&(this.logInfo.traceId=m);}catch(e){console.warn("Failed to get traceId from context:",e);}this.traceInfo(e.sendErrorTime),L.label=4;case 4:return [2,d.clone()];case 5:w=L.sent(),L.label=6;case 6:if(L.trys.push([6,8,,9]),b=St(t).url,E=w instanceof Error?w.message:"Unknown fetch error",R=b.href,S="Fetch exception: ".concat(E,", URL: ").concat(R),T=w instanceof Error?w.stack||w.toString():"net::ERR_FETCH_EXCEPTION",O={category:a.FETCH_ERROR,grade:c.ERROR,errorUrl:R,message:H(e,S),stack:T,reqErrType:"exception"},e.noErrorPaths&&e.noErrorPaths.length>0&&e.noErrorPaths.some((function(e){return "string"==typeof e?O.errorUrl.indexOf(e)>-1:e instanceof RegExp&&e.test(O.errorUrl)})))throw console.log("The Fetch error was filtered out by noErrorPaths:: ".concat(O.errorUrl)),w;return [4,q(e,O)];case 7:if(L.sent()){k=A(e,[]),k=this.handleWeblogError(O.errorUrl,k),this.logInfo=It(It({},k),O);try{(null==(I=Ot.findContextByUrl(b.href))?void 0:I.traceId)&&(this.logInfo.traceId=I.traceId);}catch(e){}this.traceInfo(e.sendErrorTime);}return [3,9];case 8:return x=L.sent(),console.warn("Failed to report fetch error:",x),[3,9];case 9:throw w;case 10:return [2]}}))}))};}},t.isInterceptorRegistered=false,t}(nt),Ct=new _t,Lt=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t;}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n);}}(),At=function(){return At=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},At.apply(this,arguments)},Ht=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},qt=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},Mt=function(e,t,r){for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))},Dt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Lt(t,e),t.prototype.handleErrors=function(e){var t=this;window.addEventListener("error",(function(r){return Ht(t,void 0,void 0,(function(){var t,n,o,i,s,u,l,f,p,h;return qt(this,(function(d){switch(d.label){case 0:if(!r)return [2];d.label=1;case 1:return d.trys.push([1,3,,4]),t=r.target||r.srcElement,t instanceof HTMLScriptElement||t instanceof HTMLLinkElement||t instanceof HTMLImageElement?(n=t.src||t.href||"",o=[location.href,"".concat(location.origin).concat(location.pathname)],!n||o.includes(n)?[2]:(i=[],(i=["stat.10jqka.com.cn","jjstat.10jqka.com.cn","razor.10jqka.com.cn"]).push("/favicon.ico"),Mt(Mt([],i,true),e.noErrorPaths).some((function(e){return n.indexOf(e)>-1}))?[2]:(s="load ".concat(t.tagName," resource error"),s=H(e,s),u="load ".concat(n," resource error"),/[\?|\&]callback/.test(n)&&(l=(null===(h=null==r?void 0:r.error)||void 0===h?void 0:h.stack)||"no stack information",u="JSONP request failed, stack: ".concat(l)),f={category:a.RESOURCE_ERROR,grade:"IMG"===t.tagName?c.WARNING:c.ERROR,errorUrl:n,message:s,stack:u},[4,q(e,f)]))):[2];case 2:return d.sent()?(p=A(e,[]),this.logInfo=At(At({},p),f),this.traceInfo(e.sendErrorTime),[3,4]):[2];case 3:throw d.sent();case 4:return [2]}}))}))}),true);},t}(nt),jt=new Dt,Nt=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t;}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n);}}(),Ut=function(){return Ut=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},Ut.apply(this,arguments)},Ft=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},Gt=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},Wt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Nt(t,e),t.prototype.handleErrors=function(e,t){var r=this;if(!t)return console.warn("Vue handle errors set failed.(SkyWalking)");t.config.errorHandler=function(t,n,o){return Ft(r,void 0,void 0,(function(){var r,n,i;return Gt(this,(function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),r=H(e,r=o),n={category:a.VUE_ERROR,grade:c.ERROR,errorUrl:location.href,message:r,stack:t.stack},[4,q(e,n)];case 1:return s.sent()?(i=A(e,[]),this.logInfo=Ut(Ut({},i),n),this.traceInfo(e.sendErrorTime),[3,3]):[2];case 2:throw s.sent();case 3:return [2]}}))}))};},t}(nt),Vt=new Wt,Bt=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t;}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n);}}(),Qt=function(){return Qt=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},Qt.apply(this,arguments)},Kt=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},Jt=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},Xt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Bt(t,e),t.prototype.handleErrors=function(e,t){return Kt(this,void 0,void 0,(function(){var r,n,o,i,s,u,l;return Jt(this,(function(f){switch(f.label){case 0:return t=t||{name:"",message:"",stack:""},r=e.category,n=e.grade,o=e.level,i=e.content,s=e.timeout,u={category:r||a.JS_ERROR,grade:n||c.ERROR,errorUrl:t.name||location.href,message:t.message,stack:t.stack},"number"==typeof o&&(u.level=o),i&&(u.content=i),[4,q(e,u)];case 1:return f.sent()?(l=A(e,[]),this.logInfo=Qt(Qt({},l),u),this.traceInfo(s||e.sendErrorTime),[2]):[2]}}))}))},t}(nt),zt=new Xt,Yt=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t;}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n);}}(),Zt=function(){return Zt=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},Zt.apply(this,arguments)},$t=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.isLockMonitor=false,t.whiteScreenDetectionCount=0,t.maxDetectionCount=5,t.detectionInterval=500,t}return Yt(t,e),t.prototype.report=function(e,t){var r={message:"检测出白屏,检测方式为: ".concat(t),grade:c.ERROR,category:a.WHITE_SCREEN_ERROR,errorUrl:location.href,whiteScreen:t},n=A(e,[]);this.logInfo=Zt(Zt({},n),r);this.traceInfo(10),"timeout"===t&&Me.recordPerf({options:Zt(Zt(Zt({},e),this.logInfo),{sendPerfTime:10}),uniqueId:n.uniqueId});},t.prototype.checkWhiteScreen=function(){var e,t,r=false,n=document.querySelector("#app")||document.querySelector("#root");if(n)(n.innerHTML?n.innerHTML.replace(/<!---->/g,"").trim():"").length||(r=true);else if(!(null===(e=document.querySelector("body"))||void 0===e?void 0:e.innerText)){r=true;for(var o=document.querySelectorAll("body > div"),i=o.length,a=0;a<i;a++)if(null===(t=o[a])||void 0===t?void 0:t.innerHTML){r=false;break}}return r},t.prototype.monitorWhiteScreenTimeout=function(e){this.isLockMonitor||(this.isLockMonitor=true,this.checkWhiteScreen()&&this.report(e,"timeout"));},t.prototype.monitorWhiteScreenLoad=function(e){var t=this;this.isLockMonitor||(this.checkWhiteScreen()?(this.whiteScreenDetectionCount++,console.log("load: detected white screen for the ".concat(this.whiteScreenDetectionCount,"th time")),this.whiteScreenDetectionCount>=this.maxDetectionCount?(console.log("load: detected white screen ".concat(this.maxDetectionCount," times, confirmed as white screen")),this.isLockMonitor=true,this.report(e,"load")):setTimeout((function(){t.monitorWhiteScreenLoad(e);}),this.detectionInterval)):(this.whiteScreenDetectionCount=0,this.isLockMonitor=true));},t.prototype.handleWhiteScreen=function(e){var t=this;false!==e.whiteScreen&&(setTimeout((function(){t.monitorWhiteScreenTimeout(e);}),e.whiteScreenTimeout||2500),window.addEventListener("load",(function(){setTimeout((function(){t.whiteScreenDetectionCount=0,t.monitorWhiteScreenLoad(e);}),100);})));},t}(nt),er=new $t,tr=function(){return tr=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},tr.apply(this,arguments)},rr=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{s(n.next(e));}catch(e){i(e);}}function c(e){try{s(n.throw(e));}catch(e){i(e);}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t);}))).then(a,c);}s((n=n.apply(e,[])).next());}))},nr=function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,n=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a);}catch(e){c=[6,e],n=0;}finally{r=o=0;}if(5&c[0])throw c[1];return {value:c[0]?c[1]:void 0,done:true}}([c,s])}}},or=new(function(){function t(){this.minSendErrorTime=3e3,this.registered=false,this.reportHRT=false,this.customOptions={collector:"//apm.hexin.cn/skywalking-web",group:"unknown",subGroup:"unknown",rate:1e-4,jsErrors:true,apiErrors:true,resourceErrors:true,autoTracePerf:true,useFmp:false,enableSPA:false,traceSDKInternal:false,perfEntries:false,detailMode:true,noErrorPaths:[],maxReqCostTime:1e4,whiteScreen:true,whiteScreenTimeout:2500,slowInteraction:{enable:false,threshold:200,reportInterval:3e4}};}return t.prototype.register=function(t){"weblog"!==t.service&&(this.registered||(this.registered=true,console.time("register finished"),this._authConfig(t,"register"),this._catchErrors(this.customOptions),this.customOptions.enableSPA||this.customOptions.rate&&e()<this.customOptions.rate&&(this.customOptions.rate=1,this._performance()),function(e){var t,r=this,n=[],o=(null===(t=e.hooks)||void 0===t?void 0:t.reportHook)||e.reportHook;e.noTrace||We(e,n),window.onbeforeunload=function(t){n.length&&new k("SEGMENTS",e.collector,o).send(n);},setInterval((function(){return Ve(r,void 0,void 0,(function(){return Be(this,(function(t){switch(t.label){case 0:return n.length?[4,new k("SEGMENTS",e.collector,o).send(n)]:[2];case 1:return t.sent(),n=[],[2]}}))}))}),e.sendSegmentsTime||12e4);}(this.customOptions),er.handleWhiteScreen(this.customOptions),this._initSlowInteraction(),console.timeEnd("register finished")));},t.prototype.setPerformance=function(e,t){var r=this._authConfig(e,"performance");r.autoTracePerf||(r.autoTracePerf=true),1!==r.rate&&(r.rate=1),this._performance(r,t);},t.prototype.setHRT=function(e,t){if(void 0===e&&(e={}),!this.reportHRT){this.reportHRT=true;var r=this._authConfig(e,"performance");r.autoTracePerf||(r.autoTracePerf=true),1!==r.rate&&(r.rate=1);var n,o,a,c,s,u,l=(n=Date.now(),o=i(performance.now()),a={HRT:o},c=window.__FRONTEND_BRIDGE__||{},s=c.webviewLaunchTime,u=c.webviewType,s&&"preload"!==u&&(a.NHRT=i(n-s),a.NRT=i(n-s-o)),a),f=t?tr(tr({},l),t):l;this._performance(r,f);}},t.prototype._catchErrors=function(e){var t=this._getHandleOpts(e);e.jsErrors&&(ut.handleErrors(t),vt.handleErrors(t),e.vue&&Vt.handleErrors(t,e.vue)),e.apiErrors&&(Rt.handleError(t),Ct.handleError(t)),e.resourceErrors&&jt.handleErrors(t);},t.prototype._performance=function(t,r){var n=t||this.customOptions;if(n.autoTracePerf){var o=n.rate;o&&e()>o||("complete"===document.readyState?Me.recordPerf({options:n,customPerf:r}):window.addEventListener("load",(function(){return Me.recordPerf({options:n,customPerf:r})}),false),n.enableSPA&&window.addEventListener("hashchange",(function(){return Me.recordPerf({options:n,customPerf:r})}),false));}},t.prototype._initSlowInteraction=function(){var e=this.customOptions;e.autoTracePerf&&e.slowInteraction.enable&&function(e,t,r){ void 0===e&&(e=200),void 0===t&&(t=3e4),Ye&&Ye.stop(),(Ye=new ze(e,t)).start(r);}(e.slowInteraction.threshold,e.slowInteraction.reportInterval,e);},t.prototype._authConfig=function(e,t){var r,n,o,i=e.collector,a=e.service,c=e.serviceVersion,s=e.group,u=e.subGroup,l=e.sendErrorTime;if(i){e.collector=i&&i.replace(/\/+$/,"");}if(c&&(e.serviceVersion=function(e){return !e||e.indexOf("offline")>-1?e:"".concat(e).concat(window._offlinePkg?".hxapp":"")}(c)),a){var f=a.split("::"),p=f.length;!s&&p>1&&f[0]&&(e.group=f[0]),!u&&p>2&&f[1]&&(e.subGroup=f[1]),e.service=f.pop();}"object"!=typeof e.hooks&&(e.hooks=tr({},(null===(r=this.customOptions)||void 0===r?void 0:r.hooks)||{})),(null===(n=e.hooks)||void 0===n?void 0:n.reportHook)&&e.reportHook&&(e.hooks.reportHook=e.reportHook),(null===(o=e.hooks)||void 0===o?void 0:o.filterHook)&&e.filterHook&&(e.hooks.filterHook=e.filterHook),l&&l<this.minSendErrorTime&&(l=this.minSendErrorTime);var h=tr(tr({},this.customOptions),e);return "register"===t&&(this.customOptions=h),h},t.prototype._getHandleOpts=function(e){var t=tr(tr({},e),{collector:e.collector,service:e.service,serviceVersion:e.serviceVersion,group:e.group,subGroup:e.subGroup,pagePath:e.pagePath,sendErrorTime:e.sendErrorTime,sendPerfTime:e.sendPerfTime,extraMsg:e.extraMsg,category:e.category,noErrorPaths:e.noErrorPaths,hooks:e.hooks||{},grade:e.grade,level:e.level,content:e.content,maxReqCostTime:e.maxReqCostTime,timeout:e.timeout,pageKey:e.pageKey});return e.pageKey&&(t.pageKey=e.pageKey),t},t.prototype.reportFrameErrors=function(e,t){return rr(this,void 0,void 0,(function(){var r,n,o;return nr(this,(function(i){switch(i.label){case 0:return (null==(r=e.pagePath)?void 0:r.includes("/weblog/weblog.js"))?[2]:(n=this._authConfig(e,"report"),o=this._getHandleOpts(tr({},n)),[4,zt.handleErrors(o,t)]);case 1:return i.sent(),[2]}}))}))},t}());window.ClientMonitor=or;}},n={};function o(e){var t=n[e];if(void 0!==t){if(void 0!==t.error)throw t.error;return t.exports}var i=n[e]={exports:{}};try{var a={id:e,module:i,factory:r[e],require:o};o.i.forEach((function(e){e(a);})),i=a.module,a.factory.call(i.exports,i,i.exports,a.require);}catch(e){throw i.error=e,e}return i.exports}o.m=r,o.c=n,o.i=[],o.hu=function(e){return e+"."+o.h()+".hot-update.js"},o.hmrF=function(){return "main."+o.h()+".hot-update.json"},o.h=function(){return "c9af4ce59e7569c4242c"},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},e={},t="skywalking-client-js:",o.l=function(r,n,i,a){if(e[r])e[r].push(n);else {var c,s;if(void 0!==i)for(var u=document.getElementsByTagName("script"),l=0;l<u.length;l++){var f=u[l];if(f.getAttribute("src")==r||f.getAttribute("data-webpack")==t+i){c=f;break}}c||(s=true,(c=document.createElement("script")).charset="utf-8",c.timeout=120,o.nc&&c.setAttribute("nonce",o.nc),c.setAttribute("data-webpack",t+i),c.src=r),e[r]=[n];var p=function(t,n){c.onerror=c.onload=null,clearTimeout(h);var o=e[r];if(delete e[r],c.parentNode&&c.parentNode.removeChild(c),o&&o.forEach((function(e){return e(n)})),t)return t(n)},h=setTimeout(p.bind(null,void 0,{type:"timeout",target:c}),12e4);c.onerror=p.bind(null,c.onerror),c.onload=p.bind(null,c.onload),s&&document.head.appendChild(c);}},function(){var e,t,r,n={},i=o.c,a=[],c=[],s="idle",u=0,l=[];function f(e){s=e;for(var t=[],r=0;r<c.length;r++)t[r]=c[r].call(null,e);return Promise.all(t).then((function(){}))}function p(){0==--u&&f("ready").then((function(){if(0===u){var e=l;l=[];for(var t=0;t<e.length;t++)e[t]();}}));}function h(e){if("idle"!==s)throw new Error("check() is only allowed in idle status");return f("check").then(o.hmrM).then((function(r){return r?f("prepare").then((function(){var n=[];return t=[],Promise.all(Object.keys(o.hmrC).reduce((function(e,i){return o.hmrC[i](r.c,r.r,r.m,e,t,n),e}),[])).then((function(){return t=function(){return e?v(e):f("ready").then((function(){return n}))},0===u?t():new Promise((function(e){l.push((function(){e(t());}));}));var t;}))})):f(y()?"ready":"idle").then((function(){return null}))}))}function d(e){return "ready"!==s?Promise.resolve().then((function(){throw new Error("apply() is only allowed in ready status (state: "+s+")")})):v(e)}function v(e){e=e||{},y();var n=t.map((function(t){return t(e)}));t=void 0;var o=n.map((function(e){return e.error})).filter(Boolean);if(o.length>0)return f("abort").then((function(){throw o[0]}));var i=f("dispose");n.forEach((function(e){e.dispose&&e.dispose();}));var a,c=f("apply"),s=function(e){a||(a=e);},u=[];return n.forEach((function(e){if(e.apply){var t=e.apply(s);if(t)for(var r=0;r<t.length;r++)u.push(t[r]);}})),Promise.all([i,c]).then((function(){return a?f("fail").then((function(){throw a})):r?v(e).then((function(e){return u.forEach((function(t){e.indexOf(t)<0&&e.push(t);})),e})):f("idle").then((function(){return u}))}))}function y(){if(r)return t||(t=[]),Object.keys(o.hmrI).forEach((function(e){r.forEach((function(r){o.hmrI[e](r,t);}));})),r=void 0,true}o.hmrD=n,o.i.push((function(l){var v,y,g,m,w=l.module,b=function(t,r){var n=i[r];if(!n)return t;var o=function(o){if(n.hot.active){if(i[o]){var c=i[o].parents;-1===c.indexOf(r)&&c.push(r);}else a=[r],e=o;-1===n.children.indexOf(o)&&n.children.push(o);}else console.warn("[HMR] unexpected require("+o+") from disposed module "+r),a=[];return t(o)},c=function(e){return {configurable:true,enumerable:true,get:function(){return t[e]},set:function(r){t[e]=r;}}};for(var l in t)Object.prototype.hasOwnProperty.call(t,l)&&"e"!==l&&Object.defineProperty(o,l,c(l));return o.e=function(e,r){return function(e){switch(s){case "ready":f("prepare");case "prepare":return u++,e.then(p,p),e;default:return e}}(t.e(e,r))},o}(l.require,l.id);w.hot=(v=l.id,y=w,m={_acceptedDependencies:{},_acceptedErrorHandlers:{},_declinedDependencies:{},_selfAccepted:false,_selfDeclined:false,_selfInvalidated:false,_disposeHandlers:[],_main:g=e!==v,_requireSelf:function(){a=y.parents.slice(),e=g?void 0:v,o(v);},active:true,accept:function(e,t,r){if(void 0===e)m._selfAccepted=true;else if("function"==typeof e)m._selfAccepted=e;else if("object"==typeof e&&null!==e)for(var n=0;n<e.length;n++)m._acceptedDependencies[e[n]]=t||function(){},m._acceptedErrorHandlers[e[n]]=r;else m._acceptedDependencies[e]=t||function(){},m._acceptedErrorHandlers[e]=r;},decline:function(e){if(void 0===e)m._selfDeclined=true;else if("object"==typeof e&&null!==e)for(var t=0;t<e.length;t++)m._declinedDependencies[e[t]]=true;else m._declinedDependencies[e]=true;},dispose:function(e){m._disposeHandlers.push(e);},addDisposeHandler:function(e){m._disposeHandlers.push(e);},removeDisposeHandler:function(e){var t=m._disposeHandlers.indexOf(e);t>=0&&m._disposeHandlers.splice(t,1);},invalidate:function(){switch(this._selfInvalidated=true,s){case "idle":t=[],Object.keys(o.hmrI).forEach((function(e){o.hmrI[e](v,t);})),f("ready");break;case "ready":Object.keys(o.hmrI).forEach((function(e){o.hmrI[e](v,t);}));break;case "prepare":case "check":case "dispose":case "apply":(r=r||[]).push(v);}},check:h,apply:d,status:function(e){if(!e)return s;c.push(e);},addStatusHandler:function(e){c.push(e);},removeStatusHandler:function(e){var t=c.indexOf(e);t>=0&&c.splice(t,1);},data:n[v]},e=void 0,m),w.parents=a,w.children=[],a=[],l.require=b;})),o.hmrC={},o.hmrI={};}(),o.p="/",function(){var e,t,r,n,i,a=o.hmrS_jsonp=o.hmrS_jsonp||{792:0},c={};function s(t,r){return e=r,new Promise((function(e,r){c[t]=e;var n=o.p+o.hu(t),i=new Error;o.l(n,(function(e){if(c[t]){c[t]=void 0;var n=e&&("load"===e.type?"missing":e.type),o=e&&e.target&&e.target.src;i.message="Loading hot update chunk "+t+" failed.\n("+n+": "+o+")",i.name="ChunkLoadError",i.type=n,i.request=o,r(i);}}));}))}function u(e){function c(e){for(var t=[e],r={},n=t.map((function(e){return {chain:[e],id:e}}));n.length>0;){var i=n.pop(),a=i.id,c=i.chain,u=o.c[a];if(u&&(!u.hot._selfAccepted||u.hot._selfInvalidated)){if(u.hot._selfDeclined)return {type:"self-declined",chain:c,moduleId:a};if(u.hot._main)return {type:"unaccepted",chain:c,moduleId:a};for(var l=0;l<u.parents.length;l++){var f=u.parents[l],p=o.c[f];if(p){if(p.hot._declinedDependencies[a])return {type:"declined",chain:c.concat([f]),moduleId:a,parentId:f};-1===t.indexOf(f)&&(p.hot._acceptedDependencies[a]?(r[f]||(r[f]=[]),s(r[f],[a])):(delete r[f],t.push(f),n.push({chain:c.concat([f]),id:f})));}}}}return {type:"accepted",moduleId:e,outdatedModules:t,outdatedDependencies:r}}function s(e,t){for(var r=0;r<t.length;r++){var n=t[r];-1===e.indexOf(n)&&e.push(n);}}o.f&&delete o.f.jsonpHmr,t=void 0;var u={},l=[],f={},p=function(e){console.warn("[HMR] unexpected require("+e.id+") to disposed module");};for(var h in r)if(o.o(r,h)){var d,v=r[h],y=false,g=false,m=false,w="";switch((d=v?c(h):{type:"disposed",moduleId:h}).chain&&(w="\nUpdate propagation: "+d.chain.join(" -> ")),d.type){case "self-declined":e.onDeclined&&e.onDeclined(d),e.ignoreDeclined||(y=new Error("Aborted because of self decline: "+d.moduleId+w));break;case "declined":e.onDeclined&&e.onDeclined(d),e.ignoreDeclined||(y=new Error("Aborted because of declined dependency: "+d.moduleId+" in "+d.parentId+w));break;case "unaccepted":e.onUnaccepted&&e.onUnaccepted(d),e.ignoreUnaccepted||(y=new Error("Aborted because "+h+" is not accepted"+w));break;case "accepted":e.onAccepted&&e.onAccepted(d),g=true;break;case "disposed":e.onDisposed&&e.onDisposed(d),m=true;break;default:throw new Error("Unexception type "+d.type)}if(y)return {error:y};if(g)for(h in f[h]=v,s(l,d.outdatedModules),d.outdatedDependencies)o.o(d.outdatedDependencies,h)&&(u[h]||(u[h]=[]),s(u[h],d.outdatedDependencies[h]));m&&(s(l,[d.moduleId]),f[h]=p);}r=void 0;for(var b,E=[],R=0;R<l.length;R++){var S=l[R],T=o.c[S];T&&(T.hot._selfAccepted||T.hot._main)&&f[S]!==p&&!T.hot._selfInvalidated&&E.push({module:S,require:T.hot._requireSelf,errorHandler:T.hot._selfAccepted});}return {dispose:function(){var e;n.forEach((function(e){delete a[e];})),n=void 0;for(var t,r=l.slice();r.length>0;){var i=r.pop(),c=o.c[i];if(c){var s={},f=c.hot._disposeHandlers;for(R=0;R<f.length;R++)f[R].call(null,s);for(o.hmrD[i]=s,c.hot.active=false,delete o.c[i],delete u[i],R=0;R<c.children.length;R++){var p=o.c[c.children[R]];p&&((e=p.parents.indexOf(i))>=0&&p.parents.splice(e,1));}}}for(var h in u)if(o.o(u,h)&&(c=o.c[h]))for(b=u[h],R=0;R<b.length;R++)t=b[R],(e=c.children.indexOf(t))>=0&&c.children.splice(e,1);},apply:function(t){for(var r in f)o.o(f,r)&&(o.m[r]=f[r]);for(var n=0;n<i.length;n++)i[n](o);for(var a in u)if(o.o(u,a)){var c=o.c[a];if(c){b=u[a];for(var s=[],p=[],h=[],d=0;d<b.length;d++){var v=b[d],y=c.hot._acceptedDependencies[v],g=c.hot._acceptedErrorHandlers[v];if(y){if(-1!==s.indexOf(y))continue;s.push(y),p.push(g),h.push(v);}}for(var m=0;m<s.length;m++)try{s[m].call(null,b);}catch(r){if("function"==typeof p[m])try{p[m](r,{moduleId:a,dependencyId:h[m]});}catch(n){e.onErrored&&e.onErrored({type:"accept-error-handler-errored",moduleId:a,dependencyId:h[m],error:n,originalError:r}),e.ignoreErrored||(t(n),t(r));}else e.onErrored&&e.onErrored({type:"accept-errored",moduleId:a,dependencyId:h[m],error:r}),e.ignoreErrored||t(r);}}}for(var w=0;w<E.length;w++){var R=E[w],S=R.module;try{R.require(S);}catch(r){if("function"==typeof R.errorHandler)try{R.errorHandler(r,{moduleId:S,module:o.c[S]});}catch(n){e.onErrored&&e.onErrored({type:"self-accept-error-handler-errored",moduleId:S,error:n,originalError:r}),e.ignoreErrored||(t(n),t(r));}else e.onErrored&&e.onErrored({type:"self-accept-errored",moduleId:S,error:r}),e.ignoreErrored||t(r);}}return l}}}self.webpackHotUpdateskywalking_client_js=function(t,n,a){for(var s in n)o.o(n,s)&&(r[s]=n[s],e&&e.push(s));a&&i.push(a),c[t]&&(c[t](),c[t]=void 0);},o.hmrI.jsonp=function(e,t){r||(r={},i=[],n=[],t.push(u)),o.o(r,e)||(r[e]=o.m[e]);},o.hmrC.jsonp=function(e,c,l,f,p,h){p.push(u),t={},n=c,r=l.reduce((function(e,t){return e[t]=false,e}),{}),i=[],e.forEach((function(e){o.o(a,e)&&void 0!==a[e]?(f.push(s(e,h)),t[e]=true):t[e]=false;})),o.f&&(o.f.jsonpHmr=function(e,r){t&&o.o(t,e)&&!t[e]&&(r.push(s(e)),t[e]=true);});},o.hmrM=function(){if("undefined"==typeof fetch)throw new Error("No browser support: need fetch API");return fetch(o.p+o.hmrF()).then((function(e){if(404!==e.status){if(!e.ok)throw new Error("Failed to fetch update manifest "+e.statusText);return e.json()}}))};}();o("./src/index.ts");}();
21
21
  }
22
22
 
23
- /** Stable identifier used by the LiveAvatar SDK plugin host. */
23
+ const EMPTY = {};
24
+ const PHASE = { phase: "string" };
25
+ const CONFIG = { source: "string", willRetry: "boolean" };
26
+ const TEXT_LENGTH = { textLength: "number" };
27
+ // Public v2 event/data allowlist. Correlation and operation use their own
28
+ // common public contracts; a module alone never makes an event reportable.
29
+ const TIMELINE_FIELDS = {
30
+ "operation.started": EMPTY,
31
+ "operation.finished": EMPTY,
32
+ "protocol.received": { protocolEvent: "string" },
33
+ "protocol.failed": { protocolEvent: "string" },
34
+ "client.created": EMPTY,
35
+ "client.disposed": EMPTY,
36
+ "monitoring.session.started": { startReason: "string" },
37
+ "monitoring.session.ended": { endReason: "string", cleanupOutcome: "string" },
38
+ "config.fetch.started": CONFIG,
39
+ "config.fetch.completed": CONFIG,
40
+ "config.fetch.failed": CONFIG,
41
+ "connect.started": PHASE,
42
+ "connect.completed": PHASE,
43
+ "connect.failed": PHASE,
44
+ "disconnect.started": PHASE,
45
+ "disconnect.completed": PHASE,
46
+ "disconnect.failed": PHASE,
47
+ "reconnect.started": PHASE,
48
+ "reconnect.completed": PHASE,
49
+ "reconnect.failed": PHASE,
50
+ "livekit.connected": EMPTY,
51
+ "livekit.disconnected": { hasReason: "boolean" },
52
+ "http.connected": EMPTY,
53
+ "http.disconnected": { hasReason: "boolean" },
54
+ "rtc.state-changed": {
55
+ phase: "string",
56
+ roomExists: "boolean",
57
+ roomState: "string",
58
+ hasConnected: "boolean",
59
+ },
60
+ "connection.quality-changed": { quality: "string", isLocal: "boolean" },
61
+ "video.track-added": EMPTY,
62
+ "video.track-removed": EMPTY,
63
+ "audio.track-added": EMPTY,
64
+ "audio.track-removed": EMPTY,
65
+ "audio.capture-started": EMPTY,
66
+ "audio.capture-stopped": EMPTY,
67
+ "camera.started": EMPTY,
68
+ "camera.stopped": EMPTY,
69
+ "question.sent": TEXT_LENGTH,
70
+ "answer.waiting": EMPTY,
71
+ "answer.first-chunk": { deltaLength: "number", textLength: "number" },
72
+ "answer.completed": TEXT_LENGTH,
73
+ "asr.final": TEXT_LENGTH,
74
+ "server.message": { textLength: "number", type: "string" },
75
+ "avsync.session.started": { startedAtMs: "number" },
76
+ "avsync.session.ended": { endedAtMs: "number", reason: "string" },
77
+ };
78
+ function sourceCorrelation(source) {
79
+ return project(source, {
80
+ clientInstanceId: "string",
81
+ monitoringSessionId: "string",
82
+ serverSessionId: "string",
83
+ avsyncSessionId: "string",
84
+ });
85
+ }
86
+ function operationalSource(record) {
87
+ return {
88
+ sourceSchema: "sdk.log",
89
+ sourceSchemaVersion: 2,
90
+ ...sourceCorrelation(record),
91
+ clientInstanceId: record.clientInstanceId,
92
+ eventId: record.eventId,
93
+ streamId: record.streamId,
94
+ sequence: record.sequence,
95
+ occurredAtMs: record.occurredAtMs,
96
+ ...project(record, { observedAtMs: "number", clockId: "string" }),
97
+ };
98
+ }
99
+ /** Copy only the public v2 envelope and documented diagnostic fields. */
100
+ function projectRecord(record) {
101
+ const correlation = project(record.correlation, {
102
+ questionId: "string",
103
+ attemptId: "number",
104
+ configRoundId: "number",
105
+ attempt: "number",
106
+ alertId: "string",
107
+ participantId: "string",
108
+ trackId: "string",
109
+ mediaKind: "string",
110
+ pairId: "string",
111
+ trackKey: "string",
112
+ streamId: "string",
113
+ playbackTargetId: "string",
114
+ captureId: "string",
115
+ relatedOperationId: "string",
116
+ }, true);
117
+ const snapshot = project(record.snapshot, {
118
+ sdkState: "string",
119
+ httpConnected: "boolean",
120
+ rtcConnected: "boolean",
121
+ hasVideoTrack: "boolean",
122
+ roomExists: "boolean",
123
+ roomState: "string",
124
+ hasConnected: "boolean",
125
+ });
126
+ const disconnect = project(object$1(record.snapshot).lastDisconnect, {
127
+ occurredAtMs: "number",
128
+ reasonCode: "number",
129
+ reasonName: "string",
130
+ clientInitiated: "boolean",
131
+ });
132
+ if (Object.keys(disconnect).length)
133
+ snapshot.lastDisconnect = disconnect;
134
+ const error = record.error && {
135
+ failureId: record.error.failureId,
136
+ code: record.error.code,
137
+ reasonCategory: record.error.reasonCategory,
138
+ ...project(record.error, { reason: "string" }),
139
+ ...(record.error.evidence
140
+ ? {
141
+ evidence: {
142
+ ...project(record.error.evidence, {
143
+ name: "string",
144
+ httpStatus: "number",
145
+ connectionErrorReason: "number",
146
+ connectionErrorReasonName: "string",
147
+ }),
148
+ ...(["string", "number"].includes(typeof record.error.evidence.backendCode)
149
+ ? { backendCode: record.error.evidence.backendCode }
150
+ : {}),
151
+ },
152
+ }
153
+ : {}),
154
+ };
155
+ return {
156
+ schema: "sdk.log",
157
+ schemaVersion: 2,
158
+ eventId: record.eventId,
159
+ streamId: record.streamId,
160
+ sequence: record.sequence,
161
+ occurredAtMs: record.occurredAtMs,
162
+ ...project(record, { observedAtMs: "number", clockId: "string" }),
163
+ ...sourceCorrelation(record),
164
+ clientInstanceId: record.clientInstanceId,
165
+ level: record.level,
166
+ module: record.module,
167
+ event: record.event,
168
+ trigger: { kind: record.trigger.kind, entry: record.trigger.entry },
169
+ ...(record.operation
170
+ ? {
171
+ operation: {
172
+ operationId: record.operation.operationId,
173
+ rootOperationId: record.operation.rootOperationId,
174
+ name: record.operation.name,
175
+ phase: record.operation.phase,
176
+ ...project(record.operation, {
177
+ parentOperationId: "string",
178
+ relatedOperationId: "string",
179
+ }),
180
+ ...(record.operation.outcome
181
+ ? { outcome: record.operation.outcome }
182
+ : {}),
183
+ },
184
+ }
185
+ : {}),
186
+ ...(record.failureRef
187
+ ? {
188
+ failureRef: {
189
+ failureId: record.failureRef.failureId,
190
+ eventId: record.failureRef.eventId,
191
+ },
192
+ }
193
+ : {}),
194
+ ...(error ? { error } : {}),
195
+ ...(Object.keys(correlation).length ? { correlation } : {}),
196
+ ...(Object.keys(snapshot).length ? { snapshot } : {}),
197
+ ...(record.data ? { data: eventData(record) } : {}),
198
+ };
199
+ }
200
+ function eventData(record) {
201
+ const fields = Object.prototype.hasOwnProperty.call(TIMELINE_FIELDS, record.event)
202
+ ? TIMELINE_FIELDS[record.event]
203
+ : EMPTY;
204
+ const data = project(record.data, fields);
205
+ if (record.event === "rtc.state-changed") {
206
+ const disconnect = project(object$1(record.data).lastDisconnect, {
207
+ occurredAtMs: "number",
208
+ reasonCode: "number",
209
+ reasonName: "string",
210
+ clientInitiated: "boolean",
211
+ });
212
+ if (Object.keys(disconnect).length)
213
+ data.lastDisconnect = disconnect;
214
+ }
215
+ if (record.event === "avsync.alert")
216
+ return project(record.data, {
217
+ phase: "string",
218
+ finding: "string",
219
+ confidence: "string",
220
+ status: "string",
221
+ capturedAtMs: "number",
222
+ });
223
+ if (record.event === "performance.first-frame") {
224
+ Object.assign(data, project(record.data, {
225
+ outcome: "string",
226
+ renderMode: "string",
227
+ timeoutAfterRtcMs: "number",
228
+ }));
229
+ data.nodes = project(object$1(record.data).nodes, {
230
+ configReadyMs: "number",
231
+ rtcConnectedMs: "number",
232
+ videoTrackAddedMs: "number",
233
+ videoMetadataMs: "number",
234
+ firstFrameMs: "number",
235
+ });
236
+ }
237
+ return data;
238
+ }
239
+ function toTimeline(record) {
240
+ if (!Object.prototype.hasOwnProperty.call(TIMELINE_FIELDS, record.event))
241
+ return undefined;
242
+ const copy = projectRecord(record);
243
+ return {
244
+ kind: "liveavatar.session.timeline",
245
+ schemaVersion: 4,
246
+ ...operationalSource(copy),
247
+ level: copy.level,
248
+ module: copy.module,
249
+ event: copy.event,
250
+ trigger: copy.trigger,
251
+ ...(copy.operation ? { operation: copy.operation } : {}),
252
+ ...(copy.failureRef ? { failureRef: copy.failureRef } : {}),
253
+ ...(copy.snapshot ? { snapshot: copy.snapshot } : {}),
254
+ ...(copy.correlation ? { correlation: copy.correlation } : {}),
255
+ ...(copy.data && Object.keys(copy.data).length ? { data: copy.data } : {}),
256
+ };
257
+ }
258
+ function object$1(value) {
259
+ return value !== null && typeof value === "object" && !Array.isArray(value)
260
+ ? value
261
+ : {};
262
+ }
263
+ function project(value, fields, nullable = false) {
264
+ const input = object$1(value);
265
+ const result = {};
266
+ for (const [key, type] of Object.entries(fields)) {
267
+ const entry = input[key];
268
+ if (entry === null && nullable)
269
+ result[key] = null;
270
+ else if (type === "string" && typeof entry === "string")
271
+ result[key] = entry;
272
+ else if (type === "boolean" && typeof entry === "boolean")
273
+ result[key] = entry;
274
+ else if (type === "number" &&
275
+ typeof entry === "number" &&
276
+ Number.isFinite(entry))
277
+ result[key] = entry;
278
+ }
279
+ return result;
280
+ }
281
+
282
+ /** Complete content, including its envelope and JSON escapes, must fit this limit. */
283
+ const EVIDENCE_CONTENT_BYTE_LIMIT = 28 * 1024;
284
+ function utf8ByteLength(value) {
285
+ return new TextEncoder().encode(value).byteLength;
286
+ }
287
+ /** Content is level one; containers at level three become lossless JSON text. */
288
+ function serializeEvidenceContent(value, depth = 1) {
289
+ if (value === null || typeof value !== "object")
290
+ return value;
291
+ if (depth >= 3)
292
+ return JSON.stringify(value);
293
+ if (Array.isArray(value))
294
+ return value.map((entry) => serializeEvidenceContent(entry, depth + 1));
295
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
296
+ key,
297
+ serializeEvidenceContent(entry, depth + 1),
298
+ ]));
299
+ }
300
+ function assertContentFits(content) {
301
+ if (utf8ByteLength(JSON.stringify(content)) > EVIDENCE_CONTENT_BYTE_LIMIT)
302
+ throw new Error("A/V Sync content exceeds the 28 KiB limit");
303
+ }
304
+ function pageReasons(page) {
305
+ const reasons = [];
306
+ if (!page.enabled)
307
+ reasons.push("diagnostics-disabled");
308
+ if (page.page.truncated)
309
+ reasons.push("source-truncated");
310
+ if (!page.retention.storageAvailable)
311
+ reasons.push("storage-unavailable");
312
+ if (page.retention.storageWriteFailed)
313
+ reasons.push("storage-write-failed");
314
+ if (page.retention.droppedLogCount > 0 ||
315
+ page.retention.droppedSegmentCount > 0)
316
+ reasons.push("retention-dropped");
317
+ if (page.page.availableFromWallClockMs === null ||
318
+ page.page.availableToWallClockMs === null)
319
+ reasons.push("window-unavailable");
320
+ else if (page.page.availableFromWallClockMs > page.page.requestedFromWallClockMs)
321
+ reasons.push("window-start-uncovered");
322
+ return reasons;
323
+ }
324
+ function ownsPage(alert, page) {
325
+ // Missing optional SDK identities are not filled from the latest session.
326
+ return (page.avsyncSessionId === alert.avsyncSessionId &&
327
+ (page.clientInstanceId === undefined ||
328
+ page.clientInstanceId === alert.clientInstanceId) &&
329
+ (page.monitoringSessionId === undefined ||
330
+ page.monitoringSessionId === alert.monitoringSessionId) &&
331
+ page.records.every((record) => record.clientInstanceId === alert.clientInstanceId &&
332
+ record.avsyncSessionId === alert.avsyncSessionId &&
333
+ (record.monitoringSessionId === undefined ||
334
+ record.monitoringSessionId === alert.monitoringSessionId)));
335
+ }
336
+ async function collectEvidence(diagnostics, alert, range, isActive) {
337
+ const pages = [];
338
+ const reasons = new Set();
339
+ const cursors = new Set();
340
+ let cursor;
341
+ let queryComplete = false;
342
+ const retrievedAtWallClockMs = Date.now();
343
+ while (isActive()) {
344
+ let page;
345
+ try {
346
+ const result = await diagnostics.getAvSyncLogEvidence(cursor === undefined
347
+ ? { range, pageSize: 1000, includeSummary: true }
348
+ : { cursor, pageSize: 1000, includeSummary: false });
349
+ if (!isActive())
350
+ return undefined;
351
+ // Own the snapshot even when the transport implementation reuses objects.
352
+ page = JSON.parse(JSON.stringify(result));
353
+ }
354
+ catch {
355
+ if (!isActive())
356
+ return undefined;
357
+ reasons.add(pages.length ? "continuation-query-failed" : "initial-query-failed");
358
+ break;
359
+ }
360
+ pages.push(page);
361
+ for (const reason of pageReasons(page))
362
+ reasons.add(reason);
363
+ if (!ownsPage(alert, page)) {
364
+ reasons.add("session-mismatch");
365
+ break;
366
+ }
367
+ const first = pages[0];
368
+ if (page.page.requestedFromWallClockMs !==
369
+ first.page.requestedFromWallClockMs ||
370
+ page.page.requestedToWallClockMs !== first.page.requestedToWallClockMs) {
371
+ reasons.add("window-mismatch");
372
+ break;
373
+ }
374
+ if (!page.page.hasMore) {
375
+ queryComplete = true;
376
+ break;
377
+ }
378
+ const next = page.page.nextCursor;
379
+ if (!next || cursors.has(next)) {
380
+ reasons.add("cursor-did-not-advance");
381
+ break;
382
+ }
383
+ cursors.add(next);
384
+ cursor = next;
385
+ }
386
+ if (!isActive())
387
+ return undefined;
388
+ if (pages.reduce((count, page) => count + page.records.length, 0) === 0)
389
+ reasons.add("empty-window");
390
+ return {
391
+ schema: "liveavatar.avsync.evidence",
392
+ schemaVersion: 4,
393
+ alert,
394
+ query: { range, retrievedAtWallClockMs, complete: queryComplete },
395
+ pages,
396
+ completeness: {
397
+ complete: queryComplete && reasons.size === 0,
398
+ reasons: [...reasons],
399
+ },
400
+ };
401
+ }
402
+ /** Lossless framing of the whole evidence document, including oversized metadata. */
403
+ function createEvidencePayloads(evidenceId, evidence) {
404
+ const source = operationalSource(evidence.alert);
405
+ const alertId = evidence.alert.correlation?.alertId;
406
+ if (!alertId)
407
+ throw new Error("A/V alert is missing its source alertId");
408
+ const document = JSON.stringify(evidence);
409
+ const base = {
410
+ ...source,
411
+ kind: "liveavatar.avsync.alert-evidence",
412
+ schemaVersion: 4,
413
+ evidenceId,
414
+ alertId,
415
+ };
416
+ const chunkPayload = (data, index, total) => ({
417
+ ...base,
418
+ recordType: "log-chunk",
419
+ chunk: { index, total, byteLength: utf8ByteLength(data), data },
420
+ });
421
+ // A fragment contains at least one UTF-16 code unit, so document.length bounds
422
+ // both index and total. Use that conservative envelope during packing.
423
+ const maximumTotal = Math.max(1, document.length);
424
+ const parts = [];
425
+ let start = 0;
426
+ while (start < document.length) {
427
+ let low = start;
428
+ let high = Math.min(document.length, start + EVIDENCE_CONTENT_BYTE_LIMIT);
429
+ while (low < high) {
430
+ const end = Math.ceil((low + high) / 2);
431
+ if (utf8ByteLength(JSON.stringify(chunkPayload(document.slice(start, end), maximumTotal, maximumTotal))) <= EVIDENCE_CONTENT_BYTE_LIMIT)
432
+ low = end;
433
+ else
434
+ high = end - 1;
435
+ }
436
+ // Move left if the fitted UTF-16 slice cuts a surrogate pair.
437
+ if (low < document.length &&
438
+ low > start &&
439
+ /[\uD800-\uDBFF]/.test(document[low - 1]) &&
440
+ /[\uDC00-\uDFFF]/.test(document[low]))
441
+ low--;
442
+ if (low === start)
443
+ throw new Error("A/V evidence envelope leaves no room for a fragment");
444
+ parts.push(document.slice(start, low));
445
+ start = low;
446
+ }
447
+ const chunks = parts.map((data, index) => chunkPayload(data, index, parts.length));
448
+ const summary = serializeEvidenceContent({
449
+ ...base,
450
+ recordType: "summary",
451
+ evidence: {
452
+ complete: evidence.completeness.complete,
453
+ reasons: evidence.completeness.reasons,
454
+ logChunkCount: chunks.length,
455
+ logRecordCount: evidence.pages.reduce((count, page) => count + page.records.length, 0),
456
+ byteLength: utf8ByteLength(document),
457
+ },
458
+ });
459
+ assertContentFits(summary);
460
+ for (const chunk of chunks)
461
+ assertContentFits(chunk);
462
+ return { summary, chunks };
463
+ }
464
+
24
465
  const SKYWALKING_PLUGIN_ID = "liveavatar.skywalking";
25
- const AVSYNC_ALERTS_CONTRIBUTION_ID = "liveavatar.skywalking.avsync-alerts";
26
466
  const OPERATIONAL_LOGS_CONTRIBUTION_ID = "liveavatar.skywalking.operational-logs";
27
- const ALERT_LOG_DURATION_MS = 30000;
28
- const TELEMETRY_PAGE_SIZE = 1000;
29
- /**
30
- * The platform limits the complete top-level `content` value of one error
31
- * record to 32 KiB. Keep a margin for platform serialization differences.
32
- */
33
- const EVIDENCE_CONTENT_BYTE_LIMIT = 28 * 1024;
34
- const FRAME_METADATA_MAX_ASSOCIATION_AGE_MS = 150;
35
- const TIME_SYNC_BUCKET_MS = 1000;
36
467
  const SKYWALKING_SERVICE = "yy-tx::liveavatar-js-sdk";
37
468
  const DOMESTIC_COLLECTOR = "https://apm.hexin.cn/skywalking-web";
38
- const OVERSEAS_COLLECTOR = "https://apm.ainvest.com/skywalking-web";
469
+ const OVERSEAS_COLLECTOR = "https://ai.dreamfaceapp.com/skywalking-web";
39
470
  const REGISTRATION_STATE_KEY = Symbol.for("liveavatar.skywalking.registration-state");
40
- /**
41
- * Reports LiveAvatar A/V-sync incident lifecycle events through the bundled or
42
- * externally provided SkyWalking client.
43
- */
471
+ const MAX_PENDING_ALERTS = 1000;
472
+ const DEFAULT_PLAYBACK_STATUS_INTERVAL_MS = 5000;
473
+ /** Consumes SDK facts and samples playback through the public Plugin API v1. */
44
474
  class SkyWalkingPlugin {
45
475
  constructor(config = {}) {
46
476
  this.id = SKYWALKING_PLUGIN_ID;
47
- /** SDK Plugin API v1 is the registrar-based public plugin contract. */
48
477
  this.apiVersion = 1;
49
- this._nextInstallationGeneration = 0;
478
+ this.terminalObserverDelivery = "sync-before-dispose";
50
479
  this._skyWalkingConfig = { ...config };
51
480
  this._reporting = normalizeReportingConfig(config.reporting);
481
+ const interval = config.playbackStatusIntervalMs;
482
+ this._playbackStatusIntervalMs =
483
+ typeof interval === "number" &&
484
+ Number.isInteger(interval) &&
485
+ interval > 0 &&
486
+ interval <= 2147483647
487
+ ? interval
488
+ : DEFAULT_PLAYBACK_STATUS_INTERVAL_MS;
489
+ if (interval !== undefined && interval !== this._playbackStatusIntervalMs)
490
+ this._warn("Invalid playbackStatusIntervalMs; using 5000 ms");
52
491
  }
53
492
  setup(registrar) {
54
493
  this._deactivateInstallation();
@@ -56,26 +495,45 @@
56
495
  return;
57
496
  registerSkyWalking(this._skyWalkingConfig);
58
497
  const installation = {
59
- generation: ++this._nextInstallationGeneration,
498
+ active: true,
60
499
  abortController: new AbortController(),
500
+ retiredPlaybackOwners: new Set(),
501
+ playbackSequences: new Map(),
61
502
  alertReportStates: new Map(),
62
- active: true,
503
+ pending: [],
504
+ draining: false,
63
505
  };
64
506
  this._installation = installation;
65
507
  try {
66
- if (this._reporting.avSync) {
67
- installation.diagnostics = registrar.consume(liveavatarJsSdk.SDK_AVSYNC_DIAGNOSTICS_V1);
68
- registrar.observe(liveavatarJsSdk.SDK_AVSYNC_ALERTS_V1, {
69
- id: AVSYNC_ALERTS_CONTRIBUTION_ID,
70
- handler: (alert, context) => this._handleAlertNotification(installation, alert, context.signal),
71
- });
72
- }
73
- if (this._reporting.sdkError || this._reporting.firstFrame) {
74
- registrar.observe(liveavatarJsSdk.SDK_OPERATIONAL_LOGS_V1, {
75
- id: OPERATIONAL_LOGS_CONTRIBUTION_ID,
76
- handler: (record, context) => this._handleOperationalLog(installation, record, context.signal),
77
- });
508
+ if (this._reporting.playbackStatus) {
509
+ try {
510
+ const service = registrar.consume(liveavatarJsSdk.SDK_AVSYNC_DIAGNOSTICS_V1);
511
+ if (typeof service?.getPlaybackStatus !== "function")
512
+ throw new Error("getPlaybackStatus is unavailable");
513
+ installation.playbackService = service;
514
+ }
515
+ catch (error) {
516
+ this._warn("Playback status service unavailable; sampling disabled", error);
517
+ }
78
518
  }
519
+ if (this._reporting.avSync)
520
+ installation.diagnostics = registrar.consume(liveavatarJsSdk.SDK_AVSYNC_DIAGNOSTICS_V2);
521
+ registrar.observe(liveavatarJsSdk.SDK_OPERATIONAL_LOGS_V2, {
522
+ id: OPERATIONAL_LOGS_CONTRIBUTION_ID,
523
+ handler: (record, context) => {
524
+ if (!this._isActive(installation, context.signal))
525
+ return;
526
+ this._handlePlaybackLifecycle(installation, record);
527
+ if (record.event === "avsync.alert") {
528
+ if (this._reporting.avSync)
529
+ this._queueAlert(installation, record, context.signal);
530
+ return;
531
+ }
532
+ // These async methods call ClientMonitor synchronously before their first
533
+ // await, preserving the SDK's terminal handoff during dispose.
534
+ return this._handleOperationalLog(installation, record, context.signal)?.then(() => undefined);
535
+ },
536
+ });
79
537
  }
80
538
  catch (error) {
81
539
  this._deactivateInstallation();
@@ -85,1215 +543,364 @@
85
543
  dispose() {
86
544
  this._deactivateInstallation();
87
545
  }
88
- _handleAlertNotification(installation, alert, signal) {
89
- if (!this._isInvocationActive(installation, signal)) {
90
- return Promise.resolve();
91
- }
92
- try {
93
- if (alert.phase === "raised") {
94
- const state = installation.alertReportStates.get(alert.alertId) ?? {
95
- tail: Promise.resolve(),
96
- lastSuccessfulToWallClockMs: undefined,
97
- closing: false,
98
- };
99
- if (state.closing)
100
- return Promise.resolve();
101
- installation.alertReportStates.set(alert.alertId, state);
102
- return this._enqueue(state, () => this._runObserverTask(installation, signal, "A/V Sync alert", () => this._reportActiveAlert(installation, alert, state, signal)));
103
- }
104
- const state = installation.alertReportStates.get(alert.alertId);
105
- if (state === undefined || state.closing)
106
- return Promise.resolve();
107
- if (alert.phase === "updated") {
108
- return this._enqueue(state, () => this._runObserverTask(installation, signal, "A/V Sync alert update", () => this._reportActiveAlert(installation, alert, state, signal)));
109
- }
110
- state.closing = true;
111
- const recoveredAtWallClockMs = Date.now();
112
- const report = this._enqueue(state, () => this._runObserverTask(installation, signal, "A/V Sync recovery", () => this._reportRecovery(installation, alert.alertId, recoveredAtWallClockMs, signal)));
113
- const removeState = () => {
114
- if (installation.alertReportStates.get(alert.alertId) === state) {
115
- installation.alertReportStates.delete(alert.alertId);
116
- }
117
- };
118
- void report.then(removeState, removeState);
119
- return report;
120
- }
121
- catch (error) {
122
- this._warnInvocationFailure(installation, signal, "Failed to handle an A/V Sync alert", error, { alert: toJsonSafeAlert(alert) });
123
- return Promise.resolve();
124
- }
125
- }
126
- _handleOperationalLog(installation, record, signal) {
127
- if (!this._isInvocationActive(installation, signal))
128
- return Promise.resolve();
129
- if (this._reporting.sdkError &&
130
- record.level === "error" &&
131
- record.event === "sdk.error") {
132
- return this._runObserverTask(installation, signal, "SDK error log", () => this._reportSdkError(installation, record, signal));
133
- }
134
- if (this._reporting.firstFrame &&
135
- record.category === "media" &&
136
- record.event === "performance.first-frame") {
137
- return this._runObserverTask(installation, signal, "first-frame log", () => this._reportFirstFrameLog(installation, record, signal));
138
- }
139
- return Promise.resolve();
140
- }
141
- _enqueue(state, task) {
142
- const queued = state.tail.then(task, task);
143
- state.tail = queued.catch(() => undefined);
144
- return queued;
546
+ _deactivateInstallation() {
547
+ const installation = this._installation;
548
+ if (!installation)
549
+ return;
550
+ installation.active = false;
551
+ this._stopPlayback(installation);
552
+ installation.abortController.abort();
553
+ installation.pending.length = 0;
554
+ installation.alertReportStates.clear();
555
+ installation.retiredPlaybackOwners.clear();
556
+ installation.playbackSequences.clear();
557
+ this._installation = undefined;
145
558
  }
146
- async _reportActiveAlert(installation, alert, state, signal) {
147
- const isActive = () => this._isInvocationActive(installation, signal);
148
- if (!isActive())
559
+ _stopPlayback(installation) {
560
+ const sampling = installation.playback;
561
+ if (!sampling)
149
562
  return;
150
- const diagnostics = installation.diagnostics;
151
- if (diagnostics === undefined)
563
+ sampling.abortController.abort();
564
+ if (sampling.timer !== undefined)
565
+ clearInterval(sampling.timer);
566
+ installation.playback = undefined;
567
+ }
568
+ _handlePlaybackLifecycle(installation, record) {
569
+ if (!installation.playbackService)
152
570
  return;
153
- const clientMonitor = getClientMonitor();
154
- if (clientMonitor === undefined) {
155
- this._warnInvocation(installation, signal, "ClientMonitor.reportFrameErrors is unavailable", {
156
- pluginId: this.id,
157
- alert: toJsonSafeAlert(alert),
158
- });
571
+ const event = record.event;
572
+ const starts = [
573
+ "connect.completed",
574
+ "reconnect.completed",
575
+ "livekit.connected",
576
+ ].includes(event) ||
577
+ (event === "rtc.state-changed" &&
578
+ record.data?.roomState === "connected" &&
579
+ ["connected", "state-changed"].includes(String(record.data?.phase)));
580
+ const stops = [
581
+ "connect.failed",
582
+ "reconnect.started",
583
+ "reconnect.failed",
584
+ "disconnect.completed",
585
+ "monitoring.session.ended",
586
+ "client.disposed",
587
+ "livekit.disconnected",
588
+ ].includes(event) ||
589
+ (event === "rtc.state-changed" &&
590
+ ["disconnected", "reconnecting", "connecting"].includes(String(record.data?.roomState)));
591
+ if (!starts &&
592
+ !stops &&
593
+ event !== "monitoring.session.started" &&
594
+ event !== "avsync.session.started")
159
595
  return;
160
- }
161
- const retrievedAtWallClockMs = Date.now();
162
- const query = await createEvidenceQuery(alert.phase, state.lastSuccessfulToWallClockMs, [signal, installation.abortController.signal]);
163
- if (!isActive() || query === undefined)
596
+ const owner = JSON.stringify([
597
+ record.clientInstanceId,
598
+ record.monitoringSessionId,
599
+ ]);
600
+ if (installation.retiredPlaybackOwners.has(owner))
164
601
  return;
165
- const collection = await collectTelemetry(diagnostics, alert, retrievedAtWallClockMs, query, isActive, (message, error) => this._warnInvocationFailure(installation, signal, message, error, {
166
- alert: toJsonSafeAlert(alert),
167
- }));
168
- if (!isActive() || collection === undefined)
602
+ // Lifecycle facts share SDK-owned streams. Ignore delayed older facts, without
603
+ // comparing sequence numbers from different streams or monitoring sessions.
604
+ const stream = JSON.stringify([owner, record.streamId]);
605
+ const previous = installation.playbackSequences.get(stream);
606
+ if (previous !== undefined && record.sequence <= previous)
169
607
  return;
170
- const evidenceId = createEvidenceId();
171
- const chunks = createLogChunkPayloads(evidenceId, alert.alertId, collection.evidence.sessionId, collectPreparedCompactLogs(collection.evidence));
172
- const payload = createSummaryPayload(evidenceId, toJsonSafeAlert(alert), collection.evidence, chunks.length);
173
- if (!isActive())
608
+ installation.playbackSequences.set(stream, record.sequence);
609
+ if (event === "client.disposed") {
610
+ this._stopPlayback(installation);
174
611
  return;
175
- try {
176
- await Promise.resolve(clientMonitor.reportFrameErrors({
177
- category: "avsync",
178
- grade: "Warning",
179
- content: payload,
180
- }, {
181
- // The bundled SkyWalking script uses this as errorUrl. An empty
182
- // name lets it fall back to the browser page URL.
183
- name: "",
184
- message: `[LiveAvatar A/V Sync] ${alert.finding}: ${alert.message}`,
185
- stack: "",
186
- }));
187
- for (const chunk of chunks) {
188
- if (!isActive())
189
- return;
190
- await Promise.resolve(clientMonitor.reportFrameErrors({
191
- category: "avsync",
192
- grade: "Info",
193
- content: chunk,
194
- }, {
195
- name: "",
196
- message: `[LiveAvatar A/V Sync] evidence chunk ${chunk.chunk.index + 1}/${chunk.chunk.total}`,
197
- stack: "",
198
- }));
199
- }
200
612
  }
201
- catch (error) {
202
- this._warnInvocationFailure(installation, signal, "Failed to report an A/V Sync alert to SkyWalking", error, { alert: toJsonSafeAlert(alert) });
203
- return;
204
- }
205
- if (!isActive())
206
- return;
207
- if (collection.evidence.window.complete &&
208
- collection.requestedToWallClockMs !== null) {
209
- state.lastSuccessfulToWallClockMs = collection.requestedToWallClockMs;
210
- }
211
- }
212
- async _reportRecovery(installation, alertId, recoveredAtWallClockMs, signal) {
213
- if (!this._isInvocationActive(installation, signal))
214
- return;
215
- const clientMonitor = getClientMonitor();
216
- if (clientMonitor === undefined) {
217
- this._warnInvocation(installation, signal, "ClientMonitor.reportFrameErrors is unavailable", {
218
- pluginId: this.id,
219
- alertId,
220
- recoveredAtWallClockMs,
221
- });
222
- return;
613
+ if (installation.playbackOwner !== owner) {
614
+ if (!starts && event !== "monitoring.session.started")
615
+ return;
616
+ if (installation.playbackOwner !== undefined)
617
+ installation.retiredPlaybackOwners.add(installation.playbackOwner);
618
+ this._stopPlayback(installation);
619
+ installation.playbackOwner = owner;
223
620
  }
224
- if (!this._isInvocationActive(installation, signal))
621
+ if (stops) {
622
+ this._stopPlayback(installation);
623
+ if (event === "monitoring.session.ended")
624
+ installation.retiredPlaybackOwners.add(owner);
225
625
  return;
226
- try {
227
- await Promise.resolve(clientMonitor.reportFrameErrors({
228
- category: "avsync",
229
- grade: "Recovered",
230
- content: { alertId, recoveredAtWallClockMs },
231
- }, {
232
- name: "",
233
- message: "[LiveAvatar A/V Sync] alert recovered",
234
- stack: "",
235
- }));
236
626
  }
237
- catch (error) {
238
- this._warnInvocationFailure(installation, signal, "Failed to report an A/V Sync recovery to SkyWalking", error, { alertId, recoveredAtWallClockMs });
627
+ const identities = {
628
+ ...sourceCorrelation(record),
629
+ clientInstanceId: record.clientInstanceId,
630
+ };
631
+ if (installation.playback) {
632
+ const updated = {
633
+ ...installation.playback.owner,
634
+ ...identities,
635
+ };
636
+ const changed = ["serverSessionId", "avsyncSessionId"];
637
+ if (!changed.some((key) => updated[key] !== installation.playback.owner[key])) {
638
+ installation.playback.owner = updated;
639
+ return;
640
+ }
641
+ // A changed diagnostic segment also invalidates a pending sample.
642
+ this._stopPlayback(installation);
643
+ this._startPlayback(installation, updated);
239
644
  return;
240
645
  }
241
- if (!this._isInvocationActive(installation, signal))
646
+ if (!starts)
242
647
  return;
648
+ this._startPlayback(installation, identities);
243
649
  }
244
- async _reportSdkError(installation, record, signal) {
245
- if (!this._isInvocationActive(installation, signal))
246
- return;
247
- const code = stringOr(record.attributes?.code, "SDK_ERROR");
248
- const clientMonitor = getClientMonitor();
249
- if (clientMonitor === undefined) {
250
- this._warnInvocation(installation, signal, "ClientMonitor.reportFrameErrors is unavailable", {
251
- pluginId: this.id,
252
- sdkError: { code },
253
- });
254
- return;
255
- }
256
- const payload = {
257
- schemaVersion: 2,
258
- kind: "liveavatar.sdk.error",
259
- sdkVersion: liveavatarJsSdk.VERSION,
260
- error: stringifyJson({
261
- code,
262
- eventId: record.eventId,
263
- sequence: record.sequence,
264
- occurredAtMs: record.occurredAtMs,
265
- category: record.category,
266
- event: record.event,
267
- clientInstanceId: record.clientInstanceId,
268
- ...(record.sessionId === undefined
269
- ? {}
270
- : { sessionId: record.sessionId }),
271
- }),
650
+ _startPlayback(installation, owner) {
651
+ const sampling = {
652
+ owner,
653
+ abortController: new AbortController(),
654
+ busy: false,
272
655
  };
273
- if (!this._isInvocationActive(installation, signal))
274
- return;
275
- try {
276
- await Promise.resolve(clientMonitor.reportFrameErrors({
277
- category: "unknown",
278
- grade: "Error",
279
- content: payload,
280
- }, {
281
- name: "",
282
- message: `[LiveAvatar SDK] ${code}`,
283
- stack: "",
284
- }));
285
- }
286
- catch (error) {
287
- this._warnInvocationFailure(installation, signal, "Failed to report an SDK error to SkyWalking", error, { eventId: record.eventId, code });
288
- return;
289
- }
290
- if (!this._isInvocationActive(installation, signal))
291
- return;
656
+ installation.playback = sampling;
657
+ sampling.timer = setInterval(() => {
658
+ void this._samplePlayback(installation, sampling);
659
+ }, this._playbackStatusIntervalMs);
660
+ void this._samplePlayback(installation, sampling);
292
661
  }
293
- async _reportFirstFrameLog(installation, record, signal) {
294
- if (!this._isInvocationActive(installation, signal))
295
- return;
296
- const payload = toSkyWalkingFirstFrameLogPayload(record);
297
- if (payload === undefined) {
298
- this._warnInvocation(installation, signal, "Skipped invalid first-frame Operational Log", { eventId: record.eventId });
299
- return;
300
- }
301
- const clientMonitor = getClientMonitor();
302
- if (clientMonitor === undefined) {
303
- this._warnInvocation(installation, signal, "ClientMonitor.reportFrameErrors is unavailable", {
304
- pluginId: this.id,
305
- attemptId: payload.attemptId,
306
- outcome: payload.outcome,
307
- });
308
- return;
309
- }
310
- if (!this._isInvocationActive(installation, signal))
662
+ async _samplePlayback(installation, sampling) {
663
+ const signal = sampling.abortController.signal;
664
+ const active = () => installation.playback === sampling &&
665
+ this._isActive(installation, signal);
666
+ if (sampling.busy || !active())
311
667
  return;
668
+ sampling.busy = true;
669
+ // Capture ownership before the asynchronous query; never attribute its result
670
+ // using a later connection or diagnostic session.
671
+ const owner = { ...sampling.owner };
312
672
  try {
313
- await Promise.resolve(clientMonitor.reportFrameErrors({
673
+ const status = await installation.playbackService.getPlaybackStatus();
674
+ if (!active())
675
+ return;
676
+ if (!status.connection.rtc.connected) {
677
+ this._stopPlayback(installation);
678
+ return;
679
+ }
680
+ const payload = {
681
+ schemaVersion: 4,
682
+ kind: "liveavatar.playback.status",
683
+ ...owner,
684
+ occurredAtMs: Date.now(),
685
+ playback: {
686
+ sampledAtMs: status.sampledAtMs,
687
+ connection: JSON.stringify(status.connection),
688
+ ice: JSON.stringify(status.ice),
689
+ output: status.output === null ? null : JSON.stringify(status.output),
690
+ tracks: JSON.stringify(status.tracks),
691
+ quality: status.quality,
692
+ qualityReasons: JSON.stringify(status.qualityReasons),
693
+ presentationSamplingEnabled: status.presentationSamplingEnabled,
694
+ },
695
+ };
696
+ if (utf8ByteLength(JSON.stringify(payload)) > 28 * 1024)
697
+ throw new Error("Playback status content exceeds the 28 KiB limit");
698
+ await this._report(installation, signal, {
314
699
  category: "media",
315
- grade: payload.outcome === "first-frame" ? "Info" : "Warning",
316
- content: payload,
317
- // The bundled client batches error records. Its public timeout
318
- // option bypasses the default delay for these terminal events.
700
+ grade: "Info",
319
701
  timeout: 1,
320
- }, {
321
- name: "",
322
- message: `[LiveAvatar first-frame] ${payload.outcome}`,
323
- stack: "",
324
- }));
702
+ content: payload,
703
+ }, "[LiveAvatar playback] status");
325
704
  }
326
705
  catch (error) {
327
- this._warnInvocationFailure(installation, signal, "Failed to report first-frame Operational Log to SkyWalking", error, { attemptId: payload.attemptId, outcome: payload.outcome });
706
+ if (active())
707
+ this._warn("Failed to sample playback status", error);
708
+ }
709
+ finally {
710
+ sampling.busy = false;
328
711
  }
329
712
  }
330
- _deactivateInstallation() {
331
- const installation = this._installation;
332
- if (installation === undefined)
333
- return;
334
- installation.active = false;
335
- installation.abortController.abort();
336
- installation.alertReportStates.clear();
337
- if (this._installation === installation)
338
- this._installation = undefined;
339
- }
340
- _isInvocationActive(installation, signal) {
713
+ _isActive(installation, signal) {
341
714
  return (this._installation === installation &&
342
715
  installation.active &&
343
716
  !installation.abortController.signal.aborted &&
344
717
  !signal.aborted);
345
718
  }
346
- async _runObserverTask(installation, signal, description, task) {
347
- try {
348
- await task();
349
- }
350
- catch (error) {
351
- this._warnInvocationFailure(installation, signal, `Failed to handle ${description}`, error);
352
- }
353
- }
354
- _warnInvocationFailure(installation, signal, message, error, details = {}) {
355
- this._warnInvocation(installation, signal, message, { ...details, error });
356
- }
357
- _warnInvocation(installation, signal, message, details) {
358
- if (!this._isInvocationActive(installation, signal))
359
- return;
719
+ _warn(message, error) {
360
720
  try {
361
- console.warn(`[LiveAvatar SkyWalking plugin] ${message}`, details);
721
+ console.warn(`[LiveAvatar SkyWalking plugin] ${message}`, error);
362
722
  }
363
723
  catch {
364
- // Observability warnings must never fault a detached SDK contribution.
724
+ /* Diagnostics must not fault the SDK. */
365
725
  }
366
726
  }
367
- }
368
- /** Creates a fresh plugin instance suitable for `createClient({ plugins })`. */
369
- function createSkyWalkingPlugin(config = {}) {
370
- return new SkyWalkingPlugin(config);
371
- }
372
- async function collectTelemetry(diagnostics, alert, retrievedAtWallClockMs, query, shouldContinue, onDiagnosticFailure) {
373
- if (!shouldContinue())
374
- return undefined;
375
- let firstPage;
376
- let analysis = null;
377
- let analysisUnavailable = false;
378
- let telemetryResult;
379
- let analysisResult;
380
- try {
381
- [telemetryResult, analysisResult] = await Promise.allSettled([
382
- diagnostics.getAvSyncRawTelemetry({
383
- range: query.range,
384
- pageSize: TELEMETRY_PAGE_SIZE,
385
- includeSummary: true,
386
- }),
387
- diagnostics.getAvSyncAnalysis({ range: query.range }),
388
- ]);
389
- }
390
- catch (error) {
391
- if (!shouldContinue())
392
- return undefined;
393
- onDiagnosticFailure("Failed to query A/V Sync telemetry", error);
394
- return {
395
- evidence: unavailableEvidence(retrievedAtWallClockMs, query, "initial-query-failed", alert),
396
- requestedToWallClockMs: null,
397
- };
398
- }
399
- if (!shouldContinue())
400
- return undefined;
401
- if (telemetryResult.status === "rejected") {
402
- onDiagnosticFailure("Failed to query A/V Sync telemetry", telemetryResult.reason);
403
- return {
404
- evidence: unavailableEvidence(retrievedAtWallClockMs, query, "initial-query-failed", alert),
405
- requestedToWallClockMs: null,
406
- };
407
- }
408
- firstPage = telemetryResult.value;
409
- if (analysisResult.status === "fulfilled") {
410
- analysis = analysisResult.value;
411
- }
412
- else {
413
- analysisUnavailable = true;
414
- onDiagnosticFailure("Failed to query A/V Sync analysis", analysisResult.reason);
415
- }
416
- if (!shouldContinue())
417
- return undefined;
418
- const firstPageEvidence = evidenceFromFirstPage(firstPage, query);
419
- if (firstPage.sessionId !== alert.sessionId) {
420
- return {
421
- evidence: {
422
- ...firstPageEvidence,
423
- window: {
424
- ...firstPageEvidence.window,
425
- complete: false,
426
- unavailableReason: "session-mismatch",
427
- },
428
- triage: createTriage(alert, null, ["session-mismatch"]),
429
- },
430
- requestedToWallClockMs: firstPage.page.requestedToWallClockMs,
431
- };
432
- }
433
- const logs = [...firstPage.avSyncLogs];
434
- let page = firstPage.page;
435
- let truncated = page.truncated;
436
- const seenCursors = new Set();
437
- while (page.hasMore) {
438
- if (!shouldContinue())
439
- return undefined;
440
- const cursor = page.nextCursor;
441
- if (cursor === null || seenCursors.has(cursor)) {
442
- return {
443
- evidence: compactEvidence(firstPageEvidence, logs, truncated, "cursor-did-not-advance", alert, analysis, analysisUnavailable, firstPage),
444
- requestedToWallClockMs: firstPage.page.requestedToWallClockMs,
445
- };
727
+ async _report(installation, signal, config, message) {
728
+ if (!this._isActive(installation, signal))
729
+ return false;
730
+ const monitor = getClientMonitor();
731
+ if (!monitor) {
732
+ this._warn("ClientMonitor.reportFrameErrors is unavailable");
733
+ return false;
446
734
  }
447
- seenCursors.add(cursor);
448
- let continuation;
449
735
  try {
450
- continuation = await diagnostics.getAvSyncRawTelemetry({
451
- cursor,
452
- pageSize: TELEMETRY_PAGE_SIZE,
453
- includeSummary: false,
454
- });
736
+ await Promise.resolve(monitor.reportFrameErrors({ ...config, serviceVersion: liveavatarJsSdk.VERSION }, { name: "", message, stack: "" }));
737
+ return this._isActive(installation, signal);
455
738
  }
456
739
  catch (error) {
457
- if (!shouldContinue())
458
- return undefined;
459
- onDiagnosticFailure("Failed to query A/V Sync telemetry continuation", error);
460
- return {
461
- evidence: compactEvidence(firstPageEvidence, logs, truncated, "continuation-query-failed", alert, analysis, analysisUnavailable, firstPage),
462
- requestedToWallClockMs: firstPage.page.requestedToWallClockMs,
463
- };
740
+ if (this._isActive(installation, signal))
741
+ this._warn("Failed to report to SkyWalking", error);
742
+ return false;
464
743
  }
465
- if (!shouldContinue())
466
- return undefined;
467
- if (continuation.sessionId !== alert.sessionId) {
468
- return {
469
- evidence: compactEvidence(firstPageEvidence, logs, truncated, "session-mismatch", alert, analysis, analysisUnavailable, firstPage),
470
- requestedToWallClockMs: firstPage.page.requestedToWallClockMs,
744
+ }
745
+ _handleOperationalLog(installation, record, signal) {
746
+ if (record.event === "sdk.failure") {
747
+ if (!this._reporting.sdkError ||
748
+ !record.error ||
749
+ !["warn", "error"].includes(record.level))
750
+ return;
751
+ const payload = {
752
+ ...operationalSource(record),
753
+ kind: "liveavatar.sdk.error",
754
+ schemaVersion: 4,
755
+ error: JSON.stringify(projectRecord(record)),
471
756
  };
757
+ return this._report(installation, signal, {
758
+ category: record.module,
759
+ grade: record.level === "warn" ? "Warning" : "Error",
760
+ content: payload,
761
+ timeout: 1,
762
+ }, `[LiveAvatar SDK] ${record.error.code}`);
472
763
  }
473
- logs.push(...continuation.avSyncLogs);
474
- page = continuation.page;
475
- truncated = truncated || page.truncated;
476
- }
477
- if (!shouldContinue())
478
- return undefined;
479
- return {
480
- evidence: compactEvidence(firstPageEvidence, logs, truncated, undefined, alert, analysis, analysisUnavailable, firstPage, true),
481
- requestedToWallClockMs: firstPage.page.requestedToWallClockMs,
482
- };
483
- }
484
- function evidenceFromFirstPage(telemetry, query) {
485
- return {
486
- evidenceSchemaVersion: 2,
487
- sessionId: telemetry.sessionId ?? null,
488
- window: {
489
- mode: query.mode,
490
- requestedFromWallClockMs: telemetry.page.requestedFromWallClockMs,
491
- requestedToWallClockMs: telemetry.page.requestedToWallClockMs,
492
- availableFromWallClockMs: telemetry.page.availableFromWallClockMs,
493
- availableToWallClockMs: telemetry.page.availableToWallClockMs,
494
- complete: false,
495
- truncated: telemetry.page.truncated,
496
- },
497
- retention: compactRetention(telemetry.avSyncLogRetention),
498
- triage: null,
499
- logChunkCount: 0,
500
- logRecordCount: 0,
501
- detail: emptyDetail(),
502
- };
503
- }
504
- function unavailableEvidence(_retrievedAtWallClockMs, query, unavailableReason, alert) {
505
- return {
506
- evidenceSchemaVersion: 2,
507
- retention: null,
508
- sessionId: null,
509
- window: {
510
- mode: query.mode,
511
- requestedFromWallClockMs: null,
512
- requestedToWallClockMs: null,
513
- availableFromWallClockMs: null,
514
- availableToWallClockMs: null,
515
- complete: false,
516
- truncated: false,
517
- unavailableReason,
518
- },
519
- triage: createTriage(alert, null, [unavailableReason]),
520
- logChunkCount: 0,
521
- logRecordCount: 0,
522
- detail: emptyDetail(),
523
- };
524
- }
525
- async function createEvidenceQuery(phase, lastSuccessfulToWallClockMs, signals) {
526
- if (isAnySignalAborted(signals))
527
- return undefined;
528
- if (phase === "raised" || lastSuccessfulToWallClockMs === undefined) {
529
- return {
530
- mode: "recent",
531
- range: { kind: "recent", durationMs: ALERT_LOG_DURATION_MS },
532
- requestedDurationMs: ALERT_LOG_DURATION_MS,
533
- };
534
- }
535
- let now = Date.now();
536
- const nextFromMs = lastSuccessfulToWallClockMs + 1;
537
- if (now < nextFromMs) {
538
- await waitForWallClock(nextFromMs, signals);
539
- if (isAnySignalAborted(signals))
540
- return undefined;
541
- now = Date.now();
542
- }
543
- const fromMs = Math.max(nextFromMs, now - ALERT_LOG_DURATION_MS);
544
- const toMs = Math.max(fromMs, now);
545
- return {
546
- mode: "wall-clock",
547
- range: { kind: "wall-clock", fromMs, toMs },
548
- requestedDurationMs: toMs - fromMs,
549
- };
550
- }
551
- function waitForWallClock(targetMs, signals) {
552
- if (isAnySignalAborted(signals))
553
- return Promise.resolve();
554
- return new Promise((resolve) => {
555
- let settled = false;
556
- let timeout;
557
- const finish = () => {
558
- if (settled)
764
+ if (record.event === "performance.first-frame") {
765
+ if (!this._reporting.firstFrame)
766
+ return;
767
+ const payload = toSkyWalkingFirstFrameLogPayload(record);
768
+ if (!payload) {
769
+ this._warn("Skipped invalid first-frame Operational Log");
559
770
  return;
560
- settled = true;
561
- if (timeout !== undefined)
562
- clearTimeout(timeout);
563
- for (const signal of signals) {
564
- signal.removeEventListener("abort", finish);
565
771
  }
566
- resolve();
567
- };
568
- timeout = setTimeout(finish, Math.max(1, targetMs - Date.now()));
569
- for (const signal of signals)
570
- signal.addEventListener("abort", finish);
571
- });
572
- }
573
- function isAnySignalAborted(signals) {
574
- return signals.some((signal) => signal.aborted);
575
- }
576
- function compactEvidence(firstPageEvidence, logs, truncated, unavailableReason, alert, analysis, analysisUnavailable, telemetry, complete = false) {
577
- const compacted = compactLogs(logs, telemetry);
578
- return {
579
- ...firstPageEvidence,
580
- window: {
581
- ...firstPageEvidence.window,
582
- complete,
583
- truncated,
584
- ...(unavailableReason === undefined ? {} : { unavailableReason }),
585
- },
586
- triage: createTriage(alert, analysis, analysisUnavailable ? ["analysis-query-failed"] : []),
587
- ...chunkCompactLogs(compacted.logs, compacted.detail),
588
- };
589
- }
590
- function compactRetention(retention) {
591
- if (retention === null)
592
- return null;
593
- return {
594
- storageWriteFailed: retention.storageWriteFailed,
595
- droppedSegmentCount: retention.droppedSegmentCount,
596
- droppedLogCount: retention.droppedLogCount,
597
- oldestSegmentAtMs: retention.oldestSegmentAtMs,
598
- newestSegmentAtMs: retention.newestSegmentAtMs,
599
- };
600
- }
601
- function createTriage(alert, analysis, limitations) {
602
- const usableAnalysis = analysis !== null &&
603
- analysis.layers !== null &&
604
- typeof analysis.layers === "object" &&
605
- Array.isArray(analysis.participants) &&
606
- typeof analysis.finding === "string";
607
- return {
608
- trigger: {
609
- finding: alert.finding,
610
- status: alert.status,
611
- confidence: alert.confidence,
612
- capturedAtMs: alert.capturedAtMs,
613
- },
614
- evaluation: !usableAnalysis || analysis === null
615
- ? null
616
- : {
617
- finding: analysis.finding,
618
- status: analysis.status,
619
- confidence: analysis.confidence,
620
- },
621
- layers: !usableAnalysis || analysis === null
622
- ? null
623
- : Object.fromEntries(Object.entries(analysis.layers).map(([name, layer]) => [
624
- name,
625
- {
626
- status: layer.status,
627
- finding: layer.finding,
628
- confidence: layer.confidence,
629
- },
630
- ])),
631
- participants: (!usableAnalysis || analysis === null ? [] : analysis.participants).map((participant) => ({
632
- participantId: participant.participantId,
633
- status: participant.status,
634
- finding: participant.finding,
635
- confidence: participant.confidence,
636
- audioTrackId: participant.audioTrackId,
637
- videoTrackId: participant.videoTrackId,
638
- metrics: participant.metrics,
639
- })) ?? [],
640
- limitations: [
641
- ...new Set([
642
- ...(!usableAnalysis || analysis === null ? [] : analysis.limitations),
643
- ...limitations,
644
- ...(!usableAnalysis && analysis !== null ? ["analysis-invalid"] : []),
645
- ]),
646
- ],
647
- };
648
- }
649
- function emptyDetail() {
650
- return {
651
- projectionVersion: 2,
652
- sourceRecordCount: 0,
653
- reportedRecordCount: 0,
654
- timeSyncInputCount: 0,
655
- timeSyncReportedCount: 0,
656
- framePresentationReportedCount: 0,
657
- verifiedMetadataTimestampCount: 0,
658
- omittedSetupLifecycleCount: 0,
659
- oversizeFallbackRecordCount: 0,
660
- contentByteLimit: EVIDENCE_CONTENT_BYTE_LIMIT,
661
- chunks: [],
662
- };
663
- }
664
- function compactLogs(logs, telemetry) {
665
- const compacted = [];
666
- const detail = emptyDetail();
667
- detail.sourceRecordCount = logs.length;
668
- const timeSyncBuckets = new Map();
669
- for (const log of logs) {
670
- if (log.eventName === "time-sync-updated") {
671
- detail.timeSyncInputCount += 1;
672
- const correlation = toRecord(log.correlation);
673
- const key = [
674
- correlation.participantId ?? "",
675
- correlation.trackId ?? "",
676
- correlation.mediaKind ?? "",
677
- Math.floor(log.wallClockMs / TIME_SYNC_BUCKET_MS),
678
- ].join("|");
679
- timeSyncBuckets.set(key, log);
680
- continue;
772
+ return this._report(installation, signal, {
773
+ category: "media",
774
+ grade: payload.outcome === "first-frame" ? "Info" : "Warning",
775
+ content: payload,
776
+ timeout: 1,
777
+ }, `[LiveAvatar first-frame] ${payload.outcome}`);
681
778
  }
682
- const compact = compactSourceLog(log);
683
- if (compact !== null)
684
- compacted.push(compact);
685
- else if (log.logType === "lifecycle")
686
- detail.omittedSetupLifecycleCount += 1;
687
- }
688
- const timeSync = [...timeSyncBuckets.values()]
689
- .sort(compareSourceLogs)
690
- .map(compactTimeSyncLog);
691
- detail.timeSyncReportedCount = timeSync.length;
692
- compacted.push(...timeSync);
693
- compacted.push(...compactMediaTimeline(telemetry.mediaTimeline));
694
- compacted.push(...compactDiagnoses(telemetry.diagnosis));
695
- const presentations = compactVideoFrames(telemetry.videoFrames);
696
- detail.framePresentationReportedCount = presentations.logs.length;
697
- detail.verifiedMetadataTimestampCount = presentations.verifiedCount;
698
- compacted.push(...presentations.logs);
699
- compacted.sort(compareCompactLogs);
700
- detail.reportedRecordCount = compacted.length;
701
- return { logs: compacted, detail };
702
- }
703
- function compactMediaTimeline(value) {
704
- const buckets = new Map();
705
- for (const item of value) {
706
- const record = toRecord(item);
707
- const participantId = stringOr(record.participantId, "");
708
- const videoTrackId = stringOr(record.videoTrackId, "");
709
- const wallClock = numberOr(record.wallClock, 0);
710
- buckets.set(`${participantId}|${videoTrackId}|${Math.floor(wallClock / TIME_SYNC_BUCKET_MS)}`, record);
779
+ if (!this._reporting.timeline)
780
+ return;
781
+ const payload = toTimeline(record);
782
+ if (!payload)
783
+ return;
784
+ return this._report(installation, signal, {
785
+ category: record.module,
786
+ grade: record.level === "warn"
787
+ ? "Warning"
788
+ : record.level === "error"
789
+ ? "Error"
790
+ : "Info",
791
+ content: payload,
792
+ ...(["monitoring.session.ended", "client.disposed"].includes(record.event)
793
+ ? { timeout: 1 }
794
+ : {}),
795
+ }, `[LiveAvatar SDK] ${record.event}`);
711
796
  }
712
- return [...buckets.values()].map((record) => ({
713
- q: numberOr(record.seq, 0),
714
- t: numberOr(record.wallClock, 0),
715
- o: numberOr(record.perfNow, 0),
716
- y: "timeline",
717
- e: "relative-drift",
718
- c: removeUndefined({
719
- participantId: record.participantId,
720
- audioTrackId: record.audioTrackId,
721
- videoTrackId: record.videoTrackId,
722
- }),
723
- d: pick(record, [
724
- "normalizationStatus",
725
- "normalizationGeneration",
726
- "normalizationResetReason",
727
- "pairingCoverage",
728
- "validPairCount",
729
- "relativeWindowSpanMs",
730
- "relativeDriftMs",
731
- "relativeDriftAvgMs",
732
- "relativeDriftJitterMs",
733
- "relativeDriftSlopeMsPerMinute",
734
- "videoFrameId",
735
- ]),
736
- }));
737
- }
738
- function compactDiagnoses(value) {
739
- return value.map((item) => {
740
- const record = toRecord(item);
741
- return {
742
- q: numberOr(record.seq, 0),
743
- t: numberOr(record.wallClock, 0),
744
- o: numberOr(record.perfNow, 0),
745
- y: "diagnosis",
746
- e: stringOr(record.status, "unknown"),
747
- d: pick(record, [
748
- "suspectedNode",
749
- "responsibility",
750
- "confidence",
751
- "receiverIncident",
752
- "normalizationStatus",
753
- "normalizationGeneration",
754
- "normalizationResetReason",
755
- "pairingCoverage",
756
- "relativeDriftMs",
757
- "relativeDriftAvgMs",
758
- "relativeDriftJitterMs",
759
- "relativeDriftSlopeMsPerMinute",
760
- "videoCaptureToDisplayRelativeMs",
761
- ]),
762
- };
763
- });
764
- }
765
- function compactSourceLog(log) {
766
- if (log.eventName === "remote-media-capture-completed") {
767
- const data = toRecord(log.data);
768
- return compactLog(log, "capture", "completed", {
769
- id: data.captureId,
770
- status: data.captureStatus,
771
- mode: data.captureMode,
772
- durationMs: data.captureDurationMs,
773
- pairCount: data.pairCount,
774
- unpairedChannelCount: data.unpairedChannelCount,
775
- channelGroupCount: data.channelGroupCount,
776
- playback: compactPlayback(data.playback),
777
- timeSync: compactTimeSyncSummary(data.timeSync),
797
+ _queueAlert(installation, record, signal) {
798
+ if (!record.correlation?.alertId ||
799
+ !["raised", "updated", "recovered"].includes(String(record.data?.phase)))
800
+ return;
801
+ if (installation.pending.length >= MAX_PENDING_ALERTS) {
802
+ installation.pending.shift();
803
+ this._warn("A/V reporting queue full; dropped oldest pending alert");
804
+ }
805
+ // The SDK freezes observer records; still take an independent synchronous copy.
806
+ installation.pending.push({
807
+ record: JSON.parse(JSON.stringify(record)),
808
+ signal,
778
809
  });
779
- }
780
- if (log.eventName === "receiver-stats-sampled") {
781
- const data = toRecord(log.data);
782
- return compactLog(log, "receiver", "sampled", compactReceiverData(data));
783
- }
784
- if (log.eventName === "video-pipeline-stalled") {
785
- return compactLog(log, "incident", "video-pipeline-stalled", toRecord(log.data));
786
- }
787
- if (log.logType === "connection") {
788
- return compactLog(log, "connection", log.eventName, toRecord(log.data));
789
- }
790
- if (log.logType === "lifecycle" && isCausalLifecycleEvent(log.eventName)) {
791
- return compactLog(log, "lifecycle", log.eventName, compactLifecycleDetails(toRecord(log.data)));
792
- }
793
- return null;
794
- }
795
- function compactTimeSyncLog(log) {
796
- const data = toRecord(log.data);
797
- return compactLog(log, "time-sync", "updated", {
798
- receiverTimestampMs: data.receiverTimestampMs,
799
- frameId: data.frameId,
800
- });
801
- }
802
- function compactLog(log, type, event, data) {
803
- return {
804
- q: log.sequence,
805
- t: log.wallClockMs,
806
- o: log.observedAtMs,
807
- y: type,
808
- e: event,
809
- ...(Object.keys(compactCorrelation(toRecord(log.correlation))).length === 0
810
- ? {}
811
- : { c: compactCorrelation(toRecord(log.correlation)) }),
812
- ...(data === undefined || Object.keys(data).length === 0
813
- ? {}
814
- : { d: data }),
815
- };
816
- }
817
- function compactCorrelation(correlation) {
818
- return pick(correlation, [
819
- "participantId",
820
- "trackId",
821
- "mediaKind",
822
- "pairId",
823
- "streamId",
824
- "playbackTargetId",
825
- "captureId",
826
- ]);
827
- }
828
- function compactReceiverData(data) {
829
- return removeUndefined({
830
- source: data.statsSource,
831
- error: data.statsError,
832
- delta: compactReceiverDelta(toRecord(data.delta)),
833
- transport: compactTransport(toRecord(data.transport)),
834
- computed: compactReceiverComputed(toRecord(data.computed)),
835
- frameMetadata: compactFrameMetadata(toRecord(data.frameMetadata)),
836
- });
837
- }
838
- function compactReceiverDelta(data) {
839
- return pick(data, [
840
- "intervalMs",
841
- "packetsReceived",
842
- "packetsLost",
843
- "concealedSamples",
844
- "concealmentEvents",
845
- "framesReceived",
846
- "framesDecoded",
847
- "framesDropped",
848
- "nackCount",
849
- "pliCount",
850
- "firCount",
851
- "freezeCount",
852
- "framesDecodedPerSecond",
853
- ]);
854
- }
855
- function compactReceiverComputed(data) {
856
- return pick(data, [
857
- "packetLossRate",
858
- "jitterMs",
859
- "audioConcealedSamplesPerSecond",
860
- "audioConcealmentEventsPerSecond",
861
- "videoDecodedFramesPerSecond",
862
- "videoDroppedFramesPerSecond",
863
- "videoDecodeRatio",
864
- ]);
865
- }
866
- function compactTransport(transport) {
867
- return pick(transport, [
868
- "iceState",
869
- "candidatePairState",
870
- "candidatePairWritable",
871
- "currentRoundTripTimeSeconds",
872
- ]);
873
- }
874
- function compactPlayback(value) {
875
- return compactLifecycleDetails(toRecord(value));
876
- }
877
- function compactTimeSyncSummary(value) {
878
- const summary = toRecord(value);
879
- const latest = Array.isArray(summary.latest)
880
- ? summary.latest.map((entry) => pick(toRecord(entry), [
881
- "trackId",
882
- "participantId",
883
- "kind",
884
- "observedAtMs",
885
- "receiverTimestampMs",
886
- "frameId",
887
- ]))
888
- : [];
889
- return removeUndefined({ status: summary.status, latest });
890
- }
891
- function isCausalLifecycleEvent(eventName) {
892
- return [
893
- "track-subscribed",
894
- "track-validated",
895
- "pair-bind-started",
896
- "pair-bind-completed",
897
- "pair-bind-failed",
898
- "track-replaced",
899
- "playback-snapshot",
900
- "element-waiting",
901
- "element-stalled",
902
- "element-recovered",
903
- "native-playing",
904
- "video-first-frame-presented",
905
- "element-error",
906
- ].includes(eventName);
907
- }
908
- function compactLifecycleDetails(details) {
909
- return pick(details, [
910
- "requiredMediaKinds",
911
- "attachedMediaKind",
912
- "attachedKinds",
913
- "bindingGeneration",
914
- "targetId",
915
- "elementTag",
916
- "elementRole",
917
- "elementBindingId",
918
- "elementBound",
919
- "srcObjectType",
920
- "streamBindingState",
921
- "streamId",
922
- "streamTrackCount",
923
- "streamTrackKinds",
924
- "activeAudioTrackId",
925
- "activeAudioParticipantId",
926
- "activeVideoTrackId",
927
- "activeVideoParticipantId",
928
- "readyState",
929
- "networkState",
930
- "paused",
931
- "currentTime",
932
- "playbackRate",
933
- "width",
934
- "height",
935
- "videoWidth",
936
- "videoHeight",
937
- "eventSemantic",
938
- "pairReady",
939
- "pendingPairCommit",
940
- "source",
941
- "presentationObservedAtMs",
942
- "presentedFrames",
943
- "videoCurrentTime",
944
- "videoReadyState",
945
- "videoPaused",
946
- "videoPlaybackRate",
947
- "errorCode",
948
- "errorMessage",
949
- ]);
950
- }
951
- function compactFrameMetadata(metadata) {
952
- if (Object.keys(metadata).length === 0)
953
- return null;
954
- const lookup = toRecord(metadata.captureLookup);
955
- const item = toRecord(lookup.metadata);
956
- const verifiedTimestamp = verifiedCaptureTimestamp(lookup, item);
957
- return removeUndefined({
958
- analysisEnabled: metadata.analysisEnabled,
959
- workerConfigured: metadata.workerConfigured,
960
- featureStatus: metadata.featureStatus,
961
- lookupStatus: lookup.status,
962
- associationAgeMs: lookup.associationAgeMs,
963
- frameId: item.frameId,
964
- userTimestamp: item.userTimestamp,
965
- userDataByteLength: item.userDataByteLength,
966
- userDataIsTruncated: item.userDataIsTruncated,
967
- timestampEncoding: verifiedTimestamp === null ? undefined : "ascii-decimal-unix-us",
968
- timestampVerified: verifiedTimestamp !== null,
969
- videoCaptureTimestampUs: verifiedTimestamp,
970
- });
971
- }
972
- function verifiedCaptureTimestamp(lookup, metadata) {
973
- if (lookup.status !== "available" ||
974
- metadata.userDataIsTruncated === true ||
975
- typeof lookup.rtpTimestamp !== "number" ||
976
- typeof metadata.frameId !== "number" ||
977
- typeof lookup.associationAgeMs !== "number" ||
978
- lookup.associationAgeMs > FRAME_METADATA_MAX_ASSOCIATION_AGE_MS) {
979
- return null;
980
- }
981
- return decodeAsciiDecimalBase64(typeof metadata.userDataBase64 === "string"
982
- ? metadata.userDataBase64
983
- : null);
984
- }
985
- function compactVideoFrames(videoFrames) {
986
- const buckets = new Map();
987
- for (const frame of videoFrames) {
988
- if (frame.videoCaptureTimestampUs === null &&
989
- frame.videoCaptureToDisplayRelativeMs === null) {
990
- continue;
810
+ if (!installation.draining) {
811
+ installation.draining = true;
812
+ queueMicrotask(() => {
813
+ void this._drainAlerts(installation);
814
+ });
991
815
  }
992
- buckets.set(`${frame.trackId}|${Math.floor(frame.wallClock / TIME_SYNC_BUCKET_MS)}`, frame);
993
816
  }
994
- let verifiedCount = 0;
995
- const logs = [...buckets.values()].map((frame) => {
996
- if (frame.videoCaptureTimestampUs !== null)
997
- verifiedCount += 1;
998
- return {
999
- q: frame.seq,
1000
- t: frame.wallClock,
1001
- o: frame.perfNow,
1002
- y: "frame-presentation",
1003
- e: "presented",
1004
- c: { trackId: frame.trackId, mediaKind: "video" },
1005
- d: removeUndefined({
1006
- presentedFrames: frame.presentedFrames,
1007
- associationAgeMs: frame.metadataAssociationAgeMs,
1008
- timestampEncoding: frame.videoCaptureTimestampUs === null
1009
- ? undefined
1010
- : "ascii-decimal-unix-us",
1011
- timestampVerified: frame.videoCaptureTimestampUs !== null,
1012
- videoCaptureTimestampUs: frame.videoCaptureTimestampUs,
1013
- videoCaptureToDisplayRelativeMs: frame.videoCaptureToDisplayRelativeMs,
1014
- }),
1015
- };
1016
- });
1017
- return { logs, verifiedCount };
1018
- }
1019
- function chunkCompactLogs(logs, detail) {
1020
- const chunks = [];
1021
- let current = [];
1022
- for (const log of logs) {
1023
- if (utf8JsonByteLength([log]) > EVIDENCE_CONTENT_BYTE_LIMIT) {
1024
- detail.oversizeFallbackRecordCount += 1;
1025
- const fallback = {
1026
- q: log.q,
1027
- t: log.t,
1028
- o: log.o,
1029
- y: log.y,
1030
- e: log.e,
1031
- ...(log.c === undefined ? {} : { c: log.c }),
1032
- d: {
1033
- projection: "oversize-fallback",
1034
- projectedByteLength: utf8JsonByteLength(log),
1035
- },
1036
- };
1037
- current = appendCompactLog(chunks, current, fallback);
1038
- continue;
817
+ async _drainAlerts(installation) {
818
+ try {
819
+ while (installation.active && installation.pending.length) {
820
+ const task = installation.pending.shift();
821
+ if (!this._isActive(installation, task.signal))
822
+ continue;
823
+ try {
824
+ await this._reportAlert(installation, task.record, task.signal);
825
+ }
826
+ catch (error) {
827
+ if (this._isActive(installation, task.signal))
828
+ this._warn("Failed to handle A/V evidence", error);
829
+ }
830
+ }
1039
831
  }
1040
- current = appendCompactLog(chunks, current, log);
1041
- }
1042
- if (current.length > 0)
1043
- chunks.push(current);
1044
- const manifest = chunks.map((chunk, index) => ({
1045
- index,
1046
- byteLength: utf8JsonByteLength(chunk),
1047
- recordCount: chunk.length,
1048
- firstSequence: chunk[0]?.q ?? null,
1049
- lastSequence: chunk[chunk.length - 1]?.q ?? null,
1050
- }));
1051
- const finalDetail = {
1052
- ...detail,
1053
- reportedRecordCount: chunks.reduce((count, chunk) => count + chunk.length, 0),
1054
- chunks: manifest,
1055
- };
1056
- const result = {
1057
- logChunkCount: chunks.length,
1058
- logRecordCount: chunks.reduce((count, chunk) => count + chunk.length, 0),
1059
- detail: finalDetail,
1060
- };
1061
- if (chunks[0] !== undefined)
1062
- result.logs = chunks[0];
1063
- for (let index = 1; index < chunks.length; index += 1) {
1064
- const chunk = chunks[index];
1065
- if (chunk !== undefined)
1066
- result[`logs_${index}`] = chunk;
1067
- }
1068
- return result;
1069
- }
1070
- function appendCompactLog(chunks, current, log) {
1071
- const candidate = [...current, log];
1072
- if (current.length > 0 &&
1073
- utf8JsonByteLength(candidate) > EVIDENCE_CONTENT_BYTE_LIMIT) {
1074
- chunks.push(current);
1075
- return [log];
1076
- }
1077
- return candidate;
1078
- }
1079
- function createEvidenceId() {
1080
- return `avse_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
1081
- }
1082
- function collectPreparedCompactLogs(evidence) {
1083
- const logs = [];
1084
- for (const chunk of evidence.detail.chunks ?? []) {
1085
- const value = chunk.index === 0
1086
- ? evidence.logs
1087
- : evidence[`logs_${chunk.index}`];
1088
- if (value !== undefined)
1089
- logs.push(...value);
1090
- }
1091
- return logs;
1092
- }
1093
- function createLogChunkPayloads(evidenceId, alertId, sessionId, logs) {
1094
- const safeLogs = logs.map((log) => fitsInLogChunk(log, evidenceId, alertId, sessionId, logs.length)
1095
- ? log
1096
- : fallbackCompactLog(log));
1097
- const chunks = [];
1098
- let current = [];
1099
- const maximumTotal = Math.max(1, safeLogs.length);
1100
- for (const log of safeLogs) {
1101
- const candidate = [...current, log];
1102
- if (current.length > 0 &&
1103
- !logChunkFits(candidate, evidenceId, alertId, sessionId, safeLogs.length, maximumTotal)) {
1104
- chunks.push(current);
1105
- current = [log];
832
+ finally {
833
+ installation.draining = false;
1106
834
  }
1107
- else {
1108
- current = candidate;
835
+ }
836
+ async _reportAlert(installation, alert, signal) {
837
+ const key = JSON.stringify([
838
+ alert.clientInstanceId,
839
+ alert.monitoringSessionId,
840
+ alert.avsyncSessionId,
841
+ alert.correlation.alertId,
842
+ ]);
843
+ const phase = alert.data.phase;
844
+ const alertId = alert.correlation.alertId;
845
+ const state = installation.alertReportStates.get(key) ?? {};
846
+ if (phase === "recovered") {
847
+ const payload = {
848
+ ...operationalSource(alert),
849
+ kind: "liveavatar.avsync.recovery",
850
+ schemaVersion: 4,
851
+ alertId,
852
+ recoveredAtWallClockMs: alert.occurredAtMs,
853
+ };
854
+ await this._report(installation, signal, { category: "avsync", grade: "Recovered", content: payload }, "[LiveAvatar A/V Sync] alert recovered");
855
+ installation.alertReportStates.delete(key);
856
+ return;
1109
857
  }
1110
- if (!logChunkFits(current, evidenceId, alertId, sessionId, safeLogs.length, maximumTotal)) {
1111
- throw new Error("A/V Sync log fallback exceeds the platform content limit");
858
+ if (!installation.diagnostics)
859
+ return;
860
+ installation.alertReportStates.set(key, state);
861
+ // Bound inactive alert bookkeeping as well as queued work.
862
+ if (installation.alertReportStates.size > MAX_PENDING_ALERTS)
863
+ installation.alertReportStates.delete(installation.alertReportStates.keys().next().value);
864
+ const now = Date.now();
865
+ const previous = state.lastSuccessfulToWallClockMs;
866
+ const range = phase === "raised" || previous === undefined
867
+ ? { kind: "recent", durationMs: 30000 }
868
+ : {
869
+ kind: "wall-clock",
870
+ fromMs: Math.max(now - 30000, Math.min(previous + 1, now)),
871
+ toMs: now,
872
+ };
873
+ const active = () => this._isActive(installation, signal);
874
+ const evidence = await collectEvidence(installation.diagnostics, alert, range, active);
875
+ if (!evidence || !active())
876
+ return;
877
+ const evidenceId = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
878
+ ? crypto.randomUUID()
879
+ : `avse_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
880
+ const { summary, chunks } = createEvidencePayloads(evidenceId, evidence);
881
+ if (!(await this._report(installation, signal, { category: "avsync", grade: "Warning", content: summary }, `[LiveAvatar A/V Sync] ${String(alert.data?.finding)}`)))
882
+ return;
883
+ for (const chunk of chunks) {
884
+ if (!(await this._report(installation, signal, { category: "avsync", grade: "Info", content: chunk }, `[LiveAvatar A/V Sync] evidence chunk ${chunk.chunk.index + 1}/${chunk.chunk.total}`)))
885
+ return;
1112
886
  }
887
+ // A successful local handoff is not a server delivery acknowledgment.
888
+ if (evidence.completeness.complete)
889
+ state.lastSuccessfulToWallClockMs =
890
+ evidence.pages[0]?.page.requestedToWallClockMs;
1113
891
  }
1114
- if (current.length > 0)
1115
- chunks.push(current);
1116
- return chunks.map((chunk, index) => createLogChunkPayload(evidenceId, alertId, sessionId, chunk, index, chunks.length));
1117
- }
1118
- function fitsInLogChunk(log, evidenceId, alertId, sessionId, total) {
1119
- return logChunkFits([log], evidenceId, alertId, sessionId, total, total);
1120
892
  }
1121
- function logChunkFits(logs, evidenceId, alertId, sessionId, index, total) {
1122
- return (utf8JsonByteLength(createLogChunkPayload(evidenceId, alertId, sessionId, logs, index, total)) <= EVIDENCE_CONTENT_BYTE_LIMIT);
1123
- }
1124
- function fallbackCompactLog(log) {
1125
- return {
1126
- q: log.q,
1127
- t: log.t,
1128
- o: log.o,
1129
- y: log.y,
1130
- e: log.e,
1131
- d: {
1132
- projection: "oversize-fallback",
1133
- projectedByteLength: utf8JsonByteLength(log),
1134
- },
1135
- };
1136
- }
1137
- function createLogChunkPayload(evidenceId, alertId, sessionId, logs, index, total) {
1138
- return {
1139
- schemaVersion: 1,
1140
- kind: "liveavatar.avsync.alert-evidence",
1141
- sdkVersion: liveavatarJsSdk.VERSION,
1142
- recordType: "log-chunk",
1143
- evidenceId,
1144
- alertId,
1145
- sessionId,
1146
- chunk: {
1147
- index,
1148
- total,
1149
- byteLength: utf8JsonByteLength(logs),
1150
- recordCount: logs.length,
1151
- firstSequence: logs[0]?.q ?? null,
1152
- lastSequence: logs[logs.length - 1]?.q ?? null,
1153
- logs,
1154
- },
1155
- };
1156
- }
1157
- function createSummaryPayload(evidenceId, alert, evidence, logChunkCount) {
1158
- const summaryEvidence = withoutPreparedLogs(evidence, logChunkCount);
1159
- const payload = {
1160
- schemaVersion: 1,
1161
- kind: "liveavatar.avsync.alert-evidence",
1162
- sdkVersion: liveavatarJsSdk.VERSION,
1163
- recordType: "summary",
1164
- evidenceId,
1165
- alert,
1166
- evidence: summaryEvidence,
1167
- };
1168
- if (utf8JsonByteLength(payload) <= EVIDENCE_CONTENT_BYTE_LIMIT)
1169
- return payload;
1170
- const compactPayload = {
1171
- ...payload,
1172
- summaryTruncated: true,
1173
- alert: compactAlertForSummary(alert),
1174
- evidence: {
1175
- ...summaryEvidence,
1176
- retention: null,
1177
- triage: {
1178
- trigger: summaryEvidence.triage?.trigger ?? {
1179
- finding: alert.finding,
1180
- status: alert.status,
1181
- confidence: alert.confidence,
1182
- capturedAtMs: alert.capturedAtMs,
1183
- },
1184
- evaluation: null,
1185
- layers: null,
1186
- participants: [],
1187
- limitations: ["summary-truncated"],
1188
- },
1189
- detail: {
1190
- projectionVersion: summaryEvidence.detail.projectionVersion,
1191
- sourceRecordCount: summaryEvidence.detail.sourceRecordCount,
1192
- reportedRecordCount: summaryEvidence.logRecordCount,
1193
- timeSyncInputCount: 0,
1194
- timeSyncReportedCount: 0,
1195
- framePresentationReportedCount: 0,
1196
- verifiedMetadataTimestampCount: 0,
1197
- omittedSetupLifecycleCount: 0,
1198
- oversizeFallbackRecordCount: summaryEvidence.detail.oversizeFallbackRecordCount,
1199
- contentByteLimit: EVIDENCE_CONTENT_BYTE_LIMIT,
1200
- },
1201
- },
1202
- };
1203
- if (utf8JsonByteLength(compactPayload) <= EVIDENCE_CONTENT_BYTE_LIMIT)
1204
- return compactPayload;
1205
- throw new Error("A/V Sync summary exceeds the platform content limit");
1206
- }
1207
- function compactAlertForSummary(alert) {
1208
- return {
1209
- ...alert,
1210
- participantIds: alert.participantIds.slice(0, 32),
1211
- message: truncateUtf8String(alert.message, 1024),
1212
- };
1213
- }
1214
- function truncateUtf8String(value, byteLimit) {
1215
- if (new TextEncoder().encode(value).byteLength <= byteLimit)
1216
- return value;
1217
- let end = value.length;
1218
- while (end > 0) {
1219
- const candidate = `${value.slice(0, end)}…`;
1220
- if (new TextEncoder().encode(candidate).byteLength <= byteLimit)
1221
- return candidate;
1222
- end -= 1;
1223
- }
1224
- return "";
1225
- }
1226
- function withoutPreparedLogs(evidence, logChunkCount) {
1227
- const { logs: _logs, detail, ...rest } = evidence;
1228
- const { chunks: _chunks, ...summaryDetail } = detail;
1229
- const summary = Object.fromEntries(Object.entries(rest).filter(([key]) => !/^logs_\d+$/.test(key)));
1230
- return {
1231
- ...summary,
1232
- logChunkCount,
1233
- detail: summaryDetail,
1234
- };
1235
- }
1236
- function decodeAsciiDecimalBase64(value) {
1237
- if (value === null)
1238
- return null;
1239
- try {
1240
- const decoded = atob(value);
1241
- if (!/^\d{16}$/.test(decoded))
1242
- return null;
1243
- const parsed = Number(decoded);
1244
- return Number.isSafeInteger(parsed) ? decoded : null;
1245
- }
1246
- catch {
1247
- return null;
1248
- }
1249
- }
1250
- function utf8JsonByteLength(value) {
1251
- return new TextEncoder().encode(JSON.stringify(value)).byteLength;
893
+ function createSkyWalkingPlugin(config = {}) {
894
+ return new SkyWalkingPlugin(config);
1252
895
  }
1253
- function toRecord(value) {
896
+ function object(value) {
1254
897
  return value !== null && typeof value === "object" && !Array.isArray(value)
1255
898
  ? value
1256
899
  : {};
1257
900
  }
1258
- function pick(source, keys) {
1259
- const result = {};
1260
- for (const key of keys) {
1261
- if (source[key] !== undefined && source[key] !== null)
1262
- result[key] = source[key];
1263
- }
1264
- return result;
1265
- }
1266
- function removeUndefined(value) {
1267
- return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
1268
- }
1269
- function numberOr(value, fallback) {
1270
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
1271
- }
1272
- function stringOr(value, fallback) {
1273
- return typeof value === "string" ? value : fallback;
1274
- }
1275
- function compareSourceLogs(left, right) {
1276
- return left.sequence - right.sequence;
1277
- }
1278
- function compareCompactLogs(left, right) {
1279
- return left.q - right.q || left.o - right.o;
1280
- }
1281
- function toJsonSafeAlert(alert) {
1282
- return {
1283
- ...alert,
1284
- sessionId: alert.sessionId ?? null,
1285
- participantIds: [...alert.participantIds],
1286
- features: { ...alert.features },
1287
- };
1288
- }
1289
- /**
1290
- * Strictly projects the published first-frame Operational Log. The SDK record
1291
- * has additional identifiers and arbitrary attributes; none of those can
1292
- * reach SkyWalking through this path.
1293
- */
1294
901
  function toSkyWalkingFirstFrameLogPayload(record) {
1295
- const correlation = toRecord(record.correlation);
1296
- const attributes = toRecord(record.attributes);
902
+ const correlation = object(record.correlation);
903
+ const attributes = object(record.data);
1297
904
  const attemptId = correlation.attemptId;
1298
905
  const outcome = attributes.outcome;
1299
906
  if (!isNonNegativeNumber(record.occurredAtMs) ||
@@ -1301,7 +908,7 @@
1301
908
  !isFirstFrameOutcome(outcome)) {
1302
909
  return undefined;
1303
910
  }
1304
- const sourceNodes = toRecord(attributes.nodes);
911
+ const sourceNodes = object(attributes.nodes);
1305
912
  const nodes = {};
1306
913
  copyNonNegativeNumber(sourceNodes, "configReadyMs", nodes);
1307
914
  copyNonNegativeNumber(sourceNodes, "rtcConnectedMs", nodes);
@@ -1309,10 +916,9 @@
1309
916
  copyNonNegativeNumber(sourceNodes, "videoMetadataMs", nodes);
1310
917
  copyNonNegativeNumber(sourceNodes, "firstFrameMs", nodes);
1311
918
  return {
1312
- schemaVersion: 1,
919
+ schemaVersion: 4,
1313
920
  kind: "liveavatar.performance.first-frame",
1314
- sdkVersion: liveavatarJsSdk.VERSION,
1315
- occurredAtMs: record.occurredAtMs,
921
+ ...operationalSource(record),
1316
922
  attemptId,
1317
923
  outcome,
1318
924
  ...(typeof attributes.renderMode === "string"
@@ -1340,18 +946,6 @@
1340
946
  function isNonNegativeNumber(value) {
1341
947
  return typeof value === "number" && Number.isFinite(value) && value >= 0;
1342
948
  }
1343
- function stringifyJson(value) {
1344
- const serialized = JSON.stringify(value);
1345
- if (serialized === undefined) {
1346
- throw new Error("LiveAvatar SkyWalking payload serialization failed");
1347
- }
1348
- return serialized;
1349
- }
1350
- /**
1351
- * Loads the bundled browser client when needed and registers it exactly once.
1352
- * An application-provided `window.ClientMonitor` is treated as already
1353
- * registered and is never overwritten or registered again.
1354
- */
1355
949
  function registerSkyWalking(config = {}) {
1356
950
  if (typeof window === "undefined") {
1357
951
  warnOnce("register-unavailable", "[LiveAvatar SkyWalking plugin] SkyWalking registration requires a browser window");
@@ -1417,12 +1011,18 @@
1417
1011
  function normalizeReportingConfig(config) {
1418
1012
  return {
1419
1013
  sdkError: config?.sdkError ?? true,
1014
+ timeline: config?.timeline ?? true,
1420
1015
  firstFrame: config?.firstFrame ?? true,
1421
1016
  avSync: config?.avSync ?? true,
1017
+ playbackStatus: config?.playbackStatus ?? true,
1422
1018
  };
1423
1019
  }
1424
1020
  function hasEnabledReporting(config) {
1425
- return config.sdkError || config.firstFrame || config.avSync;
1021
+ return (config.sdkError ||
1022
+ config.firstFrame ||
1023
+ config.avSync ||
1024
+ config.timeline ||
1025
+ config.playbackStatus);
1426
1026
  }
1427
1027
  function normalizeSkyWalkingConfig(config) {
1428
1028
  return {
@@ -1449,7 +1049,7 @@
1449
1049
  extraMsg: config.extraMsg,
1450
1050
  hooks: { ...config.hooks },
1451
1051
  pagePath: config.pagePath ?? "",
1452
- serviceVersion: config.serviceVersion ?? "",
1052
+ serviceVersion: liveavatarJsSdk.VERSION,
1453
1053
  pageKey: config.pageKey ?? "",
1454
1054
  group: config.group ?? "unknown",
1455
1055
  subGroup: config.subGroup ?? "unknown",