@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.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import { SDK_AVSYNC_DIAGNOSTICS_V1, SDK_AVSYNC_ALERTS_V1, SDK_OPERATIONAL_LOGS_V1, VERSION } from '@sanseng/liveavatar-js-sdk';
1
+ import { SDK_AVSYNC_DIAGNOSTICS_V1, SDK_AVSYNC_DIAGNOSTICS_V2, SDK_OPERATIONAL_LOGS_V2, VERSION } from '@sanseng/liveavatar-js-sdk';
2
2
 
3
3
  /**
4
4
  * Build-time placeholder for the bundled SkyWalking browser client.
@@ -16,35 +16,474 @@ SkyWalking js-sdk
16
16
  !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");}();
17
17
  }
18
18
 
19
- /** Stable identifier used by the LiveAvatar SDK plugin host. */
19
+ const EMPTY = {};
20
+ const PHASE = { phase: "string" };
21
+ const CONFIG = { source: "string", willRetry: "boolean" };
22
+ const TEXT_LENGTH = { textLength: "number" };
23
+ // Public v2 event/data allowlist. Correlation and operation use their own
24
+ // common public contracts; a module alone never makes an event reportable.
25
+ const TIMELINE_FIELDS = {
26
+ "operation.started": EMPTY,
27
+ "operation.finished": EMPTY,
28
+ "protocol.received": { protocolEvent: "string" },
29
+ "protocol.failed": { protocolEvent: "string" },
30
+ "client.created": EMPTY,
31
+ "client.disposed": EMPTY,
32
+ "monitoring.session.started": { startReason: "string" },
33
+ "monitoring.session.ended": { endReason: "string", cleanupOutcome: "string" },
34
+ "config.fetch.started": CONFIG,
35
+ "config.fetch.completed": CONFIG,
36
+ "config.fetch.failed": CONFIG,
37
+ "connect.started": PHASE,
38
+ "connect.completed": PHASE,
39
+ "connect.failed": PHASE,
40
+ "disconnect.started": PHASE,
41
+ "disconnect.completed": PHASE,
42
+ "disconnect.failed": PHASE,
43
+ "reconnect.started": PHASE,
44
+ "reconnect.completed": PHASE,
45
+ "reconnect.failed": PHASE,
46
+ "livekit.connected": EMPTY,
47
+ "livekit.disconnected": { hasReason: "boolean" },
48
+ "http.connected": EMPTY,
49
+ "http.disconnected": { hasReason: "boolean" },
50
+ "rtc.state-changed": {
51
+ phase: "string",
52
+ roomExists: "boolean",
53
+ roomState: "string",
54
+ hasConnected: "boolean",
55
+ },
56
+ "connection.quality-changed": { quality: "string", isLocal: "boolean" },
57
+ "video.track-added": EMPTY,
58
+ "video.track-removed": EMPTY,
59
+ "audio.track-added": EMPTY,
60
+ "audio.track-removed": EMPTY,
61
+ "audio.capture-started": EMPTY,
62
+ "audio.capture-stopped": EMPTY,
63
+ "camera.started": EMPTY,
64
+ "camera.stopped": EMPTY,
65
+ "question.sent": TEXT_LENGTH,
66
+ "answer.waiting": EMPTY,
67
+ "answer.first-chunk": { deltaLength: "number", textLength: "number" },
68
+ "answer.completed": TEXT_LENGTH,
69
+ "asr.final": TEXT_LENGTH,
70
+ "server.message": { textLength: "number", type: "string" },
71
+ "avsync.session.started": { startedAtMs: "number" },
72
+ "avsync.session.ended": { endedAtMs: "number", reason: "string" },
73
+ };
74
+ function sourceCorrelation(source) {
75
+ return project(source, {
76
+ clientInstanceId: "string",
77
+ monitoringSessionId: "string",
78
+ serverSessionId: "string",
79
+ avsyncSessionId: "string",
80
+ });
81
+ }
82
+ function operationalSource(record) {
83
+ return {
84
+ sourceSchema: "sdk.log",
85
+ sourceSchemaVersion: 2,
86
+ ...sourceCorrelation(record),
87
+ clientInstanceId: record.clientInstanceId,
88
+ eventId: record.eventId,
89
+ streamId: record.streamId,
90
+ sequence: record.sequence,
91
+ occurredAtMs: record.occurredAtMs,
92
+ ...project(record, { observedAtMs: "number", clockId: "string" }),
93
+ };
94
+ }
95
+ /** Copy only the public v2 envelope and documented diagnostic fields. */
96
+ function projectRecord(record) {
97
+ const correlation = project(record.correlation, {
98
+ questionId: "string",
99
+ attemptId: "number",
100
+ configRoundId: "number",
101
+ attempt: "number",
102
+ alertId: "string",
103
+ participantId: "string",
104
+ trackId: "string",
105
+ mediaKind: "string",
106
+ pairId: "string",
107
+ trackKey: "string",
108
+ streamId: "string",
109
+ playbackTargetId: "string",
110
+ captureId: "string",
111
+ relatedOperationId: "string",
112
+ }, true);
113
+ const snapshot = project(record.snapshot, {
114
+ sdkState: "string",
115
+ httpConnected: "boolean",
116
+ rtcConnected: "boolean",
117
+ hasVideoTrack: "boolean",
118
+ roomExists: "boolean",
119
+ roomState: "string",
120
+ hasConnected: "boolean",
121
+ });
122
+ const disconnect = project(object$1(record.snapshot).lastDisconnect, {
123
+ occurredAtMs: "number",
124
+ reasonCode: "number",
125
+ reasonName: "string",
126
+ clientInitiated: "boolean",
127
+ });
128
+ if (Object.keys(disconnect).length)
129
+ snapshot.lastDisconnect = disconnect;
130
+ const error = record.error && {
131
+ failureId: record.error.failureId,
132
+ code: record.error.code,
133
+ reasonCategory: record.error.reasonCategory,
134
+ ...project(record.error, { reason: "string" }),
135
+ ...(record.error.evidence
136
+ ? {
137
+ evidence: {
138
+ ...project(record.error.evidence, {
139
+ name: "string",
140
+ httpStatus: "number",
141
+ connectionErrorReason: "number",
142
+ connectionErrorReasonName: "string",
143
+ }),
144
+ ...(["string", "number"].includes(typeof record.error.evidence.backendCode)
145
+ ? { backendCode: record.error.evidence.backendCode }
146
+ : {}),
147
+ },
148
+ }
149
+ : {}),
150
+ };
151
+ return {
152
+ schema: "sdk.log",
153
+ schemaVersion: 2,
154
+ eventId: record.eventId,
155
+ streamId: record.streamId,
156
+ sequence: record.sequence,
157
+ occurredAtMs: record.occurredAtMs,
158
+ ...project(record, { observedAtMs: "number", clockId: "string" }),
159
+ ...sourceCorrelation(record),
160
+ clientInstanceId: record.clientInstanceId,
161
+ level: record.level,
162
+ module: record.module,
163
+ event: record.event,
164
+ trigger: { kind: record.trigger.kind, entry: record.trigger.entry },
165
+ ...(record.operation
166
+ ? {
167
+ operation: {
168
+ operationId: record.operation.operationId,
169
+ rootOperationId: record.operation.rootOperationId,
170
+ name: record.operation.name,
171
+ phase: record.operation.phase,
172
+ ...project(record.operation, {
173
+ parentOperationId: "string",
174
+ relatedOperationId: "string",
175
+ }),
176
+ ...(record.operation.outcome
177
+ ? { outcome: record.operation.outcome }
178
+ : {}),
179
+ },
180
+ }
181
+ : {}),
182
+ ...(record.failureRef
183
+ ? {
184
+ failureRef: {
185
+ failureId: record.failureRef.failureId,
186
+ eventId: record.failureRef.eventId,
187
+ },
188
+ }
189
+ : {}),
190
+ ...(error ? { error } : {}),
191
+ ...(Object.keys(correlation).length ? { correlation } : {}),
192
+ ...(Object.keys(snapshot).length ? { snapshot } : {}),
193
+ ...(record.data ? { data: eventData(record) } : {}),
194
+ };
195
+ }
196
+ function eventData(record) {
197
+ const fields = Object.prototype.hasOwnProperty.call(TIMELINE_FIELDS, record.event)
198
+ ? TIMELINE_FIELDS[record.event]
199
+ : EMPTY;
200
+ const data = project(record.data, fields);
201
+ if (record.event === "rtc.state-changed") {
202
+ const disconnect = project(object$1(record.data).lastDisconnect, {
203
+ occurredAtMs: "number",
204
+ reasonCode: "number",
205
+ reasonName: "string",
206
+ clientInitiated: "boolean",
207
+ });
208
+ if (Object.keys(disconnect).length)
209
+ data.lastDisconnect = disconnect;
210
+ }
211
+ if (record.event === "avsync.alert")
212
+ return project(record.data, {
213
+ phase: "string",
214
+ finding: "string",
215
+ confidence: "string",
216
+ status: "string",
217
+ capturedAtMs: "number",
218
+ });
219
+ if (record.event === "performance.first-frame") {
220
+ Object.assign(data, project(record.data, {
221
+ outcome: "string",
222
+ renderMode: "string",
223
+ timeoutAfterRtcMs: "number",
224
+ }));
225
+ data.nodes = project(object$1(record.data).nodes, {
226
+ configReadyMs: "number",
227
+ rtcConnectedMs: "number",
228
+ videoTrackAddedMs: "number",
229
+ videoMetadataMs: "number",
230
+ firstFrameMs: "number",
231
+ });
232
+ }
233
+ return data;
234
+ }
235
+ function toTimeline(record) {
236
+ if (!Object.prototype.hasOwnProperty.call(TIMELINE_FIELDS, record.event))
237
+ return undefined;
238
+ const copy = projectRecord(record);
239
+ return {
240
+ kind: "liveavatar.session.timeline",
241
+ schemaVersion: 4,
242
+ ...operationalSource(copy),
243
+ level: copy.level,
244
+ module: copy.module,
245
+ event: copy.event,
246
+ trigger: copy.trigger,
247
+ ...(copy.operation ? { operation: copy.operation } : {}),
248
+ ...(copy.failureRef ? { failureRef: copy.failureRef } : {}),
249
+ ...(copy.snapshot ? { snapshot: copy.snapshot } : {}),
250
+ ...(copy.correlation ? { correlation: copy.correlation } : {}),
251
+ ...(copy.data && Object.keys(copy.data).length ? { data: copy.data } : {}),
252
+ };
253
+ }
254
+ function object$1(value) {
255
+ return value !== null && typeof value === "object" && !Array.isArray(value)
256
+ ? value
257
+ : {};
258
+ }
259
+ function project(value, fields, nullable = false) {
260
+ const input = object$1(value);
261
+ const result = {};
262
+ for (const [key, type] of Object.entries(fields)) {
263
+ const entry = input[key];
264
+ if (entry === null && nullable)
265
+ result[key] = null;
266
+ else if (type === "string" && typeof entry === "string")
267
+ result[key] = entry;
268
+ else if (type === "boolean" && typeof entry === "boolean")
269
+ result[key] = entry;
270
+ else if (type === "number" &&
271
+ typeof entry === "number" &&
272
+ Number.isFinite(entry))
273
+ result[key] = entry;
274
+ }
275
+ return result;
276
+ }
277
+
278
+ /** Complete content, including its envelope and JSON escapes, must fit this limit. */
279
+ const EVIDENCE_CONTENT_BYTE_LIMIT = 28 * 1024;
280
+ function utf8ByteLength(value) {
281
+ return new TextEncoder().encode(value).byteLength;
282
+ }
283
+ /** Content is level one; containers at level three become lossless JSON text. */
284
+ function serializeEvidenceContent(value, depth = 1) {
285
+ if (value === null || typeof value !== "object")
286
+ return value;
287
+ if (depth >= 3)
288
+ return JSON.stringify(value);
289
+ if (Array.isArray(value))
290
+ return value.map((entry) => serializeEvidenceContent(entry, depth + 1));
291
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
292
+ key,
293
+ serializeEvidenceContent(entry, depth + 1),
294
+ ]));
295
+ }
296
+ function assertContentFits(content) {
297
+ if (utf8ByteLength(JSON.stringify(content)) > EVIDENCE_CONTENT_BYTE_LIMIT)
298
+ throw new Error("A/V Sync content exceeds the 28 KiB limit");
299
+ }
300
+ function pageReasons(page) {
301
+ const reasons = [];
302
+ if (!page.enabled)
303
+ reasons.push("diagnostics-disabled");
304
+ if (page.page.truncated)
305
+ reasons.push("source-truncated");
306
+ if (!page.retention.storageAvailable)
307
+ reasons.push("storage-unavailable");
308
+ if (page.retention.storageWriteFailed)
309
+ reasons.push("storage-write-failed");
310
+ if (page.retention.droppedLogCount > 0 ||
311
+ page.retention.droppedSegmentCount > 0)
312
+ reasons.push("retention-dropped");
313
+ if (page.page.availableFromWallClockMs === null ||
314
+ page.page.availableToWallClockMs === null)
315
+ reasons.push("window-unavailable");
316
+ else if (page.page.availableFromWallClockMs > page.page.requestedFromWallClockMs)
317
+ reasons.push("window-start-uncovered");
318
+ return reasons;
319
+ }
320
+ function ownsPage(alert, page) {
321
+ // Missing optional SDK identities are not filled from the latest session.
322
+ return (page.avsyncSessionId === alert.avsyncSessionId &&
323
+ (page.clientInstanceId === undefined ||
324
+ page.clientInstanceId === alert.clientInstanceId) &&
325
+ (page.monitoringSessionId === undefined ||
326
+ page.monitoringSessionId === alert.monitoringSessionId) &&
327
+ page.records.every((record) => record.clientInstanceId === alert.clientInstanceId &&
328
+ record.avsyncSessionId === alert.avsyncSessionId &&
329
+ (record.monitoringSessionId === undefined ||
330
+ record.monitoringSessionId === alert.monitoringSessionId)));
331
+ }
332
+ async function collectEvidence(diagnostics, alert, range, isActive) {
333
+ const pages = [];
334
+ const reasons = new Set();
335
+ const cursors = new Set();
336
+ let cursor;
337
+ let queryComplete = false;
338
+ const retrievedAtWallClockMs = Date.now();
339
+ while (isActive()) {
340
+ let page;
341
+ try {
342
+ const result = await diagnostics.getAvSyncLogEvidence(cursor === undefined
343
+ ? { range, pageSize: 1000, includeSummary: true }
344
+ : { cursor, pageSize: 1000, includeSummary: false });
345
+ if (!isActive())
346
+ return undefined;
347
+ // Own the snapshot even when the transport implementation reuses objects.
348
+ page = JSON.parse(JSON.stringify(result));
349
+ }
350
+ catch {
351
+ if (!isActive())
352
+ return undefined;
353
+ reasons.add(pages.length ? "continuation-query-failed" : "initial-query-failed");
354
+ break;
355
+ }
356
+ pages.push(page);
357
+ for (const reason of pageReasons(page))
358
+ reasons.add(reason);
359
+ if (!ownsPage(alert, page)) {
360
+ reasons.add("session-mismatch");
361
+ break;
362
+ }
363
+ const first = pages[0];
364
+ if (page.page.requestedFromWallClockMs !==
365
+ first.page.requestedFromWallClockMs ||
366
+ page.page.requestedToWallClockMs !== first.page.requestedToWallClockMs) {
367
+ reasons.add("window-mismatch");
368
+ break;
369
+ }
370
+ if (!page.page.hasMore) {
371
+ queryComplete = true;
372
+ break;
373
+ }
374
+ const next = page.page.nextCursor;
375
+ if (!next || cursors.has(next)) {
376
+ reasons.add("cursor-did-not-advance");
377
+ break;
378
+ }
379
+ cursors.add(next);
380
+ cursor = next;
381
+ }
382
+ if (!isActive())
383
+ return undefined;
384
+ if (pages.reduce((count, page) => count + page.records.length, 0) === 0)
385
+ reasons.add("empty-window");
386
+ return {
387
+ schema: "liveavatar.avsync.evidence",
388
+ schemaVersion: 4,
389
+ alert,
390
+ query: { range, retrievedAtWallClockMs, complete: queryComplete },
391
+ pages,
392
+ completeness: {
393
+ complete: queryComplete && reasons.size === 0,
394
+ reasons: [...reasons],
395
+ },
396
+ };
397
+ }
398
+ /** Lossless framing of the whole evidence document, including oversized metadata. */
399
+ function createEvidencePayloads(evidenceId, evidence) {
400
+ const source = operationalSource(evidence.alert);
401
+ const alertId = evidence.alert.correlation?.alertId;
402
+ if (!alertId)
403
+ throw new Error("A/V alert is missing its source alertId");
404
+ const document = JSON.stringify(evidence);
405
+ const base = {
406
+ ...source,
407
+ kind: "liveavatar.avsync.alert-evidence",
408
+ schemaVersion: 4,
409
+ evidenceId,
410
+ alertId,
411
+ };
412
+ const chunkPayload = (data, index, total) => ({
413
+ ...base,
414
+ recordType: "log-chunk",
415
+ chunk: { index, total, byteLength: utf8ByteLength(data), data },
416
+ });
417
+ // A fragment contains at least one UTF-16 code unit, so document.length bounds
418
+ // both index and total. Use that conservative envelope during packing.
419
+ const maximumTotal = Math.max(1, document.length);
420
+ const parts = [];
421
+ let start = 0;
422
+ while (start < document.length) {
423
+ let low = start;
424
+ let high = Math.min(document.length, start + EVIDENCE_CONTENT_BYTE_LIMIT);
425
+ while (low < high) {
426
+ const end = Math.ceil((low + high) / 2);
427
+ if (utf8ByteLength(JSON.stringify(chunkPayload(document.slice(start, end), maximumTotal, maximumTotal))) <= EVIDENCE_CONTENT_BYTE_LIMIT)
428
+ low = end;
429
+ else
430
+ high = end - 1;
431
+ }
432
+ // Move left if the fitted UTF-16 slice cuts a surrogate pair.
433
+ if (low < document.length &&
434
+ low > start &&
435
+ /[\uD800-\uDBFF]/.test(document[low - 1]) &&
436
+ /[\uDC00-\uDFFF]/.test(document[low]))
437
+ low--;
438
+ if (low === start)
439
+ throw new Error("A/V evidence envelope leaves no room for a fragment");
440
+ parts.push(document.slice(start, low));
441
+ start = low;
442
+ }
443
+ const chunks = parts.map((data, index) => chunkPayload(data, index, parts.length));
444
+ const summary = serializeEvidenceContent({
445
+ ...base,
446
+ recordType: "summary",
447
+ evidence: {
448
+ complete: evidence.completeness.complete,
449
+ reasons: evidence.completeness.reasons,
450
+ logChunkCount: chunks.length,
451
+ logRecordCount: evidence.pages.reduce((count, page) => count + page.records.length, 0),
452
+ byteLength: utf8ByteLength(document),
453
+ },
454
+ });
455
+ assertContentFits(summary);
456
+ for (const chunk of chunks)
457
+ assertContentFits(chunk);
458
+ return { summary, chunks };
459
+ }
460
+
20
461
  const SKYWALKING_PLUGIN_ID = "liveavatar.skywalking";
21
- const AVSYNC_ALERTS_CONTRIBUTION_ID = "liveavatar.skywalking.avsync-alerts";
22
462
  const OPERATIONAL_LOGS_CONTRIBUTION_ID = "liveavatar.skywalking.operational-logs";
23
- const ALERT_LOG_DURATION_MS = 30000;
24
- const TELEMETRY_PAGE_SIZE = 1000;
25
- /**
26
- * The platform limits the complete top-level `content` value of one error
27
- * record to 32 KiB. Keep a margin for platform serialization differences.
28
- */
29
- const EVIDENCE_CONTENT_BYTE_LIMIT = 28 * 1024;
30
- const FRAME_METADATA_MAX_ASSOCIATION_AGE_MS = 150;
31
- const TIME_SYNC_BUCKET_MS = 1000;
32
463
  const SKYWALKING_SERVICE = "yy-tx::liveavatar-js-sdk";
33
464
  const DOMESTIC_COLLECTOR = "https://apm.hexin.cn/skywalking-web";
34
- const OVERSEAS_COLLECTOR = "https://apm.ainvest.com/skywalking-web";
465
+ const OVERSEAS_COLLECTOR = "https://ai.dreamfaceapp.com/skywalking-web";
35
466
  const REGISTRATION_STATE_KEY = Symbol.for("liveavatar.skywalking.registration-state");
36
- /**
37
- * Reports LiveAvatar A/V-sync incident lifecycle events through the bundled or
38
- * externally provided SkyWalking client.
39
- */
467
+ const MAX_PENDING_ALERTS = 1000;
468
+ const DEFAULT_PLAYBACK_STATUS_INTERVAL_MS = 5000;
469
+ /** Consumes SDK facts and samples playback through the public Plugin API v1. */
40
470
  class SkyWalkingPlugin {
41
471
  constructor(config = {}) {
42
472
  this.id = SKYWALKING_PLUGIN_ID;
43
- /** SDK Plugin API v1 is the registrar-based public plugin contract. */
44
473
  this.apiVersion = 1;
45
- this._nextInstallationGeneration = 0;
474
+ this.terminalObserverDelivery = "sync-before-dispose";
46
475
  this._skyWalkingConfig = { ...config };
47
476
  this._reporting = normalizeReportingConfig(config.reporting);
477
+ const interval = config.playbackStatusIntervalMs;
478
+ this._playbackStatusIntervalMs =
479
+ typeof interval === "number" &&
480
+ Number.isInteger(interval) &&
481
+ interval > 0 &&
482
+ interval <= 2147483647
483
+ ? interval
484
+ : DEFAULT_PLAYBACK_STATUS_INTERVAL_MS;
485
+ if (interval !== undefined && interval !== this._playbackStatusIntervalMs)
486
+ this._warn("Invalid playbackStatusIntervalMs; using 5000 ms");
48
487
  }
49
488
  setup(registrar) {
50
489
  this._deactivateInstallation();
@@ -52,26 +491,45 @@ class SkyWalkingPlugin {
52
491
  return;
53
492
  registerSkyWalking(this._skyWalkingConfig);
54
493
  const installation = {
55
- generation: ++this._nextInstallationGeneration,
494
+ active: true,
56
495
  abortController: new AbortController(),
496
+ retiredPlaybackOwners: new Set(),
497
+ playbackSequences: new Map(),
57
498
  alertReportStates: new Map(),
58
- active: true,
499
+ pending: [],
500
+ draining: false,
59
501
  };
60
502
  this._installation = installation;
61
503
  try {
62
- if (this._reporting.avSync) {
63
- installation.diagnostics = registrar.consume(SDK_AVSYNC_DIAGNOSTICS_V1);
64
- registrar.observe(SDK_AVSYNC_ALERTS_V1, {
65
- id: AVSYNC_ALERTS_CONTRIBUTION_ID,
66
- handler: (alert, context) => this._handleAlertNotification(installation, alert, context.signal),
67
- });
68
- }
69
- if (this._reporting.sdkError || this._reporting.firstFrame) {
70
- registrar.observe(SDK_OPERATIONAL_LOGS_V1, {
71
- id: OPERATIONAL_LOGS_CONTRIBUTION_ID,
72
- handler: (record, context) => this._handleOperationalLog(installation, record, context.signal),
73
- });
504
+ if (this._reporting.playbackStatus) {
505
+ try {
506
+ const service = registrar.consume(SDK_AVSYNC_DIAGNOSTICS_V1);
507
+ if (typeof service?.getPlaybackStatus !== "function")
508
+ throw new Error("getPlaybackStatus is unavailable");
509
+ installation.playbackService = service;
510
+ }
511
+ catch (error) {
512
+ this._warn("Playback status service unavailable; sampling disabled", error);
513
+ }
74
514
  }
515
+ if (this._reporting.avSync)
516
+ installation.diagnostics = registrar.consume(SDK_AVSYNC_DIAGNOSTICS_V2);
517
+ registrar.observe(SDK_OPERATIONAL_LOGS_V2, {
518
+ id: OPERATIONAL_LOGS_CONTRIBUTION_ID,
519
+ handler: (record, context) => {
520
+ if (!this._isActive(installation, context.signal))
521
+ return;
522
+ this._handlePlaybackLifecycle(installation, record);
523
+ if (record.event === "avsync.alert") {
524
+ if (this._reporting.avSync)
525
+ this._queueAlert(installation, record, context.signal);
526
+ return;
527
+ }
528
+ // These async methods call ClientMonitor synchronously before their first
529
+ // await, preserving the SDK's terminal handoff during dispose.
530
+ return this._handleOperationalLog(installation, record, context.signal)?.then(() => undefined);
531
+ },
532
+ });
75
533
  }
76
534
  catch (error) {
77
535
  this._deactivateInstallation();
@@ -81,1215 +539,364 @@ class SkyWalkingPlugin {
81
539
  dispose() {
82
540
  this._deactivateInstallation();
83
541
  }
84
- _handleAlertNotification(installation, alert, signal) {
85
- if (!this._isInvocationActive(installation, signal)) {
86
- return Promise.resolve();
87
- }
88
- try {
89
- if (alert.phase === "raised") {
90
- const state = installation.alertReportStates.get(alert.alertId) ?? {
91
- tail: Promise.resolve(),
92
- lastSuccessfulToWallClockMs: undefined,
93
- closing: false,
94
- };
95
- if (state.closing)
96
- return Promise.resolve();
97
- installation.alertReportStates.set(alert.alertId, state);
98
- return this._enqueue(state, () => this._runObserverTask(installation, signal, "A/V Sync alert", () => this._reportActiveAlert(installation, alert, state, signal)));
99
- }
100
- const state = installation.alertReportStates.get(alert.alertId);
101
- if (state === undefined || state.closing)
102
- return Promise.resolve();
103
- if (alert.phase === "updated") {
104
- return this._enqueue(state, () => this._runObserverTask(installation, signal, "A/V Sync alert update", () => this._reportActiveAlert(installation, alert, state, signal)));
105
- }
106
- state.closing = true;
107
- const recoveredAtWallClockMs = Date.now();
108
- const report = this._enqueue(state, () => this._runObserverTask(installation, signal, "A/V Sync recovery", () => this._reportRecovery(installation, alert.alertId, recoveredAtWallClockMs, signal)));
109
- const removeState = () => {
110
- if (installation.alertReportStates.get(alert.alertId) === state) {
111
- installation.alertReportStates.delete(alert.alertId);
112
- }
113
- };
114
- void report.then(removeState, removeState);
115
- return report;
116
- }
117
- catch (error) {
118
- this._warnInvocationFailure(installation, signal, "Failed to handle an A/V Sync alert", error, { alert: toJsonSafeAlert(alert) });
119
- return Promise.resolve();
120
- }
121
- }
122
- _handleOperationalLog(installation, record, signal) {
123
- if (!this._isInvocationActive(installation, signal))
124
- return Promise.resolve();
125
- if (this._reporting.sdkError &&
126
- record.level === "error" &&
127
- record.event === "sdk.error") {
128
- return this._runObserverTask(installation, signal, "SDK error log", () => this._reportSdkError(installation, record, signal));
129
- }
130
- if (this._reporting.firstFrame &&
131
- record.category === "media" &&
132
- record.event === "performance.first-frame") {
133
- return this._runObserverTask(installation, signal, "first-frame log", () => this._reportFirstFrameLog(installation, record, signal));
134
- }
135
- return Promise.resolve();
136
- }
137
- _enqueue(state, task) {
138
- const queued = state.tail.then(task, task);
139
- state.tail = queued.catch(() => undefined);
140
- return queued;
542
+ _deactivateInstallation() {
543
+ const installation = this._installation;
544
+ if (!installation)
545
+ return;
546
+ installation.active = false;
547
+ this._stopPlayback(installation);
548
+ installation.abortController.abort();
549
+ installation.pending.length = 0;
550
+ installation.alertReportStates.clear();
551
+ installation.retiredPlaybackOwners.clear();
552
+ installation.playbackSequences.clear();
553
+ this._installation = undefined;
141
554
  }
142
- async _reportActiveAlert(installation, alert, state, signal) {
143
- const isActive = () => this._isInvocationActive(installation, signal);
144
- if (!isActive())
555
+ _stopPlayback(installation) {
556
+ const sampling = installation.playback;
557
+ if (!sampling)
145
558
  return;
146
- const diagnostics = installation.diagnostics;
147
- if (diagnostics === undefined)
559
+ sampling.abortController.abort();
560
+ if (sampling.timer !== undefined)
561
+ clearInterval(sampling.timer);
562
+ installation.playback = undefined;
563
+ }
564
+ _handlePlaybackLifecycle(installation, record) {
565
+ if (!installation.playbackService)
148
566
  return;
149
- const clientMonitor = getClientMonitor();
150
- if (clientMonitor === undefined) {
151
- this._warnInvocation(installation, signal, "ClientMonitor.reportFrameErrors is unavailable", {
152
- pluginId: this.id,
153
- alert: toJsonSafeAlert(alert),
154
- });
567
+ const event = record.event;
568
+ const starts = [
569
+ "connect.completed",
570
+ "reconnect.completed",
571
+ "livekit.connected",
572
+ ].includes(event) ||
573
+ (event === "rtc.state-changed" &&
574
+ record.data?.roomState === "connected" &&
575
+ ["connected", "state-changed"].includes(String(record.data?.phase)));
576
+ const stops = [
577
+ "connect.failed",
578
+ "reconnect.started",
579
+ "reconnect.failed",
580
+ "disconnect.completed",
581
+ "monitoring.session.ended",
582
+ "client.disposed",
583
+ "livekit.disconnected",
584
+ ].includes(event) ||
585
+ (event === "rtc.state-changed" &&
586
+ ["disconnected", "reconnecting", "connecting"].includes(String(record.data?.roomState)));
587
+ if (!starts &&
588
+ !stops &&
589
+ event !== "monitoring.session.started" &&
590
+ event !== "avsync.session.started")
155
591
  return;
156
- }
157
- const retrievedAtWallClockMs = Date.now();
158
- const query = await createEvidenceQuery(alert.phase, state.lastSuccessfulToWallClockMs, [signal, installation.abortController.signal]);
159
- if (!isActive() || query === undefined)
592
+ const owner = JSON.stringify([
593
+ record.clientInstanceId,
594
+ record.monitoringSessionId,
595
+ ]);
596
+ if (installation.retiredPlaybackOwners.has(owner))
160
597
  return;
161
- const collection = await collectTelemetry(diagnostics, alert, retrievedAtWallClockMs, query, isActive, (message, error) => this._warnInvocationFailure(installation, signal, message, error, {
162
- alert: toJsonSafeAlert(alert),
163
- }));
164
- if (!isActive() || collection === undefined)
598
+ // Lifecycle facts share SDK-owned streams. Ignore delayed older facts, without
599
+ // comparing sequence numbers from different streams or monitoring sessions.
600
+ const stream = JSON.stringify([owner, record.streamId]);
601
+ const previous = installation.playbackSequences.get(stream);
602
+ if (previous !== undefined && record.sequence <= previous)
165
603
  return;
166
- const evidenceId = createEvidenceId();
167
- const chunks = createLogChunkPayloads(evidenceId, alert.alertId, collection.evidence.sessionId, collectPreparedCompactLogs(collection.evidence));
168
- const payload = createSummaryPayload(evidenceId, toJsonSafeAlert(alert), collection.evidence, chunks.length);
169
- if (!isActive())
604
+ installation.playbackSequences.set(stream, record.sequence);
605
+ if (event === "client.disposed") {
606
+ this._stopPlayback(installation);
170
607
  return;
171
- try {
172
- await Promise.resolve(clientMonitor.reportFrameErrors({
173
- category: "avsync",
174
- grade: "Warning",
175
- content: payload,
176
- }, {
177
- // The bundled SkyWalking script uses this as errorUrl. An empty
178
- // name lets it fall back to the browser page URL.
179
- name: "",
180
- message: `[LiveAvatar A/V Sync] ${alert.finding}: ${alert.message}`,
181
- stack: "",
182
- }));
183
- for (const chunk of chunks) {
184
- if (!isActive())
185
- return;
186
- await Promise.resolve(clientMonitor.reportFrameErrors({
187
- category: "avsync",
188
- grade: "Info",
189
- content: chunk,
190
- }, {
191
- name: "",
192
- message: `[LiveAvatar A/V Sync] evidence chunk ${chunk.chunk.index + 1}/${chunk.chunk.total}`,
193
- stack: "",
194
- }));
195
- }
196
608
  }
197
- catch (error) {
198
- this._warnInvocationFailure(installation, signal, "Failed to report an A/V Sync alert to SkyWalking", error, { alert: toJsonSafeAlert(alert) });
199
- return;
200
- }
201
- if (!isActive())
202
- return;
203
- if (collection.evidence.window.complete &&
204
- collection.requestedToWallClockMs !== null) {
205
- state.lastSuccessfulToWallClockMs = collection.requestedToWallClockMs;
206
- }
207
- }
208
- async _reportRecovery(installation, alertId, recoveredAtWallClockMs, signal) {
209
- if (!this._isInvocationActive(installation, signal))
210
- return;
211
- const clientMonitor = getClientMonitor();
212
- if (clientMonitor === undefined) {
213
- this._warnInvocation(installation, signal, "ClientMonitor.reportFrameErrors is unavailable", {
214
- pluginId: this.id,
215
- alertId,
216
- recoveredAtWallClockMs,
217
- });
218
- return;
609
+ if (installation.playbackOwner !== owner) {
610
+ if (!starts && event !== "monitoring.session.started")
611
+ return;
612
+ if (installation.playbackOwner !== undefined)
613
+ installation.retiredPlaybackOwners.add(installation.playbackOwner);
614
+ this._stopPlayback(installation);
615
+ installation.playbackOwner = owner;
219
616
  }
220
- if (!this._isInvocationActive(installation, signal))
617
+ if (stops) {
618
+ this._stopPlayback(installation);
619
+ if (event === "monitoring.session.ended")
620
+ installation.retiredPlaybackOwners.add(owner);
221
621
  return;
222
- try {
223
- await Promise.resolve(clientMonitor.reportFrameErrors({
224
- category: "avsync",
225
- grade: "Recovered",
226
- content: { alertId, recoveredAtWallClockMs },
227
- }, {
228
- name: "",
229
- message: "[LiveAvatar A/V Sync] alert recovered",
230
- stack: "",
231
- }));
232
622
  }
233
- catch (error) {
234
- this._warnInvocationFailure(installation, signal, "Failed to report an A/V Sync recovery to SkyWalking", error, { alertId, recoveredAtWallClockMs });
623
+ const identities = {
624
+ ...sourceCorrelation(record),
625
+ clientInstanceId: record.clientInstanceId,
626
+ };
627
+ if (installation.playback) {
628
+ const updated = {
629
+ ...installation.playback.owner,
630
+ ...identities,
631
+ };
632
+ const changed = ["serverSessionId", "avsyncSessionId"];
633
+ if (!changed.some((key) => updated[key] !== installation.playback.owner[key])) {
634
+ installation.playback.owner = updated;
635
+ return;
636
+ }
637
+ // A changed diagnostic segment also invalidates a pending sample.
638
+ this._stopPlayback(installation);
639
+ this._startPlayback(installation, updated);
235
640
  return;
236
641
  }
237
- if (!this._isInvocationActive(installation, signal))
642
+ if (!starts)
238
643
  return;
644
+ this._startPlayback(installation, identities);
239
645
  }
240
- async _reportSdkError(installation, record, signal) {
241
- if (!this._isInvocationActive(installation, signal))
242
- return;
243
- const code = stringOr(record.attributes?.code, "SDK_ERROR");
244
- const clientMonitor = getClientMonitor();
245
- if (clientMonitor === undefined) {
246
- this._warnInvocation(installation, signal, "ClientMonitor.reportFrameErrors is unavailable", {
247
- pluginId: this.id,
248
- sdkError: { code },
249
- });
250
- return;
251
- }
252
- const payload = {
253
- schemaVersion: 2,
254
- kind: "liveavatar.sdk.error",
255
- sdkVersion: VERSION,
256
- error: stringifyJson({
257
- code,
258
- eventId: record.eventId,
259
- sequence: record.sequence,
260
- occurredAtMs: record.occurredAtMs,
261
- category: record.category,
262
- event: record.event,
263
- clientInstanceId: record.clientInstanceId,
264
- ...(record.sessionId === undefined
265
- ? {}
266
- : { sessionId: record.sessionId }),
267
- }),
646
+ _startPlayback(installation, owner) {
647
+ const sampling = {
648
+ owner,
649
+ abortController: new AbortController(),
650
+ busy: false,
268
651
  };
269
- if (!this._isInvocationActive(installation, signal))
270
- return;
271
- try {
272
- await Promise.resolve(clientMonitor.reportFrameErrors({
273
- category: "unknown",
274
- grade: "Error",
275
- content: payload,
276
- }, {
277
- name: "",
278
- message: `[LiveAvatar SDK] ${code}`,
279
- stack: "",
280
- }));
281
- }
282
- catch (error) {
283
- this._warnInvocationFailure(installation, signal, "Failed to report an SDK error to SkyWalking", error, { eventId: record.eventId, code });
284
- return;
285
- }
286
- if (!this._isInvocationActive(installation, signal))
287
- return;
652
+ installation.playback = sampling;
653
+ sampling.timer = setInterval(() => {
654
+ void this._samplePlayback(installation, sampling);
655
+ }, this._playbackStatusIntervalMs);
656
+ void this._samplePlayback(installation, sampling);
288
657
  }
289
- async _reportFirstFrameLog(installation, record, signal) {
290
- if (!this._isInvocationActive(installation, signal))
291
- return;
292
- const payload = toSkyWalkingFirstFrameLogPayload(record);
293
- if (payload === undefined) {
294
- this._warnInvocation(installation, signal, "Skipped invalid first-frame Operational Log", { eventId: record.eventId });
295
- return;
296
- }
297
- const clientMonitor = getClientMonitor();
298
- if (clientMonitor === undefined) {
299
- this._warnInvocation(installation, signal, "ClientMonitor.reportFrameErrors is unavailable", {
300
- pluginId: this.id,
301
- attemptId: payload.attemptId,
302
- outcome: payload.outcome,
303
- });
304
- return;
305
- }
306
- if (!this._isInvocationActive(installation, signal))
658
+ async _samplePlayback(installation, sampling) {
659
+ const signal = sampling.abortController.signal;
660
+ const active = () => installation.playback === sampling &&
661
+ this._isActive(installation, signal);
662
+ if (sampling.busy || !active())
307
663
  return;
664
+ sampling.busy = true;
665
+ // Capture ownership before the asynchronous query; never attribute its result
666
+ // using a later connection or diagnostic session.
667
+ const owner = { ...sampling.owner };
308
668
  try {
309
- await Promise.resolve(clientMonitor.reportFrameErrors({
669
+ const status = await installation.playbackService.getPlaybackStatus();
670
+ if (!active())
671
+ return;
672
+ if (!status.connection.rtc.connected) {
673
+ this._stopPlayback(installation);
674
+ return;
675
+ }
676
+ const payload = {
677
+ schemaVersion: 4,
678
+ kind: "liveavatar.playback.status",
679
+ ...owner,
680
+ occurredAtMs: Date.now(),
681
+ playback: {
682
+ sampledAtMs: status.sampledAtMs,
683
+ connection: JSON.stringify(status.connection),
684
+ ice: JSON.stringify(status.ice),
685
+ output: status.output === null ? null : JSON.stringify(status.output),
686
+ tracks: JSON.stringify(status.tracks),
687
+ quality: status.quality,
688
+ qualityReasons: JSON.stringify(status.qualityReasons),
689
+ presentationSamplingEnabled: status.presentationSamplingEnabled,
690
+ },
691
+ };
692
+ if (utf8ByteLength(JSON.stringify(payload)) > 28 * 1024)
693
+ throw new Error("Playback status content exceeds the 28 KiB limit");
694
+ await this._report(installation, signal, {
310
695
  category: "media",
311
- grade: payload.outcome === "first-frame" ? "Info" : "Warning",
312
- content: payload,
313
- // The bundled client batches error records. Its public timeout
314
- // option bypasses the default delay for these terminal events.
696
+ grade: "Info",
315
697
  timeout: 1,
316
- }, {
317
- name: "",
318
- message: `[LiveAvatar first-frame] ${payload.outcome}`,
319
- stack: "",
320
- }));
698
+ content: payload,
699
+ }, "[LiveAvatar playback] status");
321
700
  }
322
701
  catch (error) {
323
- this._warnInvocationFailure(installation, signal, "Failed to report first-frame Operational Log to SkyWalking", error, { attemptId: payload.attemptId, outcome: payload.outcome });
702
+ if (active())
703
+ this._warn("Failed to sample playback status", error);
704
+ }
705
+ finally {
706
+ sampling.busy = false;
324
707
  }
325
708
  }
326
- _deactivateInstallation() {
327
- const installation = this._installation;
328
- if (installation === undefined)
329
- return;
330
- installation.active = false;
331
- installation.abortController.abort();
332
- installation.alertReportStates.clear();
333
- if (this._installation === installation)
334
- this._installation = undefined;
335
- }
336
- _isInvocationActive(installation, signal) {
709
+ _isActive(installation, signal) {
337
710
  return (this._installation === installation &&
338
711
  installation.active &&
339
712
  !installation.abortController.signal.aborted &&
340
713
  !signal.aborted);
341
714
  }
342
- async _runObserverTask(installation, signal, description, task) {
343
- try {
344
- await task();
345
- }
346
- catch (error) {
347
- this._warnInvocationFailure(installation, signal, `Failed to handle ${description}`, error);
348
- }
349
- }
350
- _warnInvocationFailure(installation, signal, message, error, details = {}) {
351
- this._warnInvocation(installation, signal, message, { ...details, error });
352
- }
353
- _warnInvocation(installation, signal, message, details) {
354
- if (!this._isInvocationActive(installation, signal))
355
- return;
715
+ _warn(message, error) {
356
716
  try {
357
- console.warn(`[LiveAvatar SkyWalking plugin] ${message}`, details);
717
+ console.warn(`[LiveAvatar SkyWalking plugin] ${message}`, error);
358
718
  }
359
719
  catch {
360
- // Observability warnings must never fault a detached SDK contribution.
720
+ /* Diagnostics must not fault the SDK. */
361
721
  }
362
722
  }
363
- }
364
- /** Creates a fresh plugin instance suitable for `createClient({ plugins })`. */
365
- function createSkyWalkingPlugin(config = {}) {
366
- return new SkyWalkingPlugin(config);
367
- }
368
- async function collectTelemetry(diagnostics, alert, retrievedAtWallClockMs, query, shouldContinue, onDiagnosticFailure) {
369
- if (!shouldContinue())
370
- return undefined;
371
- let firstPage;
372
- let analysis = null;
373
- let analysisUnavailable = false;
374
- let telemetryResult;
375
- let analysisResult;
376
- try {
377
- [telemetryResult, analysisResult] = await Promise.allSettled([
378
- diagnostics.getAvSyncRawTelemetry({
379
- range: query.range,
380
- pageSize: TELEMETRY_PAGE_SIZE,
381
- includeSummary: true,
382
- }),
383
- diagnostics.getAvSyncAnalysis({ range: query.range }),
384
- ]);
385
- }
386
- catch (error) {
387
- if (!shouldContinue())
388
- return undefined;
389
- onDiagnosticFailure("Failed to query A/V Sync telemetry", error);
390
- return {
391
- evidence: unavailableEvidence(retrievedAtWallClockMs, query, "initial-query-failed", alert),
392
- requestedToWallClockMs: null,
393
- };
394
- }
395
- if (!shouldContinue())
396
- return undefined;
397
- if (telemetryResult.status === "rejected") {
398
- onDiagnosticFailure("Failed to query A/V Sync telemetry", telemetryResult.reason);
399
- return {
400
- evidence: unavailableEvidence(retrievedAtWallClockMs, query, "initial-query-failed", alert),
401
- requestedToWallClockMs: null,
402
- };
403
- }
404
- firstPage = telemetryResult.value;
405
- if (analysisResult.status === "fulfilled") {
406
- analysis = analysisResult.value;
407
- }
408
- else {
409
- analysisUnavailable = true;
410
- onDiagnosticFailure("Failed to query A/V Sync analysis", analysisResult.reason);
411
- }
412
- if (!shouldContinue())
413
- return undefined;
414
- const firstPageEvidence = evidenceFromFirstPage(firstPage, query);
415
- if (firstPage.sessionId !== alert.sessionId) {
416
- return {
417
- evidence: {
418
- ...firstPageEvidence,
419
- window: {
420
- ...firstPageEvidence.window,
421
- complete: false,
422
- unavailableReason: "session-mismatch",
423
- },
424
- triage: createTriage(alert, null, ["session-mismatch"]),
425
- },
426
- requestedToWallClockMs: firstPage.page.requestedToWallClockMs,
427
- };
428
- }
429
- const logs = [...firstPage.avSyncLogs];
430
- let page = firstPage.page;
431
- let truncated = page.truncated;
432
- const seenCursors = new Set();
433
- while (page.hasMore) {
434
- if (!shouldContinue())
435
- return undefined;
436
- const cursor = page.nextCursor;
437
- if (cursor === null || seenCursors.has(cursor)) {
438
- return {
439
- evidence: compactEvidence(firstPageEvidence, logs, truncated, "cursor-did-not-advance", alert, analysis, analysisUnavailable, firstPage),
440
- requestedToWallClockMs: firstPage.page.requestedToWallClockMs,
441
- };
723
+ async _report(installation, signal, config, message) {
724
+ if (!this._isActive(installation, signal))
725
+ return false;
726
+ const monitor = getClientMonitor();
727
+ if (!monitor) {
728
+ this._warn("ClientMonitor.reportFrameErrors is unavailable");
729
+ return false;
442
730
  }
443
- seenCursors.add(cursor);
444
- let continuation;
445
731
  try {
446
- continuation = await diagnostics.getAvSyncRawTelemetry({
447
- cursor,
448
- pageSize: TELEMETRY_PAGE_SIZE,
449
- includeSummary: false,
450
- });
732
+ await Promise.resolve(monitor.reportFrameErrors({ ...config, serviceVersion: VERSION }, { name: "", message, stack: "" }));
733
+ return this._isActive(installation, signal);
451
734
  }
452
735
  catch (error) {
453
- if (!shouldContinue())
454
- return undefined;
455
- onDiagnosticFailure("Failed to query A/V Sync telemetry continuation", error);
456
- return {
457
- evidence: compactEvidence(firstPageEvidence, logs, truncated, "continuation-query-failed", alert, analysis, analysisUnavailable, firstPage),
458
- requestedToWallClockMs: firstPage.page.requestedToWallClockMs,
459
- };
736
+ if (this._isActive(installation, signal))
737
+ this._warn("Failed to report to SkyWalking", error);
738
+ return false;
460
739
  }
461
- if (!shouldContinue())
462
- return undefined;
463
- if (continuation.sessionId !== alert.sessionId) {
464
- return {
465
- evidence: compactEvidence(firstPageEvidence, logs, truncated, "session-mismatch", alert, analysis, analysisUnavailable, firstPage),
466
- requestedToWallClockMs: firstPage.page.requestedToWallClockMs,
740
+ }
741
+ _handleOperationalLog(installation, record, signal) {
742
+ if (record.event === "sdk.failure") {
743
+ if (!this._reporting.sdkError ||
744
+ !record.error ||
745
+ !["warn", "error"].includes(record.level))
746
+ return;
747
+ const payload = {
748
+ ...operationalSource(record),
749
+ kind: "liveavatar.sdk.error",
750
+ schemaVersion: 4,
751
+ error: JSON.stringify(projectRecord(record)),
467
752
  };
753
+ return this._report(installation, signal, {
754
+ category: record.module,
755
+ grade: record.level === "warn" ? "Warning" : "Error",
756
+ content: payload,
757
+ timeout: 1,
758
+ }, `[LiveAvatar SDK] ${record.error.code}`);
468
759
  }
469
- logs.push(...continuation.avSyncLogs);
470
- page = continuation.page;
471
- truncated = truncated || page.truncated;
472
- }
473
- if (!shouldContinue())
474
- return undefined;
475
- return {
476
- evidence: compactEvidence(firstPageEvidence, logs, truncated, undefined, alert, analysis, analysisUnavailable, firstPage, true),
477
- requestedToWallClockMs: firstPage.page.requestedToWallClockMs,
478
- };
479
- }
480
- function evidenceFromFirstPage(telemetry, query) {
481
- return {
482
- evidenceSchemaVersion: 2,
483
- sessionId: telemetry.sessionId ?? null,
484
- window: {
485
- mode: query.mode,
486
- requestedFromWallClockMs: telemetry.page.requestedFromWallClockMs,
487
- requestedToWallClockMs: telemetry.page.requestedToWallClockMs,
488
- availableFromWallClockMs: telemetry.page.availableFromWallClockMs,
489
- availableToWallClockMs: telemetry.page.availableToWallClockMs,
490
- complete: false,
491
- truncated: telemetry.page.truncated,
492
- },
493
- retention: compactRetention(telemetry.avSyncLogRetention),
494
- triage: null,
495
- logChunkCount: 0,
496
- logRecordCount: 0,
497
- detail: emptyDetail(),
498
- };
499
- }
500
- function unavailableEvidence(_retrievedAtWallClockMs, query, unavailableReason, alert) {
501
- return {
502
- evidenceSchemaVersion: 2,
503
- retention: null,
504
- sessionId: null,
505
- window: {
506
- mode: query.mode,
507
- requestedFromWallClockMs: null,
508
- requestedToWallClockMs: null,
509
- availableFromWallClockMs: null,
510
- availableToWallClockMs: null,
511
- complete: false,
512
- truncated: false,
513
- unavailableReason,
514
- },
515
- triage: createTriage(alert, null, [unavailableReason]),
516
- logChunkCount: 0,
517
- logRecordCount: 0,
518
- detail: emptyDetail(),
519
- };
520
- }
521
- async function createEvidenceQuery(phase, lastSuccessfulToWallClockMs, signals) {
522
- if (isAnySignalAborted(signals))
523
- return undefined;
524
- if (phase === "raised" || lastSuccessfulToWallClockMs === undefined) {
525
- return {
526
- mode: "recent",
527
- range: { kind: "recent", durationMs: ALERT_LOG_DURATION_MS },
528
- requestedDurationMs: ALERT_LOG_DURATION_MS,
529
- };
530
- }
531
- let now = Date.now();
532
- const nextFromMs = lastSuccessfulToWallClockMs + 1;
533
- if (now < nextFromMs) {
534
- await waitForWallClock(nextFromMs, signals);
535
- if (isAnySignalAborted(signals))
536
- return undefined;
537
- now = Date.now();
538
- }
539
- const fromMs = Math.max(nextFromMs, now - ALERT_LOG_DURATION_MS);
540
- const toMs = Math.max(fromMs, now);
541
- return {
542
- mode: "wall-clock",
543
- range: { kind: "wall-clock", fromMs, toMs },
544
- requestedDurationMs: toMs - fromMs,
545
- };
546
- }
547
- function waitForWallClock(targetMs, signals) {
548
- if (isAnySignalAborted(signals))
549
- return Promise.resolve();
550
- return new Promise((resolve) => {
551
- let settled = false;
552
- let timeout;
553
- const finish = () => {
554
- if (settled)
760
+ if (record.event === "performance.first-frame") {
761
+ if (!this._reporting.firstFrame)
762
+ return;
763
+ const payload = toSkyWalkingFirstFrameLogPayload(record);
764
+ if (!payload) {
765
+ this._warn("Skipped invalid first-frame Operational Log");
555
766
  return;
556
- settled = true;
557
- if (timeout !== undefined)
558
- clearTimeout(timeout);
559
- for (const signal of signals) {
560
- signal.removeEventListener("abort", finish);
561
767
  }
562
- resolve();
563
- };
564
- timeout = setTimeout(finish, Math.max(1, targetMs - Date.now()));
565
- for (const signal of signals)
566
- signal.addEventListener("abort", finish);
567
- });
568
- }
569
- function isAnySignalAborted(signals) {
570
- return signals.some((signal) => signal.aborted);
571
- }
572
- function compactEvidence(firstPageEvidence, logs, truncated, unavailableReason, alert, analysis, analysisUnavailable, telemetry, complete = false) {
573
- const compacted = compactLogs(logs, telemetry);
574
- return {
575
- ...firstPageEvidence,
576
- window: {
577
- ...firstPageEvidence.window,
578
- complete,
579
- truncated,
580
- ...(unavailableReason === undefined ? {} : { unavailableReason }),
581
- },
582
- triage: createTriage(alert, analysis, analysisUnavailable ? ["analysis-query-failed"] : []),
583
- ...chunkCompactLogs(compacted.logs, compacted.detail),
584
- };
585
- }
586
- function compactRetention(retention) {
587
- if (retention === null)
588
- return null;
589
- return {
590
- storageWriteFailed: retention.storageWriteFailed,
591
- droppedSegmentCount: retention.droppedSegmentCount,
592
- droppedLogCount: retention.droppedLogCount,
593
- oldestSegmentAtMs: retention.oldestSegmentAtMs,
594
- newestSegmentAtMs: retention.newestSegmentAtMs,
595
- };
596
- }
597
- function createTriage(alert, analysis, limitations) {
598
- const usableAnalysis = analysis !== null &&
599
- analysis.layers !== null &&
600
- typeof analysis.layers === "object" &&
601
- Array.isArray(analysis.participants) &&
602
- typeof analysis.finding === "string";
603
- return {
604
- trigger: {
605
- finding: alert.finding,
606
- status: alert.status,
607
- confidence: alert.confidence,
608
- capturedAtMs: alert.capturedAtMs,
609
- },
610
- evaluation: !usableAnalysis || analysis === null
611
- ? null
612
- : {
613
- finding: analysis.finding,
614
- status: analysis.status,
615
- confidence: analysis.confidence,
616
- },
617
- layers: !usableAnalysis || analysis === null
618
- ? null
619
- : Object.fromEntries(Object.entries(analysis.layers).map(([name, layer]) => [
620
- name,
621
- {
622
- status: layer.status,
623
- finding: layer.finding,
624
- confidence: layer.confidence,
625
- },
626
- ])),
627
- participants: (!usableAnalysis || analysis === null ? [] : analysis.participants).map((participant) => ({
628
- participantId: participant.participantId,
629
- status: participant.status,
630
- finding: participant.finding,
631
- confidence: participant.confidence,
632
- audioTrackId: participant.audioTrackId,
633
- videoTrackId: participant.videoTrackId,
634
- metrics: participant.metrics,
635
- })) ?? [],
636
- limitations: [
637
- ...new Set([
638
- ...(!usableAnalysis || analysis === null ? [] : analysis.limitations),
639
- ...limitations,
640
- ...(!usableAnalysis && analysis !== null ? ["analysis-invalid"] : []),
641
- ]),
642
- ],
643
- };
644
- }
645
- function emptyDetail() {
646
- return {
647
- projectionVersion: 2,
648
- sourceRecordCount: 0,
649
- reportedRecordCount: 0,
650
- timeSyncInputCount: 0,
651
- timeSyncReportedCount: 0,
652
- framePresentationReportedCount: 0,
653
- verifiedMetadataTimestampCount: 0,
654
- omittedSetupLifecycleCount: 0,
655
- oversizeFallbackRecordCount: 0,
656
- contentByteLimit: EVIDENCE_CONTENT_BYTE_LIMIT,
657
- chunks: [],
658
- };
659
- }
660
- function compactLogs(logs, telemetry) {
661
- const compacted = [];
662
- const detail = emptyDetail();
663
- detail.sourceRecordCount = logs.length;
664
- const timeSyncBuckets = new Map();
665
- for (const log of logs) {
666
- if (log.eventName === "time-sync-updated") {
667
- detail.timeSyncInputCount += 1;
668
- const correlation = toRecord(log.correlation);
669
- const key = [
670
- correlation.participantId ?? "",
671
- correlation.trackId ?? "",
672
- correlation.mediaKind ?? "",
673
- Math.floor(log.wallClockMs / TIME_SYNC_BUCKET_MS),
674
- ].join("|");
675
- timeSyncBuckets.set(key, log);
676
- continue;
768
+ return this._report(installation, signal, {
769
+ category: "media",
770
+ grade: payload.outcome === "first-frame" ? "Info" : "Warning",
771
+ content: payload,
772
+ timeout: 1,
773
+ }, `[LiveAvatar first-frame] ${payload.outcome}`);
677
774
  }
678
- const compact = compactSourceLog(log);
679
- if (compact !== null)
680
- compacted.push(compact);
681
- else if (log.logType === "lifecycle")
682
- detail.omittedSetupLifecycleCount += 1;
683
- }
684
- const timeSync = [...timeSyncBuckets.values()]
685
- .sort(compareSourceLogs)
686
- .map(compactTimeSyncLog);
687
- detail.timeSyncReportedCount = timeSync.length;
688
- compacted.push(...timeSync);
689
- compacted.push(...compactMediaTimeline(telemetry.mediaTimeline));
690
- compacted.push(...compactDiagnoses(telemetry.diagnosis));
691
- const presentations = compactVideoFrames(telemetry.videoFrames);
692
- detail.framePresentationReportedCount = presentations.logs.length;
693
- detail.verifiedMetadataTimestampCount = presentations.verifiedCount;
694
- compacted.push(...presentations.logs);
695
- compacted.sort(compareCompactLogs);
696
- detail.reportedRecordCount = compacted.length;
697
- return { logs: compacted, detail };
698
- }
699
- function compactMediaTimeline(value) {
700
- const buckets = new Map();
701
- for (const item of value) {
702
- const record = toRecord(item);
703
- const participantId = stringOr(record.participantId, "");
704
- const videoTrackId = stringOr(record.videoTrackId, "");
705
- const wallClock = numberOr(record.wallClock, 0);
706
- buckets.set(`${participantId}|${videoTrackId}|${Math.floor(wallClock / TIME_SYNC_BUCKET_MS)}`, record);
775
+ if (!this._reporting.timeline)
776
+ return;
777
+ const payload = toTimeline(record);
778
+ if (!payload)
779
+ return;
780
+ return this._report(installation, signal, {
781
+ category: record.module,
782
+ grade: record.level === "warn"
783
+ ? "Warning"
784
+ : record.level === "error"
785
+ ? "Error"
786
+ : "Info",
787
+ content: payload,
788
+ ...(["monitoring.session.ended", "client.disposed"].includes(record.event)
789
+ ? { timeout: 1 }
790
+ : {}),
791
+ }, `[LiveAvatar SDK] ${record.event}`);
707
792
  }
708
- return [...buckets.values()].map((record) => ({
709
- q: numberOr(record.seq, 0),
710
- t: numberOr(record.wallClock, 0),
711
- o: numberOr(record.perfNow, 0),
712
- y: "timeline",
713
- e: "relative-drift",
714
- c: removeUndefined({
715
- participantId: record.participantId,
716
- audioTrackId: record.audioTrackId,
717
- videoTrackId: record.videoTrackId,
718
- }),
719
- d: pick(record, [
720
- "normalizationStatus",
721
- "normalizationGeneration",
722
- "normalizationResetReason",
723
- "pairingCoverage",
724
- "validPairCount",
725
- "relativeWindowSpanMs",
726
- "relativeDriftMs",
727
- "relativeDriftAvgMs",
728
- "relativeDriftJitterMs",
729
- "relativeDriftSlopeMsPerMinute",
730
- "videoFrameId",
731
- ]),
732
- }));
733
- }
734
- function compactDiagnoses(value) {
735
- return value.map((item) => {
736
- const record = toRecord(item);
737
- return {
738
- q: numberOr(record.seq, 0),
739
- t: numberOr(record.wallClock, 0),
740
- o: numberOr(record.perfNow, 0),
741
- y: "diagnosis",
742
- e: stringOr(record.status, "unknown"),
743
- d: pick(record, [
744
- "suspectedNode",
745
- "responsibility",
746
- "confidence",
747
- "receiverIncident",
748
- "normalizationStatus",
749
- "normalizationGeneration",
750
- "normalizationResetReason",
751
- "pairingCoverage",
752
- "relativeDriftMs",
753
- "relativeDriftAvgMs",
754
- "relativeDriftJitterMs",
755
- "relativeDriftSlopeMsPerMinute",
756
- "videoCaptureToDisplayRelativeMs",
757
- ]),
758
- };
759
- });
760
- }
761
- function compactSourceLog(log) {
762
- if (log.eventName === "remote-media-capture-completed") {
763
- const data = toRecord(log.data);
764
- return compactLog(log, "capture", "completed", {
765
- id: data.captureId,
766
- status: data.captureStatus,
767
- mode: data.captureMode,
768
- durationMs: data.captureDurationMs,
769
- pairCount: data.pairCount,
770
- unpairedChannelCount: data.unpairedChannelCount,
771
- channelGroupCount: data.channelGroupCount,
772
- playback: compactPlayback(data.playback),
773
- timeSync: compactTimeSyncSummary(data.timeSync),
793
+ _queueAlert(installation, record, signal) {
794
+ if (!record.correlation?.alertId ||
795
+ !["raised", "updated", "recovered"].includes(String(record.data?.phase)))
796
+ return;
797
+ if (installation.pending.length >= MAX_PENDING_ALERTS) {
798
+ installation.pending.shift();
799
+ this._warn("A/V reporting queue full; dropped oldest pending alert");
800
+ }
801
+ // The SDK freezes observer records; still take an independent synchronous copy.
802
+ installation.pending.push({
803
+ record: JSON.parse(JSON.stringify(record)),
804
+ signal,
774
805
  });
775
- }
776
- if (log.eventName === "receiver-stats-sampled") {
777
- const data = toRecord(log.data);
778
- return compactLog(log, "receiver", "sampled", compactReceiverData(data));
779
- }
780
- if (log.eventName === "video-pipeline-stalled") {
781
- return compactLog(log, "incident", "video-pipeline-stalled", toRecord(log.data));
782
- }
783
- if (log.logType === "connection") {
784
- return compactLog(log, "connection", log.eventName, toRecord(log.data));
785
- }
786
- if (log.logType === "lifecycle" && isCausalLifecycleEvent(log.eventName)) {
787
- return compactLog(log, "lifecycle", log.eventName, compactLifecycleDetails(toRecord(log.data)));
788
- }
789
- return null;
790
- }
791
- function compactTimeSyncLog(log) {
792
- const data = toRecord(log.data);
793
- return compactLog(log, "time-sync", "updated", {
794
- receiverTimestampMs: data.receiverTimestampMs,
795
- frameId: data.frameId,
796
- });
797
- }
798
- function compactLog(log, type, event, data) {
799
- return {
800
- q: log.sequence,
801
- t: log.wallClockMs,
802
- o: log.observedAtMs,
803
- y: type,
804
- e: event,
805
- ...(Object.keys(compactCorrelation(toRecord(log.correlation))).length === 0
806
- ? {}
807
- : { c: compactCorrelation(toRecord(log.correlation)) }),
808
- ...(data === undefined || Object.keys(data).length === 0
809
- ? {}
810
- : { d: data }),
811
- };
812
- }
813
- function compactCorrelation(correlation) {
814
- return pick(correlation, [
815
- "participantId",
816
- "trackId",
817
- "mediaKind",
818
- "pairId",
819
- "streamId",
820
- "playbackTargetId",
821
- "captureId",
822
- ]);
823
- }
824
- function compactReceiverData(data) {
825
- return removeUndefined({
826
- source: data.statsSource,
827
- error: data.statsError,
828
- delta: compactReceiverDelta(toRecord(data.delta)),
829
- transport: compactTransport(toRecord(data.transport)),
830
- computed: compactReceiverComputed(toRecord(data.computed)),
831
- frameMetadata: compactFrameMetadata(toRecord(data.frameMetadata)),
832
- });
833
- }
834
- function compactReceiverDelta(data) {
835
- return pick(data, [
836
- "intervalMs",
837
- "packetsReceived",
838
- "packetsLost",
839
- "concealedSamples",
840
- "concealmentEvents",
841
- "framesReceived",
842
- "framesDecoded",
843
- "framesDropped",
844
- "nackCount",
845
- "pliCount",
846
- "firCount",
847
- "freezeCount",
848
- "framesDecodedPerSecond",
849
- ]);
850
- }
851
- function compactReceiverComputed(data) {
852
- return pick(data, [
853
- "packetLossRate",
854
- "jitterMs",
855
- "audioConcealedSamplesPerSecond",
856
- "audioConcealmentEventsPerSecond",
857
- "videoDecodedFramesPerSecond",
858
- "videoDroppedFramesPerSecond",
859
- "videoDecodeRatio",
860
- ]);
861
- }
862
- function compactTransport(transport) {
863
- return pick(transport, [
864
- "iceState",
865
- "candidatePairState",
866
- "candidatePairWritable",
867
- "currentRoundTripTimeSeconds",
868
- ]);
869
- }
870
- function compactPlayback(value) {
871
- return compactLifecycleDetails(toRecord(value));
872
- }
873
- function compactTimeSyncSummary(value) {
874
- const summary = toRecord(value);
875
- const latest = Array.isArray(summary.latest)
876
- ? summary.latest.map((entry) => pick(toRecord(entry), [
877
- "trackId",
878
- "participantId",
879
- "kind",
880
- "observedAtMs",
881
- "receiverTimestampMs",
882
- "frameId",
883
- ]))
884
- : [];
885
- return removeUndefined({ status: summary.status, latest });
886
- }
887
- function isCausalLifecycleEvent(eventName) {
888
- return [
889
- "track-subscribed",
890
- "track-validated",
891
- "pair-bind-started",
892
- "pair-bind-completed",
893
- "pair-bind-failed",
894
- "track-replaced",
895
- "playback-snapshot",
896
- "element-waiting",
897
- "element-stalled",
898
- "element-recovered",
899
- "native-playing",
900
- "video-first-frame-presented",
901
- "element-error",
902
- ].includes(eventName);
903
- }
904
- function compactLifecycleDetails(details) {
905
- return pick(details, [
906
- "requiredMediaKinds",
907
- "attachedMediaKind",
908
- "attachedKinds",
909
- "bindingGeneration",
910
- "targetId",
911
- "elementTag",
912
- "elementRole",
913
- "elementBindingId",
914
- "elementBound",
915
- "srcObjectType",
916
- "streamBindingState",
917
- "streamId",
918
- "streamTrackCount",
919
- "streamTrackKinds",
920
- "activeAudioTrackId",
921
- "activeAudioParticipantId",
922
- "activeVideoTrackId",
923
- "activeVideoParticipantId",
924
- "readyState",
925
- "networkState",
926
- "paused",
927
- "currentTime",
928
- "playbackRate",
929
- "width",
930
- "height",
931
- "videoWidth",
932
- "videoHeight",
933
- "eventSemantic",
934
- "pairReady",
935
- "pendingPairCommit",
936
- "source",
937
- "presentationObservedAtMs",
938
- "presentedFrames",
939
- "videoCurrentTime",
940
- "videoReadyState",
941
- "videoPaused",
942
- "videoPlaybackRate",
943
- "errorCode",
944
- "errorMessage",
945
- ]);
946
- }
947
- function compactFrameMetadata(metadata) {
948
- if (Object.keys(metadata).length === 0)
949
- return null;
950
- const lookup = toRecord(metadata.captureLookup);
951
- const item = toRecord(lookup.metadata);
952
- const verifiedTimestamp = verifiedCaptureTimestamp(lookup, item);
953
- return removeUndefined({
954
- analysisEnabled: metadata.analysisEnabled,
955
- workerConfigured: metadata.workerConfigured,
956
- featureStatus: metadata.featureStatus,
957
- lookupStatus: lookup.status,
958
- associationAgeMs: lookup.associationAgeMs,
959
- frameId: item.frameId,
960
- userTimestamp: item.userTimestamp,
961
- userDataByteLength: item.userDataByteLength,
962
- userDataIsTruncated: item.userDataIsTruncated,
963
- timestampEncoding: verifiedTimestamp === null ? undefined : "ascii-decimal-unix-us",
964
- timestampVerified: verifiedTimestamp !== null,
965
- videoCaptureTimestampUs: verifiedTimestamp,
966
- });
967
- }
968
- function verifiedCaptureTimestamp(lookup, metadata) {
969
- if (lookup.status !== "available" ||
970
- metadata.userDataIsTruncated === true ||
971
- typeof lookup.rtpTimestamp !== "number" ||
972
- typeof metadata.frameId !== "number" ||
973
- typeof lookup.associationAgeMs !== "number" ||
974
- lookup.associationAgeMs > FRAME_METADATA_MAX_ASSOCIATION_AGE_MS) {
975
- return null;
976
- }
977
- return decodeAsciiDecimalBase64(typeof metadata.userDataBase64 === "string"
978
- ? metadata.userDataBase64
979
- : null);
980
- }
981
- function compactVideoFrames(videoFrames) {
982
- const buckets = new Map();
983
- for (const frame of videoFrames) {
984
- if (frame.videoCaptureTimestampUs === null &&
985
- frame.videoCaptureToDisplayRelativeMs === null) {
986
- continue;
806
+ if (!installation.draining) {
807
+ installation.draining = true;
808
+ queueMicrotask(() => {
809
+ void this._drainAlerts(installation);
810
+ });
987
811
  }
988
- buckets.set(`${frame.trackId}|${Math.floor(frame.wallClock / TIME_SYNC_BUCKET_MS)}`, frame);
989
812
  }
990
- let verifiedCount = 0;
991
- const logs = [...buckets.values()].map((frame) => {
992
- if (frame.videoCaptureTimestampUs !== null)
993
- verifiedCount += 1;
994
- return {
995
- q: frame.seq,
996
- t: frame.wallClock,
997
- o: frame.perfNow,
998
- y: "frame-presentation",
999
- e: "presented",
1000
- c: { trackId: frame.trackId, mediaKind: "video" },
1001
- d: removeUndefined({
1002
- presentedFrames: frame.presentedFrames,
1003
- associationAgeMs: frame.metadataAssociationAgeMs,
1004
- timestampEncoding: frame.videoCaptureTimestampUs === null
1005
- ? undefined
1006
- : "ascii-decimal-unix-us",
1007
- timestampVerified: frame.videoCaptureTimestampUs !== null,
1008
- videoCaptureTimestampUs: frame.videoCaptureTimestampUs,
1009
- videoCaptureToDisplayRelativeMs: frame.videoCaptureToDisplayRelativeMs,
1010
- }),
1011
- };
1012
- });
1013
- return { logs, verifiedCount };
1014
- }
1015
- function chunkCompactLogs(logs, detail) {
1016
- const chunks = [];
1017
- let current = [];
1018
- for (const log of logs) {
1019
- if (utf8JsonByteLength([log]) > EVIDENCE_CONTENT_BYTE_LIMIT) {
1020
- detail.oversizeFallbackRecordCount += 1;
1021
- const fallback = {
1022
- q: log.q,
1023
- t: log.t,
1024
- o: log.o,
1025
- y: log.y,
1026
- e: log.e,
1027
- ...(log.c === undefined ? {} : { c: log.c }),
1028
- d: {
1029
- projection: "oversize-fallback",
1030
- projectedByteLength: utf8JsonByteLength(log),
1031
- },
1032
- };
1033
- current = appendCompactLog(chunks, current, fallback);
1034
- continue;
813
+ async _drainAlerts(installation) {
814
+ try {
815
+ while (installation.active && installation.pending.length) {
816
+ const task = installation.pending.shift();
817
+ if (!this._isActive(installation, task.signal))
818
+ continue;
819
+ try {
820
+ await this._reportAlert(installation, task.record, task.signal);
821
+ }
822
+ catch (error) {
823
+ if (this._isActive(installation, task.signal))
824
+ this._warn("Failed to handle A/V evidence", error);
825
+ }
826
+ }
1035
827
  }
1036
- current = appendCompactLog(chunks, current, log);
1037
- }
1038
- if (current.length > 0)
1039
- chunks.push(current);
1040
- const manifest = chunks.map((chunk, index) => ({
1041
- index,
1042
- byteLength: utf8JsonByteLength(chunk),
1043
- recordCount: chunk.length,
1044
- firstSequence: chunk[0]?.q ?? null,
1045
- lastSequence: chunk[chunk.length - 1]?.q ?? null,
1046
- }));
1047
- const finalDetail = {
1048
- ...detail,
1049
- reportedRecordCount: chunks.reduce((count, chunk) => count + chunk.length, 0),
1050
- chunks: manifest,
1051
- };
1052
- const result = {
1053
- logChunkCount: chunks.length,
1054
- logRecordCount: chunks.reduce((count, chunk) => count + chunk.length, 0),
1055
- detail: finalDetail,
1056
- };
1057
- if (chunks[0] !== undefined)
1058
- result.logs = chunks[0];
1059
- for (let index = 1; index < chunks.length; index += 1) {
1060
- const chunk = chunks[index];
1061
- if (chunk !== undefined)
1062
- result[`logs_${index}`] = chunk;
1063
- }
1064
- return result;
1065
- }
1066
- function appendCompactLog(chunks, current, log) {
1067
- const candidate = [...current, log];
1068
- if (current.length > 0 &&
1069
- utf8JsonByteLength(candidate) > EVIDENCE_CONTENT_BYTE_LIMIT) {
1070
- chunks.push(current);
1071
- return [log];
1072
- }
1073
- return candidate;
1074
- }
1075
- function createEvidenceId() {
1076
- return `avse_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
1077
- }
1078
- function collectPreparedCompactLogs(evidence) {
1079
- const logs = [];
1080
- for (const chunk of evidence.detail.chunks ?? []) {
1081
- const value = chunk.index === 0
1082
- ? evidence.logs
1083
- : evidence[`logs_${chunk.index}`];
1084
- if (value !== undefined)
1085
- logs.push(...value);
1086
- }
1087
- return logs;
1088
- }
1089
- function createLogChunkPayloads(evidenceId, alertId, sessionId, logs) {
1090
- const safeLogs = logs.map((log) => fitsInLogChunk(log, evidenceId, alertId, sessionId, logs.length)
1091
- ? log
1092
- : fallbackCompactLog(log));
1093
- const chunks = [];
1094
- let current = [];
1095
- const maximumTotal = Math.max(1, safeLogs.length);
1096
- for (const log of safeLogs) {
1097
- const candidate = [...current, log];
1098
- if (current.length > 0 &&
1099
- !logChunkFits(candidate, evidenceId, alertId, sessionId, safeLogs.length, maximumTotal)) {
1100
- chunks.push(current);
1101
- current = [log];
828
+ finally {
829
+ installation.draining = false;
1102
830
  }
1103
- else {
1104
- current = candidate;
831
+ }
832
+ async _reportAlert(installation, alert, signal) {
833
+ const key = JSON.stringify([
834
+ alert.clientInstanceId,
835
+ alert.monitoringSessionId,
836
+ alert.avsyncSessionId,
837
+ alert.correlation.alertId,
838
+ ]);
839
+ const phase = alert.data.phase;
840
+ const alertId = alert.correlation.alertId;
841
+ const state = installation.alertReportStates.get(key) ?? {};
842
+ if (phase === "recovered") {
843
+ const payload = {
844
+ ...operationalSource(alert),
845
+ kind: "liveavatar.avsync.recovery",
846
+ schemaVersion: 4,
847
+ alertId,
848
+ recoveredAtWallClockMs: alert.occurredAtMs,
849
+ };
850
+ await this._report(installation, signal, { category: "avsync", grade: "Recovered", content: payload }, "[LiveAvatar A/V Sync] alert recovered");
851
+ installation.alertReportStates.delete(key);
852
+ return;
1105
853
  }
1106
- if (!logChunkFits(current, evidenceId, alertId, sessionId, safeLogs.length, maximumTotal)) {
1107
- throw new Error("A/V Sync log fallback exceeds the platform content limit");
854
+ if (!installation.diagnostics)
855
+ return;
856
+ installation.alertReportStates.set(key, state);
857
+ // Bound inactive alert bookkeeping as well as queued work.
858
+ if (installation.alertReportStates.size > MAX_PENDING_ALERTS)
859
+ installation.alertReportStates.delete(installation.alertReportStates.keys().next().value);
860
+ const now = Date.now();
861
+ const previous = state.lastSuccessfulToWallClockMs;
862
+ const range = phase === "raised" || previous === undefined
863
+ ? { kind: "recent", durationMs: 30000 }
864
+ : {
865
+ kind: "wall-clock",
866
+ fromMs: Math.max(now - 30000, Math.min(previous + 1, now)),
867
+ toMs: now,
868
+ };
869
+ const active = () => this._isActive(installation, signal);
870
+ const evidence = await collectEvidence(installation.diagnostics, alert, range, active);
871
+ if (!evidence || !active())
872
+ return;
873
+ const evidenceId = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
874
+ ? crypto.randomUUID()
875
+ : `avse_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
876
+ const { summary, chunks } = createEvidencePayloads(evidenceId, evidence);
877
+ if (!(await this._report(installation, signal, { category: "avsync", grade: "Warning", content: summary }, `[LiveAvatar A/V Sync] ${String(alert.data?.finding)}`)))
878
+ return;
879
+ for (const chunk of chunks) {
880
+ 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}`)))
881
+ return;
1108
882
  }
883
+ // A successful local handoff is not a server delivery acknowledgment.
884
+ if (evidence.completeness.complete)
885
+ state.lastSuccessfulToWallClockMs =
886
+ evidence.pages[0]?.page.requestedToWallClockMs;
1109
887
  }
1110
- if (current.length > 0)
1111
- chunks.push(current);
1112
- return chunks.map((chunk, index) => createLogChunkPayload(evidenceId, alertId, sessionId, chunk, index, chunks.length));
1113
- }
1114
- function fitsInLogChunk(log, evidenceId, alertId, sessionId, total) {
1115
- return logChunkFits([log], evidenceId, alertId, sessionId, total, total);
1116
888
  }
1117
- function logChunkFits(logs, evidenceId, alertId, sessionId, index, total) {
1118
- return (utf8JsonByteLength(createLogChunkPayload(evidenceId, alertId, sessionId, logs, index, total)) <= EVIDENCE_CONTENT_BYTE_LIMIT);
1119
- }
1120
- function fallbackCompactLog(log) {
1121
- return {
1122
- q: log.q,
1123
- t: log.t,
1124
- o: log.o,
1125
- y: log.y,
1126
- e: log.e,
1127
- d: {
1128
- projection: "oversize-fallback",
1129
- projectedByteLength: utf8JsonByteLength(log),
1130
- },
1131
- };
1132
- }
1133
- function createLogChunkPayload(evidenceId, alertId, sessionId, logs, index, total) {
1134
- return {
1135
- schemaVersion: 1,
1136
- kind: "liveavatar.avsync.alert-evidence",
1137
- sdkVersion: VERSION,
1138
- recordType: "log-chunk",
1139
- evidenceId,
1140
- alertId,
1141
- sessionId,
1142
- chunk: {
1143
- index,
1144
- total,
1145
- byteLength: utf8JsonByteLength(logs),
1146
- recordCount: logs.length,
1147
- firstSequence: logs[0]?.q ?? null,
1148
- lastSequence: logs[logs.length - 1]?.q ?? null,
1149
- logs,
1150
- },
1151
- };
1152
- }
1153
- function createSummaryPayload(evidenceId, alert, evidence, logChunkCount) {
1154
- const summaryEvidence = withoutPreparedLogs(evidence, logChunkCount);
1155
- const payload = {
1156
- schemaVersion: 1,
1157
- kind: "liveavatar.avsync.alert-evidence",
1158
- sdkVersion: VERSION,
1159
- recordType: "summary",
1160
- evidenceId,
1161
- alert,
1162
- evidence: summaryEvidence,
1163
- };
1164
- if (utf8JsonByteLength(payload) <= EVIDENCE_CONTENT_BYTE_LIMIT)
1165
- return payload;
1166
- const compactPayload = {
1167
- ...payload,
1168
- summaryTruncated: true,
1169
- alert: compactAlertForSummary(alert),
1170
- evidence: {
1171
- ...summaryEvidence,
1172
- retention: null,
1173
- triage: {
1174
- trigger: summaryEvidence.triage?.trigger ?? {
1175
- finding: alert.finding,
1176
- status: alert.status,
1177
- confidence: alert.confidence,
1178
- capturedAtMs: alert.capturedAtMs,
1179
- },
1180
- evaluation: null,
1181
- layers: null,
1182
- participants: [],
1183
- limitations: ["summary-truncated"],
1184
- },
1185
- detail: {
1186
- projectionVersion: summaryEvidence.detail.projectionVersion,
1187
- sourceRecordCount: summaryEvidence.detail.sourceRecordCount,
1188
- reportedRecordCount: summaryEvidence.logRecordCount,
1189
- timeSyncInputCount: 0,
1190
- timeSyncReportedCount: 0,
1191
- framePresentationReportedCount: 0,
1192
- verifiedMetadataTimestampCount: 0,
1193
- omittedSetupLifecycleCount: 0,
1194
- oversizeFallbackRecordCount: summaryEvidence.detail.oversizeFallbackRecordCount,
1195
- contentByteLimit: EVIDENCE_CONTENT_BYTE_LIMIT,
1196
- },
1197
- },
1198
- };
1199
- if (utf8JsonByteLength(compactPayload) <= EVIDENCE_CONTENT_BYTE_LIMIT)
1200
- return compactPayload;
1201
- throw new Error("A/V Sync summary exceeds the platform content limit");
1202
- }
1203
- function compactAlertForSummary(alert) {
1204
- return {
1205
- ...alert,
1206
- participantIds: alert.participantIds.slice(0, 32),
1207
- message: truncateUtf8String(alert.message, 1024),
1208
- };
1209
- }
1210
- function truncateUtf8String(value, byteLimit) {
1211
- if (new TextEncoder().encode(value).byteLength <= byteLimit)
1212
- return value;
1213
- let end = value.length;
1214
- while (end > 0) {
1215
- const candidate = `${value.slice(0, end)}…`;
1216
- if (new TextEncoder().encode(candidate).byteLength <= byteLimit)
1217
- return candidate;
1218
- end -= 1;
1219
- }
1220
- return "";
1221
- }
1222
- function withoutPreparedLogs(evidence, logChunkCount) {
1223
- const { logs: _logs, detail, ...rest } = evidence;
1224
- const { chunks: _chunks, ...summaryDetail } = detail;
1225
- const summary = Object.fromEntries(Object.entries(rest).filter(([key]) => !/^logs_\d+$/.test(key)));
1226
- return {
1227
- ...summary,
1228
- logChunkCount,
1229
- detail: summaryDetail,
1230
- };
1231
- }
1232
- function decodeAsciiDecimalBase64(value) {
1233
- if (value === null)
1234
- return null;
1235
- try {
1236
- const decoded = atob(value);
1237
- if (!/^\d{16}$/.test(decoded))
1238
- return null;
1239
- const parsed = Number(decoded);
1240
- return Number.isSafeInteger(parsed) ? decoded : null;
1241
- }
1242
- catch {
1243
- return null;
1244
- }
1245
- }
1246
- function utf8JsonByteLength(value) {
1247
- return new TextEncoder().encode(JSON.stringify(value)).byteLength;
889
+ function createSkyWalkingPlugin(config = {}) {
890
+ return new SkyWalkingPlugin(config);
1248
891
  }
1249
- function toRecord(value) {
892
+ function object(value) {
1250
893
  return value !== null && typeof value === "object" && !Array.isArray(value)
1251
894
  ? value
1252
895
  : {};
1253
896
  }
1254
- function pick(source, keys) {
1255
- const result = {};
1256
- for (const key of keys) {
1257
- if (source[key] !== undefined && source[key] !== null)
1258
- result[key] = source[key];
1259
- }
1260
- return result;
1261
- }
1262
- function removeUndefined(value) {
1263
- return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
1264
- }
1265
- function numberOr(value, fallback) {
1266
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
1267
- }
1268
- function stringOr(value, fallback) {
1269
- return typeof value === "string" ? value : fallback;
1270
- }
1271
- function compareSourceLogs(left, right) {
1272
- return left.sequence - right.sequence;
1273
- }
1274
- function compareCompactLogs(left, right) {
1275
- return left.q - right.q || left.o - right.o;
1276
- }
1277
- function toJsonSafeAlert(alert) {
1278
- return {
1279
- ...alert,
1280
- sessionId: alert.sessionId ?? null,
1281
- participantIds: [...alert.participantIds],
1282
- features: { ...alert.features },
1283
- };
1284
- }
1285
- /**
1286
- * Strictly projects the published first-frame Operational Log. The SDK record
1287
- * has additional identifiers and arbitrary attributes; none of those can
1288
- * reach SkyWalking through this path.
1289
- */
1290
897
  function toSkyWalkingFirstFrameLogPayload(record) {
1291
- const correlation = toRecord(record.correlation);
1292
- const attributes = toRecord(record.attributes);
898
+ const correlation = object(record.correlation);
899
+ const attributes = object(record.data);
1293
900
  const attemptId = correlation.attemptId;
1294
901
  const outcome = attributes.outcome;
1295
902
  if (!isNonNegativeNumber(record.occurredAtMs) ||
@@ -1297,7 +904,7 @@ function toSkyWalkingFirstFrameLogPayload(record) {
1297
904
  !isFirstFrameOutcome(outcome)) {
1298
905
  return undefined;
1299
906
  }
1300
- const sourceNodes = toRecord(attributes.nodes);
907
+ const sourceNodes = object(attributes.nodes);
1301
908
  const nodes = {};
1302
909
  copyNonNegativeNumber(sourceNodes, "configReadyMs", nodes);
1303
910
  copyNonNegativeNumber(sourceNodes, "rtcConnectedMs", nodes);
@@ -1305,10 +912,9 @@ function toSkyWalkingFirstFrameLogPayload(record) {
1305
912
  copyNonNegativeNumber(sourceNodes, "videoMetadataMs", nodes);
1306
913
  copyNonNegativeNumber(sourceNodes, "firstFrameMs", nodes);
1307
914
  return {
1308
- schemaVersion: 1,
915
+ schemaVersion: 4,
1309
916
  kind: "liveavatar.performance.first-frame",
1310
- sdkVersion: VERSION,
1311
- occurredAtMs: record.occurredAtMs,
917
+ ...operationalSource(record),
1312
918
  attemptId,
1313
919
  outcome,
1314
920
  ...(typeof attributes.renderMode === "string"
@@ -1336,18 +942,6 @@ function isPositiveInteger(value) {
1336
942
  function isNonNegativeNumber(value) {
1337
943
  return typeof value === "number" && Number.isFinite(value) && value >= 0;
1338
944
  }
1339
- function stringifyJson(value) {
1340
- const serialized = JSON.stringify(value);
1341
- if (serialized === undefined) {
1342
- throw new Error("LiveAvatar SkyWalking payload serialization failed");
1343
- }
1344
- return serialized;
1345
- }
1346
- /**
1347
- * Loads the bundled browser client when needed and registers it exactly once.
1348
- * An application-provided `window.ClientMonitor` is treated as already
1349
- * registered and is never overwritten or registered again.
1350
- */
1351
945
  function registerSkyWalking(config = {}) {
1352
946
  if (typeof window === "undefined") {
1353
947
  warnOnce("register-unavailable", "[LiveAvatar SkyWalking plugin] SkyWalking registration requires a browser window");
@@ -1413,12 +1007,18 @@ async function reportSkyWalkingFrameErrors(config, error) {
1413
1007
  function normalizeReportingConfig(config) {
1414
1008
  return {
1415
1009
  sdkError: config?.sdkError ?? true,
1010
+ timeline: config?.timeline ?? true,
1416
1011
  firstFrame: config?.firstFrame ?? true,
1417
1012
  avSync: config?.avSync ?? true,
1013
+ playbackStatus: config?.playbackStatus ?? true,
1418
1014
  };
1419
1015
  }
1420
1016
  function hasEnabledReporting(config) {
1421
- return config.sdkError || config.firstFrame || config.avSync;
1017
+ return (config.sdkError ||
1018
+ config.firstFrame ||
1019
+ config.avSync ||
1020
+ config.timeline ||
1021
+ config.playbackStatus);
1422
1022
  }
1423
1023
  function normalizeSkyWalkingConfig(config) {
1424
1024
  return {
@@ -1445,7 +1045,7 @@ function normalizeSkyWalkingConfig(config) {
1445
1045
  extraMsg: config.extraMsg,
1446
1046
  hooks: { ...config.hooks },
1447
1047
  pagePath: config.pagePath ?? "",
1448
- serviceVersion: config.serviceVersion ?? "",
1048
+ serviceVersion: VERSION,
1449
1049
  pageKey: config.pageKey ?? "",
1450
1050
  group: config.group ?? "unknown",
1451
1051
  subGroup: config.subGroup ?? "unknown",