o11y 238.3.0 → 238.6.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/modules/o11y/client/client.js +1723 -1
- package/dist/modules/o11y/client/client.js.map +1 -1
- package/dist/modules/o11y/client/collectors/core-collector/CoreEnvelopeBuilder.d.ts +4 -1
- package/dist/modules/o11y/client/collectors/core-collector/interfaces/CoreEnvelopeContents.d.ts +2 -0
- package/dist/modules/o11y/client/collectors/core-collector/interfaces/CoreEnvelopeDiagnostics.d.ts +1 -0
- package/dist/modules/o11y/client/collectors/metrics/BucketHistogram.d.ts +11 -0
- package/dist/modules/o11y/client/collectors/metrics/Metrics.d.ts +2 -0
- package/dist/modules/o11y/client/interfaces/BucketHistogram.d.ts +3 -0
- package/dist/modules/o11y/client/interfaces/BucketMetric.d.ts +4 -0
- package/dist/modules/o11y/client/interfaces/Instrumentation.d.ts +1 -0
- package/dist/modules/o11y/client/interfaces/InstrumentedAppMethods.d.ts +5 -4
- package/dist/modules/o11y/client/interfaces/MetricsExtractorMethods.d.ts +2 -0
- package/dist/modules/o11y/client/interfaces/MetricsReporter.d.ts +2 -0
- package/dist/modules/o11y/client/interfaces/index.d.ts +2 -0
- package/dist/modules/o11y/client/library/ActivityImpl.d.ts +1 -1
- package/dist/modules/o11y/client/library/BucketHistogramImpl.d.ts +26 -0
- package/dist/modules/o11y/client/library/InstrumentationImpl.d.ts +4 -3
- package/dist/modules/o11y/client/library/MetricsImpl.d.ts +5 -0
- package/dist/modules/o11y/client/library/NextgenImpl.d.ts +1 -0
- package/dist/modules/o11y/client/{library → shared}/PublicSafety.d.ts +0 -0
- package/dist/modules/o11y/client/shared/index.d.ts +2 -1
- package/dist/modules/o11y/client/web_vitals/WebVitals.d.ts +19 -0
- package/dist/modules/o11y/client/web_vitals.d.ts +1 -0
- package/dist/modules/o11y/collectors/collectors/core-collector/CoreEnvelopeBuilder.d.ts +4 -1
- package/dist/modules/o11y/collectors/collectors/core-collector/interfaces/CoreEnvelopeContents.d.ts +2 -0
- package/dist/modules/o11y/collectors/collectors/core-collector/interfaces/CoreEnvelopeDiagnostics.d.ts +1 -0
- package/dist/modules/o11y/collectors/collectors/metrics/BucketHistogram.d.ts +11 -0
- package/dist/modules/o11y/collectors/collectors/metrics/Metrics.d.ts +2 -0
- package/dist/modules/o11y/collectors/collectors.js +675 -1
- package/dist/modules/o11y/collectors/collectors.js.map +1 -1
- package/dist/modules/o11y/collectors/interfaces/BucketHistogram.d.ts +3 -0
- package/dist/modules/o11y/collectors/interfaces/BucketMetric.d.ts +4 -0
- package/dist/modules/o11y/collectors/interfaces/Instrumentation.d.ts +1 -0
- package/dist/modules/o11y/collectors/interfaces/InstrumentedAppMethods.d.ts +5 -4
- package/dist/modules/o11y/collectors/interfaces/MetricsExtractorMethods.d.ts +2 -0
- package/dist/modules/o11y/collectors/interfaces/MetricsReporter.d.ts +2 -0
- package/dist/modules/o11y/collectors/interfaces/index.d.ts +2 -0
- package/dist/modules/o11y/collectors/library/ActivityImpl.d.ts +1 -1
- package/dist/modules/o11y/collectors/library/BucketHistogramImpl.d.ts +26 -0
- package/dist/modules/o11y/collectors/library/InstrumentationImpl.d.ts +4 -3
- package/dist/modules/o11y/collectors/library/MetricsImpl.d.ts +5 -0
- package/dist/modules/o11y/collectors/library/NextgenImpl.d.ts +1 -0
- package/dist/modules/o11y/collectors/{library → shared}/PublicSafety.d.ts +0 -0
- package/dist/modules/o11y/collectors/shared/index.d.ts +2 -1
- package/dist/modules/o11y/collectors/web_vitals/WebVitals.d.ts +19 -0
- package/dist/modules/o11y/collectors/web_vitals.d.ts +1 -0
- package/dist/modules/o11y/shared/collectors/core-collector/CoreEnvelopeBuilder.d.ts +4 -1
- package/dist/modules/o11y/shared/collectors/core-collector/interfaces/CoreEnvelopeContents.d.ts +2 -0
- package/dist/modules/o11y/shared/collectors/core-collector/interfaces/CoreEnvelopeDiagnostics.d.ts +1 -0
- package/dist/modules/o11y/shared/collectors/metrics/BucketHistogram.d.ts +11 -0
- package/dist/modules/o11y/shared/collectors/metrics/Metrics.d.ts +2 -0
- package/dist/modules/o11y/shared/interfaces/BucketHistogram.d.ts +3 -0
- package/dist/modules/o11y/shared/interfaces/BucketMetric.d.ts +4 -0
- package/dist/modules/o11y/shared/interfaces/Instrumentation.d.ts +1 -0
- package/dist/modules/o11y/shared/interfaces/InstrumentedAppMethods.d.ts +5 -4
- package/dist/modules/o11y/shared/interfaces/MetricsExtractorMethods.d.ts +2 -0
- package/dist/modules/o11y/shared/interfaces/MetricsReporter.d.ts +2 -0
- package/dist/modules/o11y/shared/interfaces/index.d.ts +2 -0
- package/dist/modules/o11y/shared/library/ActivityImpl.d.ts +1 -1
- package/dist/modules/o11y/shared/library/BucketHistogramImpl.d.ts +26 -0
- package/dist/modules/o11y/shared/library/InstrumentationImpl.d.ts +4 -3
- package/dist/modules/o11y/shared/library/MetricsImpl.d.ts +5 -0
- package/dist/modules/o11y/shared/library/NextgenImpl.d.ts +1 -0
- package/dist/modules/o11y/shared/{library → shared}/PublicSafety.d.ts +0 -0
- package/dist/modules/o11y/shared/shared/index.d.ts +2 -1
- package/dist/modules/o11y/shared/shared.js +413 -1
- package/dist/modules/o11y/shared/shared.js.map +1 -1
- package/dist/modules/o11y/shared/web_vitals/WebVitals.d.ts +19 -0
- package/dist/modules/o11y/shared/web_vitals.d.ts +1 -0
- package/dist/modules/o11y/web_vitals/client.d.ts +4 -0
- package/dist/modules/o11y/web_vitals/collectors/EncodedSchematizedPayload.d.ts +4 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/CoreCollector.d.ts +49 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/CoreEnvelopeBuilder.d.ts +22 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/UploadMode.d.ts +5 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/interfaces/CoreCollectorOptions.d.ts +8 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/interfaces/CoreEnvelope.d.ts +10 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/interfaces/CoreEnvelopeContents.d.ts +13 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/interfaces/CoreEnvelopeDiagnostics.d.ts +9 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/interfaces/LogMessage.d.ts +13 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/interfaces/MessageBundle.d.ts +5 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/interfaces/StaticAttributes.d.ts +8 -0
- package/dist/modules/o11y/web_vitals/collectors/core-collector/interfaces/UploadResult.d.ts +6 -0
- package/dist/modules/o11y/web_vitals/collectors/hybrid-collector/HybridCollector.d.ts +15 -0
- package/dist/modules/o11y/web_vitals/collectors/index.d.ts +2 -0
- package/dist/modules/o11y/web_vitals/collectors/metrics/BucketHistogram.d.ts +11 -0
- package/dist/modules/o11y/web_vitals/collectors/metrics/MetricTag.d.ts +4 -0
- package/dist/modules/o11y/web_vitals/collectors/metrics/Metrics.d.ts +8 -0
- package/dist/modules/o11y/web_vitals/collectors/metrics/UpCounter.d.ts +10 -0
- package/dist/modules/o11y/web_vitals/collectors/metrics/ValueRecorder.d.ts +10 -0
- package/dist/modules/o11y/web_vitals/collectors/protobuf-util.d.ts +15 -0
- package/dist/modules/o11y/web_vitals/collectors.d.ts +1 -0
- package/dist/modules/o11y/web_vitals/console-collector/ConsoleCollector.d.ts +7 -0
- package/dist/modules/o11y/web_vitals/index.d.ts +8 -0
- package/dist/modules/o11y/web_vitals/interfaces/Activity.d.ts +16 -0
- package/dist/modules/o11y/web_vitals/interfaces/ActivityDetail.d.ts +17 -0
- package/dist/modules/o11y/web_vitals/interfaces/ApiOptions.d.ts +4 -0
- package/dist/modules/o11y/web_vitals/interfaces/BucketHistogram.d.ts +3 -0
- package/dist/modules/o11y/web_vitals/interfaces/BucketMetric.d.ts +4 -0
- package/dist/modules/o11y/web_vitals/interfaces/BufferedLog.d.ts +8 -0
- package/dist/modules/o11y/web_vitals/interfaces/DomEventApiOptions.d.ts +4 -0
- package/dist/modules/o11y/web_vitals/interfaces/Environment.d.ts +8 -0
- package/dist/modules/o11y/web_vitals/interfaces/IdleDetector.d.ts +18 -0
- package/dist/modules/o11y/web_vitals/interfaces/Instrumentation.d.ts +15 -0
- package/dist/modules/o11y/web_vitals/interfaces/InstrumentationContext.d.ts +4 -0
- package/dist/modules/o11y/web_vitals/interfaces/InstrumentedAppMethods.d.ts +16 -0
- package/dist/modules/o11y/web_vitals/interfaces/InstrumentedAppOptions.d.ts +8 -0
- package/dist/modules/o11y/web_vitals/interfaces/LogCollector.d.ts +7 -0
- package/dist/modules/o11y/web_vitals/interfaces/LogCollectorOptions.d.ts +3 -0
- package/dist/modules/o11y/web_vitals/interfaces/LogMeta.d.ts +11 -0
- package/dist/modules/o11y/web_vitals/interfaces/Metric.d.ts +11 -0
- package/dist/modules/o11y/web_vitals/interfaces/MetricsCollector.d.ts +4 -0
- package/dist/modules/o11y/web_vitals/interfaces/MetricsExtractorMethods.d.ts +7 -0
- package/dist/modules/o11y/web_vitals/interfaces/MetricsReporter.d.ts +7 -0
- package/dist/modules/o11y/web_vitals/interfaces/NetworkInstrumentationOptions.d.ts +9 -0
- package/dist/modules/o11y/web_vitals/interfaces/Nextgen.d.ts +7 -0
- package/dist/modules/o11y/web_vitals/interfaces/PayloadProvider.d.ts +4 -0
- package/dist/modules/o11y/web_vitals/interfaces/RootActivity.d.ts +2 -0
- package/dist/modules/o11y/web_vitals/interfaces/Schema.d.ts +6 -0
- package/dist/modules/o11y/web_vitals/interfaces/SchemaTokens.d.ts +5 -0
- package/dist/modules/o11y/web_vitals/interfaces/SchematizedPayload.d.ts +6 -0
- package/dist/modules/o11y/web_vitals/interfaces/TracingHeadersOptions.d.ts +6 -0
- package/dist/modules/o11y/web_vitals/interfaces/UpCounter.d.ts +3 -0
- package/dist/modules/o11y/web_vitals/interfaces/ValueRecorder.d.ts +3 -0
- package/dist/modules/o11y/web_vitals/interfaces/index.d.ts +31 -0
- package/dist/modules/o11y/web_vitals/interfaces/pbjs.d.ts +68 -0
- package/dist/modules/o11y/web_vitals/interfaces-private/ActivityData.d.ts +13 -0
- package/dist/modules/o11y/web_vitals/interfaces-private/ErrorData.d.ts +9 -0
- package/dist/modules/o11y/web_vitals/interfaces-private/InstrumentedEventData.d.ts +11 -0
- package/dist/modules/o11y/web_vitals/interfaces-private/MouseEventData.d.ts +28 -0
- package/dist/modules/o11y/web_vitals/interfaces-private/index.d.ts +4 -0
- package/dist/modules/o11y/web_vitals/library/ActivityImpl.d.ts +43 -0
- package/dist/modules/o11y/web_vitals/library/ActivityNoOp.d.ts +16 -0
- package/dist/modules/o11y/web_vitals/library/AppInstrumentationImpl.d.ts +17 -0
- package/dist/modules/o11y/web_vitals/library/AutomaticClickTracker.d.ts +14 -0
- package/dist/modules/o11y/web_vitals/library/BucketHistogramImpl.d.ts +26 -0
- package/dist/modules/o11y/web_vitals/library/DomEventHelpers.d.ts +8 -0
- package/dist/modules/o11y/web_vitals/library/IdleDetectorImpl.d.ts +19 -0
- package/dist/modules/o11y/web_vitals/library/InstrumentationImpl.d.ts +41 -0
- package/dist/modules/o11y/web_vitals/library/LogValidator.d.ts +11 -0
- package/dist/modules/o11y/web_vitals/library/MetricsImpl.d.ts +24 -0
- package/dist/modules/o11y/web_vitals/library/MockEvent.d.ts +7 -0
- package/dist/modules/o11y/web_vitals/library/NextgenImpl.d.ts +40 -0
- package/dist/modules/o11y/web_vitals/library/RootActivityImpl.d.ts +11 -0
- package/dist/modules/o11y/web_vitals/library/RootActivityNoOp.d.ts +16 -0
- package/dist/modules/o11y/web_vitals/library/SizeLimitedMap.d.ts +11 -0
- package/dist/modules/o11y/web_vitals/library/TaskerImpl.d.ts +13 -0
- package/dist/modules/o11y/web_vitals/library/Tracing.d.ts +19 -0
- package/dist/modules/o11y/web_vitals/library/UpCounterImpl.d.ts +22 -0
- package/dist/modules/o11y/web_vitals/library/ValueRecorderImpl.d.ts +23 -0
- package/dist/modules/o11y/web_vitals/shared/LazyMapToList.d.ts +13 -0
- package/dist/modules/o11y/web_vitals/shared/PublicSafety.d.ts +9 -0
- package/dist/modules/o11y/web_vitals/shared/SchemaUtil.d.ts +14 -0
- package/dist/modules/o11y/web_vitals/shared/TypeDefinitions.d.ts +22 -0
- package/dist/modules/o11y/web_vitals/shared/Utility.d.ts +29 -0
- package/dist/modules/o11y/web_vitals/shared/index.d.ts +5 -0
- package/dist/modules/o11y/web_vitals/shared.d.ts +1 -0
- package/dist/modules/o11y/web_vitals/types/TypeDefinitions-Private.d.ts +2 -0
- package/dist/modules/o11y/web_vitals/web_vitals/WebVitals.d.ts +19 -0
- package/dist/modules/o11y/web_vitals/web_vitals.d.ts +1 -0
- package/dist/modules/o11y/web_vitals/web_vitals.js +56 -0
- package/dist/modules/o11y/web_vitals/web_vitals.js.map +1 -0
- package/package.json +7 -8
|
@@ -1,2 +1,1724 @@
|
|
|
1
|
-
import{utility as t,schemaUtil as e}from"o11y/shared";class PublicSafety{constructor(t){this._errorCounter=t,this._safeCatchMode=!1}tryCatch(t){try{t()}catch(t){this._prodSafeCatch(t)}}tryCatchReturn(e,r){try{return t.requireArgument(r,"noopValue"),e()}catch(t){return this._prodSafeCatch(t),r}}_prodSafeCatch(e){let r;try{if(r=!t.isProduction,r)throw e;if(this._safeCatchMode)throw this._safeCatchMode=!1,new Error("Internal error in prodSafeCatch.");if(this._safeCatchMode=!0,this._errorCounter&&this._errorCounter.increment(),!(e instanceof Error)){const t=e&&e.message||("function"==typeof e.toString?e.toString():"");e=new Error(t)}this._safeCatchMode=!1}catch(t){if(r)throw t;if(t&&console&&"function"==typeof console.error)try{console.error(t)}catch(t){}this._safeCatchMode=!1}}}class Tracing{constructor(e){this.instr=e,t.requireArgument(e,"instr","object")}static _getB3CompactFormat(t,e,r,i){let s=`${t}-${e}`;return void 0===r&&void 0===i||(s+=r?"-1":"-0",void 0!==i&&(s+=`-${i}`)),s}static _getW3CompactFormat(t,e,r){return`00-${t}-${e}-${r?"01":"00"}`}static _conformTextAsId(t,e){const r=(t=t.toLowerCase()).length;for(let e=0;e<r;e+=1){const r=t[e];if(!(r>="a"&&r<="f"||r>="0"&&r<="9"))throw new Error(`The text '${t}' has an invalid character at index #${e}`)}return r>e?t.substr(r-e):r<e?t.padStart(e,"0"):t}static getHeaders(e,r,i,s){t.requireArgument(e,"traceId","string"),t.requireArgument(r,"spanId","string");const n=s&&s.useB3Headers;e=this._conformTextAsId(e,s&&void 0!==s.traceIdEffectiveLength?s.traceIdEffectiveLength:n?16:32),r=this._conformTextAsId(r,16);const o=s&&void 0!==s.parentSpanId&&this._conformTextAsId(s.parentSpanId,16)||void 0,a={};if(n){s&&s.useCompactHeader?a.b3=this._getB3CompactFormat(e,r,i,o):(a["X-B3-TraceId"]=e,a["X-B3-SpanId"]=r,void 0!==o&&(a["X-B3-ParentSpanId"]=o),void 0!==i&&(a["X-B3-Sampled"]=i?"1":"0"))}else a.traceparent=this._getW3CompactFormat(e,r,i);return a}_disableNetworkInstrumentation(){Tracing._isNetworkInstrumentationEnabled&&(Tracing._originalFetch&&(Tracing._global.fetch=Tracing._originalFetch,Tracing._originalFetch=void 0),Tracing._originalXhr&&(Tracing._global.XMLHttpRequest=Tracing._originalXhr,Tracing._originalXhr=void 0),Tracing._originalXhrSend&&(Tracing._global.XMLHttpRequest.prototype.send=Tracing._originalXhrSend,Tracing._originalXhrSend=void 0),Tracing._isNetworkInstrumentationEnabled=!1)}_enableNetworkInstrumentation(t,e,r,i,s){"function"==typeof Tracing._global.fetch&&(this._overrideFetch(t,e,r,i,s),Tracing._isNetworkInstrumentationEnabled=!0),"function"==typeof Tracing._global.XMLHttpRequest&&(this._overrideXhr(t,e,r,i,s),Tracing._isNetworkInstrumentationEnabled=!0)}_overrideFetch(t,e,r,i,s){Tracing._originalFetch=Tracing._global.fetch;Tracing._global.fetch=async(n,o,...a)=>{let c;try{if(c=t.startActivity(r||"fetch"),i){o=o||{};const t=c.getTraceHeaders(s);o.headers=Object.assign(o.headers||{},t)}return await Tracing._originalFetch.call(Tracing._global,n,o,...a)}catch(r){throw e&&(c?c.error(r):t.error(r)),r}finally{c&&c.stop()}}}_overrideXhr(t,e,r,i,s){Tracing._originalXhr=Tracing._global.XMLHttpRequest,Tracing._originalXhrSend=Tracing._originalXhr.prototype.send,Tracing._originalXhr.prototype.send=function(...n){let o;const a=this;try{if(a._o11yActivity=o=t.startActivity(r||"xhr_send"),i){const t=o.getTraceHeaders(s);Object.entries(t).forEach((t=>{a.setRequestHeader(t[0],t[1])}))}Tracing._originalXhrSend.call(this,...n)}catch(r){throw e&&(o?o.error(r):t.error(r)),o&&o.stop(),r}};const n=new Proxy(Tracing._originalXhr,{construct(r){const i=new r;return i.addEventListener("load",(()=>{const t=i._o11yActivity;t&&t.stop()})),i.addEventListener("error",(r=>{const s=new Error("XHR Network-Level Error"),n=i._o11yActivity;n?(e&&n.error(s),n.stop()):e&&t.error(s)})),i.addEventListener("abort",(()=>{const t=i._o11yActivity;t&&t.discard()})),i}});Tracing._global.XMLHttpRequest=n}networkInstrumentation(e){if(t.requireArgument(e,"options",["boolean","object"]),e){this._disableNetworkInstrumentation();const r="object"==typeof e?e:{};this._enableNetworkInstrumentation(t.definedValueOrDefault(r.instrumentation,this.instr),t.definedValueOrDefault(r.logErrors,!0),r.activityName,t.definedValueOrDefault(r.useTracing,!0),r.tracingHeadersOptions)}else this._disableNetworkInstrumentation()}}Tracing._global=t.getGlobal(),Tracing._isNetworkInstrumentationEnabled=!1;const r="timedout",i="terminated",s="discarded";class ActivityImpl{constructor(e,i,s,n,o,a,c){this._name=e,this._rootId=i,this._onStopped=s,this._onError=n,this._isSampled=c,this._errorCount=0;const{tsNow:l,perfNow:d}=t.time();if(ActivityImpl._count+=1,this._id=a||t.generateUniqueId(),this._usePerf="undefined"!=typeof performance&&"function"==typeof performance.mark&&"function"==typeof performance.measure,this._usePerf){this._perfName=`${this._name}__${ActivityImpl._count}`,this._perfId=`${this._name}__${this.id}`;try{performance.mark(this._perfId)}catch(t){this._usePerf=!1}}this._startTimestamp=l,this._startPerfTime=d,o>0&&(this._timer=setTimeout((()=>{this._stopReason=this._stopReason||r,this.stop()}),o)),this._safety=new PublicSafety}get id(){return this._id}getId(){return this.id}getRootId(){return this._rootId}get stopReason(){return this._stopReason}error(t,e,r){this._safety.tryCatch((()=>{this._errorCount+=1,"string"==typeof t&&(t=new Error(t)),this._onError(t,this._getDetail(e,r))}))}stop(t,e){this._safety.tryCatch((()=>this._stopInternal(t,e)))}_stopInternal(e,r){const i=t.perfNow();if(this._usePerf)try{performance.measure(this._perfName,this._perfId),performance.clearMarks(this._perfId),performance.clearMeasures(this._perfName)}catch(t){}if(this._timer&&(clearTimeout(this._timer),this._timer=void 0),this.isStopped)return;this._stopPerfTime=i;const s=this._getDetail(e,r);this._onStopped(s)}get isStopped(){return void 0!==this._stopPerfTime}discard(){this._safety.tryCatch((()=>{this._stopReason=this._stopReason||s,this.stop()}))}terminate(){this._safety.tryCatch((()=>{this._stopReason=this._stopReason||i,this.stop()}))}getIsSampled(){return this._isSampled||!1}_getDetail(t,e){return{id:this._id,rootId:this._rootId,name:this._name,userSchemaOrText:t,userData:e,stopReason:this._stopReason,startTimestamp:this._startTimestamp,startPerfTime:this._startPerfTime,stopPerfTime:this._stopPerfTime,errorCount:this._errorCount,isSampled:this.getIsSampled()}}getTraceHeaders(t){const e=this.id,r=this._rootId||e;return Tracing.getHeaders(r,e,this.getIsSampled(),t)}getStartTimestamp(){return this._startTimestamp}getStartPerfTime(){return this._startPerfTime}getStopPerfTime(){return this._stopPerfTime}}ActivityImpl._count=0;const n={namespace:"sf.instrumentation",name:"Activity",pbjsSchema:{nested:{sf:{nested:{instrumentation:{nested:{Activity:{reserved:[[5,5],[7,7]],fields:{duration:{options:{},id:3,type:"double"},stopReason:{options:{},id:6,type:"string"},isRoot:{options:{},id:8,type:"bool"},name:{options:{"(meta.max_length)":25},id:2,type:"string"},isSampled:{options:{},id:11,type:"bool"},preRootId:{options:{},id:9,type:"string"},id:{options:{},id:1,type:"string"},userPayload:{options:{},id:4,type:"Payload"},errorCount:{options:{},id:10,type:"uint32"}}},Payload:{fields:{payload:{options:{},id:2,type:"bytes"},schemaName:{options:{},id:1,type:"string"}}}}}}}}}},o={namespace:"sf.instrumentation",name:"Error",pbjsSchema:{nested:{sf:{nested:{instrumentation:{nested:{Error:{reserved:[[5,5],[7,7]],fields:{activityId:{options:{},id:6,type:"string"},stack:{options:{},id:3,type:"string"},name:{options:{},id:1,type:"string"},message:{options:{"(meta.max_length)":200},id:2,type:"string"},userPayload:{options:{},id:4,type:"Payload"}}},Payload:{fields:{payload:{options:{},id:2,type:"bytes"},schemaName:{options:{},id:1,type:"string"}}}}}}}}}},a={namespace:"sf.instrumentation",name:"InstrumentedEvent",pbjsSchema:{nested:{sf:{nested:{instrumentation:{nested:{MouseEvent:{fields:{cancelable:{options:{},id:5,type:"bool"},ctrlKey:{options:{},id:9,type:"bool"},type:{options:{},id:25,type:"string"},button:{options:{},id:3,type:"uint32"},offsetX:{options:{},id:17,type:"uint32"},eventPhase:{options:{},id:12,type:"uint32"},shiftKey:{options:{},id:23,type:"bool"},offsetY:{options:{},id:18,type:"uint32"},composed:{options:{},id:8,type:"bool"},altKey:{options:{},id:1,type:"bool"},isTrusted:{options:{},id:13,type:"bool"},buttons:{options:{},id:4,type:"uint32"},movementY:{options:{},id:16,type:"uint32"},clientY:{options:{},id:7,type:"uint32"},clientX:{options:{},id:6,type:"uint32"},movementX:{options:{},id:15,type:"uint32"},defaultPrevented:{options:{},id:10,type:"bool"},metaKey:{options:{},id:14,type:"bool"},timeStamp:{options:{},id:24,type:"double"},bubbles:{options:{},id:2,type:"bool"},detail:{options:{},id:11,type:"int64"},pageY:{options:{},id:20,type:"uint32"},pageX:{options:{},id:19,type:"uint32"},screenX:{options:{},id:21,type:"uint32"},screenY:{options:{},id:22,type:"uint32"}}},InstrumentedEvent:{oneofs:{event:{oneof:["mouseEvent"]}},reserved:[[4,4],"xpath",[6,6],[8,8]],fields:{mouseEvent:{options:{},id:7,type:"MouseEvent"},auto:{options:{},id:3,type:"bool"},parentComponent:{options:{},id:2,type:"string"},ownerComponent:{options:{},id:1,type:"string"},userPayload:{options:{},id:5,type:"Payload"},simplePath:{options:{},id:9,type:"string"}}},Payload:{fields:{payload:{options:{},id:2,type:"bytes"},schemaName:{options:{},id:1,type:"string"}}}}}}}}}},c={namespace:"sf.instrumentation",name:"Simple",pbjsSchema:{nested:{sf:{nested:{instrumentation:{nested:{Simple:{options:{"(meta.msg.desc)":"This message is used internally to allow convenient logging of simple text via the API without requiring a schema."},fields:{text:{options:{"(meta.max_length)":25},id:1,type:"string"}}}}}}}}}},l=new Array(16).fill(0).join("");const d=Object.freeze(new class{getId(){return l}getRootId(){}error(){}stop(){}discard(){}terminate(){}getIsSampled(){return!1}getTraceHeaders(t){return{}}getStartTimestamp(){}getStartPerfTime(){}getStopPerfTime(){}});const h=new class{getInstrumentedEventData(r,i,s){const n={ownerComponent:i.tagName,parentComponent:i.parentElement&&i.parentElement.tagName||void 0,event:r,simplePath:t.getXpath(i)};return s&&(n.userPayload=e.makePayload(s.schema,s.payload,!0)),n}getMouseEventData(t){return{altKey:t.altKey,bubbles:t.bubbles,button:t.button,buttons:t.buttons,cancelable:t.cancelable,clientX:t.clientX,clientY:t.clientY,composed:t.composed,defaultPrevented:t.defaultPrevented,detail:t.detail,eventPhase:t.eventPhase,isTrusted:t.isTrusted,timeStamp:t.timeStamp,type:t.type,ctrlKey:t.ctrlKey,metaKey:t.metaKey,movementX:t.movementX,movementY:t.movementY,offsetX:t.offsetX,offsetY:t.offsetY,pageX:t.pageX,pageY:t.pageY,screenX:t.screenX,screenY:t.screenY,shiftKey:t.shiftKey}}};const u=new class{validate(r,i){const s=e.checkSchema(r);t.requireArgument(i,"data","object");const n=e.getTypes(r),o=this.validateFields(i,n[s.message],n,e.getSchemaId(r));if(o)throw new Error(o)}validateFields(t,e,r,i){const s=e.oneofs||{},n=e.fields||{};let o;for(const e in t){const a=t[e];if(this.isNullOrUndefinedOrEmpty(a)||(s[e]?o=this.matchFieldTypes(a,s[e].oneof[0],r,i,e):n[e]&&(o=this.matchFieldTypes(a,n[e].type,r,i,e,n[e].rule))),o)return o}}isNullOrUndefinedOrEmpty(t){return null==t||""===t}matchFieldTypes(t,e,r,i,s,n){let o,a;if("repeated"===n){let n;if(Array.isArray(t)){for(const o in t)if(n=this.matchFieldTypes(t[o],e,r,i,s),n)break}else n=`Schema ${i} on field: ${s}, repeated field should be an array`;return n}switch(e){case"string":o="string";break;case"bytes":o="object",t instanceof Uint8Array||(a=`Schema ${i} on field: ${s}, bytes array is malformed`);break;case"bool":o="boolean";break;case"uint32":o="number",a=this.checkNumberRange(t,4294967295,0,i,s);break;case"int32":case"sint32":case"fixed32":case"sfixed32":o="number",a=this.checkNumberRange(t,2147483647,-2147483648,i,s);break;case"uint64":o="number",a=this.checkNumberRange(t,0x10000000000000000,0,i,s);break;case"fixed64":case"sfixed64":case"int64":case"sint64":o="number",a=this.checkNumberRange(t,0x8000000000000000,-0x8000000000000000,i,s);break;case"double":case"float":o="number",Number.isFinite(t)||(a=`Schema ${i} on field: ${s}. Value must be finite`);break;default:const n={},c=Object.keys(r);for(const t in c)n[c[t].toLowerCase()]=c[t];n[e.toLowerCase()]&&(a=this.validateFields(t,r[n[e.toLowerCase()]],r,i),o="object")}const c=(t+"").length;return typeof t!==o?`Schema ${i} on field: ${s}. Expected type ${e} but received type ${typeof t}`:c<0||c>1e4?`Schema ${i} on field: ${s}, exceeded maximum or minimum field length`:a||void 0}checkNumberRange(t,e,r,i,s){if(t>e||t<r)return`Schema ${i} on field: ${s}, number value is too large or small`}};class UpCounterImpl{constructor(e,r,i,s){this._name=e,this._ownerName=r,this._ownerAppName=i,this._tags=s,this._value=0,this._createdOn=t.time().tsNow}getName(){return this._name}getCreatedOn(){return this._createdOn}getLastUpdatedOn(){return this._lastUpdatedOn}getData(){return this._value}increment(e=1){if("number"==typeof e&&e>0)return this._value+=Math.round(e),void(this._lastUpdatedOn=t.time().tsNow);throw new Error("UpCounter can only increment positive numbers.")}reset(){this._lastUpdatedOn=void 0,this._value=0}getOwnerName(){return this._ownerName}getOwnerAppName(){return this._ownerAppName}getTags(){return this._tags}}class ValueRecorderImpl{constructor(e,r,i,s){this._name=e,this._ownerName=r,this._ownerAppName=i,this._tags=s,this._values=new Array,this._createdOn=t.time().tsNow}getName(){return this._name}getCreatedOn(){return this._createdOn}getLastUpdatedOn(){return this._lastUpdatedOn}getData(){return this.values}get values(){return this._values.slice(0,this._values.length)}record(e){if("number"==typeof e)return this._values.push(e),void(this._lastUpdatedOn=t.time().tsNow);throw new Error("ValueRecorder can only record numbers.")}reset(){this._lastUpdatedOn=void 0,this._values=[]}getOwnerName(){return this._ownerName}getOwnerAppName(){return this._ownerAppName}getTags(){return this._tags}}class SizeLimitedMap{constructor(t){if(this._map=new Map,!("number"==typeof t&&t>0))throw new Error("maxSize must be a positive number");this._maxSize=Math.ceil(t)}get maxSize(){return this._maxSize}get(t){return this._map.get(t)}has(t){return this._map.has(t)}set(t,e){return!!(this.has(t)||this._map.size<this.maxSize)&&(this._map.set(t,e),!0)}getElements(){return Array.from(this._map.values())}clear(){this._map.clear()}}var p;!function(t){t[t.Counter=0]="Counter",t[t.Percentile=1]="Percentile"}(p||(p={}));class MetricsImpl{constructor(t,e){this._ownerName=t,this._getOwnerAppName=e,this._upCounters=new SizeLimitedMap(1e3),this._valueRecorders=new SizeLimitedMap(500)}incrementCounter(t,e,r=!1,i={}){this._tagError(i,r),this._upCounter(t,i).increment(e)}trackValue(t,e,r=!1,i={}){this._tagError(i,r),this._valueRecorder(t,i).record(e)}_upCounter(t,e){const{key:r,sortedTags:i}=this._getKeyAndSortedTags(t,e,p.Counter);let s=this._upCounters.get(r);if(!s&&(s=new UpCounterImpl(t,this._ownerName,this._getOwnerAppName(),i),!this._upCounters.set(r,s)))throw new Error("Max size of 1000 exceeeded for UpCounters");return s}_valueRecorder(t,e){const{key:r,sortedTags:i}=this._getKeyAndSortedTags(t,e,p.Percentile);let s=this._valueRecorders.get(r);if(!s&&(s=new ValueRecorderImpl(t,this._ownerName,this._getOwnerAppName(),i),!this._valueRecorders.set(r,s)))throw new Error("Max size of 500 exceeeded for ValueRecorders");return s}getUpCounters(){return this._upCounters.getElements()}getValueRecorders(){return this._valueRecorders.getElements()}_tagError(t,e){t.status=!0===e?"error":"success"}_getKeyAndSortedTags(t,e,r){const i=Object.keys(e).sort().reduce(((t,r)=>(t[r]=e[r],t)),{});return{key:`${p[r]}:${t}${JSON.stringify(i)}`,sortedTags:i}}}class MockEvent{constructor(t,e,r){this.type=t,this.composed=e,this._composedPaths=r}composedPath(){return this._composedPaths}}const m=["`"],g={internalError:"o11y-error"},_=Object.freeze(Array.from(Object.values(g)));class InstrumentationImpl{constructor(t,r){this._nextGen=t,this._name=r,this._onActivityStoppedCallback=this._handleActivityStop.bind(this),this._onActivityErrorCallback=this._handleActivityError.bind(this);for(const t of m)if(this._name.indexOf(t)>=0)throw new Error(`Name cannot include the reserved character "${t}"`);this._safety=new PublicSafety({increment:t=>this._incrementError(t)}),this._metrics=this._initMetrics();const i=e.getOptions(c,"Simple","text");this._simpleTextMaxLength=i?i["(meta.max_length)"]:Number.MAX_VALUE}_initMetrics(){return new MetricsImpl(this.name,(()=>this._nextGen.appName||InstrumentationImpl.defaultAppName))}_incrementError(t=1){this._metrics.incrementCounter(g.internalError,t,!1)}get name(){return this._name}_wrapUserPayload(t,r,i=!1){let s;return"string"==typeof t?(s=c,r=t?{text:t.substr(0,this._simpleTextMaxLength)}:void 0):s=t,e.makePayload(s,r,i)}getEffectiveRootId(t){var e,r;return null!==(r=null===(e=null==t?void 0:t.instrumentationContext)||void 0===e?void 0:e.rootId)&&void 0!==r?r:this._nextGen.getDefaultInstrumentationContext().rootId}log(e,r,i){this._safety.tryCatch((()=>{const s=t.time().tsNow;t.requireArgument(e,"userSchemaOrText",["object","string"]),t.requireArgumentIfDefined(r,"userData","object"),t.requireArgumentIfDefined(i,"options","object");const n=this._wrapUserPayload(e,r);(null==n?void 0:n.payload)&&this._logInternal(this.name,n.schema,n.payload,s,this.getEffectiveRootId(i))}))}_logInternal(t,e,r,i,s){this._checkInputs(e,r);const n=this._getPayloadFromProvider(this._nextGen.appPayloadProvider),o=this._getPayloadFromProvider(this._nextGen.pagePayloadProvider);return this._nextGen.addLog(t,e,r,i,s,o,n)}error(e,r,i,s){return this._safety.tryCatch((()=>{t.requireArgumentIfDefined(r,"userSchemaOrText",["object","string"]),t.requireArgumentIfDefined(i,"userData","object"),t.requireArgumentIfDefined(s,"options","object");const n=this.getEffectiveRootId(s);this._errorInternal(e,r,i,void 0,n)}))}_errorInternal(e,r,i,s,n){const a=t.time().tsNow;let c;if(e instanceof Error)c=e;else{let t;t=null==e||"function"!=typeof e.toString?"UNKNOWN":e.toString(),c=new Error(t)}const l=this._wrapUserPayload(r,i,!0),d={name:c.name,message:c.message,stack:c.stack,userPayload:l,activityId:s};return this._logInternal(this.name,o,d,a,n)}startActivity(e,r){return this._safety.tryCatchReturn((()=>{var i;let s;t.requireArgument(e,"name"),t.requireArgumentIfDefined(r,"options","object");const n=null===(i=null==r?void 0:r.instrumentationContext)||void 0===i?void 0:i.rootId;s=n?{rootId:n,isRootActivitySampled:r.instrumentationContext.isRootActivitySampled}:this._nextGen.getDefaultInstrumentationContext();return new ActivityImpl(e,s.rootId,this._onActivityStoppedCallback,this._onActivityErrorCallback,undefined,void 0,s.isRootActivitySampled)}),d)}_getActivityData(t){const e=this._wrapUserPayload(t.userSchemaOrText,t.userData,!0);return{id:t.id,name:t.name,duration:t.stopPerfTime-t.startPerfTime,stopReason:t.stopReason,userPayload:e,errorCount:t.errorCount,isSampled:t.isSampled}}_handleActivityStop(t){if("discarded"===t.stopReason)return;const e=this._getActivityData(t);this._logActivity(e,t.startTimestamp,t.rootId)}_logActivity(t,e,r){this._logInternal(this.name,n,t,e,r)}_handleActivityError(t,e){this._errorInternal(t,e.userSchemaOrText,e.userData,e.id,e.rootId)}_getPayloadFromProvider(t){const e=(null==t?void 0:t.getPayload())||void 0;return e&&this._checkInputs(e.schema,e.payload),e}domEvent(e,r,i,s,n){this._safety.tryCatch((()=>{const o=t.time().tsNow;let c;t.requireArgument(e,"event",[Event,MockEvent]),t.requireArgument(r,"handledBy",[HTMLElement,"object"]),r instanceof HTMLElement?c=r:(r=r).template&&r.template.host instanceof HTMLElement?c=r.template.host:t.requireArgument(void 0,"handledBy");const l=this._wrapUserPayload(i,s,!0),d=this.getEffectiveRootId(n);switch(e.type){case"click":{const t=e,r=this._nextGen.getClickTracker();r&&r.markEventHandled(t);const i=h.getMouseEventData(t),s=h.getInstrumentedEventData(i,c,l);s.auto=n&&n._auto,this._logInternal(this.name,a,s,o,d);break}default:throw new Error(t.notImplemented)}}))}incrementCounter(e,r=1,i=!1,s={}){this._safety.tryCatch((()=>{t.requireArgument(e,"operation","string"),t.checkForDenyListedValues(e,"operation",_),t.checkForReservedCharacters(e,"operation",m),t.requireArgument(r,"increment","number"),t.requireArgument(i,"hasError","boolean"),t.requireArgument(s,"tags","object"),Object.entries(s).forEach((e=>{t.requireArgument(e[1],`Tag value for '${e[0]}'`,["string","number","boolean"])})),this._metrics.incrementCounter(e,r,i,s)}))}trackValue(e,r,i=!1,s={}){this._safety.tryCatch((()=>{t.requireArgument(e,"operation","string"),t.checkForDenyListedValues(e,"operation",_),t.checkForReservedCharacters(e,"operation",m),t.requireArgument(r,"value","number"),t.requireArgument(i,"hasError","boolean"),t.requireArgument(s,"tags","object"),Object.entries(s).forEach((e=>{t.requireArgument(e[1],`Tag value for '${e[0]}'`,["string","number","boolean"])})),this._metrics.trackValue(e,r,i,s)}))}_checkInputs(r,i){let s;e.checkSchema(r),t.requireArgument(i,"data","object"),void 0!==i.userPayload&&e.isInternal(r)&&(s=i.userPayload,u.validate(s.schema,s.payload),i.userPayload=void 0),u.validate(r,i),void 0!==s&&(i.userPayload=s)}getUpCounters(){return this._metrics.getUpCounters().filter((t=>t.getLastUpdatedOn()))}getValueRecorders(){return this._metrics.getValueRecorders().filter((t=>t.getLastUpdatedOn()))}registerForLogPrompt(e){t.requireArgument(e,"listener","function"),this._nextGen.registerForLogPrompt(e)}}InstrumentationImpl.defaultAppName="APP_NOT_REGISTERED";class RootActivityImpl extends ActivityImpl{constructor(e,r,i,s,n){super(e,void 0,r,i,void 0,s||t.generateUniqueId(32),n)}get preRootId(){return this._preRootId}set preRootId(t){this._preRootId=t}_getDetail(t,e){const r=super._getDetail(t,e);return r.isRoot=!0,r.preRootId=this.preRootId,r}}const y=new Array(32).fill(0).join("");const f=Object.freeze(new class{getId(){return y}getRootId(){}error(){}stop(){}discard(){}terminate(){}getIsSampled(){return!1}getTraceHeaders(t){return{}}getStartTimestamp(){}getStartPerfTime(){}getStopPerfTime(){}});class AppInstrumentationImpl extends InstrumentationImpl{constructor(t,e,r){super(t,e),this._allowMulti=r,this._onRootActivityStoppedCallback=this.handleRootActivityStop.bind(this)}startRootActivity(e,r,i){return this._safety.tryCatchReturn((()=>{t.requireArgument(e,"name");const s=new RootActivityImpl(e,this._onRootActivityStoppedCallback,this._onActivityErrorCallback,r,i);if(!this._allowMulti){if(this._singleRootActivity&&!this._singleRootActivity.isStopped){const t=this._singleRootActivity.getId();this._singleRootActivity.terminate(),s.preRootId=t}this._singleRootActivity=s}return s}),f)}handleRootActivityStop(t){if("discarded"===t.stopReason)return;const e=this._getActivityData(t);this._logActivity(e,t.startTimestamp),this._singleRootActivity=void 0}_getActivityData(t){const e=super._getActivityData(t);return e.isRoot=t.isRoot,e.preRootId=t.preRootId,e}getSingleRootActivityId(){var t;return null===(t=this._singleRootActivity)||void 0===t?void 0:t.getId()}isSingleRootActivitySampled(){var t;return null===(t=this._singleRootActivity)||void 0===t?void 0:t.getIsSampled()}_initMetrics(){return new MetricsImpl(this.name,(()=>this.name))}}class AutomaticClickTracker{constructor(e,r){this.isActive=!1,this._boundClickListener=this.clickListener.bind(this),t.requireArgument(e,"instrumentation"),t.requireArgument(r,"document"),this.instr=e,this.document=r}activate(){this.isActive||(this.document.addEventListener("click",this._boundClickListener,!0),this.isActive=!0)}deactivate(){this.isActive&&(this.document.removeEventListener("click",this._boundClickListener,!0),this.isActive=!1)}markEventHandled(t){this.ignoredEvent=t}clickListener(t){let e=t.composedPath&&t.composedPath();e&&e.length||(e=t.path);const r=this.getClickableElement(e);r&&setTimeout((()=>{t!==this.ignoredEvent&&this.instr.domEvent(t,r,void 0,void 0,{_auto:!0})}))}getClickableElement(t){const e=t?Math.min(t.length,5):0;for(let r=0;r<e;r+=1){const e=t[r],i=e.tagName&&e.tagName.toLowerCase();if("a"===i||"button"===i)return e;if("input"===i){const t=e;if(t.type&&"button"===t.type.toLowerCase())return t}}}}const v=80-"_CUT".length;class NextgenImpl{constructor(){this._logCollectors=new Set,this._instruments=new Map,this._sequence=0,this._forceDisabledLogCollectors=new Set,this._logCollectorFailures=new Map,this._isBufferingEnabled=!1,this._buffer=[],this._logCollectionListeners=new Set}get pagePayloadProvider(){return this._pagePayloadProvider}set pagePayloadProvider(t){this._pagePayloadProvider=t}get appPayloadProvider(){return this._appPayloadProvider}set appPayloadProvider(t){this._appPayloadProvider=t}registerApp(e,r){if(t.requireArgument(e,"name","string"),this._appInstr)throw new Error("An app has already been registered with instrumentation.");if(this._instruments.get(e))throw new Error(`The instrumentation name ${e} is already taken`);this._appInstr=new AppInstrumentationImpl(this,e,r&&r.allowMultipleRootActivities),this._instruments.set(e,this._appInstr),this._isBufferingEnabled=r&&r.enableBuffering;const i=new Tracing(this._appInstr);return{log:this._appInstr.log.bind(this._appInstr),error:this._appInstr.error.bind(this._appInstr),startActivity:this._appInstr.startActivity.bind(this._appInstr),domEvent:this._appInstr.domEvent.bind(this._appInstr),incrementCounter:this._appInstr.incrementCounter.bind(this._appInstr),trackValue:this._appInstr.trackValue.bind(this._appInstr),networkInstrumentation:i.networkInstrumentation.bind(i),registerForLogPrompt:this._appInstr.registerForLogPrompt.bind(this._appInstr),startRootActivity:this._appInstr.startRootActivity.bind(this._appInstr),registerLogCollector:this.registerLogCollector.bind(this),registerMetricsCollector:this.registerMetricsCollector.bind(this),activateClickTracker:this.activateClickTracker.bind(this),deactivateClickTracker:this.deactivateClickTracker.bind(this),disableBuffering:this.disableBuffering.bind(this),promptLogCollection:this.promptLogCollection.bind(this)}}getInstrumentation(e){t.requireArgument(e,"name","string"),e.length>80&&(e=e.substr(0,v)+"_CUT");let r=this._instruments.get(e);if(r){if(r===this._appInstr)throw new Error(`The instrumentation name ${e} is being used by the app.`)}else r=new InstrumentationImpl(this,e),this._instruments.set(e,r);return r}get appName(){return this._appInstr&&this._appInstr.name}addLog(e,r,i,s,n,o,a){this._sequence+=1;const c=this._sequence,l=this.appName,d=t.getConnectionType(),h={timestamp:s,rootId:n,sequence:c,loggerName:e,pagePayload:o?t.clone(o):void 0,appPayload:a?t.clone(a):void 0,loggerAppName:l,connectionType:d};this._isBufferingEnabled&&this._buffer.push({schema:r,data:t.clone(i),logMeta:h});const u=Array.from(this._logCollectors).filter((t=>!(this._forceDisabledLogCollectors.has(t)||t.getIsCollectDisabled&&t.getIsCollectDisabled())));if(u.length>0)for(const e of u){const s=t.clone(i);let n=this._logCollectorFailures.get(e)||0;try{e.collect(r,s,h),n>0&&this._logCollectorFailures.set(e,n-1)}catch(t){n+=1,n>=NextgenImpl._collectorFailureLimit?(this._forceDisabledLogCollectors.add(e),this._appInstr&&("string"==typeof t||t instanceof Error)&&this._appInstr.error(t)):this._logCollectorFailures.set(e,n)}}return this._sequence}getBuffer(){return this._buffer}disableBuffering(){this._isBufferingEnabled=!1,this._buffer=[]}getClickTracker(){return this._autoClickTracker}getDefaultInstrumentationContext(){var t,e;return{rootId:null===(t=this._appInstr)||void 0===t?void 0:t.getSingleRootActivityId(),isRootActivitySampled:null===(e=this._appInstr)||void 0===e?void 0:e.isSingleRootActivitySampled()}}activateClickTracker(){this._autoClickTracker||(this._autoClickTracker=new AutomaticClickTracker(this._appInstr,window.document)),this._autoClickTracker.activate()}deactivateClickTracker(){this._autoClickTracker&&(this._autoClickTracker.deactivate(),this._autoClickTracker=void 0)}registerLogCollector(e,r){if(t.requireArgument(e,"collector"),!this._logCollectors.has(e)&&(this._logCollectors.add(e),this._logCollectorFailures.set(e,0),(!e.getIsCollectDisabled||!e.getIsCollectDisabled())&&r&&r.retroactive))for(const t of this._buffer)e.collect(t.schema,t.data,t.logMeta)}registerMetricsCollector(e){if(t.requireArgument(e,"collector"),this._metricsCollector)throw new Error("A metrics Collector is already registered.");this._metricsCollector=e,this._metricsCollector.receiveMetricsExtractors({getAllUpCounters:this.getAllUpCounters.bind(this),getAllValueRecorders:this.getAllValueRecorders.bind(this)})}getAllUpCounters(){return Array.from(this._instruments.values()).map((t=>t.getUpCounters())).reduce(((t,e)=>t.concat(e)),[])}getAllValueRecorders(){return Array.from(this._instruments.values()).map((t=>t.getValueRecorders())).reduce(((t,e)=>t.concat(e)),[])}registerForLogPrompt(t){this._logCollectionListeners.add(t)}promptLogCollection(t){for(const e of this._logCollectionListeners.keys())try{e(t)}catch(t){}}}NextgenImpl._collectorFailureLimit=5;const b=new class{get _lazyNextGen(){return this._nextgen||(this._nextgen=new NextgenImpl),this._nextgen}registerInstrumentedApp(e,r){r&&r.isProduction&&t.markProduction();const i=this._lazyNextGen.registerApp(e,r);return r&&(this._nextgen.appPayloadProvider=r.appPayloadProvider,this._nextgen.pagePayloadProvider=r.pagePayloadProvider),i}getInstrumentation(t){return this._lazyNextGen.getInstrumentation(t)}},I=b.registerInstrumentedApp.bind(b),C=b.getInstrumentation.bind(b),A=t.time.bind(t);class TaskerImpl{constructor(t,e,r,i){this.name=t,this._doneCallback=r,this._overDoneCallback=i,this._busyCount=0,this._isOk=!0,this._busyCount=e}get isBusy(){return this._isOk?this._busyCount>0:void 0}add(){this._isOk&&(this._busyCount+=1)}done(){this._isOk&&(this._busyCount>0?(this._busyCount-=1,this._busyCount||this._doneCallback()):(this._isOk=!1,this._overDoneCallback()))}}const k={Error:"Crimson",Activity:"CadetBlue",InstrumentedEvent:"DarkOliveGreen",O11ySample:"BlueViolet"},w={Error:"white",Activity:"white",InstrumentedEvent:"white",O11ySample:"white"};class ConsoleCollector{constructor(t){t&&this._log("ConsoleCollector",t)}collect(t,r,i){let s,n,o;"sf.instrumentation"===t.namespace?(s=t.name,n=w[t.name]||"black",o=k[t.name]||"Gainsboro"):s=e.getSchemaId(t),this._log(s,r,i,n,o)}_log(t,e,r,i="black",s="Gainsboro"){const n=`color:${i};background-color:${s}`;console.log(`%cO11Y%c ${t}`,"color:white;background-color:#FF6600;font-weight:bold",n,e||"",r||"")}}const T=new class{constructor(){this._instr=C("IdleDetector"),this._taskers=new Set,this._listeners=new Set,this._busyCheckers=new Map,this._timerCheckQueued=0}requestIdleDetectedCallback(e){t.requireArgument(e,"callback","function"),this._listeners.add(e),this.checkIfLoaded()}declareNotifierTaskSingle(e){t.requireArgument(e,"name","string");const r=this.addTasker(e,1);return{get isBusy(){return r.isBusy},done:()=>{r.done(),this._taskers.delete(r)}}}declareNotifierTaskMulti(e,r=0){if(t.requireArgument(e,"name","string"),void 0!==r&&(t.requireArgument(r,"existingBusyCount","number"),r<0||parseInt(r.toString(),10)!==r))throw new Error("existingBusyCount accepts only non-negative integers");return this.addTasker(e,r)}declarePollableTaskMulti(e,r){t.requireArgument(e,"name","string"),t.requireArgument(r,"isBusyChecker","function"),this._busyCheckers.set(r,e)}addTasker(t,e){const r=new TaskerImpl(t,e,(()=>{this.checkIfLoaded()}),(()=>{throw new Error(`Tasker '${r.name}' is done too many times.`)}));return this._taskers.add(r),r}areAllNotifiersIdle(){return!Array.from(this._taskers.values()).some((t=>t.isBusy))}areAllPollablesIdle(){return!Array.from(this._busyCheckers.keys()).some(((t,e)=>{try{return t()}catch(t){return this._instr.error(t,`BusyChecker #${e}`),!1}}))}checkIfLoaded(){this._listeners.size&&(this._timerCheckQueued&&window.clearTimeout(this._timerCheckQueued),this.areAllNotifiersIdle()&&(this._timerCheckQueued=window.setTimeout((()=>{this._timerCheckQueued=window.setTimeout((()=>{this.doubleCheck()}),40)}),0)))}doubleCheck(){if(this._timerCheckQueued=0,this.areAllNotifiersIdle())if(this.areAllPollablesIdle()){const t=Array.from(this._listeners.values());this._listeners.clear(),this.notify(t)}else this._timerCheckQueued=window.setTimeout((()=>{this.doubleCheck()}),15)}notify(e){const r=t.time().tsNow;for(const[t,i]of e.entries())try{i(r)}catch(e){this._instr.error(e,`Listener #${t}`)}}};export{ConsoleCollector,C as getInstrumentation,T as idleDetector,I as registerInstrumentedApp,A as time};
|
|
1
|
+
import { utility, PublicSafety, schemaUtil } from 'o11y/shared';
|
|
2
|
+
|
|
3
|
+
const defaultTraceIdLengthW3 = 32;
|
|
4
|
+
const defaultTraceIdLengthB3 = 16;
|
|
5
|
+
const defaultSpanIdLength = 16;
|
|
6
|
+
const headerTraceParent = 'traceparent';
|
|
7
|
+
const headerB3 = 'b3';
|
|
8
|
+
const headerTraceId = 'X-B3-TraceId';
|
|
9
|
+
const headerSpanId = 'X-B3-SpanId';
|
|
10
|
+
const headerSampled = 'X-B3-Sampled';
|
|
11
|
+
const headerParentSpanId = 'X-B3-ParentSpanId';
|
|
12
|
+
const defaultActivityNameForFetch = 'fetch';
|
|
13
|
+
const defaultActivityNameForXhrSend = 'xhr_send';
|
|
14
|
+
class Tracing {
|
|
15
|
+
constructor(instr) {
|
|
16
|
+
this.instr = instr;
|
|
17
|
+
utility.requireArgument(instr, 'instr', 'object');
|
|
18
|
+
}
|
|
19
|
+
static _getB3CompactFormat(traceId, spanId, isSampled, parentSpanId) {
|
|
20
|
+
let b3 = `${traceId}-${spanId}`;
|
|
21
|
+
if (isSampled !== undefined || parentSpanId !== undefined) {
|
|
22
|
+
b3 += isSampled ? '-1' : '-0';
|
|
23
|
+
if (parentSpanId !== undefined) {
|
|
24
|
+
b3 += `-${parentSpanId}`;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return b3;
|
|
28
|
+
}
|
|
29
|
+
static _getW3CompactFormat(traceId, spanId, isSampled) {
|
|
30
|
+
return `00-${traceId}-${spanId}-${isSampled ? '01' : '00'}`;
|
|
31
|
+
}
|
|
32
|
+
static _conformTextAsId(text, numChars) {
|
|
33
|
+
text = text.toLowerCase();
|
|
34
|
+
const len = text.length;
|
|
35
|
+
for (let i = 0; i < len; i += 1) {
|
|
36
|
+
const c = text[i];
|
|
37
|
+
if (!(c >= 'a' && c <= 'f') && !(c >= '0' && c <= '9')) {
|
|
38
|
+
throw new Error(`The text '${text}' has an invalid character at index #${i}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (len > numChars) {
|
|
42
|
+
return text.substr(len - numChars);
|
|
43
|
+
}
|
|
44
|
+
if (len < numChars) {
|
|
45
|
+
return text.padStart(numChars, '0');
|
|
46
|
+
}
|
|
47
|
+
return text;
|
|
48
|
+
}
|
|
49
|
+
static getHeaders(traceId, spanId, isSampled, options) {
|
|
50
|
+
utility.requireArgument(traceId, 'traceId', 'string');
|
|
51
|
+
utility.requireArgument(spanId, 'spanId', 'string');
|
|
52
|
+
const useB3Headers = options && options.useB3Headers;
|
|
53
|
+
traceId = this._conformTextAsId(traceId, options && options.traceIdEffectiveLength !== undefined
|
|
54
|
+
? options.traceIdEffectiveLength
|
|
55
|
+
: useB3Headers
|
|
56
|
+
? defaultTraceIdLengthB3
|
|
57
|
+
: defaultTraceIdLengthW3);
|
|
58
|
+
spanId = this._conformTextAsId(spanId, defaultSpanIdLength);
|
|
59
|
+
const parentSpanId = (options &&
|
|
60
|
+
options.parentSpanId !== undefined &&
|
|
61
|
+
this._conformTextAsId(options.parentSpanId, defaultSpanIdLength)) ||
|
|
62
|
+
undefined;
|
|
63
|
+
const headers = {};
|
|
64
|
+
if (useB3Headers) {
|
|
65
|
+
const isCompact = options && options.useCompactHeader;
|
|
66
|
+
if (isCompact) {
|
|
67
|
+
headers[headerB3] = this._getB3CompactFormat(traceId, spanId, isSampled, parentSpanId);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
headers[headerTraceId] = traceId;
|
|
71
|
+
headers[headerSpanId] = spanId;
|
|
72
|
+
if (parentSpanId !== undefined) {
|
|
73
|
+
headers[headerParentSpanId] = parentSpanId;
|
|
74
|
+
}
|
|
75
|
+
if (isSampled !== undefined) {
|
|
76
|
+
headers[headerSampled] = isSampled ? '1' : '0';
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
headers[headerTraceParent] = this._getW3CompactFormat(traceId, spanId, isSampled);
|
|
82
|
+
}
|
|
83
|
+
return headers;
|
|
84
|
+
}
|
|
85
|
+
_disableNetworkInstrumentation() {
|
|
86
|
+
if (Tracing._isNetworkInstrumentationEnabled) {
|
|
87
|
+
if (Tracing._originalFetch) {
|
|
88
|
+
Tracing._global.fetch = Tracing._originalFetch;
|
|
89
|
+
Tracing._originalFetch = undefined;
|
|
90
|
+
}
|
|
91
|
+
if (Tracing._originalXhr) {
|
|
92
|
+
Tracing._global.XMLHttpRequest = Tracing._originalXhr;
|
|
93
|
+
Tracing._originalXhr = undefined;
|
|
94
|
+
}
|
|
95
|
+
if (Tracing._originalXhrSend) {
|
|
96
|
+
Tracing._global.XMLHttpRequest.prototype.send = Tracing._originalXhrSend;
|
|
97
|
+
Tracing._originalXhrSend = undefined;
|
|
98
|
+
}
|
|
99
|
+
Tracing._isNetworkInstrumentationEnabled = false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
_enableNetworkInstrumentation(instr, logErrors, activityName, useTracing, options) {
|
|
103
|
+
if (typeof Tracing._global.fetch === 'function') {
|
|
104
|
+
this._overrideFetch(instr, logErrors, activityName, useTracing, options);
|
|
105
|
+
Tracing._isNetworkInstrumentationEnabled = true;
|
|
106
|
+
}
|
|
107
|
+
if (typeof Tracing._global.XMLHttpRequest === 'function') {
|
|
108
|
+
this._overrideXhr(instr, logErrors, activityName, useTracing, options);
|
|
109
|
+
Tracing._isNetworkInstrumentationEnabled = true;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
_overrideFetch(instr, logErrors, activityName, useTracing, options) {
|
|
113
|
+
Tracing._originalFetch = Tracing._global.fetch;
|
|
114
|
+
const o11yFetch = async (url, reqOptions, ...restArgs) => {
|
|
115
|
+
let activity;
|
|
116
|
+
try {
|
|
117
|
+
activity = instr.startActivity(activityName || defaultActivityNameForFetch);
|
|
118
|
+
if (useTracing) {
|
|
119
|
+
reqOptions = reqOptions || {};
|
|
120
|
+
const traceHeaders = activity.getTraceHeaders(options);
|
|
121
|
+
reqOptions.headers = Object.assign(reqOptions.headers || {}, traceHeaders);
|
|
122
|
+
}
|
|
123
|
+
return await Tracing._originalFetch.call(Tracing._global, url, reqOptions, ...restArgs);
|
|
124
|
+
}
|
|
125
|
+
catch (ex) {
|
|
126
|
+
if (logErrors) {
|
|
127
|
+
if (activity) {
|
|
128
|
+
activity.error(ex);
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
instr.error(ex);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
throw ex;
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
if (activity) {
|
|
138
|
+
activity.stop();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
Tracing._global.fetch = o11yFetch;
|
|
143
|
+
}
|
|
144
|
+
_overrideXhr(instr, logErrors, activityName, useTracing, options) {
|
|
145
|
+
Tracing._originalXhr = Tracing._global.XMLHttpRequest;
|
|
146
|
+
Tracing._originalXhrSend = Tracing._originalXhr.prototype.send;
|
|
147
|
+
Tracing._originalXhr.prototype.send = function (...args) {
|
|
148
|
+
let activity;
|
|
149
|
+
const xhr = this;
|
|
150
|
+
try {
|
|
151
|
+
xhr._o11yActivity = activity = instr.startActivity(activityName || defaultActivityNameForXhrSend);
|
|
152
|
+
if (useTracing) {
|
|
153
|
+
const headers = activity.getTraceHeaders(options);
|
|
154
|
+
Object.entries(headers).forEach((entry) => {
|
|
155
|
+
xhr.setRequestHeader(entry[0], entry[1]);
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
Tracing._originalXhrSend.call(this, ...args);
|
|
159
|
+
}
|
|
160
|
+
catch (ex) {
|
|
161
|
+
if (logErrors) {
|
|
162
|
+
if (activity) {
|
|
163
|
+
activity.error(ex);
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
instr.error(ex);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (activity) {
|
|
170
|
+
activity.stop();
|
|
171
|
+
}
|
|
172
|
+
throw ex;
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
const xhrProxy = new Proxy(Tracing._originalXhr, {
|
|
176
|
+
construct(target) {
|
|
177
|
+
const newXhr = new target();
|
|
178
|
+
newXhr.addEventListener('load', () => {
|
|
179
|
+
const activity = newXhr._o11yActivity;
|
|
180
|
+
if (activity) {
|
|
181
|
+
activity.stop();
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
newXhr.addEventListener('error', (__err) => {
|
|
185
|
+
const error = new Error('XHR Network-Level Error');
|
|
186
|
+
const activity = newXhr._o11yActivity;
|
|
187
|
+
if (activity) {
|
|
188
|
+
if (logErrors) {
|
|
189
|
+
activity.error(error);
|
|
190
|
+
}
|
|
191
|
+
activity.stop();
|
|
192
|
+
}
|
|
193
|
+
else if (logErrors) {
|
|
194
|
+
instr.error(error);
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
newXhr.addEventListener('abort', () => {
|
|
198
|
+
const activity = newXhr._o11yActivity;
|
|
199
|
+
if (activity) {
|
|
200
|
+
activity.discard();
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
return newXhr;
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
Tracing._global.XMLHttpRequest = xhrProxy;
|
|
207
|
+
}
|
|
208
|
+
networkInstrumentation(options) {
|
|
209
|
+
utility.requireArgument(options, 'options', ['boolean', 'object']);
|
|
210
|
+
if (options) {
|
|
211
|
+
this._disableNetworkInstrumentation();
|
|
212
|
+
const tracingOptions = typeof options === 'object' ? options : {};
|
|
213
|
+
this._enableNetworkInstrumentation(utility.definedValueOrDefault(tracingOptions.instrumentation, this.instr), utility.definedValueOrDefault(tracingOptions.logErrors, true), tracingOptions.activityName, utility.definedValueOrDefault(tracingOptions.useTracing, true), tracingOptions.tracingHeadersOptions);
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
this._disableNetworkInstrumentation();
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
Tracing._global = utility.getGlobal();
|
|
221
|
+
Tracing._isNetworkInstrumentationEnabled = false;
|
|
222
|
+
|
|
223
|
+
const timedout = 'timedout';
|
|
224
|
+
const terminated = 'terminated';
|
|
225
|
+
const discarded = 'discarded';
|
|
226
|
+
const stopReason = {
|
|
227
|
+
timedout,
|
|
228
|
+
terminated,
|
|
229
|
+
discarded
|
|
230
|
+
};
|
|
231
|
+
class ActivityImpl {
|
|
232
|
+
constructor(_name, _rootId, _onStopped, _onError, timeout, id, _isSampled) {
|
|
233
|
+
this._name = _name;
|
|
234
|
+
this._rootId = _rootId;
|
|
235
|
+
this._onStopped = _onStopped;
|
|
236
|
+
this._onError = _onError;
|
|
237
|
+
this._isSampled = _isSampled;
|
|
238
|
+
this._errorCount = 0;
|
|
239
|
+
const { tsNow, perfNow } = utility.time();
|
|
240
|
+
ActivityImpl._count += 1;
|
|
241
|
+
this._id = id || utility.generateUniqueId();
|
|
242
|
+
this._usePerf =
|
|
243
|
+
typeof performance !== 'undefined' &&
|
|
244
|
+
typeof performance.mark === 'function' &&
|
|
245
|
+
typeof performance.measure === 'function';
|
|
246
|
+
if (this._usePerf) {
|
|
247
|
+
this._perfName = `${this._name}__${ActivityImpl._count}`;
|
|
248
|
+
this._perfId = `${this._name}__${this.id}`;
|
|
249
|
+
try {
|
|
250
|
+
performance.mark(this._perfId);
|
|
251
|
+
}
|
|
252
|
+
catch (_a) {
|
|
253
|
+
this._usePerf = false;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
this._startTimestamp = tsNow;
|
|
257
|
+
this._startPerfTime = perfNow;
|
|
258
|
+
if (timeout > 0) {
|
|
259
|
+
this._timer = setTimeout(() => {
|
|
260
|
+
this._stopReason = this._stopReason || stopReason.timedout;
|
|
261
|
+
this.stop();
|
|
262
|
+
}, timeout);
|
|
263
|
+
}
|
|
264
|
+
this._safety = new PublicSafety();
|
|
265
|
+
}
|
|
266
|
+
get id() {
|
|
267
|
+
return this._id;
|
|
268
|
+
}
|
|
269
|
+
getId() {
|
|
270
|
+
return this.id;
|
|
271
|
+
}
|
|
272
|
+
getRootId() {
|
|
273
|
+
return this._rootId;
|
|
274
|
+
}
|
|
275
|
+
get stopReason() {
|
|
276
|
+
return this._stopReason;
|
|
277
|
+
}
|
|
278
|
+
error(error, userSchemaOrText, userData) {
|
|
279
|
+
this._safety.tryCatch(() => {
|
|
280
|
+
this._errorCount += 1;
|
|
281
|
+
if (typeof error === 'string') {
|
|
282
|
+
error = new Error(error);
|
|
283
|
+
}
|
|
284
|
+
this._onError(error, this._getDetail(userSchemaOrText, userData));
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
stop(userSchemaOrText, userData) {
|
|
288
|
+
this._safety.tryCatch(() => this._stopInternal(userSchemaOrText, userData));
|
|
289
|
+
}
|
|
290
|
+
_stopInternal(userSchemaOrText, userData) {
|
|
291
|
+
const stopPerfTime = utility.perfNow();
|
|
292
|
+
if (this._usePerf) {
|
|
293
|
+
try {
|
|
294
|
+
performance.measure(this._perfName, this._perfId);
|
|
295
|
+
performance.clearMarks(this._perfId);
|
|
296
|
+
performance.clearMeasures(this._perfName);
|
|
297
|
+
}
|
|
298
|
+
catch (_a) { }
|
|
299
|
+
}
|
|
300
|
+
if (this._timer) {
|
|
301
|
+
clearTimeout(this._timer);
|
|
302
|
+
this._timer = undefined;
|
|
303
|
+
}
|
|
304
|
+
if (this.isStopped) {
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
this._stopPerfTime = stopPerfTime;
|
|
308
|
+
const activityDetail = this._getDetail(userSchemaOrText, userData);
|
|
309
|
+
this._onStopped(activityDetail);
|
|
310
|
+
}
|
|
311
|
+
get isStopped() {
|
|
312
|
+
return this._stopPerfTime !== undefined;
|
|
313
|
+
}
|
|
314
|
+
discard() {
|
|
315
|
+
this._safety.tryCatch(() => {
|
|
316
|
+
this._stopReason = this._stopReason || stopReason.discarded;
|
|
317
|
+
this.stop();
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
terminate() {
|
|
321
|
+
this._safety.tryCatch(() => {
|
|
322
|
+
this._stopReason = this._stopReason || stopReason.terminated;
|
|
323
|
+
this.stop();
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
getIsSampled() {
|
|
327
|
+
return this._isSampled || false;
|
|
328
|
+
}
|
|
329
|
+
_getDetail(userSchemaOrText, userData) {
|
|
330
|
+
return {
|
|
331
|
+
id: this._id,
|
|
332
|
+
rootId: this._rootId,
|
|
333
|
+
name: this._name,
|
|
334
|
+
userSchemaOrText: userSchemaOrText,
|
|
335
|
+
userData,
|
|
336
|
+
stopReason: this._stopReason,
|
|
337
|
+
startTimestamp: this._startTimestamp,
|
|
338
|
+
startPerfTime: this._startPerfTime,
|
|
339
|
+
stopPerfTime: this._stopPerfTime,
|
|
340
|
+
errorCount: this._errorCount,
|
|
341
|
+
isSampled: this.getIsSampled()
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
getTraceHeaders(options) {
|
|
345
|
+
const spanId = this.id;
|
|
346
|
+
const traceId = this._rootId || spanId;
|
|
347
|
+
return Tracing.getHeaders(traceId, spanId, this.getIsSampled(), options);
|
|
348
|
+
}
|
|
349
|
+
getStartTimestamp() {
|
|
350
|
+
return this._startTimestamp;
|
|
351
|
+
}
|
|
352
|
+
getStartPerfTime() {
|
|
353
|
+
return this._startPerfTime;
|
|
354
|
+
}
|
|
355
|
+
getStopPerfTime() {
|
|
356
|
+
return this._stopPerfTime;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
ActivityImpl._count = 0;
|
|
360
|
+
|
|
361
|
+
const activity={namespace:"sf.instrumentation",name:"Activity",pbjsSchema:{"nested":{"sf":{"nested":{"instrumentation":{"nested":{"Activity":{"reserved":[[5,5],[7,7]],"fields":{"duration":{"options":{},"id":3,"type":"double"},"stopReason":{"options":{},"id":6,"type":"string"},"isRoot":{"options":{},"id":8,"type":"bool"},"name":{"options":{"(meta.max_length)":25},"id":2,"type":"string"},"isSampled":{"options":{},"id":11,"type":"bool"},"preRootId":{"options":{},"id":9,"type":"string"},"id":{"options":{},
|
|
362
|
+
"id":1,"type":"string"},"userPayload":{"options":{},"id":4,"type":"Payload"},"errorCount":{"options":{},"id":10,"type":"uint32"}}},"Payload":{"fields":{"payload":{"options":{},"id":2,"type":"bytes"},"schemaName":{"options":{},"id":1,"type":"string"}}}}}}}}}};
|
|
363
|
+
|
|
364
|
+
const error={namespace:"sf.instrumentation",name:"Error",pbjsSchema:{"nested":{"sf":{"nested":{"instrumentation":{"nested":{"Error":{"reserved":[[5,5],[7,7]],"fields":{"activityId":{"options":{},"id":6,"type":"string"},"stack":{"options":{},"id":3,"type":"string"},"name":{"options":{},"id":1,"type":"string"},"message":{"options":{"(meta.max_length)":200},"id":2,"type":"string"},"userPayload":{"options":{},"id":4,"type":"Payload"}}},"Payload":{"fields":{"payload":{"options":{},"id":2,"type":"bytes"},
|
|
365
|
+
"schemaName":{"options":{},"id":1,"type":"string"}}}}}}}}}};
|
|
366
|
+
|
|
367
|
+
const instrumented_event={namespace:"sf.instrumentation",name:"InstrumentedEvent",pbjsSchema:{"nested":{"sf":{"nested":{"instrumentation":{"nested":{"MouseEvent":{"fields":{"cancelable":{"options":{},"id":5,"type":"bool"},"ctrlKey":{"options":{},"id":9,"type":"bool"},"type":{"options":{},"id":25,"type":"string"},"button":{"options":{},"id":3,"type":"uint32"},"offsetX":{"options":{},"id":17,"type":"uint32"},"eventPhase":{"options":{},"id":12,"type":"uint32"},"shiftKey":{"options":{},"id":23,
|
|
368
|
+
"type":"bool"},"offsetY":{"options":{},"id":18,"type":"uint32"},"composed":{"options":{},"id":8,"type":"bool"},"altKey":{"options":{},"id":1,"type":"bool"},"isTrusted":{"options":{},"id":13,"type":"bool"},"buttons":{"options":{},"id":4,"type":"uint32"},"movementY":{"options":{},"id":16,"type":"uint32"},"clientY":{"options":{},"id":7,"type":"uint32"},"clientX":{"options":{},"id":6,"type":"uint32"},"movementX":{"options":{},"id":15,"type":"uint32"},"defaultPrevented":{"options":{},"id":10,"type":"bool"},
|
|
369
|
+
"metaKey":{"options":{},"id":14,"type":"bool"},"timeStamp":{"options":{},"id":24,"type":"double"},"bubbles":{"options":{},"id":2,"type":"bool"},"detail":{"options":{},"id":11,"type":"int64"},"pageY":{"options":{},"id":20,"type":"uint32"},"pageX":{"options":{},"id":19,"type":"uint32"},"screenX":{"options":{},"id":21,"type":"uint32"},"screenY":{"options":{},"id":22,"type":"uint32"}}},"InstrumentedEvent":{"oneofs":{"event":{"oneof":["mouseEvent"]}},"reserved":[[4,4],"xpath",[6,6],[8,8]],"fields":{"mouseEvent":{"options":{},
|
|
370
|
+
"id":7,"type":"MouseEvent"},"auto":{"options":{},"id":3,"type":"bool"},"parentComponent":{"options":{},"id":2,"type":"string"},"ownerComponent":{"options":{},"id":1,"type":"string"},"userPayload":{"options":{},"id":5,"type":"Payload"},"simplePath":{"options":{},"id":9,"type":"string"}}},"Payload":{"fields":{"payload":{"options":{},"id":2,"type":"bytes"},"schemaName":{"options":{},"id":1,"type":"string"}}}}}}}}}};
|
|
371
|
+
|
|
372
|
+
const simple={namespace:"sf.instrumentation",name:"Simple",pbjsSchema:{"nested":{"sf":{"nested":{"instrumentation":{"nested":{"Simple":{"options":{"(meta.msg.desc)":"This message is used internally to allow convenient logging of simple text via the API without requiring a schema."},"fields":{"text":{"options":{"(meta.max_length)":25},"id":1,"type":"string"}}}}}}}}}};
|
|
373
|
+
|
|
374
|
+
const id = new Array(16).fill(0).join('');
|
|
375
|
+
class ActivityNoOp {
|
|
376
|
+
getId() {
|
|
377
|
+
return id;
|
|
378
|
+
}
|
|
379
|
+
getRootId() {
|
|
380
|
+
return undefined;
|
|
381
|
+
}
|
|
382
|
+
error() { }
|
|
383
|
+
stop() { }
|
|
384
|
+
discard() { }
|
|
385
|
+
terminate() { }
|
|
386
|
+
getIsSampled() {
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
getTraceHeaders(__options) {
|
|
390
|
+
return {};
|
|
391
|
+
}
|
|
392
|
+
getStartTimestamp() {
|
|
393
|
+
return undefined;
|
|
394
|
+
}
|
|
395
|
+
getStartPerfTime() {
|
|
396
|
+
return undefined;
|
|
397
|
+
}
|
|
398
|
+
getStopPerfTime() {
|
|
399
|
+
return undefined;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const activityNoOp = Object.freeze(new ActivityNoOp());
|
|
403
|
+
|
|
404
|
+
class DomEventHelpers {
|
|
405
|
+
getInstrumentedEventData(eventData, handledBy, userPayload) {
|
|
406
|
+
const instrumentedEvent = {
|
|
407
|
+
ownerComponent: handledBy.tagName,
|
|
408
|
+
parentComponent: (handledBy.parentElement && handledBy.parentElement.tagName) || undefined,
|
|
409
|
+
event: eventData,
|
|
410
|
+
simplePath: utility.getXpath(handledBy)
|
|
411
|
+
};
|
|
412
|
+
if (userPayload) {
|
|
413
|
+
instrumentedEvent.userPayload = schemaUtil.makePayload(userPayload.schema, userPayload.payload, true);
|
|
414
|
+
}
|
|
415
|
+
return instrumentedEvent;
|
|
416
|
+
}
|
|
417
|
+
getMouseEventData(e) {
|
|
418
|
+
return {
|
|
419
|
+
altKey: e.altKey,
|
|
420
|
+
bubbles: e.bubbles,
|
|
421
|
+
button: e.button,
|
|
422
|
+
buttons: e.buttons,
|
|
423
|
+
cancelable: e.cancelable,
|
|
424
|
+
clientX: e.clientX,
|
|
425
|
+
clientY: e.clientY,
|
|
426
|
+
composed: e.composed,
|
|
427
|
+
defaultPrevented: e.defaultPrevented,
|
|
428
|
+
detail: e.detail,
|
|
429
|
+
eventPhase: e.eventPhase,
|
|
430
|
+
isTrusted: e.isTrusted,
|
|
431
|
+
timeStamp: e.timeStamp,
|
|
432
|
+
type: e.type,
|
|
433
|
+
ctrlKey: e.ctrlKey,
|
|
434
|
+
metaKey: e.metaKey,
|
|
435
|
+
movementX: e.movementX,
|
|
436
|
+
movementY: e.movementY,
|
|
437
|
+
offsetX: e.offsetX,
|
|
438
|
+
offsetY: e.offsetY,
|
|
439
|
+
pageX: e.pageX,
|
|
440
|
+
pageY: e.pageY,
|
|
441
|
+
screenX: e.screenX,
|
|
442
|
+
screenY: e.screenY,
|
|
443
|
+
shiftKey: e.shiftKey
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
const singleton = new DomEventHelpers();
|
|
448
|
+
const domEventHelpers = singleton;
|
|
449
|
+
|
|
450
|
+
const maxFieldLength = 10000;
|
|
451
|
+
const minFieldLength = 0;
|
|
452
|
+
const maxFourBytesPos = 2147483647;
|
|
453
|
+
const maxFourBytesNeg = -2147483648;
|
|
454
|
+
const maxFourBytesUnsigned = 4294967295;
|
|
455
|
+
const maxEightBytesPos = 9223372036854776000;
|
|
456
|
+
const maxEightBytesNeg = -9223372036854776001;
|
|
457
|
+
const maxEightBytesUnsigned = 18446744073709552000;
|
|
458
|
+
class LogValidator {
|
|
459
|
+
validate(schema, data) {
|
|
460
|
+
const schemaTokens = schemaUtil.checkSchema(schema);
|
|
461
|
+
utility.requireArgument(data, 'data', 'object');
|
|
462
|
+
const nestedSchema = schemaUtil.getTypes(schema);
|
|
463
|
+
const errorMessage = this.validateFields(data, nestedSchema[schemaTokens.message], nestedSchema, schemaUtil.getSchemaId(schema));
|
|
464
|
+
if (errorMessage) {
|
|
465
|
+
throw new Error(errorMessage);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
validateFields(data, message, custom, schemaId) {
|
|
469
|
+
const oneofs = message.oneofs || {};
|
|
470
|
+
const fields = message.fields || {};
|
|
471
|
+
let errorMessage = undefined;
|
|
472
|
+
for (const key in data) {
|
|
473
|
+
const value = data[key];
|
|
474
|
+
if (!this.isNullOrUndefinedOrEmpty(value)) {
|
|
475
|
+
if (oneofs[key]) {
|
|
476
|
+
errorMessage = this.matchFieldTypes(value, oneofs[key].oneof[0], custom, schemaId, key);
|
|
477
|
+
}
|
|
478
|
+
else if (fields[key]) {
|
|
479
|
+
errorMessage = this.matchFieldTypes(value, fields[key].type, custom, schemaId, key, fields[key].rule);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (errorMessage) {
|
|
483
|
+
return errorMessage;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return undefined;
|
|
487
|
+
}
|
|
488
|
+
isNullOrUndefinedOrEmpty(val) {
|
|
489
|
+
return val === undefined || val === null || val === '';
|
|
490
|
+
}
|
|
491
|
+
matchFieldTypes(fieldData, fieldType, descriptor, schemaId, key, rule) {
|
|
492
|
+
let convertedSchemaType;
|
|
493
|
+
let extraContext = undefined;
|
|
494
|
+
if (rule === 'repeated') {
|
|
495
|
+
let errorMessage = undefined;
|
|
496
|
+
if (Array.isArray(fieldData)) {
|
|
497
|
+
for (const index in fieldData) {
|
|
498
|
+
errorMessage = this.matchFieldTypes(fieldData[index], fieldType, descriptor, schemaId, key);
|
|
499
|
+
if (errorMessage) {
|
|
500
|
+
break;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
else {
|
|
505
|
+
errorMessage = `Schema ${schemaId} on field: ${key}, repeated field should be an array`;
|
|
506
|
+
}
|
|
507
|
+
return errorMessage;
|
|
508
|
+
}
|
|
509
|
+
switch (fieldType) {
|
|
510
|
+
case 'string':
|
|
511
|
+
convertedSchemaType = 'string';
|
|
512
|
+
break;
|
|
513
|
+
case 'bytes':
|
|
514
|
+
convertedSchemaType = 'object';
|
|
515
|
+
if (!(fieldData instanceof Uint8Array)) {
|
|
516
|
+
extraContext = `Schema ${schemaId} on field: ${key}, bytes array is malformed`;
|
|
517
|
+
}
|
|
518
|
+
break;
|
|
519
|
+
case 'bool':
|
|
520
|
+
convertedSchemaType = 'boolean';
|
|
521
|
+
break;
|
|
522
|
+
case 'uint32':
|
|
523
|
+
convertedSchemaType = 'number';
|
|
524
|
+
extraContext = this.checkNumberRange(fieldData, maxFourBytesUnsigned, 0, schemaId, key);
|
|
525
|
+
break;
|
|
526
|
+
case 'int32':
|
|
527
|
+
case 'sint32':
|
|
528
|
+
case 'fixed32':
|
|
529
|
+
case 'sfixed32':
|
|
530
|
+
convertedSchemaType = 'number';
|
|
531
|
+
extraContext = this.checkNumberRange(fieldData, maxFourBytesPos, maxFourBytesNeg, schemaId, key);
|
|
532
|
+
break;
|
|
533
|
+
case 'uint64':
|
|
534
|
+
convertedSchemaType = 'number';
|
|
535
|
+
extraContext = this.checkNumberRange(fieldData, maxEightBytesUnsigned, 0, schemaId, key);
|
|
536
|
+
break;
|
|
537
|
+
case 'fixed64':
|
|
538
|
+
case 'sfixed64':
|
|
539
|
+
case 'int64':
|
|
540
|
+
case 'sint64':
|
|
541
|
+
convertedSchemaType = 'number';
|
|
542
|
+
extraContext = this.checkNumberRange(fieldData, maxEightBytesPos, maxEightBytesNeg, schemaId, key);
|
|
543
|
+
break;
|
|
544
|
+
case 'double':
|
|
545
|
+
case 'float':
|
|
546
|
+
convertedSchemaType = 'number';
|
|
547
|
+
if (!Number.isFinite(fieldData)) {
|
|
548
|
+
extraContext = `Schema ${schemaId} on field: ${key}. Value must be finite`;
|
|
549
|
+
}
|
|
550
|
+
break;
|
|
551
|
+
default:
|
|
552
|
+
const ref = {};
|
|
553
|
+
const keys = Object.keys(descriptor);
|
|
554
|
+
for (const x in keys) {
|
|
555
|
+
ref[keys[x].toLowerCase()] = keys[x];
|
|
556
|
+
}
|
|
557
|
+
if (ref[fieldType.toLowerCase()]) {
|
|
558
|
+
extraContext = this.validateFields(fieldData, descriptor[ref[fieldType.toLowerCase()]], descriptor, schemaId);
|
|
559
|
+
convertedSchemaType = 'object';
|
|
560
|
+
}
|
|
561
|
+
break;
|
|
562
|
+
}
|
|
563
|
+
const fieldLength = (fieldData + '').length;
|
|
564
|
+
if (typeof fieldData !== convertedSchemaType) {
|
|
565
|
+
return `Schema ${schemaId} on field: ${key}. Expected type ${fieldType} but received type ${typeof fieldData}`;
|
|
566
|
+
}
|
|
567
|
+
else if (fieldLength < minFieldLength || fieldLength > maxFieldLength) {
|
|
568
|
+
return `Schema ${schemaId} on field: ${key}, exceeded maximum or minimum field length`;
|
|
569
|
+
}
|
|
570
|
+
else if (extraContext) {
|
|
571
|
+
return extraContext;
|
|
572
|
+
}
|
|
573
|
+
return undefined;
|
|
574
|
+
}
|
|
575
|
+
checkNumberRange(value, max, min, schemaId, key) {
|
|
576
|
+
if (value > max || value < min) {
|
|
577
|
+
return `Schema ${schemaId} on field: ${key}, number value is too large or small`;
|
|
578
|
+
}
|
|
579
|
+
return undefined;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
const logValidator = new LogValidator();
|
|
583
|
+
|
|
584
|
+
class BucketHistogramImpl {
|
|
585
|
+
constructor(_name, _ownerName, _ownerAppName, _tags, _buckets) {
|
|
586
|
+
this._name = _name;
|
|
587
|
+
this._ownerName = _ownerName;
|
|
588
|
+
this._ownerAppName = _ownerAppName;
|
|
589
|
+
this._tags = _tags;
|
|
590
|
+
this._buckets = _buckets;
|
|
591
|
+
this._values = new Array();
|
|
592
|
+
this._createdOn = utility.time().tsNow;
|
|
593
|
+
}
|
|
594
|
+
getName() {
|
|
595
|
+
return this._name;
|
|
596
|
+
}
|
|
597
|
+
getCreatedOn() {
|
|
598
|
+
return this._createdOn;
|
|
599
|
+
}
|
|
600
|
+
getLastUpdatedOn() {
|
|
601
|
+
return this._lastUpdatedOn;
|
|
602
|
+
}
|
|
603
|
+
getData() {
|
|
604
|
+
return this.values;
|
|
605
|
+
}
|
|
606
|
+
getBuckets() {
|
|
607
|
+
return this.buckets;
|
|
608
|
+
}
|
|
609
|
+
get buckets() {
|
|
610
|
+
return this._buckets.slice(0, this._buckets.length);
|
|
611
|
+
}
|
|
612
|
+
get values() {
|
|
613
|
+
return this._values.slice(0, this._values.length);
|
|
614
|
+
}
|
|
615
|
+
record(value) {
|
|
616
|
+
if (typeof value === 'number') {
|
|
617
|
+
this._values.push(value);
|
|
618
|
+
this._lastUpdatedOn = utility.time().tsNow;
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
throw new Error('BucketHistogram can only record numbers.');
|
|
622
|
+
}
|
|
623
|
+
reset() {
|
|
624
|
+
this._lastUpdatedOn = undefined;
|
|
625
|
+
this._values = [];
|
|
626
|
+
}
|
|
627
|
+
getOwnerName() {
|
|
628
|
+
return this._ownerName;
|
|
629
|
+
}
|
|
630
|
+
getOwnerAppName() {
|
|
631
|
+
return this._ownerAppName;
|
|
632
|
+
}
|
|
633
|
+
getTags() {
|
|
634
|
+
return this._tags;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
class UpCounterImpl {
|
|
639
|
+
constructor(_name, _ownerName, _ownerAppName, _tags) {
|
|
640
|
+
this._name = _name;
|
|
641
|
+
this._ownerName = _ownerName;
|
|
642
|
+
this._ownerAppName = _ownerAppName;
|
|
643
|
+
this._tags = _tags;
|
|
644
|
+
this._value = 0;
|
|
645
|
+
this._createdOn = utility.time().tsNow;
|
|
646
|
+
}
|
|
647
|
+
getName() {
|
|
648
|
+
return this._name;
|
|
649
|
+
}
|
|
650
|
+
getCreatedOn() {
|
|
651
|
+
return this._createdOn;
|
|
652
|
+
}
|
|
653
|
+
getLastUpdatedOn() {
|
|
654
|
+
return this._lastUpdatedOn;
|
|
655
|
+
}
|
|
656
|
+
getData() {
|
|
657
|
+
return this._value;
|
|
658
|
+
}
|
|
659
|
+
increment(value = 1) {
|
|
660
|
+
if (typeof value === 'number' && value > 0) {
|
|
661
|
+
this._value += Math.round(value);
|
|
662
|
+
this._lastUpdatedOn = utility.time().tsNow;
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
throw new Error('UpCounter can only increment positive numbers.');
|
|
666
|
+
}
|
|
667
|
+
reset() {
|
|
668
|
+
this._lastUpdatedOn = undefined;
|
|
669
|
+
this._value = 0;
|
|
670
|
+
}
|
|
671
|
+
getOwnerName() {
|
|
672
|
+
return this._ownerName;
|
|
673
|
+
}
|
|
674
|
+
getOwnerAppName() {
|
|
675
|
+
return this._ownerAppName;
|
|
676
|
+
}
|
|
677
|
+
getTags() {
|
|
678
|
+
return this._tags;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
class ValueRecorderImpl {
|
|
683
|
+
constructor(_name, _ownerName, _ownerAppName, _tags) {
|
|
684
|
+
this._name = _name;
|
|
685
|
+
this._ownerName = _ownerName;
|
|
686
|
+
this._ownerAppName = _ownerAppName;
|
|
687
|
+
this._tags = _tags;
|
|
688
|
+
this._values = new Array();
|
|
689
|
+
this._createdOn = utility.time().tsNow;
|
|
690
|
+
}
|
|
691
|
+
getName() {
|
|
692
|
+
return this._name;
|
|
693
|
+
}
|
|
694
|
+
getCreatedOn() {
|
|
695
|
+
return this._createdOn;
|
|
696
|
+
}
|
|
697
|
+
getLastUpdatedOn() {
|
|
698
|
+
return this._lastUpdatedOn;
|
|
699
|
+
}
|
|
700
|
+
getData() {
|
|
701
|
+
return this.values;
|
|
702
|
+
}
|
|
703
|
+
get values() {
|
|
704
|
+
return this._values.slice(0, this._values.length);
|
|
705
|
+
}
|
|
706
|
+
record(value) {
|
|
707
|
+
if (typeof value === 'number') {
|
|
708
|
+
this._values.push(value);
|
|
709
|
+
this._lastUpdatedOn = utility.time().tsNow;
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
throw new Error('ValueRecorder can only record numbers.');
|
|
713
|
+
}
|
|
714
|
+
reset() {
|
|
715
|
+
this._lastUpdatedOn = undefined;
|
|
716
|
+
this._values = [];
|
|
717
|
+
}
|
|
718
|
+
getOwnerName() {
|
|
719
|
+
return this._ownerName;
|
|
720
|
+
}
|
|
721
|
+
getOwnerAppName() {
|
|
722
|
+
return this._ownerAppName;
|
|
723
|
+
}
|
|
724
|
+
getTags() {
|
|
725
|
+
return this._tags;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
class SizeLimitedMap {
|
|
730
|
+
constructor(maxSize) {
|
|
731
|
+
this._map = new Map();
|
|
732
|
+
if (typeof maxSize === 'number' && maxSize > 0) {
|
|
733
|
+
this._maxSize = Math.ceil(maxSize);
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
throw new Error('maxSize must be a positive number');
|
|
737
|
+
}
|
|
738
|
+
get maxSize() {
|
|
739
|
+
return this._maxSize;
|
|
740
|
+
}
|
|
741
|
+
get(key) {
|
|
742
|
+
return this._map.get(key);
|
|
743
|
+
}
|
|
744
|
+
has(key) {
|
|
745
|
+
return this._map.has(key);
|
|
746
|
+
}
|
|
747
|
+
set(key, value) {
|
|
748
|
+
if (this.has(key) || this._map.size < this.maxSize) {
|
|
749
|
+
this._map.set(key, value);
|
|
750
|
+
return true;
|
|
751
|
+
}
|
|
752
|
+
return false;
|
|
753
|
+
}
|
|
754
|
+
getElements() {
|
|
755
|
+
return Array.from(this._map.values());
|
|
756
|
+
}
|
|
757
|
+
clear() {
|
|
758
|
+
this._map.clear();
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
const maxCounters = 1000;
|
|
763
|
+
const maxValueRecorders = 500;
|
|
764
|
+
const maxBucketHistograms = 500;
|
|
765
|
+
var MetricType;
|
|
766
|
+
(function (MetricType) {
|
|
767
|
+
MetricType[MetricType["Counter"] = 0] = "Counter";
|
|
768
|
+
MetricType[MetricType["Percentile"] = 1] = "Percentile";
|
|
769
|
+
MetricType[MetricType["BucketHistogram"] = 2] = "BucketHistogram";
|
|
770
|
+
})(MetricType || (MetricType = {}));
|
|
771
|
+
class MetricsImpl {
|
|
772
|
+
constructor(_ownerName, _getOwnerAppName) {
|
|
773
|
+
this._ownerName = _ownerName;
|
|
774
|
+
this._getOwnerAppName = _getOwnerAppName;
|
|
775
|
+
this._upCounters = new SizeLimitedMap(maxCounters);
|
|
776
|
+
this._valueRecorders = new SizeLimitedMap(maxValueRecorders);
|
|
777
|
+
this._bucketHistograms = new SizeLimitedMap(maxBucketHistograms);
|
|
778
|
+
}
|
|
779
|
+
incrementCounter(operation, increment, hasError = false, tags = {}) {
|
|
780
|
+
this._tagError(tags, hasError);
|
|
781
|
+
this._upCounter(operation, tags).increment(increment);
|
|
782
|
+
}
|
|
783
|
+
trackValue(operation, value, hasError = false, tags = {}) {
|
|
784
|
+
this._tagError(tags, hasError);
|
|
785
|
+
this._valueRecorder(operation, tags).record(value);
|
|
786
|
+
}
|
|
787
|
+
bucketValue(operation, value, buckets, hasError = false, tags = {}) {
|
|
788
|
+
this._tagError(tags, hasError);
|
|
789
|
+
this._bucketHistogram(operation, tags, buckets).record(value);
|
|
790
|
+
}
|
|
791
|
+
_bucketHistogram(name, tags, buckets) {
|
|
792
|
+
const { key, sortedTags } = this._getKeyAndSortedTags(name, tags, MetricType.BucketHistogram);
|
|
793
|
+
let instrument = this._bucketHistograms.get(key);
|
|
794
|
+
if (!instrument) {
|
|
795
|
+
instrument = new BucketHistogramImpl(name, this._ownerName, this._getOwnerAppName(), sortedTags, buckets);
|
|
796
|
+
if (!this._bucketHistograms.set(key, instrument)) {
|
|
797
|
+
throw new Error(`Max size of ${maxBucketHistograms} exceeded for BucketHistograms`);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
return instrument;
|
|
801
|
+
}
|
|
802
|
+
_upCounter(name, tags) {
|
|
803
|
+
const { key, sortedTags } = this._getKeyAndSortedTags(name, tags, MetricType.Counter);
|
|
804
|
+
let instrument = this._upCounters.get(key);
|
|
805
|
+
if (!instrument) {
|
|
806
|
+
instrument = new UpCounterImpl(name, this._ownerName, this._getOwnerAppName(), sortedTags);
|
|
807
|
+
if (!this._upCounters.set(key, instrument)) {
|
|
808
|
+
throw new Error(`Max size of ${maxCounters} exceeded for UpCounters`);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
return instrument;
|
|
812
|
+
}
|
|
813
|
+
_valueRecorder(name, tags) {
|
|
814
|
+
const { key, sortedTags } = this._getKeyAndSortedTags(name, tags, MetricType.Percentile);
|
|
815
|
+
let instrument = this._valueRecorders.get(key);
|
|
816
|
+
if (!instrument) {
|
|
817
|
+
instrument = new ValueRecorderImpl(name, this._ownerName, this._getOwnerAppName(), sortedTags);
|
|
818
|
+
if (!this._valueRecorders.set(key, instrument)) {
|
|
819
|
+
throw new Error(`Max size of ${maxValueRecorders} exceeded for ValueRecorders`);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
return instrument;
|
|
823
|
+
}
|
|
824
|
+
getUpCounters() {
|
|
825
|
+
return this._upCounters.getElements();
|
|
826
|
+
}
|
|
827
|
+
getValueRecorders() {
|
|
828
|
+
return this._valueRecorders.getElements();
|
|
829
|
+
}
|
|
830
|
+
getBucketHistograms() {
|
|
831
|
+
return this._bucketHistograms.getElements();
|
|
832
|
+
}
|
|
833
|
+
_tagError(tags, hasError) {
|
|
834
|
+
tags.status = hasError === true ? 'error' : 'success';
|
|
835
|
+
}
|
|
836
|
+
_getKeyAndSortedTags(operation, tags, metricType) {
|
|
837
|
+
const sortedTags = Object.keys(tags)
|
|
838
|
+
.sort()
|
|
839
|
+
.reduce((prev, curr) => {
|
|
840
|
+
prev[curr] = tags[curr];
|
|
841
|
+
return prev;
|
|
842
|
+
}, {});
|
|
843
|
+
const key = `${MetricType[metricType]}:${operation}${JSON.stringify(sortedTags)}`;
|
|
844
|
+
return {
|
|
845
|
+
key,
|
|
846
|
+
sortedTags
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
class MockEvent {
|
|
852
|
+
constructor(type, composed, _composedPaths) {
|
|
853
|
+
this.type = type;
|
|
854
|
+
this.composed = composed;
|
|
855
|
+
this._composedPaths = _composedPaths;
|
|
856
|
+
}
|
|
857
|
+
composedPath() {
|
|
858
|
+
return this._composedPaths;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
const maxActivityDurationMsecs = undefined;
|
|
863
|
+
const reservedMetricCharacters = ['`'];
|
|
864
|
+
const reservedMetricNames = {
|
|
865
|
+
internalError: 'o11y-error'
|
|
866
|
+
};
|
|
867
|
+
const denyListMetricNames = Object.freeze(Array.from(Object.values(reservedMetricNames)));
|
|
868
|
+
class InstrumentationImpl {
|
|
869
|
+
constructor(_nextGen, _name) {
|
|
870
|
+
this._nextGen = _nextGen;
|
|
871
|
+
this._name = _name;
|
|
872
|
+
this._onActivityStoppedCallback = this._handleActivityStop.bind(this);
|
|
873
|
+
this._onActivityErrorCallback = this._handleActivityError.bind(this);
|
|
874
|
+
for (const reservedChar of reservedMetricCharacters) {
|
|
875
|
+
if (this._name.indexOf(reservedChar) >= 0) {
|
|
876
|
+
throw new Error(`Name cannot include the reserved character "${reservedChar}"`);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
this._safety = new PublicSafety({
|
|
880
|
+
increment: (increment) => this._incrementError(increment)
|
|
881
|
+
});
|
|
882
|
+
this._metrics = this._initMetrics();
|
|
883
|
+
const simpleTextOptions = schemaUtil.getOptions(simple, 'Simple', 'text');
|
|
884
|
+
this._simpleTextMaxLength = simpleTextOptions
|
|
885
|
+
? simpleTextOptions['(meta.max_length)']
|
|
886
|
+
: Number.MAX_VALUE;
|
|
887
|
+
}
|
|
888
|
+
_initMetrics() {
|
|
889
|
+
return new MetricsImpl(this.name, () => this._nextGen.appName || InstrumentationImpl.defaultAppName);
|
|
890
|
+
}
|
|
891
|
+
_incrementError(increment = 1) {
|
|
892
|
+
this._metrics.incrementCounter(reservedMetricNames.internalError, increment, false);
|
|
893
|
+
}
|
|
894
|
+
get name() {
|
|
895
|
+
return this._name;
|
|
896
|
+
}
|
|
897
|
+
_wrapUserPayload(userSchemaOrText, userData, onlyIfBoth = false) {
|
|
898
|
+
let userSchema;
|
|
899
|
+
if (typeof userSchemaOrText === 'string') {
|
|
900
|
+
userSchema = simple;
|
|
901
|
+
if (userSchemaOrText) {
|
|
902
|
+
userData = {
|
|
903
|
+
text: userSchemaOrText.substr(0, this._simpleTextMaxLength)
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
else {
|
|
907
|
+
userData = undefined;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
else {
|
|
911
|
+
userSchema = userSchemaOrText;
|
|
912
|
+
}
|
|
913
|
+
return schemaUtil.makePayload(userSchema, userData, onlyIfBoth);
|
|
914
|
+
}
|
|
915
|
+
getEffectiveRootId(options) {
|
|
916
|
+
var _a, _b;
|
|
917
|
+
return ((_b = (_a = options === null || options === void 0 ? void 0 : options.instrumentationContext) === null || _a === void 0 ? void 0 : _a.rootId) !== null && _b !== void 0 ? _b : this._nextGen.getDefaultInstrumentationContext().rootId);
|
|
918
|
+
}
|
|
919
|
+
log(userSchemaOrText, userData, options) {
|
|
920
|
+
this._safety.tryCatch(() => {
|
|
921
|
+
const timestamp = utility.time().tsNow;
|
|
922
|
+
utility.requireArgument(userSchemaOrText, 'userSchemaOrText', ['object', 'string']);
|
|
923
|
+
utility.requireArgumentIfDefined(userData, 'userData', 'object');
|
|
924
|
+
utility.requireArgumentIfDefined(options, 'options', 'object');
|
|
925
|
+
const userPayload = this._wrapUserPayload(userSchemaOrText, userData);
|
|
926
|
+
if (userPayload === null || userPayload === void 0 ? void 0 : userPayload.payload) {
|
|
927
|
+
this._logInternal(this.name, userPayload.schema, userPayload.payload, timestamp, this.getEffectiveRootId(options));
|
|
928
|
+
}
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
_logInternal(loggerName, schema, data, timestamp, rootId) {
|
|
932
|
+
this._checkInputs(schema, data);
|
|
933
|
+
const appPayload = this._getPayloadFromProvider(this._nextGen.appPayloadProvider);
|
|
934
|
+
const pagePayload = this._getPayloadFromProvider(this._nextGen.pagePayloadProvider);
|
|
935
|
+
return this._nextGen.addLog(loggerName, schema, data, timestamp, rootId, pagePayload, appPayload);
|
|
936
|
+
}
|
|
937
|
+
error(error, userSchemaOrText, userData, options) {
|
|
938
|
+
return this._safety.tryCatch(() => {
|
|
939
|
+
utility.requireArgumentIfDefined(userSchemaOrText, 'userSchemaOrText', [
|
|
940
|
+
'object',
|
|
941
|
+
'string'
|
|
942
|
+
]);
|
|
943
|
+
utility.requireArgumentIfDefined(userData, 'userData', 'object');
|
|
944
|
+
utility.requireArgumentIfDefined(options, 'options', 'object');
|
|
945
|
+
const rootId = this.getEffectiveRootId(options);
|
|
946
|
+
this._errorInternal(error, userSchemaOrText, userData, undefined, rootId);
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
_errorInternal(err, userSchemaOrText, userData, activityId, rootActivityId) {
|
|
950
|
+
const loggedTimestamp = utility.time().tsNow;
|
|
951
|
+
let error$1;
|
|
952
|
+
if (err instanceof Error) {
|
|
953
|
+
error$1 = err;
|
|
954
|
+
}
|
|
955
|
+
else {
|
|
956
|
+
let msg;
|
|
957
|
+
if (err === undefined || err === null || typeof err.toString !== 'function') {
|
|
958
|
+
msg = 'UNKNOWN';
|
|
959
|
+
}
|
|
960
|
+
else {
|
|
961
|
+
msg = err.toString();
|
|
962
|
+
}
|
|
963
|
+
error$1 = new Error(msg);
|
|
964
|
+
}
|
|
965
|
+
const userPayload = this._wrapUserPayload(userSchemaOrText, userData, true);
|
|
966
|
+
const errorData = {
|
|
967
|
+
name: error$1.name,
|
|
968
|
+
message: error$1.message,
|
|
969
|
+
stack: error$1.stack,
|
|
970
|
+
userPayload,
|
|
971
|
+
activityId
|
|
972
|
+
};
|
|
973
|
+
return this._logInternal(this.name, error, errorData, loggedTimestamp, rootActivityId);
|
|
974
|
+
}
|
|
975
|
+
startActivity(name, options) {
|
|
976
|
+
return this._safety.tryCatchReturn(() => {
|
|
977
|
+
var _a;
|
|
978
|
+
utility.requireArgument(name, 'name');
|
|
979
|
+
utility.requireArgumentIfDefined(options, 'options', 'object');
|
|
980
|
+
let context;
|
|
981
|
+
const rootId = (_a = options === null || options === void 0 ? void 0 : options.instrumentationContext) === null || _a === void 0 ? void 0 : _a.rootId;
|
|
982
|
+
if (rootId) {
|
|
983
|
+
context = {
|
|
984
|
+
rootId,
|
|
985
|
+
isRootActivitySampled: options.instrumentationContext.isRootActivitySampled
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
else {
|
|
989
|
+
context = this._nextGen.getDefaultInstrumentationContext();
|
|
990
|
+
}
|
|
991
|
+
const activity = new ActivityImpl(name, context.rootId, this._onActivityStoppedCallback, this._onActivityErrorCallback, maxActivityDurationMsecs, undefined, context.isRootActivitySampled);
|
|
992
|
+
return activity;
|
|
993
|
+
}, activityNoOp);
|
|
994
|
+
}
|
|
995
|
+
_getActivityData(detail) {
|
|
996
|
+
const userPayload = this._wrapUserPayload(detail.userSchemaOrText, detail.userData, true);
|
|
997
|
+
return {
|
|
998
|
+
id: detail.id,
|
|
999
|
+
name: detail.name,
|
|
1000
|
+
duration: detail.stopPerfTime - detail.startPerfTime,
|
|
1001
|
+
stopReason: detail.stopReason,
|
|
1002
|
+
userPayload,
|
|
1003
|
+
errorCount: detail.errorCount,
|
|
1004
|
+
isSampled: detail.isSampled
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
_handleActivityStop(detail) {
|
|
1008
|
+
if (detail.stopReason === discarded) {
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
const activityData = this._getActivityData(detail);
|
|
1012
|
+
this._logActivity(activityData, detail.startTimestamp, detail.rootId);
|
|
1013
|
+
}
|
|
1014
|
+
_logActivity(activityData, startTimestamp, rootId) {
|
|
1015
|
+
this._logInternal(this.name, activity, activityData, startTimestamp, rootId);
|
|
1016
|
+
}
|
|
1017
|
+
_handleActivityError(error, detail) {
|
|
1018
|
+
this._errorInternal(error, detail.userSchemaOrText, detail.userData, detail.id, detail.rootId);
|
|
1019
|
+
}
|
|
1020
|
+
_getPayloadFromProvider(provider) {
|
|
1021
|
+
const payload = (provider === null || provider === void 0 ? void 0 : provider.getPayload()) || undefined;
|
|
1022
|
+
if (payload) {
|
|
1023
|
+
this._checkInputs(payload.schema, payload.payload);
|
|
1024
|
+
}
|
|
1025
|
+
return payload;
|
|
1026
|
+
}
|
|
1027
|
+
domEvent(event, handledBy, userSchemaOrText, userData, options) {
|
|
1028
|
+
this._safety.tryCatch(() => {
|
|
1029
|
+
const tsNow = utility.time().tsNow;
|
|
1030
|
+
utility.requireArgument(event, 'event', [Event, MockEvent]);
|
|
1031
|
+
utility.requireArgument(handledBy, 'handledBy', [HTMLElement, 'object']);
|
|
1032
|
+
let htmlElement;
|
|
1033
|
+
if (handledBy instanceof HTMLElement) {
|
|
1034
|
+
htmlElement = handledBy;
|
|
1035
|
+
}
|
|
1036
|
+
else {
|
|
1037
|
+
handledBy = handledBy;
|
|
1038
|
+
if (handledBy.template && handledBy.template.host instanceof HTMLElement) {
|
|
1039
|
+
htmlElement = handledBy.template.host;
|
|
1040
|
+
}
|
|
1041
|
+
else {
|
|
1042
|
+
utility.requireArgument(undefined, 'handledBy');
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
const userPayload = this._wrapUserPayload(userSchemaOrText, userData, true);
|
|
1046
|
+
const rootId = this.getEffectiveRootId(options);
|
|
1047
|
+
switch (event.type) {
|
|
1048
|
+
case 'click': {
|
|
1049
|
+
const mouseEvent = event;
|
|
1050
|
+
const acd = this._nextGen.getClickTracker();
|
|
1051
|
+
if (acd) {
|
|
1052
|
+
acd.markEventHandled(mouseEvent);
|
|
1053
|
+
}
|
|
1054
|
+
const mouseEventData = domEventHelpers.getMouseEventData(mouseEvent);
|
|
1055
|
+
const instrumentedEvent = domEventHelpers.getInstrumentedEventData(mouseEventData, htmlElement, userPayload);
|
|
1056
|
+
instrumentedEvent.auto = options && options._auto;
|
|
1057
|
+
this._logInternal(this.name, instrumented_event, instrumentedEvent, tsNow, rootId);
|
|
1058
|
+
break;
|
|
1059
|
+
}
|
|
1060
|
+
default:
|
|
1061
|
+
throw new Error(utility.notImplemented);
|
|
1062
|
+
}
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
incrementCounter(operation, increment = 1, hasError = false, tags = {}) {
|
|
1066
|
+
this._safety.tryCatch(() => {
|
|
1067
|
+
utility.requireArgument(operation, 'operation', 'string');
|
|
1068
|
+
utility.checkForDenyListedValues(operation, 'operation', denyListMetricNames);
|
|
1069
|
+
utility.checkForReservedCharacters(operation, 'operation', reservedMetricCharacters);
|
|
1070
|
+
utility.requireArgument(increment, 'increment', 'number');
|
|
1071
|
+
utility.requireArgument(hasError, 'hasError', 'boolean');
|
|
1072
|
+
utility.requireArgument(tags, 'tags', 'object');
|
|
1073
|
+
Object.entries(tags).forEach((entry) => {
|
|
1074
|
+
utility.requireArgument(entry[1], `Tag value for '${entry[0]}'`, [
|
|
1075
|
+
'string',
|
|
1076
|
+
'number',
|
|
1077
|
+
'boolean'
|
|
1078
|
+
]);
|
|
1079
|
+
});
|
|
1080
|
+
this._metrics.incrementCounter(operation, increment, hasError, tags);
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
trackValue(operation, value, hasError = false, tags = {}) {
|
|
1084
|
+
this._safety.tryCatch(() => {
|
|
1085
|
+
utility.requireArgument(operation, 'operation', 'string');
|
|
1086
|
+
utility.checkForDenyListedValues(operation, 'operation', denyListMetricNames);
|
|
1087
|
+
utility.checkForReservedCharacters(operation, 'operation', reservedMetricCharacters);
|
|
1088
|
+
utility.requireArgument(value, 'value', 'number');
|
|
1089
|
+
utility.requireArgument(hasError, 'hasError', 'boolean');
|
|
1090
|
+
utility.requireArgument(tags, 'tags', 'object');
|
|
1091
|
+
Object.entries(tags).forEach((entry) => {
|
|
1092
|
+
utility.requireArgument(entry[1], `Tag value for '${entry[0]}'`, [
|
|
1093
|
+
'string',
|
|
1094
|
+
'number',
|
|
1095
|
+
'boolean'
|
|
1096
|
+
]);
|
|
1097
|
+
});
|
|
1098
|
+
this._metrics.trackValue(operation, value, hasError, tags);
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
bucketValue(operation, value, buckets = [], hasError = false, tags = {}) {
|
|
1102
|
+
this._safety.tryCatch(() => {
|
|
1103
|
+
utility.requireArgument(operation, 'operation', 'string');
|
|
1104
|
+
utility.checkForDenyListedValues(operation, 'operation', denyListMetricNames);
|
|
1105
|
+
utility.checkForReservedCharacters(operation, 'operation', reservedMetricCharacters);
|
|
1106
|
+
utility.requireArgument(value, 'value', 'number');
|
|
1107
|
+
utility.requireArgument(buckets, 'buckets', Array);
|
|
1108
|
+
Object.entries(buckets).forEach((entry) => {
|
|
1109
|
+
utility.requireArgument(entry[1], `Bucket value for '${entry[0]}'`, 'number');
|
|
1110
|
+
});
|
|
1111
|
+
utility.requireArgument(hasError, 'hasError', 'boolean');
|
|
1112
|
+
utility.requireArgument(tags, 'tags', 'object');
|
|
1113
|
+
Object.entries(tags).forEach((entry) => {
|
|
1114
|
+
utility.requireArgument(entry[1], `Tag value for '${entry[0]}'`, [
|
|
1115
|
+
'string',
|
|
1116
|
+
'number',
|
|
1117
|
+
'boolean'
|
|
1118
|
+
]);
|
|
1119
|
+
});
|
|
1120
|
+
this._metrics.bucketValue(operation, value, buckets, hasError, tags);
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
_checkInputs(schema, data) {
|
|
1124
|
+
schemaUtil.checkSchema(schema);
|
|
1125
|
+
utility.requireArgument(data, 'data', 'object');
|
|
1126
|
+
let savedUserPayload;
|
|
1127
|
+
if (data.userPayload !== undefined && schemaUtil.isInternal(schema)) {
|
|
1128
|
+
savedUserPayload = data.userPayload;
|
|
1129
|
+
logValidator.validate(savedUserPayload.schema, savedUserPayload.payload);
|
|
1130
|
+
data.userPayload = undefined;
|
|
1131
|
+
}
|
|
1132
|
+
logValidator.validate(schema, data);
|
|
1133
|
+
if (savedUserPayload !== undefined) {
|
|
1134
|
+
data.userPayload = savedUserPayload;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
getUpCounters() {
|
|
1138
|
+
return this._metrics.getUpCounters().filter((m) => m.getLastUpdatedOn());
|
|
1139
|
+
}
|
|
1140
|
+
getValueRecorders() {
|
|
1141
|
+
return this._metrics.getValueRecorders().filter((m) => m.getLastUpdatedOn());
|
|
1142
|
+
}
|
|
1143
|
+
getBucketHistograms() {
|
|
1144
|
+
return this._metrics.getBucketHistograms().filter((m) => m.getLastUpdatedOn());
|
|
1145
|
+
}
|
|
1146
|
+
registerForLogPrompt(listener) {
|
|
1147
|
+
utility.requireArgument(listener, 'listener', 'function');
|
|
1148
|
+
this._nextGen.registerForLogPrompt(listener);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
InstrumentationImpl.defaultAppName = 'APP_NOT_REGISTERED';
|
|
1152
|
+
|
|
1153
|
+
class RootActivityImpl extends ActivityImpl {
|
|
1154
|
+
constructor(name, onStopped, onError, rootId, _isSampled) {
|
|
1155
|
+
super(name, undefined, onStopped, onError, undefined, rootId || utility.generateUniqueId(32), _isSampled);
|
|
1156
|
+
}
|
|
1157
|
+
get preRootId() {
|
|
1158
|
+
return this._preRootId;
|
|
1159
|
+
}
|
|
1160
|
+
set preRootId(value) {
|
|
1161
|
+
this._preRootId = value;
|
|
1162
|
+
}
|
|
1163
|
+
_getDetail(userSchema, userData) {
|
|
1164
|
+
const detail = super._getDetail(userSchema, userData);
|
|
1165
|
+
detail.isRoot = true;
|
|
1166
|
+
detail.preRootId = this.preRootId;
|
|
1167
|
+
return detail;
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
const rootId = new Array(32).fill(0).join('');
|
|
1172
|
+
class RootActivityNoOp {
|
|
1173
|
+
getId() {
|
|
1174
|
+
return rootId;
|
|
1175
|
+
}
|
|
1176
|
+
getRootId() {
|
|
1177
|
+
return undefined;
|
|
1178
|
+
}
|
|
1179
|
+
error() { }
|
|
1180
|
+
stop() { }
|
|
1181
|
+
discard() { }
|
|
1182
|
+
terminate() { }
|
|
1183
|
+
getIsSampled() {
|
|
1184
|
+
return false;
|
|
1185
|
+
}
|
|
1186
|
+
getTraceHeaders(__options) {
|
|
1187
|
+
return {};
|
|
1188
|
+
}
|
|
1189
|
+
getStartTimestamp() {
|
|
1190
|
+
return undefined;
|
|
1191
|
+
}
|
|
1192
|
+
getStartPerfTime() {
|
|
1193
|
+
return undefined;
|
|
1194
|
+
}
|
|
1195
|
+
getStopPerfTime() {
|
|
1196
|
+
return undefined;
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
const rootActivityNoOp = Object.freeze(new RootActivityNoOp());
|
|
1200
|
+
|
|
1201
|
+
class AppInstrumentationImpl extends InstrumentationImpl {
|
|
1202
|
+
constructor(_nextGen, _name, _allowMulti) {
|
|
1203
|
+
super(_nextGen, _name);
|
|
1204
|
+
this._allowMulti = _allowMulti;
|
|
1205
|
+
this._onRootActivityStoppedCallback = this.handleRootActivityStop.bind(this);
|
|
1206
|
+
}
|
|
1207
|
+
startRootActivity(name, rootId, isSampled) {
|
|
1208
|
+
return this._safety.tryCatchReturn(() => {
|
|
1209
|
+
utility.requireArgument(name, 'name');
|
|
1210
|
+
const newRootActivity = new RootActivityImpl(name, this._onRootActivityStoppedCallback, this._onActivityErrorCallback, rootId, isSampled);
|
|
1211
|
+
if (!this._allowMulti) {
|
|
1212
|
+
if (this._singleRootActivity && !this._singleRootActivity.isStopped) {
|
|
1213
|
+
const preRootId = this._singleRootActivity.getId();
|
|
1214
|
+
this._singleRootActivity.terminate();
|
|
1215
|
+
newRootActivity.preRootId = preRootId;
|
|
1216
|
+
}
|
|
1217
|
+
this._singleRootActivity = newRootActivity;
|
|
1218
|
+
}
|
|
1219
|
+
return newRootActivity;
|
|
1220
|
+
}, rootActivityNoOp);
|
|
1221
|
+
}
|
|
1222
|
+
handleRootActivityStop(detail) {
|
|
1223
|
+
if (detail.stopReason === discarded) {
|
|
1224
|
+
return;
|
|
1225
|
+
}
|
|
1226
|
+
const activityData = this._getActivityData(detail);
|
|
1227
|
+
this._logActivity(activityData, detail.startTimestamp);
|
|
1228
|
+
this._singleRootActivity = undefined;
|
|
1229
|
+
}
|
|
1230
|
+
_getActivityData(detail) {
|
|
1231
|
+
const activityData = super._getActivityData(detail);
|
|
1232
|
+
activityData.isRoot = detail.isRoot;
|
|
1233
|
+
activityData.preRootId = detail.preRootId;
|
|
1234
|
+
return activityData;
|
|
1235
|
+
}
|
|
1236
|
+
getSingleRootActivityId() {
|
|
1237
|
+
var _a;
|
|
1238
|
+
return (_a = this._singleRootActivity) === null || _a === void 0 ? void 0 : _a.getId();
|
|
1239
|
+
}
|
|
1240
|
+
isSingleRootActivitySampled() {
|
|
1241
|
+
var _a;
|
|
1242
|
+
return (_a = this._singleRootActivity) === null || _a === void 0 ? void 0 : _a.getIsSampled();
|
|
1243
|
+
}
|
|
1244
|
+
_initMetrics() {
|
|
1245
|
+
return new MetricsImpl(this.name, () => this.name);
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
const pathLimit = 5;
|
|
1250
|
+
class AutomaticClickTracker {
|
|
1251
|
+
constructor(instrumentation, document) {
|
|
1252
|
+
this.isActive = false;
|
|
1253
|
+
this._boundClickListener = this.clickListener.bind(this);
|
|
1254
|
+
utility.requireArgument(instrumentation, 'instrumentation');
|
|
1255
|
+
utility.requireArgument(document, 'document');
|
|
1256
|
+
this.instr = instrumentation;
|
|
1257
|
+
this.document = document;
|
|
1258
|
+
}
|
|
1259
|
+
activate() {
|
|
1260
|
+
if (!this.isActive) {
|
|
1261
|
+
this.document.addEventListener('click', this._boundClickListener, true);
|
|
1262
|
+
this.isActive = true;
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
deactivate() {
|
|
1266
|
+
if (this.isActive) {
|
|
1267
|
+
this.document.removeEventListener('click', this._boundClickListener, true);
|
|
1268
|
+
this.isActive = false;
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
markEventHandled(event) {
|
|
1272
|
+
this.ignoredEvent = event;
|
|
1273
|
+
}
|
|
1274
|
+
clickListener(event) {
|
|
1275
|
+
let eventTargets = event.composedPath && event.composedPath();
|
|
1276
|
+
if (!eventTargets || !eventTargets.length) {
|
|
1277
|
+
eventTargets = event.path;
|
|
1278
|
+
}
|
|
1279
|
+
const handledBy = this.getClickableElement(eventTargets);
|
|
1280
|
+
if (handledBy) {
|
|
1281
|
+
setTimeout(() => {
|
|
1282
|
+
if (event !== this.ignoredEvent) {
|
|
1283
|
+
this.instr.domEvent(event, handledBy, undefined, undefined, {
|
|
1284
|
+
_auto: true
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
getClickableElement(path) {
|
|
1291
|
+
const limit = path ? Math.min(path.length, pathLimit) : 0;
|
|
1292
|
+
for (let x = 0; x < limit; x += 1) {
|
|
1293
|
+
const currentElement = path[x];
|
|
1294
|
+
const tagName = currentElement.tagName && currentElement.tagName.toLowerCase();
|
|
1295
|
+
if (tagName === 'a' || tagName === 'button') {
|
|
1296
|
+
return currentElement;
|
|
1297
|
+
}
|
|
1298
|
+
if (tagName === 'input') {
|
|
1299
|
+
const inputElement = currentElement;
|
|
1300
|
+
if (inputElement.type && inputElement.type.toLowerCase() === 'button') {
|
|
1301
|
+
return inputElement;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
return undefined;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
const maxInstrumentationLength = 80;
|
|
1310
|
+
const truncatedText = '_CUT';
|
|
1311
|
+
const maxInstrumentationLengthBeforeTruncated = maxInstrumentationLength - truncatedText.length;
|
|
1312
|
+
class NextgenImpl {
|
|
1313
|
+
constructor() {
|
|
1314
|
+
this._logCollectors = new Set();
|
|
1315
|
+
this._instruments = new Map();
|
|
1316
|
+
this._sequence = 0;
|
|
1317
|
+
this._forceDisabledLogCollectors = new Set();
|
|
1318
|
+
this._logCollectorFailures = new Map();
|
|
1319
|
+
this._isBufferingEnabled = false;
|
|
1320
|
+
this._buffer = [];
|
|
1321
|
+
this._logCollectionListeners = new Set();
|
|
1322
|
+
}
|
|
1323
|
+
get pagePayloadProvider() {
|
|
1324
|
+
return this._pagePayloadProvider;
|
|
1325
|
+
}
|
|
1326
|
+
set pagePayloadProvider(provider) {
|
|
1327
|
+
this._pagePayloadProvider = provider;
|
|
1328
|
+
}
|
|
1329
|
+
get appPayloadProvider() {
|
|
1330
|
+
return this._appPayloadProvider;
|
|
1331
|
+
}
|
|
1332
|
+
set appPayloadProvider(provider) {
|
|
1333
|
+
this._appPayloadProvider = provider;
|
|
1334
|
+
}
|
|
1335
|
+
registerApp(name, options) {
|
|
1336
|
+
utility.requireArgument(name, 'name', 'string');
|
|
1337
|
+
if (this._appInstr) {
|
|
1338
|
+
throw new Error('An app has already been registered with instrumentation.');
|
|
1339
|
+
}
|
|
1340
|
+
const instr = this._instruments.get(name);
|
|
1341
|
+
if (instr) {
|
|
1342
|
+
throw new Error(`The instrumentation name ${name} is already taken`);
|
|
1343
|
+
}
|
|
1344
|
+
this._appInstr = new AppInstrumentationImpl(this, name, options && options.allowMultipleRootActivities);
|
|
1345
|
+
this._instruments.set(name, this._appInstr);
|
|
1346
|
+
this._isBufferingEnabled = options && options.enableBuffering;
|
|
1347
|
+
const tracing = new Tracing(this._appInstr);
|
|
1348
|
+
return {
|
|
1349
|
+
log: this._appInstr.log.bind(this._appInstr),
|
|
1350
|
+
error: this._appInstr.error.bind(this._appInstr),
|
|
1351
|
+
startActivity: this._appInstr.startActivity.bind(this._appInstr),
|
|
1352
|
+
domEvent: this._appInstr.domEvent.bind(this._appInstr),
|
|
1353
|
+
incrementCounter: this._appInstr.incrementCounter.bind(this._appInstr),
|
|
1354
|
+
trackValue: this._appInstr.trackValue.bind(this._appInstr),
|
|
1355
|
+
bucketValue: this._appInstr.bucketValue.bind(this._appInstr),
|
|
1356
|
+
networkInstrumentation: tracing.networkInstrumentation.bind(tracing),
|
|
1357
|
+
registerForLogPrompt: this._appInstr.registerForLogPrompt.bind(this._appInstr),
|
|
1358
|
+
startRootActivity: this._appInstr.startRootActivity.bind(this._appInstr),
|
|
1359
|
+
registerLogCollector: this.registerLogCollector.bind(this),
|
|
1360
|
+
registerMetricsCollector: this.registerMetricsCollector.bind(this),
|
|
1361
|
+
activateClickTracker: this.activateClickTracker.bind(this),
|
|
1362
|
+
deactivateClickTracker: this.deactivateClickTracker.bind(this),
|
|
1363
|
+
disableBuffering: this.disableBuffering.bind(this),
|
|
1364
|
+
promptLogCollection: this.promptLogCollection.bind(this)
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
getInstrumentation(name) {
|
|
1368
|
+
utility.requireArgument(name, 'name', 'string');
|
|
1369
|
+
if (name.length > maxInstrumentationLength) {
|
|
1370
|
+
name = name.substr(0, maxInstrumentationLengthBeforeTruncated) + truncatedText;
|
|
1371
|
+
}
|
|
1372
|
+
let instr = this._instruments.get(name);
|
|
1373
|
+
if (!instr) {
|
|
1374
|
+
instr = new InstrumentationImpl(this, name);
|
|
1375
|
+
this._instruments.set(name, instr);
|
|
1376
|
+
}
|
|
1377
|
+
else if (instr === this._appInstr) {
|
|
1378
|
+
throw new Error(`The instrumentation name ${name} is being used by the app.`);
|
|
1379
|
+
}
|
|
1380
|
+
return instr;
|
|
1381
|
+
}
|
|
1382
|
+
get appName() {
|
|
1383
|
+
return this._appInstr && this._appInstr.name;
|
|
1384
|
+
}
|
|
1385
|
+
addLog(loggerName, schema, data, timestamp, rootId, pagePayload, appPayload) {
|
|
1386
|
+
this._sequence += 1;
|
|
1387
|
+
const sequence = this._sequence;
|
|
1388
|
+
const loggerAppName = this.appName;
|
|
1389
|
+
const connectionType = utility.getConnectionType();
|
|
1390
|
+
const logMeta = {
|
|
1391
|
+
timestamp,
|
|
1392
|
+
rootId,
|
|
1393
|
+
sequence,
|
|
1394
|
+
loggerName,
|
|
1395
|
+
pagePayload: pagePayload ? utility.clone(pagePayload) : undefined,
|
|
1396
|
+
appPayload: appPayload ? utility.clone(appPayload) : undefined,
|
|
1397
|
+
loggerAppName,
|
|
1398
|
+
connectionType
|
|
1399
|
+
};
|
|
1400
|
+
if (this._isBufferingEnabled) {
|
|
1401
|
+
this._buffer.push({ schema, data: utility.clone(data), logMeta });
|
|
1402
|
+
}
|
|
1403
|
+
const eligibleCollectors = Array.from(this._logCollectors).filter((collector) => !this._forceDisabledLogCollectors.has(collector) &&
|
|
1404
|
+
!(collector.getIsCollectDisabled && collector.getIsCollectDisabled()));
|
|
1405
|
+
if (eligibleCollectors.length > 0) {
|
|
1406
|
+
for (const collector of eligibleCollectors) {
|
|
1407
|
+
const dataClone = utility.clone(data);
|
|
1408
|
+
let failures = this._logCollectorFailures.get(collector) || 0;
|
|
1409
|
+
try {
|
|
1410
|
+
collector.collect(schema, dataClone, logMeta);
|
|
1411
|
+
if (failures > 0) {
|
|
1412
|
+
this._logCollectorFailures.set(collector, failures - 1);
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
catch (err) {
|
|
1416
|
+
failures += 1;
|
|
1417
|
+
if (failures >= NextgenImpl._collectorFailureLimit) {
|
|
1418
|
+
this._forceDisabledLogCollectors.add(collector);
|
|
1419
|
+
if (this._appInstr && (typeof err === 'string' || err instanceof Error)) {
|
|
1420
|
+
this._appInstr.error(err);
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
else {
|
|
1424
|
+
this._logCollectorFailures.set(collector, failures);
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
return this._sequence;
|
|
1430
|
+
}
|
|
1431
|
+
getBuffer() {
|
|
1432
|
+
return this._buffer;
|
|
1433
|
+
}
|
|
1434
|
+
disableBuffering() {
|
|
1435
|
+
this._isBufferingEnabled = false;
|
|
1436
|
+
this._buffer = [];
|
|
1437
|
+
}
|
|
1438
|
+
getClickTracker() {
|
|
1439
|
+
return this._autoClickTracker;
|
|
1440
|
+
}
|
|
1441
|
+
getDefaultInstrumentationContext() {
|
|
1442
|
+
var _a, _b;
|
|
1443
|
+
return {
|
|
1444
|
+
rootId: (_a = this._appInstr) === null || _a === void 0 ? void 0 : _a.getSingleRootActivityId(),
|
|
1445
|
+
isRootActivitySampled: (_b = this._appInstr) === null || _b === void 0 ? void 0 : _b.isSingleRootActivitySampled()
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
activateClickTracker() {
|
|
1449
|
+
if (!this._autoClickTracker) {
|
|
1450
|
+
this._autoClickTracker = new AutomaticClickTracker(this._appInstr, window.document);
|
|
1451
|
+
}
|
|
1452
|
+
this._autoClickTracker.activate();
|
|
1453
|
+
}
|
|
1454
|
+
deactivateClickTracker() {
|
|
1455
|
+
if (this._autoClickTracker) {
|
|
1456
|
+
this._autoClickTracker.deactivate();
|
|
1457
|
+
this._autoClickTracker = undefined;
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
registerLogCollector(collector, options) {
|
|
1461
|
+
utility.requireArgument(collector, 'collector');
|
|
1462
|
+
if (this._logCollectors.has(collector)) {
|
|
1463
|
+
return;
|
|
1464
|
+
}
|
|
1465
|
+
this._logCollectors.add(collector);
|
|
1466
|
+
this._logCollectorFailures.set(collector, 0);
|
|
1467
|
+
if ((!collector.getIsCollectDisabled || !collector.getIsCollectDisabled()) &&
|
|
1468
|
+
options &&
|
|
1469
|
+
options.retroactive) {
|
|
1470
|
+
for (const log of this._buffer) {
|
|
1471
|
+
collector.collect(log.schema, log.data, log.logMeta);
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
registerMetricsCollector(collector) {
|
|
1476
|
+
utility.requireArgument(collector, 'collector');
|
|
1477
|
+
if (this._metricsCollector) {
|
|
1478
|
+
throw new Error('A metrics Collector is already registered.');
|
|
1479
|
+
}
|
|
1480
|
+
this._metricsCollector = collector;
|
|
1481
|
+
this._metricsCollector.receiveMetricsExtractors({
|
|
1482
|
+
getAllUpCounters: this.getAllUpCounters.bind(this),
|
|
1483
|
+
getAllValueRecorders: this.getAllValueRecorders.bind(this),
|
|
1484
|
+
getAllBucketHistograms: this.getAllBucketHistograms.bind(this)
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
getAllUpCounters() {
|
|
1488
|
+
const arrOfArrs = Array.from(this._instruments.values()).map((instr) => instr.getUpCounters());
|
|
1489
|
+
return arrOfArrs.reduce((pv, cv) => pv.concat(cv), []);
|
|
1490
|
+
}
|
|
1491
|
+
getAllValueRecorders() {
|
|
1492
|
+
const arrOfArrs = Array.from(this._instruments.values()).map((instr) => instr.getValueRecorders());
|
|
1493
|
+
return arrOfArrs.reduce((pv, cv) => pv.concat(cv), []);
|
|
1494
|
+
}
|
|
1495
|
+
getAllBucketHistograms() {
|
|
1496
|
+
const arrOfArrs = Array.from(this._instruments.values()).map((instr) => instr.getBucketHistograms());
|
|
1497
|
+
return arrOfArrs.reduce((pv, cv) => pv.concat(cv), []);
|
|
1498
|
+
}
|
|
1499
|
+
registerForLogPrompt(listener) {
|
|
1500
|
+
this._logCollectionListeners.add(listener);
|
|
1501
|
+
}
|
|
1502
|
+
promptLogCollection(reason) {
|
|
1503
|
+
for (const listener of this._logCollectionListeners.keys()) {
|
|
1504
|
+
try {
|
|
1505
|
+
listener(reason);
|
|
1506
|
+
}
|
|
1507
|
+
catch (_a) {
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
NextgenImpl._collectorFailureLimit = 5;
|
|
1513
|
+
|
|
1514
|
+
class Index {
|
|
1515
|
+
get _lazyNextGen() {
|
|
1516
|
+
if (!this._nextgen) {
|
|
1517
|
+
this._nextgen = new NextgenImpl();
|
|
1518
|
+
}
|
|
1519
|
+
return this._nextgen;
|
|
1520
|
+
}
|
|
1521
|
+
registerInstrumentedApp(name, options) {
|
|
1522
|
+
if (options && options.isProduction) {
|
|
1523
|
+
utility.markProduction();
|
|
1524
|
+
}
|
|
1525
|
+
const retVal = this._lazyNextGen.registerApp(name, options);
|
|
1526
|
+
if (options) {
|
|
1527
|
+
this._nextgen.appPayloadProvider = options.appPayloadProvider;
|
|
1528
|
+
this._nextgen.pagePayloadProvider = options.pagePayloadProvider;
|
|
1529
|
+
}
|
|
1530
|
+
return retVal;
|
|
1531
|
+
}
|
|
1532
|
+
getInstrumentation(name) {
|
|
1533
|
+
return this._lazyNextGen.getInstrumentation(name);
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
const index = new Index();
|
|
1537
|
+
const registerInstrumentedApp = index.registerInstrumentedApp.bind(index);
|
|
1538
|
+
const getInstrumentation = index.getInstrumentation.bind(index);
|
|
1539
|
+
const time = utility.time.bind(utility);
|
|
1540
|
+
|
|
1541
|
+
class TaskerImpl {
|
|
1542
|
+
constructor(name, initialCount, _doneCallback, _overDoneCallback) {
|
|
1543
|
+
this.name = name;
|
|
1544
|
+
this._doneCallback = _doneCallback;
|
|
1545
|
+
this._overDoneCallback = _overDoneCallback;
|
|
1546
|
+
this._busyCount = 0;
|
|
1547
|
+
this._isOk = true;
|
|
1548
|
+
this._busyCount = initialCount;
|
|
1549
|
+
}
|
|
1550
|
+
get isBusy() {
|
|
1551
|
+
return this._isOk ? this._busyCount > 0 : undefined;
|
|
1552
|
+
}
|
|
1553
|
+
add() {
|
|
1554
|
+
if (this._isOk) {
|
|
1555
|
+
this._busyCount += 1;
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
done() {
|
|
1559
|
+
if (this._isOk) {
|
|
1560
|
+
if (this._busyCount > 0) {
|
|
1561
|
+
this._busyCount -= 1;
|
|
1562
|
+
if (!this._busyCount) {
|
|
1563
|
+
this._doneCallback();
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
else {
|
|
1567
|
+
this._isOk = false;
|
|
1568
|
+
this._overDoneCallback();
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
class IdleDetectorImpl {
|
|
1575
|
+
constructor() {
|
|
1576
|
+
this._instr = getInstrumentation('IdleDetector');
|
|
1577
|
+
this._taskers = new Set();
|
|
1578
|
+
this._listeners = new Set();
|
|
1579
|
+
this._busyCheckers = new Map();
|
|
1580
|
+
this._timerCheckQueued = 0;
|
|
1581
|
+
}
|
|
1582
|
+
requestIdleDetectedCallback(callback) {
|
|
1583
|
+
utility.requireArgument(callback, 'callback', 'function');
|
|
1584
|
+
this._listeners.add(callback);
|
|
1585
|
+
this.checkIfLoaded();
|
|
1586
|
+
}
|
|
1587
|
+
declareNotifierTaskSingle(name) {
|
|
1588
|
+
utility.requireArgument(name, 'name', 'string');
|
|
1589
|
+
const tasker = this.addTasker(name, 1);
|
|
1590
|
+
const retVal = {
|
|
1591
|
+
get isBusy() {
|
|
1592
|
+
return tasker.isBusy;
|
|
1593
|
+
},
|
|
1594
|
+
done: () => {
|
|
1595
|
+
tasker.done();
|
|
1596
|
+
this._taskers.delete(tasker);
|
|
1597
|
+
}
|
|
1598
|
+
};
|
|
1599
|
+
return retVal;
|
|
1600
|
+
}
|
|
1601
|
+
declareNotifierTaskMulti(name, existingBusyCount = 0) {
|
|
1602
|
+
utility.requireArgument(name, 'name', 'string');
|
|
1603
|
+
if (existingBusyCount !== undefined) {
|
|
1604
|
+
utility.requireArgument(existingBusyCount, 'existingBusyCount', 'number');
|
|
1605
|
+
if (existingBusyCount < 0 ||
|
|
1606
|
+
parseInt(existingBusyCount.toString(), 10) !== existingBusyCount) {
|
|
1607
|
+
throw new Error('existingBusyCount accepts only non-negative integers');
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
return this.addTasker(name, existingBusyCount);
|
|
1611
|
+
}
|
|
1612
|
+
declarePollableTaskMulti(name, isBusyChecker) {
|
|
1613
|
+
utility.requireArgument(name, 'name', 'string');
|
|
1614
|
+
utility.requireArgument(isBusyChecker, 'isBusyChecker', 'function');
|
|
1615
|
+
this._busyCheckers.set(isBusyChecker, name);
|
|
1616
|
+
}
|
|
1617
|
+
addTasker(name, existingBusyCount) {
|
|
1618
|
+
const tasker = new TaskerImpl(name, existingBusyCount, () => {
|
|
1619
|
+
this.checkIfLoaded();
|
|
1620
|
+
}, () => {
|
|
1621
|
+
throw new Error(`Tasker '${tasker.name}' is done too many times.`);
|
|
1622
|
+
});
|
|
1623
|
+
this._taskers.add(tasker);
|
|
1624
|
+
return tasker;
|
|
1625
|
+
}
|
|
1626
|
+
areAllNotifiersIdle() {
|
|
1627
|
+
return !Array.from(this._taskers.values()).some((t) => t.isBusy);
|
|
1628
|
+
}
|
|
1629
|
+
areAllPollablesIdle() {
|
|
1630
|
+
return !Array.from(this._busyCheckers.keys()).some((sc, index) => {
|
|
1631
|
+
try {
|
|
1632
|
+
return sc();
|
|
1633
|
+
}
|
|
1634
|
+
catch (e) {
|
|
1635
|
+
this._instr.error(e, `BusyChecker #${index}`);
|
|
1636
|
+
return false;
|
|
1637
|
+
}
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
checkIfLoaded() {
|
|
1641
|
+
if (!this._listeners.size) {
|
|
1642
|
+
return;
|
|
1643
|
+
}
|
|
1644
|
+
if (this._timerCheckQueued) {
|
|
1645
|
+
window.clearTimeout(this._timerCheckQueued);
|
|
1646
|
+
}
|
|
1647
|
+
if (this.areAllNotifiersIdle()) {
|
|
1648
|
+
this._timerCheckQueued = window.setTimeout(() => {
|
|
1649
|
+
this._timerCheckQueued = window.setTimeout(() => {
|
|
1650
|
+
this.doubleCheck();
|
|
1651
|
+
}, 40);
|
|
1652
|
+
}, 0);
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
doubleCheck() {
|
|
1656
|
+
this._timerCheckQueued = 0;
|
|
1657
|
+
if (this.areAllNotifiersIdle()) {
|
|
1658
|
+
if (!this.areAllPollablesIdle()) {
|
|
1659
|
+
this._timerCheckQueued = window.setTimeout(() => {
|
|
1660
|
+
this.doubleCheck();
|
|
1661
|
+
}, 15);
|
|
1662
|
+
}
|
|
1663
|
+
else {
|
|
1664
|
+
const listeners = Array.from(this._listeners.values());
|
|
1665
|
+
this._listeners.clear();
|
|
1666
|
+
this.notify(listeners);
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
notify(listeners) {
|
|
1671
|
+
const idleTimestamp = utility.time().tsNow;
|
|
1672
|
+
for (const [index, listener] of listeners.entries()) {
|
|
1673
|
+
try {
|
|
1674
|
+
listener(idleTimestamp);
|
|
1675
|
+
}
|
|
1676
|
+
catch (e) {
|
|
1677
|
+
this._instr.error(e, `Listener #${index}`);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
const bgColorMap = {
|
|
1684
|
+
Error: 'Crimson',
|
|
1685
|
+
Activity: 'CadetBlue',
|
|
1686
|
+
InstrumentedEvent: 'DarkOliveGreen',
|
|
1687
|
+
O11ySample: 'BlueViolet'
|
|
1688
|
+
};
|
|
1689
|
+
const colorMap = {
|
|
1690
|
+
Error: 'white',
|
|
1691
|
+
Activity: 'white',
|
|
1692
|
+
InstrumentedEvent: 'white',
|
|
1693
|
+
O11ySample: 'white'
|
|
1694
|
+
};
|
|
1695
|
+
const defaultColor = 'black';
|
|
1696
|
+
const defaultBgColor = 'Gainsboro';
|
|
1697
|
+
class ConsoleCollector {
|
|
1698
|
+
constructor(environment) {
|
|
1699
|
+
if (environment) {
|
|
1700
|
+
this._log('ConsoleCollector', environment);
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
collect(schema, data, logMeta) {
|
|
1704
|
+
let label, color, bgColor;
|
|
1705
|
+
if (schema.namespace === 'sf.instrumentation') {
|
|
1706
|
+
label = schema.name;
|
|
1707
|
+
color = colorMap[schema.name] || defaultColor;
|
|
1708
|
+
bgColor = bgColorMap[schema.name] || defaultBgColor;
|
|
1709
|
+
}
|
|
1710
|
+
else {
|
|
1711
|
+
label = schemaUtil.getSchemaId(schema);
|
|
1712
|
+
}
|
|
1713
|
+
this._log(label, data, logMeta, color, bgColor);
|
|
1714
|
+
}
|
|
1715
|
+
_log(label, first, second, color = defaultColor, bgColor = defaultBgColor) {
|
|
1716
|
+
const css = `color:${color};background-color:${bgColor}`;
|
|
1717
|
+
console.log(`%cO11Y%c ${label}`, 'color:white;background-color:#FF6600;font-weight:bold', css, first || '', second || '');
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
const idleDetector = new IdleDetectorImpl();
|
|
1722
|
+
|
|
1723
|
+
export { ConsoleCollector, getInstrumentation, idleDetector, registerInstrumentedApp, time };
|
|
2
1724
|
//# sourceMappingURL=client.js.map
|