Socket
Socket
Sign inDemoInstall

@microsoft/applicationinsights-core-js

Package Overview
Dependencies
Maintainers
4
Versions
561
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@microsoft/applicationinsights-core-js - npm Package Compare versions

Comparing version 2.5.6 to 2.5.7

dist-esm/JavaScriptSDK.Interfaces/IPerfEvent.js

4

browser/applicationinsights-core-js.min.js
/*!
* Application Insights JavaScript SDK - Core, 2.5.6
* Application Insights JavaScript SDK - Core, 2.5.7
* Copyright (c) Microsoft and contributors. All rights reserved.
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e.Microsoft=e.Microsoft||{},e.Microsoft.ApplicationInsights=e.Microsoft.ApplicationInsights||{}))}(this,function(c){"use strict";var r="function",o="object",t="undefined",a="prototype",s="hasOwnProperty";function e(){return typeof globalThis!==t&&globalThis?globalThis:typeof self!==t&&self?self:typeof window!==t&&window?window:typeof global!==t&&global?global:null}function i(e){var t=Object.create;if(t)return t(e);if(null==e)return{};var n=typeof e;if(n!=o&&n!=r)throw new TypeError("Object prototype may only be an Object:"+e);function i(){}return i[a]=e,new i}var l=function(e,t){return(l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t[s](n)&&(e[n]=t[n])})(e,t)},n=e()||{};__assign=n.__assign=n.__assign||Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object[a][s].call(t,r)&&(e[r]=t[r]);return e},__extends=n.__extends=n.__extends||function(e,t){function n(){this.constructor=e}l(e,t),e[a]=null===t?i(t):(n[a]=t[a],new n)};var u={Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5},f=t,g=o,d=a,h=r,p="window",v="JSON",y=e;function m(e){var t=y();return t&&t[e]?t[e]:e===p&&x()?window:null}function x(){return!(typeof window!==g||!window)}function C(){return x()?window:m(p)}function T(){return!(typeof document!==g||!document)}function I(){return T()?document:m("document")}function _(){return!(typeof navigator!==g||!navigator)}function w(){return _()?navigator:m("navigator")}function S(){return!(typeof history!==g||!history)}function N(){return!!(typeof JSON===g&&JSON||null!==m(v))}function b(){return N()?JSON||m(v):null}var L=t,E="attachEvent",F="addEventListener",M="detachEvent",P="removeEventListener";function A(e,t){return typeof e===t}function O(e){return A(e,t)||e===undefined}function R(e){return O(e)||null===e}function D(e,t){return e&&Object[a].hasOwnProperty.call(e,t)}function U(e){return A(e,o)}function j(e){return A(e,r)}function k(e,t,n,i){void 0===i&&(i=!1);var r=!1;if(!R(e))try{R(e[F])?R(e[E])||(e[E]("on"+t,n),r=!0):(e[F](t,n,i),r=!0)}catch(o){}return r}function z(e,t,n,i){if(void 0===i&&(i=!1),!R(e))try{R(e[P])?R(e[M])||e[M]("on"+t,n):e[P](t,n,i)}catch(r){}}var B=(Q.isDate=function(e){return"[object Date]"===Object[a].toString.call(e)},Q.isString=function(e){return A(e,"string")},Q.isNumber=function(e){return A(e,"number")},Q.isBoolean=function(e){return A(e,"boolean")},Q.disableCookies=function(){Q._canUseCookies=!1},Q.newGuid=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(V,function(e){var t,n=0|((t=m("crypto"))?t.getRandomValues(new Uint8Array(1))[0]%16:16*Math.random());return("x"===e?n:3&n|8).toString(16)})},Q.toISOString=function(e){if(Q.isDate(e)){var t=function(e){var t=e+"";return 1===t.length&&(t="0"+t),t};return e.getUTCFullYear()+"-"+t(1+e.getUTCMonth())+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}},Q.arrForEach=function(e,t,n){for(var i=e.length,r=0;r<i;r++)r in e&&t.call(n||e,e[r],r,e)},Q.arrIndexOf=function(e,t,n){for(var i=e.length,r=n||0,o=Math.max(0<=r?r:i-Math.abs(r),0);o<i;o++)if(o in e&&e[o]===t)return o;return-1},Q.arrMap=function(e,t,n){for(var i=e.length,r=n||e,o=Array(i),a=0;a<i;a++)a in e&&(o[a]=t.call(r,e[a],e));return o},Q.arrReduce=function(e,t,n){var i,r=e.length,o=0;if(3<=arguments.length)i=n;else{for(;o<r&&!(o in e);)o++;i=e[o++]}for(;o<r;)o in e&&(i=t(i,e[o],o,e)),o++;return i},Q.strTrim=function(e){return Q.isString(e)?e.replace(/^\s+|\s+$/g,""):e},Q.objKeys=function(e){var t=!{toString:null}.propertyIsEnumerable("toString");if(!(j(e)||U(e)&&null!==e))throw new TypeError("objKeys called on non-object");var n=[];for(var i in e)D(e,i)&&n.push(i);if(t)for(var r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=r.length,a=0;a<o;a++)D(e,r[a])&&n.push(r[a]);return n},Q.objDefineAccessors=function(e,t,n,i){var r=Object.defineProperty;if(r)try{var o={enumerable:!0,configurable:!0};return n&&(o.get=n),i&&(o.set=i),r(e,t,o),!0}catch(a){}return!1},Q.addEventHandler=function(e,t){var n=!1,i=C();i&&(n=k(i,e,t),n=k(i.body,e,t)||n);var r=I();return r&&(n=W.Attach(r,e,t)||n),n},Q.isTypeof=A,Q.isUndefined=O,Q.isNullOrUndefined=R,Q.hasOwnProperty=D,Q.isFunction=j,Q.isObject=U,Q.objCreate=i,Q);function Q(){}var q,V=/[xy]/g,W=(H.Attach=k,H.AttachEvent=k,H.Detach=z,H.DetachEvent=z,H);function H(){}(q=c.LoggingSeverity||(c.LoggingSeverity={}))[q.CRITICAL=1]="CRITICAL",q[q.WARNING=2]="WARNING";var K={BrowserDoesNotSupportLocalStorage:0,BrowserCannotReadLocalStorage:1,BrowserCannotReadSessionStorage:2,BrowserCannotWriteLocalStorage:3,BrowserCannotWriteSessionStorage:4,BrowserFailedRemovalFromLocalStorage:5,BrowserFailedRemovalFromSessionStorage:6,CannotSendEmptyTelemetry:7,ClientPerformanceMathError:8,ErrorParsingAISessionCookie:9,ErrorPVCalc:10,ExceptionWhileLoggingError:11,FailedAddingTelemetryToBuffer:12,FailedMonitorAjaxAbort:13,FailedMonitorAjaxDur:14,FailedMonitorAjaxOpen:15,FailedMonitorAjaxRSC:16,FailedMonitorAjaxSend:17,FailedMonitorAjaxGetCorrelationHeader:18,FailedToAddHandlerForOnBeforeUnload:19,FailedToSendQueuedTelemetry:20,FailedToReportDataLoss:21,FlushFailed:22,MessageLimitPerPVExceeded:23,MissingRequiredFieldSpecification:24,NavigationTimingNotSupported:25,OnError:26,SessionRenewalDateIsZero:27,SenderNotInitialized:28,StartTrackEventFailed:29,StopTrackEventFailed:30,StartTrackFailed:31,StopTrackFailed:32,TelemetrySampledAndNotSent:33,TrackEventFailed:34,TrackExceptionFailed:35,TrackMetricFailed:36,TrackPVFailed:37,TrackPVFailedCalc:38,TrackTraceFailed:39,TransmissionFailed:40,FailedToSetStorageBuffer:41,FailedToRestoreStorageBuffer:42,InvalidBackendResponse:43,FailedToFixDepricatedValues:44,InvalidDurationValue:45,TelemetryEnvelopeInvalid:46,CreateEnvelopeError:47,CannotSerializeObject:48,CannotSerializeObjectNonSerializable:49,CircularReferenceDetected:50,ClearAuthContextFailed:51,ExceptionTruncated:52,IllegalCharsInName:53,ItemNotInArray:54,MaxAjaxPerPVExceeded:55,MessageTruncated:56,NameTooLong:57,SampleRateOutOfRange:58,SetAuthContextFailed:59,SetAuthContextFailedAccountName:60,StringValueTooLong:61,StartCalledMoreThanOnce:62,StopCalledWithoutStart:63,TelemetryInitializerFailed:64,TrackArgumentsNotSpecified:65,UrlTooLong:66,SessionStorageBufferFull:67,CannotAccessCookie:68,IdTooLong:69,InvalidEvent:70,FailedMonitorAjaxSetRequestHeader:71,SendBrowserInfoOnUserInit:72,PluginException:73,NotificationException:74,SnippetScriptLoadFailure:99},G=(J.sanitizeDiagnosticText=function(e){return e?'"'+e.replace(/\"/g,"")+'"':""},J.dataType="MessageData",J.AiNonUserActionablePrefix="AI (Internal): ",J.AiUserActionablePrefix="AI: ",J);function J(e,t,n,i){void 0===n&&(n=!1),this.messageId=e,this.message=(n?J.AiUserActionablePrefix:J.AiNonUserActionablePrefix)+e;var r="";N()&&(r=b().stringify(i));var o=(t?" message:"+J.sanitizeDiagnosticText(t):"")+(i?" props:"+J.sanitizeDiagnosticText(r):"");this.message+=o}var Z=($.prototype.throwInternal=function(e,t,n,i,r){void 0===r&&(r=!1);var o,a=new G(t,n,r,i),s=this;if(s.enableDebugExceptions())throw a;!B.isUndefined(a)&&a&&(B.isUndefined(a.message)||(r?(o=+a.messageId,!s._messageLogged[o]&&s.consoleLoggingLevel()>=c.LoggingSeverity.WARNING&&(s.warnToConsole(a.message),s._messageLogged[o]=!0)):s.consoleLoggingLevel()>=c.LoggingSeverity.WARNING&&s.warnToConsole(a.message),s.logInternalMessage(e,a)))},$.prototype.warnToConsole=function(e){!B.isUndefined(console)&&console&&(B.isFunction(console.warn)?console.warn(e):B.isFunction(console.log)&&console.log(e))},$.prototype.resetInternalMessageCount=function(){this._messageCount=0,this._messageLogged={}},$.prototype.logInternalMessage=function(e,t){var n,i,r,o=this;o._areInternalMessagesThrottled()||(n=!0,i=o.AIInternalMessagePrefix+t.messageId,o._messageLogged[i]?n=!1:o._messageLogged[i]=!0,n&&(e<=o.telemetryLoggingLevel()&&(o.queue.push(t),o._messageCount++),o._messageCount===o.maxInternalMessageLimit()&&(r=new G(K.MessageLimitPerPVExceeded,"Internal events throttle limit per PageView reached for this app.",!1),o.queue.push(r),o.warnToConsole("Internal events throttle limit per PageView reached for this app."))))},$.prototype._areInternalMessagesThrottled=function(){return this._messageCount>=this.maxInternalMessageLimit()},$);function $(e){this.queue=[],this.AIInternalMessagePrefix="AITR_",this._messageCount=0,this._messageLogged={},this.enableDebugExceptions=function(){return!1},this.consoleLoggingLevel=function(){return 0},this.telemetryLoggingLevel=function(){return 1},this.maxInternalMessageLimit=function(){return 25},B.isNullOrUndefined(e)||(B.isNullOrUndefined(e.loggingLevelConsole)||(this.consoleLoggingLevel=function(){return e.loggingLevelConsole}),B.isNullOrUndefined(e.loggingLevelTelemetry)||(this.telemetryLoggingLevel=function(){return e.loggingLevelTelemetry}),B.isNullOrUndefined(e.maxMessageLimit)||(this.maxInternalMessageLimit=function(){return e.maxMessageLimit}),B.isNullOrUndefined(e.enableDebugExceptions)||(this.enableDebugExceptions=function(){return e.enableDebugExceptions}))}var Y=B.isFunction,X=function(r,o){var a=this,s=null,l=Y(r.processTelemetry),u=Y(r.setNextPlugin);a._hasRun=!1,a.getPlugin=function(){return r},a.getNext=function(){return s},a.setNext=function(e){s=e},a.processTelemetry=function(e,t){if(t=t||o,r&&l){a._hasRun=!0;try{t.setNext(s),u&&r.setNextPlugin(s),s&&(s._hasRun=!1),r.processTelemetry(e,t)}catch(i){var n=s&&s._hasRun;s&&n||t.diagLog().throwInternal(c.LoggingSeverity.CRITICAL,K.PluginException,"Plugin ["+r.identifier+"] failed during processTelemetry - "+i),s&&!n&&s.processTelemetry(e,t)}}else s&&(a._hasRun=!0,s.processTelemetry(e,t))}},ee=B.isNullOrUndefined;function te(e,t){var n=[];if(e&&0<e.length)for(var i=null,r=0;r<e.length;r++){var o,a=e[r];a&&B.isFunction(a.processTelemetry)&&(o=new X(a,t),n.push(o),i&&i.setNext(o),i=o)}return 0<n.length?n[0]:null}var ne=function Re(e,o,n,t){var i,r,a,s,l=this,u=null;null!==t&&(e&&B.isFunction(e.getPlugin)?u=function(e,t,n){var i=[],r=!n;if(e)for(;e;){var o=e.getPlugin();!r&&o!==n||(r=!0,i.push(o)),e=e.getNext()}return r||i.push(n),te(i,t)}(e,l,t||e.getPlugin()):t?(i=l,a=e,s=!1,(r=t)&&e&&(a=[],B.arrForEach(e,function(e){!s&&e!==r||(s=!0,a.push(e))})),r&&!s&&(a=a||[]).push(r),u=te(a,i)):B.isUndefined(t)&&(u=te(e,l))),l.core=function(){return n},l.diagLog=function(){return(n||{}).logger||new Z(o||{})},l.getCfg=function(){return o},l.getExtCfg=function(e,t){var n,i;return void 0===t&&(t={}),!o||(i=o.extensionConfig)&&e&&(n=i[e]),n||t},l.getConfig=function(e,t,n){var i;void 0===n&&(n=!1);var r=l.getExtCfg(e,null);return r&&!ee(r[t])?i=r[t]:o&&!ee(o[t])&&(i=o[t]),ee(i)?n:i},l.hasNext=function(){return null!=u},l.getNext=function(){return u},l.setNext=function(e){u=e},l.processNext=function(e){var t=u;t&&(u=t.getNext(),t.processTelemetry(e,l))},l.createNew=function(e,t){return void 0===e&&(e=null),new Re(e||u,o,n,t)}},ie=B.isFunction,re="getPlugin",oe=(ae.prototype.initialize=function(e,t,n,i){this._baseTelInit(e,t,n,i)},ae);function ae(){var o=this,a=!1,s=null,l=null;o.core=null,o.diagLog=function(e){return o._getTelCtx(e).diagLog()},o.isInitialized=function(){return a},o.setInitialized=function(e){a=e},o.setNextPlugin=function(e){l=e},o.processNext=function(e,t){t?t.processNext(e):l&&ie(l.processTelemetry)&&l.processTelemetry(e,null)},o._getTelCtx=function(e){void 0===e&&(e=null);var t,n=e;return n||(t=s||new ne(null,{},o.core),n=l&&l[re]?t.createNew(null,l[re]):t.createNew(null,l)),n},o._baseTelInit=function(e,t,n,i){e&&(e.extensionConfig=e.extensionConfig||[]),!i&&t&&(i=t.getProcessTelContext().getNext());var r=l;l&&l[re]&&(r=l[re]()),o.core=t,s=new ne(i,e,t,r),a=!0}}var se=B.isFunction,le="processTelemetry",ue="priority",ce="setNextPlugin",fe="isInitialized";function ge(t,n){for(var e=[],i=null,r=t.getNext();r;){var o=r.getPlugin();o&&(i&&se(i[ce])&&se(o[le])&&i[ce](o),se(o[fe])&&o[fe]()||e.push(o),i=o,r=r.getNext())}B.arrForEach(e,function(e){e.initialize(t.getCfg(),t.core(),n,t.getNext())})}function de(e){return e.sort(function(e,t){var n=0,i=se(t[le]);return se(e[le])?n=i?e[ue]-t[ue]:1:i&&(n=-1),n})}var he=B.arrForEach,pe=B.objDefineAccessors;function ve(e,t){t&&0<t.length&&(t=t.sort(function(e,t){return e.priority-t.priority}),he(t,function(e){if(e.priority<500)throw Error("Channel has invalid priority"+e.identifier)}),e.push(t))}var ye,me=(ye=oe,__extends(xe,ye),xe.prototype.processTelemetry=function(t,n){var i=this;this._channelQueue&&he(this._channelQueue,function(e){0<e.length&&i._getTelCtx(n).createNew(e).processNext(t)})},xe.prototype.getChannelControls=function(){return this._channelQueue},xe.prototype.initialize=function(t,n,i){var e,r,o,a,s;this.isInitialized()||(ye.prototype.initialize.call(this,t,n,i),t.isCookieUseDisabled&&B.disableCookies(),e=this._channelQueue=(o=i,s=[],(r=(t||{}).channels)&&he(r,function(e){return ve(s,e)}),o&&(a=[],he(o,function(e){500<e.priority&&a.push(e)}),ve(s,a)),s),he(e,function(e){return ge(new ne(e,t,n),i)}))},xe._staticInit=(pe(xe.prototype,"ChannelControls",xe.prototype.getChannelControls),void pe(xe.prototype,"channelQueue",xe.prototype.getChannelControls)),xe);function xe(){var e=null!==ye&&ye.apply(this,arguments)||this;return e.identifier="ChannelControllerPlugin",e.priority=500,e}var Ce=B.arrForEach,Te=B.isNullOrUndefined,Ie=(_e.prototype.initialize=function(e,t,i,n){var r=this;if(r.isInitialized())throw Error("Core should not be initialized more than once");if(!e||Te(e.instrumentationKey))throw Error("Please provide instrumentation key");r.config=e;var o=r._channelController;n=n||B.objCreate({addNotificationListener:function(e){},removeNotificationListener:function(e){},eventsSent:function(e){},eventsDiscarded:function(e,t){},eventsSendRequest:function(e,t){}}),r._notificationManager=n,e.extensions=Te(e.extensions)?[]:e.extensions,(e.extensionConfig=Te(e.extensionConfig)?{}:e.extensionConfig).NotificationManager=n,i=i||B.objCreate({throwInternal:function(e,t,n,i,r){void 0===r&&(r=!1)},warnToConsole:function(e){},resetInternalMessageCount:function(){}}),r.logger=i;var a=[];a.push.apply(a,t.concat(e.extensions)),a=de(a);var s=[],l={};if(Ce(a,function(e){if(Te(e)||Te(e.initialize))throw Error("Extensions must provide callback to initialize");var t=e.priority,n=e.identifier;e&&t&&(Te(l[t])?l[t]=n:i.warnToConsole("Two extensions have same priority #"+t+" - "+l[t]+", "+n)),(!t||t<o.priority)&&s.push(e)}),a.push(o),s.push(o),a=de(a),r._extensions=a,ge(new ne([o],e,r),a),ge(new ne(s,e,r),a),r._extensions=s,0===r.getTransmissionControls().length)throw Error("No channels available");r._setInit(!0),r.releaseQueue()},_e.prototype.getTransmissionControls=function(){return this._channelController.getChannelControls()},_e.prototype.track=function(e){e.iKey||(e.iKey=this.config.instrumentationKey),e.time||(e.time=B.toISOString(new Date)),Te(e.ver)&&(e.ver="4.0"),this.isInitialized()?this.getProcessTelContext().processNext(e):this._eventQueue.push(e)},_e.prototype.getProcessTelContext=function(){var e=this._extensions,t=e;return e&&0!==e.length||(t=[this._channelController]),new ne(t,this.config,this)},_e.prototype.releaseQueue=function(){var t=this;0<t._eventQueue.length&&(Ce(t._eventQueue,function(e){t.getProcessTelContext().processNext(e)}),t._eventQueue=[])},_e);function _e(){var t=!1,e=this;e._extensions=[],e._channelController=new me,e.isInitialized=function(){return t},e._setInit=function(e){t=e},e._eventQueue=[]}var we=(Se.prototype.addNotificationListener=function(e){this.listeners.push(e)},Se.prototype.removeNotificationListener=function(e){for(var t=B.arrIndexOf(this.listeners,e);-1<t;)this.listeners.splice(t,1),t=B.arrIndexOf(this.listeners,e)},Se.prototype.eventsSent=function(t){for(var n=this,i=this,e=0;e<this.listeners.length;++e)!function(e){i.listeners[e].eventsSent&&setTimeout(function(){return n.listeners[e].eventsSent(t)},0)}(e)},Se.prototype.eventsDiscarded=function(t,n){for(var i=this,r=this,e=0;e<this.listeners.length;++e)!function(e){r.listeners[e].eventsDiscarded&&setTimeout(function(){return i.listeners[e].eventsDiscarded(t,n)},0)}(e)},Se.prototype.eventsSendRequest=function(n,i){for(var r=this,o=this,e=0;e<this.listeners.length;++e)!function(e){if(o.listeners[e].eventsSendRequest)if(i)setTimeout(function(){return r.listeners[e].eventsSendRequest(n,i)},0);else try{o.listeners[e].eventsSendRequest(n,i)}catch(t){}}(e)},Se);function Se(){this.listeners=[]}var Ne,be=(Ne=Ie,__extends(Le,Ne),Le.prototype.initialize=function(e,t){var n=this;n._notificationManager=new we,n.logger=new Z(e),n.config=e,Ne.prototype.initialize.call(this,e,t,n.logger,n._notificationManager)},Le.prototype.getTransmissionControls=function(){return Ne.prototype.getTransmissionControls.call(this)},Le.prototype.track=function(e){if(null===e)throw this._notifyInvalidEvent(e),Error("Invalid telemetry item");this._validateTelemetryItem(e),Ne.prototype.track.call(this,e)},Le.prototype.addNotificationListener=function(e){this._notificationManager&&this._notificationManager.addNotificationListener(e)},Le.prototype.removeNotificationListener=function(e){this._notificationManager&&this._notificationManager.removeNotificationListener(e)},Le.prototype.pollInternalLogs=function(i){var t=this,e=this.config.diagnosticLogInterval;return e&&0<e||(e=1e4),setInterval(function(){var n=t,e=n.logger?n.logger.queue:[];B.arrForEach(e,function(e){var t={name:i||"InternalMessageId: "+e.messageId,iKey:n.config.instrumentationKey,time:B.toISOString(new Date),baseType:G.dataType,baseData:{message:e.message}};n.track(t)}),e.length=0},e)},Le.prototype._validateTelemetryItem=function(e){if(B.isNullOrUndefined(e.name))throw this._notifyInvalidEvent(e),Error("telemetry name required")},Le.prototype._notifyInvalidEvent=function(e){this._notificationManager&&this._notificationManager.eventsDiscarded([e],u.InvalidEvent)},Le);function Le(){return Ne.call(this)||this}var Ee="_aiHooks",Fe=["req","rsp","hkErr","fnErr"];function Me(e,t){if(e)for(var n=0;n<e.length&&!t(e[n],n);n++);}function Pe(e,l,u,c,f){0<=f&&f<=2&&Me(e,function(e,t){var n=e.cbks,i=n[Fe[f]];if(i){l.ctx=function(){return c[t]=c[t]||{}};try{i.apply(l.inst,u)}catch(a){var r=l.err;try{var o=n[Fe[2]];o&&(l.err=a,o.apply(l.inst,u))}catch(s){}finally{l.err=r}}}})}function Ae(e,t,n,i){if(void 0===i&&(i=!0),e&&t&&n){var r=function c(e,t,n){var i=null;return e&&(B.hasOwnProperty(e,t)?i=e:n&&(i=c(e[d],t,!1))),i}(e,t,i),o=r[t];if(typeof o===h){var a,s=o[Ee];s||(u=s={i:0,n:t,f:o,h:[]},(a=function(){var n=arguments,e=u.h,i={name:u.n,inst:this,ctx:null,set:function(e,t){(n=o([],n))[e]=t,r=o([i],n)}},t=[],r=o([i],n);function o(t,e){return Me(e,function(e){t.push(e)}),t}Pe(e,i,r,t,0);var a=u.f;try{i.rslt=a.apply(this,n)}catch(s){throw i.err=s,Pe(e,i,r,t,3),s}return Pe(e,i,r,t,1),i.rslt})[Ee]=s,r[t]=a);var l={id:s.i,cbks:n,rm:function(){var n=this.id;Me(s.h,function(e,t){return e.id===n&&(s.h.splice(t,1),1)})}};return s.i++,s.h.push(l),l}}var u;return null}function Oe(n,e,i,r){void 0===r&&(r=!0);var o=null;return Me(e,function(e){var t=Ae(n,e,i,r);t&&(o=o||[]).push(t)}),o}c.MinChannelPriorty=100,c.EventsDiscardedReason=u,c.AppInsightsCore=be,c.BaseCore=Ie,c.BaseTelemetryPlugin=oe,c.CoreUtils=B,c.EventHelper=W,c.Undefined=L,c.normalizeJsName=function(e){var t=e,n=/([^\w\d_$])/g;return n.test(e)&&(t=e.replace(n,"_")),t},c.getGlobal=y,c.getGlobalInst=m,c.hasWindow=x,c.getWindow=C,c.hasDocument=T,c.getDocument=I,c.hasNavigator=_,c.getNavigator=w,c.hasHistory=S,c.getHistory=function(){return S()?history:m("history")},c.getLocation=function(){return typeof location===g&&location?location:m("location")},c.getPerformance=function(){return m("performance")},c.hasJSON=N,c.getJSON=b,c.isReactNative=function(){var e=w();return!(!e||!e.product)&&"ReactNative"===e.product},c.strUndefined=f,c.strObject=g,c.strPrototype=d,c.strFunction=h,c.NotificationManager=we,c.DiagnosticLogger=Z,c._InternalLogMessage=G,c.ProcessTelemetryContext=ne,c.initializePlugins=ge,c.sortPlugins=de,c._InternalMessageId=K,c.InstrumentProto=function(e,t,n){return e?Ae(e[d],t,n,!1):null},c.InstrumentProtos=function(e,t,n){return e?Oe(e[d],t,n,!1):null},c.InstrumentFunc=Ae,c.InstrumentFuncs=Oe,function(e,t,n){var i=Object.defineProperty;if(i)try{return i(e,t,n)}catch(r){}typeof n.value!==undefined&&(e[t]=n.value)}(c,"__esModule",{value:!0})});
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e.Microsoft=e.Microsoft||{},e.Microsoft.ApplicationInsights=e.Microsoft.ApplicationInsights||{}))}(this,function(l){"use strict";var i="function",o="object",n="undefined",a="prototype",s="hasOwnProperty";function e(){return typeof globalThis!==n&&globalThis?globalThis:typeof self!==n&&self?self:typeof window!==n&&window?window:typeof global!==n&&global?global:null}function r(e){var n=Object.create;if(n)return n(e);if(null==e)return{};var t=typeof e;if(t!=o&&t!=i)throw new TypeError("Object prototype may only be an Object:"+e);function r(){}return r[a]=e,new r}var u=function(e,n){return(u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var t in n)n[s](t)&&(e[t]=n[t])})(e,n)},t=e()||{};__assign=t.__assign=t.__assign||Object.assign||function(e){for(var n,t=1,r=arguments.length;t<r;t++)for(var i in n=arguments[t])Object[a][s].call(n,i)&&(e[i]=n[i]);return e},__extends=t.__extends=t.__extends||function(e,n){function t(){this.constructor=e}u(e,n),e[a]=null===n?r(n):(t[a]=n[a],new t)};var c={Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5},f=n,g=o,d=a,v=i,p="window",h="JSON",y=e;function x(e){var n=y();return n&&n[e]?n[e]:e===p&&C()?window:null}function C(){return!(typeof window!==g||!window)}function m(){return C()?window:x(p)}function T(){return!(typeof document!==g||!document)}function w(){return T()?document:x("document")}function S(){return!(typeof navigator!==g||!navigator)}function I(){return S()?navigator:x("navigator")}function N(){return!(typeof history!==g||!history)}function b(){return typeof console!==f?console:x("console")}function E(){return!!(typeof JSON===g&&JSON||null!==x(h))}function P(){return E()?JSON||x(h):null}var F="constructor",_="prototype",L="function",M="_dynInstFuncs",O="_isDynProxy",A="_dynClass",j="_dynCls$",D="_unknown_",R="__proto__",k=Object.getPrototypeOf,U=0;function z(e,n){return e&&Object[_].hasOwnProperty.call(e,n)}function K(e){return typeof e===L}function B(e){return e&&(e===Object[_]||e===Array[_])}function q(e){return B(e)||e===Function[_]}function V(e){if(e){if(k)return k(e);var n=e[R]||e[_]||e[F];if(n)return n}return null}function W(e,n,t){return n!==F&&K(e[n])&&(t||z(e,n))}function H(e){throw new TypeError("DynamicProto: "+e)}function G(e,n){return z(e,_)?e.name||n||D:((e||{})[F]||{}).name||n||D}function J(e,t,n){z(e,_)||H("theClass is an invalid class definition.");var r=e[_];!function(e){for(var n=V(t);n&&!q(n);){if(n===e)return 1;n=V(n)}}(r)&&H("["+G(e)+"] is not in class heirarchy of ["+G(t)+"]");var i=null;z(r,A)?i=r[A]:(i=j+G(e,"_")+"$"+U,U++,r[A]=i);var o=function(e){var n={};for(var t in e)!n[t]&&W(e,t,!1)&&(n[t]=e[t]);return n}(t);n(t,function(e,n,t){function r(e,n){return function(){return n.apply(e,arguments)}}var i={};for(var o in t)i[o]=r(n,t[o]);for(var a=V(e),s=[];a&&!q(a)&&!function(e,n){for(var t=e.length-1;0<=t;t--)if(e[t]===n)return 1}(s,a);){for(var o in a)!i[o]&&W(a,o,!k)&&(i[o]=r(n,a[o]));s.push(a),a=V(a)}return i}(r,t,o)),function(e,n,t,r){if(!B(e)){var i=t[M]=t[M]||{},o=i[n]=i[n]||{};for(var a in t)W(t,a,!1)&&t[a]!==r[a]&&(o[a]=t[a],delete t[a],z(e,a)&&(!e[a]||e[a][O])||(e[a]=function(t,r){var i=function(){if(this&&z(t,A)){var e=((this[M]||{})[t[A]]||{})[r];if(e)return e.apply(this,arguments);H("Missing ["+r+"] "+L)}var n=t[r];return n===i&&(n=V(t)[r]),K(n)||H("["+r+"] is not a "+L),n.apply(this,arguments)};return i[O]=1,i}(e,a)))}}(r,i,t,o)}var Q="ctx",$=(Z.ParentContextKey="parent",Z.ChildrenContextKey="childEvts",Z);function Z(e,i,n){var t,o=this,a=!1;o.start=Date.now(),o.name=e,o.isAsync=n,o.isChildEvt=function(){return!1},ge.isFunction(i)&&(a=ge.objDefineAccessors(o,"payload",function(){return!t&&ge.isFunction(i)&&(t=i(),i=null),t})),o.getCtx=function(e){return e?e===Z.ParentContextKey||e===Z.ChildrenContextKey?o[e]:(o[Q]||{})[e]:null},o.setCtx=function(e,n){e&&(e===Z.ParentContextKey?(o[e]||(o.isChildEvt=function(){return!0}),o[e]=n):e===Z.ChildrenContextKey?o[e]=n:(o[Q]=o[Q]||{})[e]=n)},o.complete=function(){var e=0,n=o.getCtx(Z.ChildrenContextKey);if(ge.isArray(n))for(var t=0;t<n.length;t++){var r=n[t];r&&(e+=r.time)}o.time=Date.now()-o.start,o.exTime=o.time-e,o.complete=function(){},!a&&ge.isFunction(i)&&(o.payload=i())}}var Y=function fn(n){this.ctx={},J(fn,this,function(t){t.create=function(e,n,t){return new $(e,n,t)},t.fire=function(e){e&&e.complete(),n&&n.perfEvent(e)},t.setCtx=function(e,n){e&&((t[Q]=t[Q]||{})[e]=n)},t.getCtx=function(e){return(t[Q]||{})[e]}})},X=n,ee="attachEvent",ne="addEventListener",te="detachEvent",re="removeEventListener";function ie(e,n){return typeof e===n}function oe(e){return ie(e,n)||e===undefined}function ae(e){return oe(e)||null===e}function se(e,n){return e&&Object[a].hasOwnProperty.call(e,n)}function ue(e){return ie(e,o)}function ce(e){return ie(e,i)}function le(e,n,t,r){void 0===r&&(r=!1);var i=!1;if(!ae(e))try{ae(e[ne])?ae(e[ee])||(e[ee]("on"+n,t),i=!0):(e[ne](n,t,r),i=!0)}catch(o){}return i}function fe(e,n,t,r){if(void 0===r&&(r=!1),!ae(e))try{ae(e[re])?ae(e[te])||e[te]("on"+n,t):e[re](n,t,r)}catch(i){}}var ge=(de.isDate=function(e){return"[object Date]"===Object[a].toString.call(e)},de.isArray=function(e){return"[object Array]"===Object[a].toString.call(e)},de.isError=function(e){return"[object Error]"===Object[a].toString.call(e)},de.isString=function(e){return ie(e,"string")},de.isNumber=function(e){return ie(e,"number")},de.isBoolean=function(e){return ie(e,"boolean")},de.disableCookies=function(){de._canUseCookies=!1},de.newGuid=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(ve,function(e){var n,t=0|((n=x("crypto"))?n.getRandomValues(new Uint8Array(1))[0]%16:16*Math.random());return("x"===e?t:3&t|8).toString(16)})},de.toISOString=function(e){if(de.isDate(e)){var n=function(e){var n=e+"";return 1===n.length&&(n="0"+n),n};return e.getUTCFullYear()+"-"+n(1+e.getUTCMonth())+"-"+n(e.getUTCDate())+"T"+n(e.getUTCHours())+":"+n(e.getUTCMinutes())+":"+n(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}},de.arrForEach=function(e,n,t){for(var r=e.length,i=0;i<r;i++)i in e&&n.call(t||e,e[i],i,e)},de.arrIndexOf=function(e,n,t){for(var r=e.length,i=t||0,o=Math.max(0<=i?i:r-Math.abs(i),0);o<r;o++)if(o in e&&e[o]===n)return o;return-1},de.arrMap=function(e,n,t){for(var r=e.length,i=t||e,o=Array(r),a=0;a<r;a++)a in e&&(o[a]=n.call(i,e[a],e));return o},de.arrReduce=function(e,n,t){var r,i=e.length,o=0;if(3<=arguments.length)r=t;else{for(;o<i&&!(o in e);)o++;r=e[o++]}for(;o<i;)o in e&&(r=n(r,e[o],o,e)),o++;return r},de.strTrim=function(e){return de.isString(e)?e.replace(/^\s+|\s+$/g,""):e},de.objKeys=function(e){var n=!{toString:null}.propertyIsEnumerable("toString");if(!(ce(e)||ue(e)&&null!==e))throw new TypeError("objKeys called on non-object");var t=[];for(var r in e)se(e,r)&&t.push(r);if(n)for(var i=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=i.length,a=0;a<o;a++)se(e,i[a])&&t.push(i[a]);return t},de.objDefineAccessors=function(e,n,t,r){var i=Object.defineProperty;if(i)try{var o={enumerable:!0,configurable:!0};return t&&(o.get=t),r&&(o.set=r),i(e,n,o),!0}catch(a){}return!1},de.addEventHandler=function(e,n){var t=!1,r=m();r&&(t=le(r,e,n),t=le(r.body,e,n)||t);var i=w();return i&&(t=pe.Attach(i,e,n)||t),t},de.isTypeof=ie,de.isUndefined=oe,de.isNullOrUndefined=ae,de.hasOwnProperty=se,de.isFunction=ce,de.isObject=ue,de.objCreate=r,de);function de(){}var ve=/[xy]/g,pe=(he.Attach=le,he.AttachEvent=le,he.Detach=fe,he.DetachEvent=fe,he);function he(){}var ye,xe="CoreUtils.doPerf";function Ce(e,n,t,r,i){if(e){var o=e;if(o&&ge.isFunction(o.getPerfMgr)&&(o=o.getPerfMgr()),o){var a,s=void 0,u=o.getCtx(xe);try{if(s=o.create(n(),r,i))return u&&s.setCtx&&(s.setCtx($.ParentContextKey,u),u.getCtx&&u.setCtx&&((a=u.getCtx($.ChildrenContextKey))||(a=[],u.setCtx($.ChildrenContextKey,a)),a.push(s))),o.setCtx(xe,s),t(s)}catch(c){s&&s.setCtx&&s.setCtx("exception",c)}finally{s&&o.fire(s),o.setCtx(xe,u)}}}return t()}(ye=l.LoggingSeverity||(l.LoggingSeverity={}))[ye.CRITICAL=1]="CRITICAL",ye[ye.WARNING=2]="WARNING";var me={BrowserDoesNotSupportLocalStorage:0,BrowserCannotReadLocalStorage:1,BrowserCannotReadSessionStorage:2,BrowserCannotWriteLocalStorage:3,BrowserCannotWriteSessionStorage:4,BrowserFailedRemovalFromLocalStorage:5,BrowserFailedRemovalFromSessionStorage:6,CannotSendEmptyTelemetry:7,ClientPerformanceMathError:8,ErrorParsingAISessionCookie:9,ErrorPVCalc:10,ExceptionWhileLoggingError:11,FailedAddingTelemetryToBuffer:12,FailedMonitorAjaxAbort:13,FailedMonitorAjaxDur:14,FailedMonitorAjaxOpen:15,FailedMonitorAjaxRSC:16,FailedMonitorAjaxSend:17,FailedMonitorAjaxGetCorrelationHeader:18,FailedToAddHandlerForOnBeforeUnload:19,FailedToSendQueuedTelemetry:20,FailedToReportDataLoss:21,FlushFailed:22,MessageLimitPerPVExceeded:23,MissingRequiredFieldSpecification:24,NavigationTimingNotSupported:25,OnError:26,SessionRenewalDateIsZero:27,SenderNotInitialized:28,StartTrackEventFailed:29,StopTrackEventFailed:30,StartTrackFailed:31,StopTrackFailed:32,TelemetrySampledAndNotSent:33,TrackEventFailed:34,TrackExceptionFailed:35,TrackMetricFailed:36,TrackPVFailed:37,TrackPVFailedCalc:38,TrackTraceFailed:39,TransmissionFailed:40,FailedToSetStorageBuffer:41,FailedToRestoreStorageBuffer:42,InvalidBackendResponse:43,FailedToFixDepricatedValues:44,InvalidDurationValue:45,TelemetryEnvelopeInvalid:46,CreateEnvelopeError:47,CannotSerializeObject:48,CannotSerializeObjectNonSerializable:49,CircularReferenceDetected:50,ClearAuthContextFailed:51,ExceptionTruncated:52,IllegalCharsInName:53,ItemNotInArray:54,MaxAjaxPerPVExceeded:55,MessageTruncated:56,NameTooLong:57,SampleRateOutOfRange:58,SetAuthContextFailed:59,SetAuthContextFailedAccountName:60,StringValueTooLong:61,StartCalledMoreThanOnce:62,StopCalledWithoutStart:63,TelemetryInitializerFailed:64,TrackArgumentsNotSpecified:65,UrlTooLong:66,SessionStorageBufferFull:67,CannotAccessCookie:68,IdTooLong:69,InvalidEvent:70,FailedMonitorAjaxSetRequestHeader:71,SendBrowserInfoOnUserInit:72,PluginException:73,NotificationException:74,SnippetScriptLoadFailure:99};function Te(e){return e?'"'+e.replace(/\"/g,"")+'"':""}var we=(Se.dataType="MessageData",Se);function Se(e,n,t,r){void 0===t&&(t=!1),this.messageId=e,this.message=(t?"AI: ":"AI (Internal): ")+e;var i="";E()&&(i=P().stringify(r));var o=(n?" message:"+Te(n):"")+(r?" props:"+Te(i):"");this.message+=o}var Ie=function gn(o){this.identifier="DiagnosticLogger",this.queue=[];var a=0,c={};J(gn,this,function(s){var r=ge.isNullOrUndefined,u=ge.isUndefined,i=ge.isFunction;function e(e,n){var t=o[e];return r(t)?n:t}r(o)&&(o={}),s.consoleLoggingLevel=function(){return e("loggingLevelConsole",0)},s.telemetryLoggingLevel=function(){return e("loggingLevelTelemetry",1)},s.maxInternalMessageLimit=function(){return e("maxMessageLimit",25)},s.enableDebugExceptions=function(){return e("enableDebugExceptions",!1)},s.throwInternal=function(e,n,t,r,i){void 0===i&&(i=!1);var o,a=new we(n,t,i,r);if(s.enableDebugExceptions())throw a;!u(a)&&a&&(u(a.message)||(i?(o=+a.messageId,!c[o]&&s.consoleLoggingLevel()>=l.LoggingSeverity.WARNING&&(s.warnToConsole(a.message),c[o]=!0)):s.consoleLoggingLevel()>=l.LoggingSeverity.WARNING&&s.warnToConsole(a.message),s.logInternalMessage(e,a)))},s.warnToConsole=function(e){var n,t=b();t&&(n="log",t.warn&&(n="warn"),i(t[n])&&t[n](e))},s.resetInternalMessageCount=function(){a=0,c={}},s.logInternalMessage=function(e,n){var t,r,i;a>=s.maxInternalMessageLimit()||(t=!0,r="AITR_"+n.messageId,c[r]?t=!1:c[r]=!0,t&&(e<=s.telemetryLoggingLevel()&&(s.queue.push(n),a++),a===s.maxInternalMessageLimit()&&(i=new we(me.MessageLimitPerPVExceeded,"Internal events throttle limit per PageView reached for this app.",!1),s.queue.push(i),s.warnToConsole("Internal events throttle limit per PageView reached for this app."))))}})},Ne=ge.isFunction,be=function(i,n){var o=this,a=null,s=Ne(i.processTelemetry),u=Ne(i.setNextPlugin);o._hasRun=!1,o.getPlugin=function(){return i},o.getNext=function(){return a},o.setNext=function(e){a=e},o.processTelemetry=function(t,r){r=r||n;var e=i?i.identifier:"TelemetryPluginChain";Ce(r?r.core():null,function(){return e+":processTelemetry"},function(){if(i&&s){o._hasRun=!0;try{r.setNext(a),u&&i.setNextPlugin(a),a&&(a._hasRun=!1),i.processTelemetry(t,r)}catch(n){var e=a&&a._hasRun;a&&e||r.diagLog().throwInternal(l.LoggingSeverity.CRITICAL,me.PluginException,"Plugin ["+i.identifier+"] failed during processTelemetry - "+n),a&&!e&&a.processTelemetry(t,r)}}else a&&(o._hasRun=!0,a.processTelemetry(t,r))},function(){return{item:t}},!t.sync)}},Ee=ge.isNullOrUndefined;function Pe(e,n){var t=[];if(e&&0<e.length)for(var r=null,i=0;i<e.length;i++){var o,a=e[i];a&&ge.isFunction(a.processTelemetry)&&(o=new be(a,n),t.push(o),r&&r.setNext(o),r=o)}return 0<t.length?t[0]:null}var Fe=function dn(e,o,t,n){var r,i,a,s,u=this,c=null;null!==n&&(e&&ge.isFunction(e.getPlugin)?c=function(e,n,t){var r=[],i=!t;if(e)for(;e;){var o=e.getPlugin();!i&&o!==t||(i=!0,r.push(o)),e=e.getNext()}return i||r.push(t),Pe(r,n)}(e,u,n||e.getPlugin()):n?(r=u,a=e,s=!1,(i=n)&&e&&(a=[],ge.arrForEach(e,function(e){!s&&e!==i||(s=!0,a.push(e))})),i&&!s&&(a=a||[]).push(i),c=Pe(a,r)):ge.isUndefined(n)&&(c=Pe(e,u))),u.core=function(){return t},u.diagLog=function(){return(t||{}).logger||new Ie(o||{})},u.getCfg=function(){return o},u.getExtCfg=function(e,n){var t,r;return void 0===n&&(n={}),!o||(r=o.extensionConfig)&&e&&(t=r[e]),t||n},u.getConfig=function(e,n,t){var r;void 0===t&&(t=!1);var i=u.getExtCfg(e,null);return i&&!Ee(i[n])?r=i[n]:o&&!Ee(o[n])&&(r=o[n]),Ee(r)?t:r},u.hasNext=function(){return null!=c},u.getNext=function(){return c},u.setNext=function(e){c=e},u.processNext=function(e){var n=c;n&&(c=n.getNext(),n.processTelemetry(e,u))},u.createNew=function(e,n){return void 0===e&&(e=null),new dn(e||c,o,t,n)}},_e=ge.isFunction,Le="getPlugin",Me=(Oe.prototype.initialize=function(e,n,t,r){this._baseTelInit(e,n,t,r)},Oe);function Oe(){var o=this,a=!1,s=null,u=null;o.core=null,o.diagLog=function(e){return o._getTelCtx(e).diagLog()},o.isInitialized=function(){return a},o.setInitialized=function(e){a=e},o.setNextPlugin=function(e){u=e},o.processNext=function(e,n){n?n.processNext(e):u&&_e(u.processTelemetry)&&u.processTelemetry(e,null)},o._getTelCtx=function(e){void 0===e&&(e=null);var n,t=e;return t||(n=s||new Fe(null,{},o.core),t=u&&u[Le]?n.createNew(null,u[Le]):n.createNew(null,u)),t},o._baseTelInit=function(e,n,t,r){e&&(e.extensionConfig=e.extensionConfig||[]),!r&&n&&(r=n.getProcessTelContext().getNext());var i=u;u&&u[Le]&&(i=u[Le]()),o.core=n,s=new Fe(r,e,n,i),a=!0}}var Ae=ge.isFunction,je="processTelemetry",De="priority",Re="setNextPlugin",ke="isInitialized";function Ue(n,t){for(var e=[],r=null,i=n.getNext();i;){var o=i.getPlugin();o&&(r&&Ae(r[Re])&&Ae(o[je])&&r[Re](o),Ae(o[ke])&&o[ke]()||e.push(o),r=o,i=i.getNext())}ge.arrForEach(e,function(e){e.initialize(n.getCfg(),n.core(),t,n.getNext())})}function ze(e){return e.sort(function(e,n){var t=0,r=Ae(n[je]);return Ae(e[je])?t=r?e[De]-n[De]:1:r&&(t=-1),t})}var Ke,Be=500,qe="Channel has invalid priority",Ve=ge.objDefineAccessors,We=(Ke=Me,__extends(He,Ke),He._staticInit=(Ve(He.prototype,"ChannelControls",He.prototype.getChannelControls),void Ve(He.prototype,"channelQueue",He.prototype.getChannelControls)),He);function He(){var r=Ke.call(this)||this;r.identifier="ChannelControllerPlugin",r.priority=Be;var u,c=ge.arrForEach;function l(e){e&&0<e.length&&(e=e.sort(function(e,n){return e.priority-n.priority}),c(e,function(e){if(e.priority<Be)throw Error(qe+e.identifier)}),u.push(e))}return J(He,r,function(a,s){a.setNextPlugin=function(e){},a.processTelemetry=function(n,t){u&&c(u,function(e){0<e.length&&r._getTelCtx(t).createNew(e).processNext(n)})},a.getChannelControls=function(){return u},a.initialize=function(n,t,r){var e,i,o;a.isInitialized()||(s.initialize(n,t,r),n.isCookieUseDisabled&&ge.disableCookies(),i=r,u=[],(e=(n||{}).channels)&&c(e,l),i&&(o=[],c(i,function(e){e.priority>Be&&o.push(e)}),l(o)),c(u,function(e){return Ue(new Fe(e,n,t),r)}))}}),r}var Ge,Je=ge.arrForEach,Qe=ge.isNullOrUndefined,$e="_notificationManager",Ze=function vn(){var n,u,c,t,l=!1;J(vn,this,function(s){s._extensions=[],u=new We,n=[],s.isInitialized=function(){return l},s.initialize=function(e,n,r,t){if(s.isInitialized())throw Error("Core should not be initialized more than once");if(!e||Qe(e.instrumentationKey))throw Error("Please provide instrumentation key");c=t,s[$e]=t,s.config=e||{},e.extensions=Qe(e.extensions)?[]:e.extensions,(e.extensionConfig=Qe(e.extensionConfig)?{}:e.extensionConfig).NotificationManager=t,r=r||ge.objCreate({throwInternal:function(e,n,t,r,i){void 0===i&&(i=!1)},warnToConsole:function(e){},resetInternalMessageCount:function(){}}),s.logger=r;var i=[];i.push.apply(i,n.concat(e.extensions)),i=ze(i);var o=[],a={};if(Je(i,function(e){if(Qe(e)||Qe(e.initialize))throw Error("Extensions must provide callback to initialize");var n=e.priority,t=e.identifier;e&&n&&(Qe(a[n])?a[n]=t:r.warnToConsole("Two extensions have same priority #"+n+" - "+a[n]+", "+t)),(!n||n<u.priority)&&o.push(e)}),i.push(u),o.push(u),i=ze(i),s._extensions=i,Ue(new Fe([u],e,s),i),Ue(new Fe(o,e,s),i),s._extensions=o,0===s.getTransmissionControls().length)throw Error("No channels available");l=!0,s.releaseQueue()},s.getTransmissionControls=function(){return u.getChannelControls()},s.track=function(e){e.iKey||(e.iKey=s.config.instrumentationKey),e.time||(e.time=ge.toISOString(new Date)),Qe(e.ver)&&(e.ver="4.0"),s.isInitialized()?s.getProcessTelContext().processNext(e):n.push(e)},s.getProcessTelContext=function(){var e=s._extensions,n=e;return e&&0!==e.length||(n=[u]),new Fe(n,s.config,s)},s.getNotifyMgr=function(){return c||(c=ge.objCreate({addNotificationListener:function(e){},removeNotificationListener:function(e){},eventsSent:function(e){},eventsDiscarded:function(e,n){},eventsSendRequest:function(e,n){}}),s[$e]=c),c},s.getPerfMgr=function(){return t||s.config&&s.config.enablePerfMgr&&(t=new Y(s.getNotifyMgr())),t},s.setPerfMgr=function(e){t=e},s.eventCnt=function(){return n.length},s.releaseQueue=function(){0<n.length&&(Je(n,function(e){s.getProcessTelContext().processNext(e)}),n=[])}})},Ye=function pn(e){this.listeners=[];var o=ge.arrForEach,n=!!(e||{}).perfEvtsSendAll;J(pn,this,function(i){i.addNotificationListener=function(e){i.listeners.push(e)},i.removeNotificationListener=function(e){for(var n=ge.arrIndexOf(i.listeners,e);-1<n;)i.listeners.splice(n,1),n=ge.arrIndexOf(i.listeners,e)},i.eventsSent=function(n){o(i.listeners,function(e){e&&e.eventsSent&&setTimeout(function(){return e.eventsSent(n)},0)})},i.eventsDiscarded=function(n,t){o(i.listeners,function(e){e&&e.eventsDiscarded&&setTimeout(function(){return e.eventsDiscarded(n,t)},0)})},i.eventsSendRequest=function(t,r){o(i.listeners,function(e){if(e&&e.eventsSendRequest)if(r)setTimeout(function(){return e.eventsSendRequest(t,r)},0);else try{e.eventsSendRequest(t,r)}catch(n){}})},i.perfEvent=function(t){t&&(!n&&t.isChildEvt()||o(i.listeners,function(e){if(e&&e.perfEvent)if(t.isAsync)setTimeout(function(){return e.perfEvent(t)},0);else try{e.perfEvent(t)}catch(n){}}))}})},Xe=(Ge=Ze,__extends(en,Ge),en);function en(){var e=Ge.call(this)||this;return J(en,e,function(r,i){function n(e){var n=r.getNotifyMgr();n&&n.eventsDiscarded([e],c.InvalidEvent)}r.initialize=function(e,n,t,r){i.initialize(e,n,t||new Ie(e),r||new Ye(e))},r.track=function(e){Ce(r.getPerfMgr(),function(){return"AppInsightsCore:track"},function(){if(null===e)throw n(e),Error("Invalid telemetry item");!function(e){if(ge.isNullOrUndefined(e.name))throw n(e),Error("telemetry name required")}(e),i.track(e)},function(){return{item:e}},!e.sync)},r.addNotificationListener=function(e){var n=r.getNotifyMgr();n&&n.addNotificationListener(e)},r.removeNotificationListener=function(e){var n=r.getNotifyMgr();n&&n.removeNotificationListener(e)},r.pollInternalLogs=function(t){var e=r.config.diagnosticLogInterval;return e&&0<e||(e=1e4),setInterval(function(){var e=r.logger?r.logger.queue:[];ge.arrForEach(e,function(e){var n={name:t||"InternalMessageId: "+e.messageId,iKey:r.config.instrumentationKey,time:ge.toISOString(new Date),baseType:we.dataType,baseData:{message:e.message}};r.track(n)}),e.length=0},e)}}),e}var nn="_aiHooks",tn=["req","rsp","hkErr","fnErr"],rn="__proto__",on="constructor";function an(e,n){if(e)for(var t=0;t<e.length&&!n(e[t],t);t++);}function sn(e,u,c,l,f){0<=f&&f<=2&&an(e,function(e,n){var t=e.cbks,r=t[tn[f]];if(r){u.ctx=function(){return l[n]=l[n]||{}};try{r.apply(u.inst,c)}catch(a){var i=u.err;try{var o=t[tn[2]];o&&(u.err=a,o.apply(u.inst,c))}catch(s){}finally{u.err=i}}}})}var un=Object.getPrototypeOf;function cn(e,n,t,r){if(void 0===r&&(r=!0),e&&n&&t){var i=function l(e,n,t){var r=null;return e&&(ge.hasOwnProperty(e,n)?r=e:t&&(r=l(function(e){if(e){if(un)return un(e);var n=e[rn]||e[d]||e[on];if(n)return n}return null}(e),n,!1))),r}(e,n,r);if(i){var o=i[n];if(typeof o===v){var a,s=o[nn];s||(c=s={i:0,n:n,f:o,h:[]},(a=function(){var t=arguments,e=c.h,r={name:c.n,inst:this,ctx:null,set:function(e,n){(t=o([],t))[e]=n,i=o([r],t)}},n=[],i=o([r],t);function o(n,e){return an(e,function(e){n.push(e)}),n}sn(e,r,i,n,0);var a=c.f;try{r.rslt=a.apply(this,t)}catch(s){throw r.err=s,sn(e,r,i,n,3),s}return sn(e,r,i,n,1),r.rslt})[nn]=s,i[n]=a);var u={id:s.i,cbks:t,rm:function(){var t=this.id;an(s.h,function(e,n){return e.id===t&&(s.h.splice(n,1),1)})}};return s.i++,s.h.push(u),u}}}var c;return null}function ln(t,e,r,i){void 0===i&&(i=!0);var o=null;return an(e,function(e){var n=cn(t,e,r,i);n&&(o=o||[]).push(n)}),o}l.MinChannelPriorty=100,l.EventsDiscardedReason=c,l.AppInsightsCore=Xe,l.BaseCore=Ze,l.BaseTelemetryPlugin=Me,l.CoreUtils=ge,l.EventHelper=pe,l.Undefined=X,l.normalizeJsName=function(e){var n=e,t=/([^\w\d_$])/g;return t.test(e)&&(n=e.replace(t,"_")),n},l.doPerf=Ce,l.getGlobal=y,l.getGlobalInst=x,l.hasWindow=C,l.getWindow=m,l.hasDocument=T,l.getDocument=w,l.hasNavigator=S,l.getNavigator=I,l.hasHistory=N,l.getHistory=function(){return N()?history:x("history")},l.getLocation=function(){return typeof location===g&&location?location:x("location")},l.getPerformance=function(){return x("performance")},l.hasJSON=E,l.getJSON=P,l.isReactNative=function(){var e=I();return!(!e||!e.product)&&"ReactNative"===e.product},l.getConsole=b,l.strUndefined=f,l.strObject=g,l.strPrototype=d,l.strFunction=v,l.NotificationManager=Ye,l.PerfEvent=$,l.PerfManager=Y,l.DiagnosticLogger=Ie,l._InternalLogMessage=we,l.ProcessTelemetryContext=Fe,l.initializePlugins=Ue,l.sortPlugins=ze,l._InternalMessageId=me,l.InstrumentProto=function(e,n,t){return e?cn(e[d],n,t,!1):null},l.InstrumentProtos=function(e,n,t){return e?ln(e[d],n,t,!1):null},l.InstrumentFunc=cn,l.InstrumentFuncs=ln,function(e,n,t){var r=Object.defineProperty;if(r)try{return r(e,n,t)}catch(i){}typeof t.value!==undefined&&(e[n]=t.value)}(l,"__esModule",{value:!0})});
//# sourceMappingURL=applicationinsights-core-js.min.js.map

@@ -9,5 +9,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

export { BaseTelemetryPlugin } from './JavaScriptSDK/BaseTelemetryPlugin';
export { CoreUtils, EventHelper, Undefined, normalizeJsName } from "./JavaScriptSDK/CoreUtils";
export { getGlobal, getGlobalInst, hasWindow, getWindow, hasDocument, getDocument, hasNavigator, getNavigator, hasHistory, getHistory, getLocation, getPerformance, hasJSON, getJSON, isReactNative, strUndefined, strObject, strPrototype, strFunction } from "./JavaScriptSDK/EnvUtils";
export { CoreUtils, EventHelper, Undefined, normalizeJsName, doPerf } from "./JavaScriptSDK/CoreUtils";
export { getGlobal, getGlobalInst, hasWindow, getWindow, hasDocument, getDocument, hasNavigator, getNavigator, hasHistory, getHistory, getLocation, getPerformance, hasJSON, getJSON, isReactNative, getConsole, strUndefined, strObject, strPrototype, strFunction } from "./JavaScriptSDK/EnvUtils";
export { NotificationManager } from "./JavaScriptSDK/NotificationManager";
export { PerfEvent, PerfManager } from './JavaScriptSDK/PerfManager';
export { DiagnosticLogger, _InternalLogMessage } from './JavaScriptSDK/DiagnosticLogger';

@@ -14,0 +15,0 @@ export { ProcessTelemetryContext } from './JavaScriptSDK/ProcessTelemetryContext';

import { BaseCore } from './BaseCore';
import { EventsDiscardedReason } from "../JavaScriptSDK.Enums/EventsDiscardedReason";
import { NotificationManager } from "./NotificationManager";
import { CoreUtils } from "./CoreUtils";
import { CoreUtils, doPerf } from "./CoreUtils";
import { _InternalLogMessage, DiagnosticLogger } from "./DiagnosticLogger";
import dynamicProto from '@microsoft/dynamicproto-js';
"use strict";

@@ -10,23 +11,84 @@ var AppInsightsCore = /** @class */ (function (_super) {

function AppInsightsCore() {
return _super.call(this) || this;
var _this = _super.call(this) || this;
dynamicProto(AppInsightsCore, _this, function (_self, _base) {
_self.initialize = function (config, extensions, logger, notificationManager) {
_base.initialize(config, extensions, logger || new DiagnosticLogger(config), notificationManager || new NotificationManager(config));
};
_self.track = function (telemetryItem) {
doPerf(_self.getPerfMgr(), function () { return "AppInsightsCore:track"; }, function () {
if (telemetryItem === null) {
_notifyInvalidEvent(telemetryItem);
// throw error
throw Error("Invalid telemetry item");
}
// do basic validation before sending it through the pipeline
_validateTelemetryItem(telemetryItem);
_base.track(telemetryItem);
}, function () { return ({ item: telemetryItem }); }, !(telemetryItem.sync));
};
/**
* Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.
* The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be
* called.
* @param {INotificationListener} listener - An INotificationListener object.
*/
_self.addNotificationListener = function (listener) {
var manager = _self.getNotifyMgr();
if (manager) {
manager.addNotificationListener(listener);
}
};
/**
* Removes all instances of the listener.
* @param {INotificationListener} listener - INotificationListener to remove.
*/
_self.removeNotificationListener = function (listener) {
var manager = _self.getNotifyMgr();
if (manager) {
manager.removeNotificationListener(listener);
}
};
/**
* Periodically check logger.queue for
*/
_self.pollInternalLogs = function (eventName) {
var interval = _self.config.diagnosticLogInterval;
if (!interval || !(interval > 0)) {
interval = 10000;
}
return setInterval(function () {
var queue = _self.logger ? _self.logger.queue : [];
CoreUtils.arrForEach(queue, function (logMessage) {
var item = {
name: eventName ? eventName : "InternalMessageId: " + logMessage.messageId,
iKey: _self.config.instrumentationKey,
time: CoreUtils.toISOString(new Date()),
baseType: _InternalLogMessage.dataType,
baseData: { message: logMessage.message }
};
_self.track(item);
});
queue.length = 0;
}, interval);
};
function _validateTelemetryItem(telemetryItem) {
if (CoreUtils.isNullOrUndefined(telemetryItem.name)) {
_notifyInvalidEvent(telemetryItem);
throw Error("telemetry name required");
}
}
function _notifyInvalidEvent(telemetryItem) {
var manager = _self.getNotifyMgr();
if (manager) {
manager.eventsDiscarded([telemetryItem], EventsDiscardedReason.InvalidEvent);
}
}
});
return _this;
}
AppInsightsCore.prototype.initialize = function (config, extensions) {
var _self = this;
_self._notificationManager = new NotificationManager();
_self.logger = new DiagnosticLogger(config);
_self.config = config;
_super.prototype.initialize.call(this, config, extensions, _self.logger, _self._notificationManager);
AppInsightsCore.prototype.initialize = function (config, extensions, logger, notificationManager) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};
AppInsightsCore.prototype.getTransmissionControls = function () {
return _super.prototype.getTransmissionControls.call(this);
};
AppInsightsCore.prototype.track = function (telemetryItem) {
if (telemetryItem === null) {
this._notifyInvalidEvent(telemetryItem);
// throw error
throw Error("Invalid telemetry item");
}
// do basic validation before sending it through the pipeline
this._validateTelemetryItem(telemetryItem);
_super.prototype.track.call(this, telemetryItem);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -40,5 +102,3 @@ /**

AppInsightsCore.prototype.addNotificationListener = function (listener) {
if (this._notificationManager) {
this._notificationManager.addNotificationListener(listener);
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -50,5 +110,3 @@ /**

AppInsightsCore.prototype.removeNotificationListener = function (listener) {
if (this._notificationManager) {
this._notificationManager.removeNotificationListener(listener);
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -59,34 +117,5 @@ /**

AppInsightsCore.prototype.pollInternalLogs = function (eventName) {
var _this = this;
var interval = this.config.diagnosticLogInterval;
if (!interval || !(interval > 0)) {
interval = 10000;
}
return setInterval(function () {
var _self = _this;
var queue = _self.logger ? _self.logger.queue : [];
CoreUtils.arrForEach(queue, function (logMessage) {
var item = {
name: eventName ? eventName : "InternalMessageId: " + logMessage.messageId,
iKey: _self.config.instrumentationKey,
time: CoreUtils.toISOString(new Date()),
baseType: _InternalLogMessage.dataType,
baseData: { message: logMessage.message }
};
_self.track(item);
});
queue.length = 0;
}, interval);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 0;
};
AppInsightsCore.prototype._validateTelemetryItem = function (telemetryItem) {
if (CoreUtils.isNullOrUndefined(telemetryItem.name)) {
this._notifyInvalidEvent(telemetryItem);
throw Error("telemetry name required");
}
};
AppInsightsCore.prototype._notifyInvalidEvent = function (telemetryItem) {
if (this._notificationManager) {
this._notificationManager.eventsDiscarded([telemetryItem], EventsDiscardedReason.InvalidEvent);
}
};
return AppInsightsCore;

@@ -93,0 +122,0 @@ }(BaseCore));

@@ -8,150 +8,205 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { initializePlugins, sortPlugins } from './TelemetryHelpers';
import dynamicProto from '@microsoft/dynamicproto-js';
import { PerfManager } from "./PerfManager";
var validationError = "Extensions must provide callback to initialize";
var _arrForEach = CoreUtils.arrForEach;
var _isNullOrUndefined = CoreUtils.isNullOrUndefined;
var strNotificationManager = "_notificationManager";
var BaseCore = /** @class */ (function () {
function BaseCore() {
var _isInitialized = false;
var _this = this;
_this._extensions = new Array();
_this._channelController = new ChannelController();
_this.isInitialized = function () { return _isInitialized; };
_this._setInit = function (value) { _isInitialized = value; };
_this._eventQueue = [];
}
BaseCore.prototype.initialize = function (config, extensions, logger, notificationManager) {
var _this = this;
// Make sure core is only initialized once
if (_this.isInitialized()) {
throw Error("Core should not be initialized more than once");
}
if (!config || _isNullOrUndefined(config.instrumentationKey)) {
throw Error("Please provide instrumentation key");
}
_this.config = config;
var channelController = _this._channelController;
if (!notificationManager) {
// Create Dummy notification manager
notificationManager = CoreUtils.objCreate({
addNotificationListener: function (listener) { },
removeNotificationListener: function (listener) { },
eventsSent: function (events) { },
eventsDiscarded: function (events, reason) { },
eventsSendRequest: function (sendReason, isAsync) { }
});
}
_this._notificationManager = notificationManager;
config.extensions = _isNullOrUndefined(config.extensions) ? [] : config.extensions;
// add notification to the extensions in the config so other plugins can access it
var extConfig = config.extensionConfig = _isNullOrUndefined(config.extensionConfig) ? {} : config.extensionConfig;
extConfig.NotificationManager = notificationManager;
if (!logger) {
logger = CoreUtils.objCreate({
throwInternal: function (severity, msgId, msg, properties, isUserAct) {
if (isUserAct === void 0) { isUserAct = false; }
},
warnToConsole: function (message) { },
resetInternalMessageCount: function () { }
});
}
_this.logger = logger;
// Concat all available extensions
var allExtensions = [];
allExtensions.push.apply(allExtensions, extensions.concat(config.extensions));
allExtensions = sortPlugins(allExtensions);
var coreExtensions = [];
var channelExtensions = [];
// Check if any two extensions have the same priority, then warn to console
// And extract the local extensions from the
var extPriorities = {};
// Extension validation
_arrForEach(allExtensions, function (ext) {
if (_isNullOrUndefined(ext) || _isNullOrUndefined(ext.initialize)) {
throw Error(validationError);
}
var extPriority = ext.priority;
var identifier = ext.identifier;
if (ext && extPriority) {
if (!_isNullOrUndefined(extPriorities[extPriority])) {
logger.warnToConsole("Two extensions have same priority #" + extPriority + " - " + extPriorities[extPriority] + ", " + identifier);
var _eventQueue;
var _channelController;
var _notificationManager;
var _perfManager;
dynamicProto(BaseCore, this, function (_self) {
_self._extensions = new Array();
_channelController = new ChannelController();
_eventQueue = [];
_self.isInitialized = function () { return _isInitialized; };
_self.initialize = function (config, extensions, logger, notificationManager) {
// Make sure core is only initialized once
if (_self.isInitialized()) {
throw Error("Core should not be initialized more than once");
}
if (!config || _isNullOrUndefined(config.instrumentationKey)) {
throw Error("Please provide instrumentation key");
}
_notificationManager = notificationManager;
// For backward compatibility only
_self[strNotificationManager] = notificationManager;
_self.config = config || {};
config.extensions = _isNullOrUndefined(config.extensions) ? [] : config.extensions;
// add notification to the extensions in the config so other plugins can access it
var extConfig = config.extensionConfig = _isNullOrUndefined(config.extensionConfig) ? {} : config.extensionConfig;
extConfig.NotificationManager = notificationManager;
if (!logger) {
logger = CoreUtils.objCreate({
throwInternal: function (severity, msgId, msg, properties, isUserAct) {
if (isUserAct === void 0) { isUserAct = false; }
},
warnToConsole: function (message) { },
resetInternalMessageCount: function () { }
});
}
_self.logger = logger;
// Concat all available extensions
var allExtensions = [];
allExtensions.push.apply(allExtensions, extensions.concat(config.extensions));
allExtensions = sortPlugins(allExtensions);
var coreExtensions = [];
var channelExtensions = [];
// Check if any two extensions have the same priority, then warn to console
// And extract the local extensions from the
var extPriorities = {};
// Extension validation
_arrForEach(allExtensions, function (ext) {
if (_isNullOrUndefined(ext) || _isNullOrUndefined(ext.initialize)) {
throw Error(validationError);
}
var extPriority = ext.priority;
var identifier = ext.identifier;
if (ext && extPriority) {
if (!_isNullOrUndefined(extPriorities[extPriority])) {
logger.warnToConsole("Two extensions have same priority #" + extPriority + " - " + extPriorities[extPriority] + ", " + identifier);
}
else {
// set a value
extPriorities[extPriority] = identifier;
}
}
// Split extensions to core and channelController
if (!extPriority || extPriority < _channelController.priority) {
// Add to core extension that will be managed by BaseCore
coreExtensions.push(ext);
}
else {
// Add all other extensions to be managed by the channel controller
channelExtensions.push(ext);
}
});
// Validation complete
// Add the channelController to the complete extension collection and
// to the end of the core extensions
allExtensions.push(_channelController);
coreExtensions.push(_channelController);
// Sort the complete set of extensions by priority
allExtensions = sortPlugins(allExtensions);
_self._extensions = allExtensions;
// initialize channel controller first, this will initialize all channel plugins
initializePlugins(new ProcessTelemetryContext([_channelController], config, _self), allExtensions);
initializePlugins(new ProcessTelemetryContext(coreExtensions, config, _self), allExtensions);
// Now reset the extensions to just those being managed by Basecore
_self._extensions = coreExtensions;
if (_self.getTransmissionControls().length === 0) {
throw new Error("No channels available");
}
_isInitialized = true;
_self.releaseQueue();
};
_self.getTransmissionControls = function () {
return _channelController.getChannelControls();
};
_self.track = function (telemetryItem) {
if (!telemetryItem.iKey) {
// setup default iKey if not passed in
telemetryItem.iKey = _self.config.instrumentationKey;
}
if (!telemetryItem.time) {
// add default timestamp if not passed in
telemetryItem.time = CoreUtils.toISOString(new Date());
}
if (_isNullOrUndefined(telemetryItem.ver)) {
// CommonSchema 4.0
telemetryItem.ver = "4.0";
}
if (_self.isInitialized()) {
// Process the telemetry plugin chain
_self.getProcessTelContext().processNext(telemetryItem);
}
else {
// set a value
extPriorities[extPriority] = identifier;
// Queue events until all extensions are initialized
_eventQueue.push(telemetryItem);
}
}
// Split extensions to core and channelController
if (!extPriority || extPriority < channelController.priority) {
// Add to core extension that will be managed by BaseCore
coreExtensions.push(ext);
}
else {
// Add all other extensions to be managed by the channel controller
channelExtensions.push(ext);
}
};
_self.getProcessTelContext = function () {
var extensions = _self._extensions;
var thePlugins = extensions;
// invoke any common telemetry processors before sending through pipeline
if (!extensions || extensions.length === 0) {
// Pass to Channel controller so data is sent to correct channel queues
thePlugins = [_channelController];
}
return new ProcessTelemetryContext(thePlugins, _self.config, _self);
};
_self.getNotifyMgr = function () {
if (!_notificationManager) {
// Create Dummy notification manager
_notificationManager = CoreUtils.objCreate({
addNotificationListener: function (listener) { },
removeNotificationListener: function (listener) { },
eventsSent: function (events) { },
eventsDiscarded: function (events, reason) { },
eventsSendRequest: function (sendReason, isAsync) { }
});
// For backward compatibility only
_self[strNotificationManager] = _notificationManager;
}
return _notificationManager;
};
_self.getPerfMgr = function () {
if (!_perfManager) {
if (_self.config && _self.config.enablePerfMgr) {
_perfManager = new PerfManager(_self.getNotifyMgr());
}
}
return _perfManager;
};
_self.setPerfMgr = function (perfMgr) {
_perfManager = perfMgr;
};
_self.eventCnt = function () {
return _eventQueue.length;
};
_self.releaseQueue = function () {
if (_eventQueue.length > 0) {
_arrForEach(_eventQueue, function (event) {
_self.getProcessTelContext().processNext(event);
});
_eventQueue = [];
}
};
});
// Validation complete
// Add the channelController to the complete extension collection and
// to the end of the core extensions
allExtensions.push(channelController);
coreExtensions.push(channelController);
// Sort the complete set of extensions by priority
allExtensions = sortPlugins(allExtensions);
_this._extensions = allExtensions;
// initialize channel controller first, this will initialize all channel plugins
initializePlugins(new ProcessTelemetryContext([channelController], config, _this), allExtensions);
initializePlugins(new ProcessTelemetryContext(coreExtensions, config, _this), allExtensions);
// Now reset the extensions to just those being managed by Basecore
_this._extensions = coreExtensions;
if (_this.getTransmissionControls().length === 0) {
throw new Error("No channels available");
}
_this._setInit(true);
_this.releaseQueue();
}
BaseCore.prototype.initialize = function (config, extensions, logger, notificationManager) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};
BaseCore.prototype.getTransmissionControls = function () {
return this._channelController.getChannelControls();
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
};
BaseCore.prototype.track = function (telemetryItem) {
var _this = this;
if (!telemetryItem.iKey) {
// setup default iKey if not passed in
telemetryItem.iKey = _this.config.instrumentationKey;
}
if (!telemetryItem.time) {
// add default timestamp if not passed in
telemetryItem.time = CoreUtils.toISOString(new Date());
}
if (_isNullOrUndefined(telemetryItem.ver)) {
// CommonSchema 4.0
telemetryItem.ver = "4.0";
}
if (_this.isInitialized()) {
// Process the telemetry plugin chain
_this.getProcessTelContext().processNext(telemetryItem);
}
else {
// Queue events until all extensions are initialized
_this._eventQueue.push(telemetryItem);
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};
BaseCore.prototype.getProcessTelContext = function () {
var _this = this;
var extensions = _this._extensions;
var thePlugins = extensions;
// invoke any common telemetry processors before sending through pipeline
if (!extensions || extensions.length === 0) {
// Pass to Channel controller so data is sent to correct channel queues
thePlugins = [_this._channelController];
}
return new ProcessTelemetryContext(thePlugins, _this.config, _this);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
};
BaseCore.prototype.getNotifyMgr = function () {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
};
BaseCore.prototype.getPerfMgr = function () {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
};
BaseCore.prototype.setPerfMgr = function (perfMgr) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};
BaseCore.prototype.eventCnt = function () {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 0;
};
BaseCore.prototype.releaseQueue = function () {
var _this = this;
if (_this._eventQueue.length > 0) {
_arrForEach(_this._eventQueue, function (event) {
_this.getProcessTelContext().processNext(event);
});
_this._eventQueue = [];
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -158,0 +213,0 @@ return BaseCore;

@@ -8,79 +8,93 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { initializePlugins } from './TelemetryHelpers';
import dynamicProto from '@microsoft/dynamicproto-js';
var ChannelControllerPriority = 500;
var ChannelValidationMessage = "Channel has invalid priority";
var _arrForEach = CoreUtils.arrForEach;
var _objDefineAccessors = CoreUtils.objDefineAccessors;
function _checkQueuePriority(queue) {
_arrForEach(queue, function (queueItem) {
if (queueItem.priority < ChannelControllerPriority) {
throw Error(ChannelValidationMessage + queueItem.identifier);
}
});
}
function _addChannelQueue(channelQueues, queue) {
if (queue && queue.length > 0) {
queue = queue.sort(function (a, b) {
return a.priority - b.priority;
});
_checkQueuePriority(queue);
channelQueues.push(queue);
}
}
function _createChannelQueues(channels, extensions) {
var channelQueues = [];
if (channels) {
// Add and sort the configuration channel queues
_arrForEach(channels, function (queue) { return _addChannelQueue(channelQueues, queue); });
}
if (extensions) {
// Create a new channel queue for any extensions with a priority > the ChannelControllerPriority
var extensionQueue_1 = [];
_arrForEach(extensions, function (plugin) {
if (plugin.priority > ChannelControllerPriority) {
extensionQueue_1.push(plugin);
}
});
_addChannelQueue(channelQueues, extensionQueue_1);
}
return channelQueues;
}
var ChannelController = /** @class */ (function (_super) {
__extends(ChannelController, _super);
function ChannelController() {
var _this = _super !== null && _super.apply(this, arguments) || this;
var _this = _super.call(this) || this;
_this.identifier = "ChannelControllerPlugin";
_this.priority = ChannelControllerPriority; // in reserved range 100 to 200
var _arrForEach = CoreUtils.arrForEach;
var _channelQueue;
dynamicProto(ChannelController, _this, function (_self, _base) {
_self.setNextPlugin = function (next) {
// The Channel controller is last in pipeline
};
_self.processTelemetry = function (item, itemCtx) {
if (_channelQueue) {
_arrForEach(_channelQueue, function (queues) {
// pass on to first item in queue
if (queues.length > 0) {
// Copying the item context as we could have mutiple chains that are executing asynchronously
// and calling _getDefTelCtx as it's possible that the caller doesn't pass any context
var chainCtx = _this._getTelCtx(itemCtx).createNew(queues);
chainCtx.processNext(item);
}
});
}
};
_self.getChannelControls = function () {
return _channelQueue;
};
_self.initialize = function (config, core, extensions) {
if (_self.isInitialized()) {
// already initialized
return;
}
_base.initialize(config, core, extensions);
if (config.isCookieUseDisabled) {
CoreUtils.disableCookies();
}
_createChannelQueues((config || {}).channels, extensions);
// Initialize the Queues
_arrForEach(_channelQueue, function (queue) { return initializePlugins(new ProcessTelemetryContext(queue, config, core), extensions); });
};
});
function _checkQueuePriority(queue) {
_arrForEach(queue, function (queueItem) {
if (queueItem.priority < ChannelControllerPriority) {
throw Error(ChannelValidationMessage + queueItem.identifier);
}
});
}
function _addChannelQueue(queue) {
if (queue && queue.length > 0) {
queue = queue.sort(function (a, b) {
return a.priority - b.priority;
});
_checkQueuePriority(queue);
_channelQueue.push(queue);
}
}
function _createChannelQueues(channels, extensions) {
_channelQueue = [];
if (channels) {
// Add and sort the configuration channel queues
_arrForEach(channels, function (queue) { return _addChannelQueue(queue); });
}
if (extensions) {
// Create a new channel queue for any extensions with a priority > the ChannelControllerPriority
var extensionQueue_1 = [];
_arrForEach(extensions, function (plugin) {
if (plugin.priority > ChannelControllerPriority) {
extensionQueue_1.push(plugin);
}
});
_addChannelQueue(extensionQueue_1);
}
}
return _this;
}
ChannelController.prototype.processTelemetry = function (item, itemCtx) {
var _this = this;
if (this._channelQueue) {
_arrForEach(this._channelQueue, function (queues) {
// pass on to first item in queue
if (queues.length > 0) {
// Copying the item context as we could have mutiple chains that are executing asynchronously
// and calling _getDefTelCtx as it's possible that the caller doesn't pass any context
var chainCtx = _this._getTelCtx(itemCtx).createNew(queues);
chainCtx.processNext(item);
}
});
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};
;
ChannelController.prototype.getChannelControls = function () {
return this._channelQueue;
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
};
ChannelController.prototype.initialize = function (config, core, extensions) {
var _self = this;
if (_self.isInitialized()) {
// already initialized
return;
}
_super.prototype.initialize.call(this, config, core, extensions);
if (config.isCookieUseDisabled) {
CoreUtils.disableCookies();
}
var channelQueue = _self._channelQueue = _createChannelQueues((config || {}).channels, extensions);
// Initialize the Queues
_arrForEach(channelQueue, function (queue) { return initializePlugins(new ProcessTelemetryContext(queue, config, core), extensions); });
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -87,0 +101,0 @@ /**

@@ -6,2 +6,3 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { getWindow, getDocument, getCrypto } from './EnvUtils';
import { PerfEvent } from '../JavaScriptSDK/PerfManager';
// Added to help with minfication

@@ -115,2 +116,14 @@ export var Undefined = strShimUndefined;

/**
* Check if an object is of type Array
*/
CoreUtils.isArray = function (obj) {
return Object[strShimPrototype].toString.call(obj) === "[object Array]";
};
/**
* Check if an object is of type Error
*/
CoreUtils.isError = function (obj) {
return Object[strShimPrototype].toString.call(obj) === "[object Error]";
};
/**
* Checks if the type of value is a string.

@@ -428,2 +441,57 @@ * @param {any} value - Value to be checked.

export { EventHelper };
var doPerfActiveKey = "CoreUtils.doPerf";
/**
* Helper function to wrap a function with a perf event
* @param mgrSource - The Performance Manager or a Performance provider source (may be null)
* @param getSource - The callback to create the source name for the event (if perf monitoring is enabled)
* @param func - The function to call and measure
* @param details - A function to return the payload details
* @param isAsync - Is the event / function being call asynchronously or synchronously
*/
export function doPerf(mgrSource, getSource, func, details, isAsync) {
if (mgrSource) {
var perfMgr = mgrSource;
if (perfMgr && CoreUtils.isFunction(perfMgr["getPerfMgr"])) {
// Looks like a perf manager provider object
perfMgr = perfMgr["getPerfMgr"]();
}
if (perfMgr) {
var perfEvt = void 0;
var currentActive = perfMgr.getCtx(doPerfActiveKey);
try {
perfEvt = perfMgr.create(getSource(), details, isAsync);
if (perfEvt) {
if (currentActive && perfEvt.setCtx) {
perfEvt.setCtx(PerfEvent.ParentContextKey, currentActive);
if (currentActive.getCtx && currentActive.setCtx) {
var children = currentActive.getCtx(PerfEvent.ChildrenContextKey);
if (!children) {
children = [];
currentActive.setCtx(PerfEvent.ChildrenContextKey, children);
}
children.push(perfEvt);
}
}
// Set this event as the active event now
perfMgr.setCtx(doPerfActiveKey, perfEvt);
return func(perfEvt);
}
}
catch (ex) {
if (perfEvt && perfEvt.setCtx) {
perfEvt.setCtx("exception", ex);
}
}
finally {
// fire the perf event
if (perfEvt) {
perfMgr.fire(perfEvt);
}
// Reset the active event to the previous value
perfMgr.setCtx(doPerfActiveKey, currentActive);
}
}
}
return func();
}
//# sourceMappingURL=CoreUtils.js.map

@@ -6,9 +6,29 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { CoreUtils } from "./CoreUtils";
import { hasJSON, getJSON } from "./EnvUtils";
import { hasJSON, getJSON, getConsole } from "./EnvUtils";
import dynamicProto from '@microsoft/dynamicproto-js';
/**
* For user non actionable traces use AI Internal prefix.
*/
var AiNonUserActionablePrefix = "AI (Internal): ";
/**
* Prefix of the traces in portal.
*/
var AiUserActionablePrefix = "AI: ";
/**
* Session storage key for the prefix for the key indicating message type already logged
*/
var AIInternalMessagePrefix = "AITR_";
function _sanitizeDiagnosticText(text) {
if (text) {
return "\"" + text.replace(/\"/g, "") + "\"";
}
return "";
}
var _InternalLogMessage = /** @class */ (function () {
function _InternalLogMessage(msgId, msg, isUserAct, properties) {
if (isUserAct === void 0) { isUserAct = false; }
this.messageId = msgId;
this.message =
(isUserAct ? _InternalLogMessage.AiUserActionablePrefix : _InternalLogMessage.AiNonUserActionablePrefix) +
var _self = this;
_self.messageId = msgId;
_self.message =
(isUserAct ? AiUserActionablePrefix : AiNonUserActionablePrefix) +
msgId;

@@ -19,21 +39,7 @@ var strProps = "";

}
var diagnosticText = (msg ? " message:" + _InternalLogMessage.sanitizeDiagnosticText(msg) : "") +
(properties ? " props:" + _InternalLogMessage.sanitizeDiagnosticText(strProps) : "");
this.message += diagnosticText;
var diagnosticText = (msg ? " message:" + _sanitizeDiagnosticText(msg) : "") +
(properties ? " props:" + _sanitizeDiagnosticText(strProps) : "");
_self.message += diagnosticText;
}
_InternalLogMessage.sanitizeDiagnosticText = function (text) {
if (text) {
return "\"" + text.replace(/\"/g, "") + "\"";
}
return "";
};
_InternalLogMessage.dataType = "MessageData";
/**
* For user non actionable traces use AI Internal prefix.
*/
_InternalLogMessage.AiNonUserActionablePrefix = "AI (Internal): ";
/**
* Prefix of the traces in portal.
*/
_InternalLogMessage.AiUserActionablePrefix = "AI: ";
return _InternalLogMessage;

@@ -44,2 +50,3 @@ }());

function DiagnosticLogger(config) {
this.identifier = 'DiagnosticLogger';
/**

@@ -50,53 +57,155 @@ * The internal logging queue

/**
* Session storage key for the prefix for the key indicating message type already logged
*/
this.AIInternalMessagePrefix = "AITR_";
/**
* Count of internal messages sent
*/
this._messageCount = 0;
var _messageCount = 0;
/**
* Holds information about what message types were already logged to console or sent to server.
*/
this._messageLogged = {};
/**
* When this is true the SDK will throw exceptions to aid in debugging.
*/
this.enableDebugExceptions = function () { return false; };
/**
* 0: OFF (default)
* 1: CRITICAL
* 2: >= WARNING
*/
this.consoleLoggingLevel = function () { return 0; };
/**
* 0: OFF
* 1: CRITICAL (default)
* 2: >= WARNING
*/
this.telemetryLoggingLevel = function () { return 1; };
/**
* The maximum number of internal messages allowed to be sent per page view
*/
this.maxInternalMessageLimit = function () { return 25; };
if (CoreUtils.isNullOrUndefined(config)) {
// TODO: Use default config
// config = AppInsightsCore.defaultConfig;
// For now, use defaults specified in DiagnosticLogger members;
return;
}
if (!CoreUtils.isNullOrUndefined(config.loggingLevelConsole)) {
this.consoleLoggingLevel = function () { return config.loggingLevelConsole; };
}
if (!CoreUtils.isNullOrUndefined(config.loggingLevelTelemetry)) {
this.telemetryLoggingLevel = function () { return config.loggingLevelTelemetry; };
}
if (!CoreUtils.isNullOrUndefined(config.maxMessageLimit)) {
this.maxInternalMessageLimit = function () { return config.maxMessageLimit; };
}
if (!CoreUtils.isNullOrUndefined(config.enableDebugExceptions)) {
this.enableDebugExceptions = function () { return config.enableDebugExceptions; };
}
var _messageLogged = {};
dynamicProto(DiagnosticLogger, this, function (_self) {
var isNullOrUndefined = CoreUtils.isNullOrUndefined;
var isUndefined = CoreUtils.isUndefined;
var isFunction = CoreUtils.isFunction;
if (isNullOrUndefined(config)) {
config = {};
}
_self.consoleLoggingLevel = function () { return _getConfigValue('loggingLevelConsole', 0); };
_self.telemetryLoggingLevel = function () { return _getConfigValue('loggingLevelTelemetry', 1); };
_self.maxInternalMessageLimit = function () { return _getConfigValue('maxMessageLimit', 25); };
_self.enableDebugExceptions = function () { return _getConfigValue('enableDebugExceptions', false); };
/**
* This method will throw exceptions in debug mode or attempt to log the error as a console warning.
* @param severity {LoggingSeverity} - The severity of the log message
* @param message {_InternalLogMessage} - The log message.
*/
_self.throwInternal = function (severity, msgId, msg, properties, isUserAct) {
if (isUserAct === void 0) { isUserAct = false; }
var message = new _InternalLogMessage(msgId, msg, isUserAct, properties);
if (_self.enableDebugExceptions()) {
throw message;
}
else {
if (!isUndefined(message) && !!message) {
if (!isUndefined(message.message)) {
if (isUserAct) {
// check if this message type was already logged to console for this page view and if so, don't log it again
var messageKey = +message.messageId;
if (!_messageLogged[messageKey] && _self.consoleLoggingLevel() >= LoggingSeverity.WARNING) {
_self.warnToConsole(message.message);
_messageLogged[messageKey] = true;
}
}
else {
// don't log internal AI traces in the console, unless the verbose logging is enabled
if (_self.consoleLoggingLevel() >= LoggingSeverity.WARNING) {
_self.warnToConsole(message.message);
}
}
_self.logInternalMessage(severity, message);
}
}
}
};
/**
* This will write a warning to the console if possible
* @param message {string} - The warning message
*/
_self.warnToConsole = function (message) {
var theConsole = getConsole();
if (!!theConsole) {
var logFunc = 'log';
if (theConsole.warn) {
logFunc = 'warn';
}
if (isFunction(theConsole[logFunc])) {
theConsole[logFunc](message);
}
}
};
/**
* Resets the internal message count
*/
_self.resetInternalMessageCount = function () {
_messageCount = 0;
_messageLogged = {};
};
/**
* Logs a message to the internal queue.
* @param severity {LoggingSeverity} - The severity of the log message
* @param message {_InternalLogMessage} - The message to log.
*/
_self.logInternalMessage = function (severity, message) {
if (_areInternalMessagesThrottled()) {
return;
}
// check if this message type was already logged for this session and if so, don't log it again
var logMessage = true;
var messageKey = AIInternalMessagePrefix + message.messageId;
// if the session storage is not available, limit to only one message type per page view
if (_messageLogged[messageKey]) {
logMessage = false;
}
else {
_messageLogged[messageKey] = true;
}
if (logMessage) {
// Push the event in the internal queue
if (severity <= _self.telemetryLoggingLevel()) {
_self.queue.push(message);
_messageCount++;
}
// When throttle limit reached, send a special event
if (_messageCount === _self.maxInternalMessageLimit()) {
var throttleLimitMessage = "Internal events throttle limit per PageView reached for this app.";
var throttleMessage = new _InternalLogMessage(_InternalMessageId.MessageLimitPerPVExceeded, throttleLimitMessage, false);
_self.queue.push(throttleMessage);
_self.warnToConsole(throttleLimitMessage);
}
}
};
function _getConfigValue(name, defValue) {
var value = config[name];
if (!isNullOrUndefined(value)) {
return value;
}
return defValue;
}
function _areInternalMessagesThrottled() {
return _messageCount >= _self.maxInternalMessageLimit();
}
});
}
/**
* When this is true the SDK will throw exceptions to aid in debugging.
*/
DiagnosticLogger.prototype.enableDebugExceptions = function () {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return false;
};
/**
* 0: OFF (default)
* 1: CRITICAL
* 2: >= WARNING
*/
DiagnosticLogger.prototype.consoleLoggingLevel = function () {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 0;
};
/**
* 0: OFF
* 1: CRITICAL (default)
* 2: >= WARNING
*/
DiagnosticLogger.prototype.telemetryLoggingLevel = function () {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 1;
};
/**
* The maximum number of internal messages allowed to be sent per page view
*/
DiagnosticLogger.prototype.maxInternalMessageLimit = function () {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 25;
};
/**
* This method will throw exceptions in debug mode or attempt to log the error as a console warning.

@@ -108,28 +217,3 @@ * @param severity {LoggingSeverity} - The severity of the log message

if (isUserAct === void 0) { isUserAct = false; }
var message = new _InternalLogMessage(msgId, msg, isUserAct, properties);
var _this = this;
if (_this.enableDebugExceptions()) {
throw message;
}
else {
if (!CoreUtils.isUndefined(message) && !!message) {
if (!CoreUtils.isUndefined(message.message)) {
if (isUserAct) {
// check if this message type was already logged to console for this page view and if so, don't log it again
var messageKey = +message.messageId;
if (!_this._messageLogged[messageKey] && _this.consoleLoggingLevel() >= LoggingSeverity.WARNING) {
_this.warnToConsole(message.message);
_this._messageLogged[messageKey] = true;
}
}
else {
// don't log internal AI traces in the console, unless the verbose logging is enabled
if (_this.consoleLoggingLevel() >= LoggingSeverity.WARNING) {
_this.warnToConsole(message.message);
}
}
_this.logInternalMessage(severity, message);
}
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -141,10 +225,3 @@ /**

DiagnosticLogger.prototype.warnToConsole = function (message) {
if (!CoreUtils.isUndefined(console) && !!console) {
if (CoreUtils.isFunction(console.warn)) {
console.warn(message);
}
else if (CoreUtils.isFunction(console.log)) {
console.log(message);
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -155,4 +232,3 @@ /**

DiagnosticLogger.prototype.resetInternalMessageCount = function () {
this._messageCount = 0;
this._messageLogged = {};
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -165,37 +241,4 @@ /**

DiagnosticLogger.prototype.logInternalMessage = function (severity, message) {
var _this = this;
if (_this._areInternalMessagesThrottled()) {
return;
}
// check if this message type was already logged for this session and if so, don't log it again
var logMessage = true;
var messageKey = _this.AIInternalMessagePrefix + message.messageId;
// if the session storage is not available, limit to only one message type per page view
if (_this._messageLogged[messageKey]) {
logMessage = false;
}
else {
_this._messageLogged[messageKey] = true;
}
if (logMessage) {
// Push the event in the internal queue
if (severity <= _this.telemetryLoggingLevel()) {
_this.queue.push(message);
_this._messageCount++;
}
// When throttle limit reached, send a special event
if (_this._messageCount === _this.maxInternalMessageLimit()) {
var throttleLimitMessage = "Internal events throttle limit per PageView reached for this app.";
var throttleMessage = new _InternalLogMessage(_InternalMessageId.MessageLimitPerPVExceeded, throttleLimitMessage, false);
_this.queue.push(throttleMessage);
_this.warnToConsole(throttleLimitMessage);
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};
/**
* Indicates whether the internal events are throttled
*/
DiagnosticLogger.prototype._areInternalMessagesThrottled = function () {
return this._messageCount >= this.maxInternalMessageLimit();
};
return DiagnosticLogger;

@@ -202,0 +245,0 @@ }());

@@ -20,2 +20,3 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

var strLocation = "location";
var strConsole = "console";
var strPerformance = "performance";

@@ -151,2 +152,11 @@ var strJSON = "JSON";

/**
* Returns the global console object
*/
export function getConsole() {
if (typeof console !== strUndefined) {
return console;
}
return getGlobalInst(strConsole);
}
/**
* Returns the performance object if it is present otherwise null.

@@ -153,0 +163,0 @@ * This helper is used to access the performance object from the current

@@ -10,2 +10,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

];
/**
* Constant string defined to support minimization
* @ignore
*/
var str__Proto = "__proto__";
/**
* Constant string defined to support minimization
* @ignore
*/
var strConstructor = "constructor";
/** @ignore */

@@ -104,2 +114,25 @@ function _arrLoop(arr, fn) {

}
/**
* Pre-lookup to check if we are running on a modern browser (i.e. not IE8)
* @ignore
*/
var _objGetPrototypeOf = Object["getPrototypeOf"];
/**
* Helper used to get the prototype of the target object as getPrototypeOf is not available in an ES3 environment.
* @ignore
*/
function _getObjProto(target) {
if (target) {
// This method doesn't existing in older browsers (e.g. IE8)
if (_objGetPrototypeOf) {
return _objGetPrototypeOf(target);
}
// target[Constructor] May break if the constructor has been changed or removed
var newProto = target[str__Proto] || target[strPrototype] || target[strConstructor];
if (newProto) {
return newProto;
}
}
return null;
}
/** @ignore */

@@ -113,3 +146,3 @@ function _getOwner(target, name, checkPrototype) {

else if (checkPrototype) {
owner = _getOwner(target[strPrototype], name, false);
owner = _getOwner(_getObjProto(target), name, false);
}

@@ -154,38 +187,40 @@ }

var owner = _getOwner(target, funcName, checkPrototype);
var fn = owner[funcName];
if (typeof fn === strFunction) {
var aiHook_1 = fn[aiInstrumentHooks];
if (!aiHook_1) {
// Only hook the function once
aiHook_1 = {
i: 0,
n: funcName,
f: fn,
h: []
if (owner) {
var fn = owner[funcName];
if (typeof fn === strFunction) {
var aiHook_1 = fn[aiInstrumentHooks];
if (!aiHook_1) {
// Only hook the function once
aiHook_1 = {
i: 0,
n: funcName,
f: fn,
h: []
};
// Override (hook) the original function
var newFunc = _createFunctionHook(aiHook_1);
newFunc[aiInstrumentHooks] = aiHook_1; // Tag and store the function hooks
owner[funcName] = newFunc;
}
var theHook = {
// tslint:disable:object-literal-shorthand
id: aiHook_1.i,
cbks: callbacks,
rm: function () {
// DO NOT Use () => { shorthand for the function as the this gets replaced
// with the outer this and not the this for theHook instance.
var id = this.id;
_arrLoop(aiHook_1.h, function (hook, idx) {
if (hook.id === id) {
aiHook_1.h.splice(idx, 1);
return 1;
}
});
}
// tslint:enable:object-literal-shorthand
};
// Override (hook) the original function
var newFunc = _createFunctionHook(aiHook_1);
newFunc[aiInstrumentHooks] = aiHook_1; // Tag and store the function hooks
owner[funcName] = newFunc;
aiHook_1.i++;
aiHook_1.h.push(theHook);
return theHook;
}
var theHook = {
// tslint:disable:object-literal-shorthand
id: aiHook_1.i,
cbks: callbacks,
rm: function () {
// DO NOT Use () => { shorthand for the function as the this gets replaced
// with the outer this and not the this for theHook instance.
var id = this.id;
_arrLoop(aiHook_1.h, function (hook, idx) {
if (hook.id === id) {
aiHook_1.h.splice(idx, 1);
return 1;
}
});
}
// tslint:enable:object-literal-shorthand
};
aiHook_1.i++;
aiHook_1.h.push(theHook);
return theHook;
}

@@ -192,0 +227,0 @@ }

@@ -1,2 +0,3 @@

import { CoreUtils } from "./CoreUtils";
import { CoreUtils, } from "./CoreUtils";
import dynamicProto from "@microsoft/dynamicproto-js";
/**

@@ -6,4 +7,90 @@ * Class to manage sending notifications to all the listeners.

var NotificationManager = /** @class */ (function () {
function NotificationManager() {
function NotificationManager(config) {
this.listeners = [];
var arrForEach = CoreUtils.arrForEach;
var perfEvtsSendAll = !!(config || {}).perfEvtsSendAll;
dynamicProto(NotificationManager, this, function (_self) {
_self.addNotificationListener = function (listener) {
_self.listeners.push(listener);
};
/**
* Removes all instances of the listener.
* @param {INotificationListener} listener - AWTNotificationListener to remove.
*/
_self.removeNotificationListener = function (listener) {
var index = CoreUtils.arrIndexOf(_self.listeners, listener);
while (index > -1) {
_self.listeners.splice(index, 1);
index = CoreUtils.arrIndexOf(_self.listeners, listener);
}
};
/**
* Notification for events sent.
* @param {ITelemetryItem[]} events - The array of events that have been sent.
*/
_self.eventsSent = function (events) {
arrForEach(_self.listeners, function (listener) {
if (listener && listener.eventsSent) {
setTimeout(function () { return listener.eventsSent(events); }, 0);
}
});
};
/**
* Notification for events being discarded.
* @param {ITelemetryItem[]} events - The array of events that have been discarded by the SDK.
* @param {number} reason - The reason for which the SDK discarded the events. The EventsDiscardedReason
* constant should be used to check the different values.
*/
_self.eventsDiscarded = function (events, reason) {
arrForEach(_self.listeners, function (listener) {
if (listener && listener.eventsDiscarded) {
setTimeout(function () { return listener.eventsDiscarded(events, reason); }, 0);
}
});
};
/**
* [Optional] A function called when the events have been requested to be sent to the sever.
* @param {number} sendReason - The reason why the event batch is being sent.
* @param {boolean} isAsync - A flag which identifies whether the requests are being sent in an async or sync manner.
*/
_self.eventsSendRequest = function (sendReason, isAsync) {
arrForEach(_self.listeners, function (listener) {
if (listener && listener.eventsSendRequest) {
if (isAsync) {
setTimeout(function () { return listener.eventsSendRequest(sendReason, isAsync); }, 0);
}
else {
try {
listener.eventsSendRequest(sendReason, isAsync);
}
catch (e) {
// Catch errors to ensure we don't block sending the requests
}
}
}
});
};
_self.perfEvent = function (perfEvent) {
if (perfEvent) {
// Send all events or only parent events
if (perfEvtsSendAll || !perfEvent.isChildEvt()) {
arrForEach(_self.listeners, function (listener) {
if (listener && listener.perfEvent) {
if (perfEvent.isAsync) {
setTimeout(function () { return listener.perfEvent(perfEvent); }, 0);
}
else {
try {
listener.perfEvent(perfEvent);
}
catch (e) {
// Catch errors to ensure we don't block sending the requests
}
}
}
});
}
}
};
});
}

@@ -15,3 +102,3 @@ /**

NotificationManager.prototype.addNotificationListener = function (listener) {
this.listeners.push(listener);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -23,7 +110,3 @@ /**

NotificationManager.prototype.removeNotificationListener = function (listener) {
var index = CoreUtils.arrIndexOf(this.listeners, listener);
while (index > -1) {
this.listeners.splice(index, 1);
index = CoreUtils.arrIndexOf(this.listeners, listener);
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -35,12 +118,3 @@ /**

NotificationManager.prototype.eventsSent = function (events) {
var _this = this;
var _loop_1 = function (i) {
if (this_1.listeners[i].eventsSent) {
setTimeout(function () { return _this.listeners[i].eventsSent(events); }, 0);
}
};
var this_1 = this;
for (var i = 0; i < this.listeners.length; ++i) {
_loop_1(i);
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -54,12 +128,3 @@ /**

NotificationManager.prototype.eventsDiscarded = function (events, reason) {
var _this = this;
var _loop_2 = function (i) {
if (this_2.listeners[i].eventsDiscarded) {
setTimeout(function () { return _this.listeners[i].eventsDiscarded(events, reason); }, 0);
}
};
var this_2 = this;
for (var i = 0; i < this.listeners.length; ++i) {
_loop_2(i);
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -72,22 +137,3 @@ /**

NotificationManager.prototype.eventsSendRequest = function (sendReason, isAsync) {
var _this = this;
var _loop_3 = function (i) {
if (this_3.listeners[i].eventsSendRequest) {
if (isAsync) {
setTimeout(function () { return _this.listeners[i].eventsSendRequest(sendReason, isAsync); }, 0);
}
else {
try {
this_3.listeners[i].eventsSendRequest(sendReason, isAsync);
}
catch (e) {
// Catch errors to ensure we don't block sending the requests
}
}
}
};
var this_3 = this;
for (var i = 0; i < this.listeners.length; ++i) {
_loop_3(i);
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};

@@ -94,0 +140,0 @@ return NotificationManager;

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
"use strict";
import { CoreUtils } from "./CoreUtils";
import { CoreUtils, doPerf } from "./CoreUtils";
import { LoggingSeverity, _InternalMessageId } from '../JavaScriptSDK.Enums/LoggingEnums';

@@ -28,37 +28,40 @@ var _isFunction = CoreUtils.isFunction;

}
if (plugin && _hasProcessTelemetry) {
_self._hasRun = true;
try {
// Ensure that we keep the context in sync (for processNext()), just in case a plugin
// doesn't calls processTelemetry() instead of itemContext.processNext() or some
// other form of error occurred
itemCtx.setNext(_nextProxy);
if (_hasSetNext) {
// Backward compatibility setting the next plugin on the instance
plugin.setNextPlugin(_nextProxy);
var identifier = plugin ? plugin.identifier : "TelemetryPluginChain";
doPerf(itemCtx ? itemCtx.core() : null, function () { return identifier + ":processTelemetry"; }, function () {
if (plugin && _hasProcessTelemetry) {
_self._hasRun = true;
try {
// Ensure that we keep the context in sync (for processNext()), just in case a plugin
// doesn't calls processTelemetry() instead of itemContext.processNext() or some
// other form of error occurred
itemCtx.setNext(_nextProxy);
if (_hasSetNext) {
// Backward compatibility setting the next plugin on the instance
plugin.setNextPlugin(_nextProxy);
}
// Set a flag on the next plugin so we know if it was attempted to be executed
_nextProxy && (_nextProxy._hasRun = false);
plugin.processTelemetry(env, itemCtx);
}
// Set a flag on the next plugin so we know if it was attempted to be executed
_nextProxy && (_nextProxy._hasRun = false);
plugin.processTelemetry(env, itemCtx);
}
catch (error) {
var hasRun = _nextProxy && _nextProxy._hasRun;
if (!_nextProxy || !hasRun) {
// Either we have no next plugin or the current one did not attempt to call the next plugin
// Which means the current one is the root of the failure so log/report this failure
itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.PluginException, "Plugin [" + plugin.identifier + "] failed during processTelemetry - " + error);
catch (error) {
var hasRun = _nextProxy && _nextProxy._hasRun;
if (!_nextProxy || !hasRun) {
// Either we have no next plugin or the current one did not attempt to call the next plugin
// Which means the current one is the root of the failure so log/report this failure
itemCtx.diagLog().throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.PluginException, "Plugin [" + plugin.identifier + "] failed during processTelemetry - " + error);
}
if (_nextProxy && !hasRun) {
// As part of the failure the current plugin did not attempt to call the next plugin in the cahin
// So rather than leave the pipeline dead in the water we call the next plugin
_nextProxy.processTelemetry(env, itemCtx);
}
}
if (_nextProxy && !hasRun) {
// As part of the failure the current plugin did not attempt to call the next plugin in the cahin
// So rather than leave the pipeline dead in the water we call the next plugin
_nextProxy.processTelemetry(env, itemCtx);
}
}
}
else if (_nextProxy) {
_self._hasRun = true;
// The underlying plugin is either not defined or does not have a processTelemetry implementation
// so we still want the next plugin to be executed.
_nextProxy.processTelemetry(env, itemCtx);
}
else if (_nextProxy) {
_self._hasRun = true;
// The underlying plugin is either not defined or does not have a processTelemetry implementation
// so we still want the next plugin to be executed.
_nextProxy.processTelemetry(env, itemCtx);
}
}, function () { return ({ item: env }); }, !(env.sync));
};

@@ -65,0 +68,0 @@ }

/*!
* Application Insights JavaScript SDK - Core, 2.5.6
* Application Insights JavaScript SDK - Core, 2.5.7
* Copyright (c) Microsoft and contributors. All rights reserved.
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e.Microsoft=e.Microsoft||{},e.Microsoft.ApplicationInsights=e.Microsoft.ApplicationInsights||{}))}(this,function(c){"use strict";var r="function",o="object",t="undefined",a="prototype",s="hasOwnProperty";function e(){return typeof globalThis!==t&&globalThis?globalThis:typeof self!==t&&self?self:typeof window!==t&&window?window:typeof global!==t&&global?global:null}function i(e){var t=Object.create;if(t)return t(e);if(null==e)return{};var n=typeof e;if(n!=o&&n!=r)throw new TypeError("Object prototype may only be an Object:"+e);function i(){}return i[a]=e,new i}var l=function(e,t){return(l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t[s](n)&&(e[n]=t[n])})(e,t)},n=e()||{};__assign=n.__assign=n.__assign||Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object[a][s].call(t,r)&&(e[r]=t[r]);return e},__extends=n.__extends=n.__extends||function(e,t){function n(){this.constructor=e}l(e,t),e[a]=null===t?i(t):(n[a]=t[a],new n)};var u={Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5},f=t,g=o,d=a,h=r,p="window",v="JSON",y=e;function m(e){var t=y();return t&&t[e]?t[e]:e===p&&x()?window:null}function x(){return!(typeof window!==g||!window)}function C(){return x()?window:m(p)}function T(){return!(typeof document!==g||!document)}function I(){return T()?document:m("document")}function _(){return!(typeof navigator!==g||!navigator)}function w(){return _()?navigator:m("navigator")}function S(){return!(typeof history!==g||!history)}function N(){return!!(typeof JSON===g&&JSON||null!==m(v))}function b(){return N()?JSON||m(v):null}var L=t,E="attachEvent",F="addEventListener",M="detachEvent",P="removeEventListener";function A(e,t){return typeof e===t}function O(e){return A(e,t)||e===undefined}function R(e){return O(e)||null===e}function D(e,t){return e&&Object[a].hasOwnProperty.call(e,t)}function U(e){return A(e,o)}function j(e){return A(e,r)}function k(e,t,n,i){void 0===i&&(i=!1);var r=!1;if(!R(e))try{R(e[F])?R(e[E])||(e[E]("on"+t,n),r=!0):(e[F](t,n,i),r=!0)}catch(o){}return r}function z(e,t,n,i){if(void 0===i&&(i=!1),!R(e))try{R(e[P])?R(e[M])||e[M]("on"+t,n):e[P](t,n,i)}catch(r){}}var B=(Q.isDate=function(e){return"[object Date]"===Object[a].toString.call(e)},Q.isString=function(e){return A(e,"string")},Q.isNumber=function(e){return A(e,"number")},Q.isBoolean=function(e){return A(e,"boolean")},Q.disableCookies=function(){Q._canUseCookies=!1},Q.newGuid=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(V,function(e){var t,n=0|((t=m("crypto"))?t.getRandomValues(new Uint8Array(1))[0]%16:16*Math.random());return("x"===e?n:3&n|8).toString(16)})},Q.toISOString=function(e){if(Q.isDate(e)){var t=function(e){var t=e+"";return 1===t.length&&(t="0"+t),t};return e.getUTCFullYear()+"-"+t(1+e.getUTCMonth())+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}},Q.arrForEach=function(e,t,n){for(var i=e.length,r=0;r<i;r++)r in e&&t.call(n||e,e[r],r,e)},Q.arrIndexOf=function(e,t,n){for(var i=e.length,r=n||0,o=Math.max(0<=r?r:i-Math.abs(r),0);o<i;o++)if(o in e&&e[o]===t)return o;return-1},Q.arrMap=function(e,t,n){for(var i=e.length,r=n||e,o=Array(i),a=0;a<i;a++)a in e&&(o[a]=t.call(r,e[a],e));return o},Q.arrReduce=function(e,t,n){var i,r=e.length,o=0;if(3<=arguments.length)i=n;else{for(;o<r&&!(o in e);)o++;i=e[o++]}for(;o<r;)o in e&&(i=t(i,e[o],o,e)),o++;return i},Q.strTrim=function(e){return Q.isString(e)?e.replace(/^\s+|\s+$/g,""):e},Q.objKeys=function(e){var t=!{toString:null}.propertyIsEnumerable("toString");if(!(j(e)||U(e)&&null!==e))throw new TypeError("objKeys called on non-object");var n=[];for(var i in e)D(e,i)&&n.push(i);if(t)for(var r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=r.length,a=0;a<o;a++)D(e,r[a])&&n.push(r[a]);return n},Q.objDefineAccessors=function(e,t,n,i){var r=Object.defineProperty;if(r)try{var o={enumerable:!0,configurable:!0};return n&&(o.get=n),i&&(o.set=i),r(e,t,o),!0}catch(a){}return!1},Q.addEventHandler=function(e,t){var n=!1,i=C();i&&(n=k(i,e,t),n=k(i.body,e,t)||n);var r=I();return r&&(n=W.Attach(r,e,t)||n),n},Q.isTypeof=A,Q.isUndefined=O,Q.isNullOrUndefined=R,Q.hasOwnProperty=D,Q.isFunction=j,Q.isObject=U,Q.objCreate=i,Q);function Q(){}var q,V=/[xy]/g,W=(H.Attach=k,H.AttachEvent=k,H.Detach=z,H.DetachEvent=z,H);function H(){}(q=c.LoggingSeverity||(c.LoggingSeverity={}))[q.CRITICAL=1]="CRITICAL",q[q.WARNING=2]="WARNING";var K={BrowserDoesNotSupportLocalStorage:0,BrowserCannotReadLocalStorage:1,BrowserCannotReadSessionStorage:2,BrowserCannotWriteLocalStorage:3,BrowserCannotWriteSessionStorage:4,BrowserFailedRemovalFromLocalStorage:5,BrowserFailedRemovalFromSessionStorage:6,CannotSendEmptyTelemetry:7,ClientPerformanceMathError:8,ErrorParsingAISessionCookie:9,ErrorPVCalc:10,ExceptionWhileLoggingError:11,FailedAddingTelemetryToBuffer:12,FailedMonitorAjaxAbort:13,FailedMonitorAjaxDur:14,FailedMonitorAjaxOpen:15,FailedMonitorAjaxRSC:16,FailedMonitorAjaxSend:17,FailedMonitorAjaxGetCorrelationHeader:18,FailedToAddHandlerForOnBeforeUnload:19,FailedToSendQueuedTelemetry:20,FailedToReportDataLoss:21,FlushFailed:22,MessageLimitPerPVExceeded:23,MissingRequiredFieldSpecification:24,NavigationTimingNotSupported:25,OnError:26,SessionRenewalDateIsZero:27,SenderNotInitialized:28,StartTrackEventFailed:29,StopTrackEventFailed:30,StartTrackFailed:31,StopTrackFailed:32,TelemetrySampledAndNotSent:33,TrackEventFailed:34,TrackExceptionFailed:35,TrackMetricFailed:36,TrackPVFailed:37,TrackPVFailedCalc:38,TrackTraceFailed:39,TransmissionFailed:40,FailedToSetStorageBuffer:41,FailedToRestoreStorageBuffer:42,InvalidBackendResponse:43,FailedToFixDepricatedValues:44,InvalidDurationValue:45,TelemetryEnvelopeInvalid:46,CreateEnvelopeError:47,CannotSerializeObject:48,CannotSerializeObjectNonSerializable:49,CircularReferenceDetected:50,ClearAuthContextFailed:51,ExceptionTruncated:52,IllegalCharsInName:53,ItemNotInArray:54,MaxAjaxPerPVExceeded:55,MessageTruncated:56,NameTooLong:57,SampleRateOutOfRange:58,SetAuthContextFailed:59,SetAuthContextFailedAccountName:60,StringValueTooLong:61,StartCalledMoreThanOnce:62,StopCalledWithoutStart:63,TelemetryInitializerFailed:64,TrackArgumentsNotSpecified:65,UrlTooLong:66,SessionStorageBufferFull:67,CannotAccessCookie:68,IdTooLong:69,InvalidEvent:70,FailedMonitorAjaxSetRequestHeader:71,SendBrowserInfoOnUserInit:72,PluginException:73,NotificationException:74,SnippetScriptLoadFailure:99},G=(J.sanitizeDiagnosticText=function(e){return e?'"'+e.replace(/\"/g,"")+'"':""},J.dataType="MessageData",J.AiNonUserActionablePrefix="AI (Internal): ",J.AiUserActionablePrefix="AI: ",J);function J(e,t,n,i){void 0===n&&(n=!1),this.messageId=e,this.message=(n?J.AiUserActionablePrefix:J.AiNonUserActionablePrefix)+e;var r="";N()&&(r=b().stringify(i));var o=(t?" message:"+J.sanitizeDiagnosticText(t):"")+(i?" props:"+J.sanitizeDiagnosticText(r):"");this.message+=o}var Z=($.prototype.throwInternal=function(e,t,n,i,r){void 0===r&&(r=!1);var o,a=new G(t,n,r,i),s=this;if(s.enableDebugExceptions())throw a;!B.isUndefined(a)&&a&&(B.isUndefined(a.message)||(r?(o=+a.messageId,!s._messageLogged[o]&&s.consoleLoggingLevel()>=c.LoggingSeverity.WARNING&&(s.warnToConsole(a.message),s._messageLogged[o]=!0)):s.consoleLoggingLevel()>=c.LoggingSeverity.WARNING&&s.warnToConsole(a.message),s.logInternalMessage(e,a)))},$.prototype.warnToConsole=function(e){!B.isUndefined(console)&&console&&(B.isFunction(console.warn)?console.warn(e):B.isFunction(console.log)&&console.log(e))},$.prototype.resetInternalMessageCount=function(){this._messageCount=0,this._messageLogged={}},$.prototype.logInternalMessage=function(e,t){var n,i,r,o=this;o._areInternalMessagesThrottled()||(n=!0,i=o.AIInternalMessagePrefix+t.messageId,o._messageLogged[i]?n=!1:o._messageLogged[i]=!0,n&&(e<=o.telemetryLoggingLevel()&&(o.queue.push(t),o._messageCount++),o._messageCount===o.maxInternalMessageLimit()&&(r=new G(K.MessageLimitPerPVExceeded,"Internal events throttle limit per PageView reached for this app.",!1),o.queue.push(r),o.warnToConsole("Internal events throttle limit per PageView reached for this app."))))},$.prototype._areInternalMessagesThrottled=function(){return this._messageCount>=this.maxInternalMessageLimit()},$);function $(e){this.queue=[],this.AIInternalMessagePrefix="AITR_",this._messageCount=0,this._messageLogged={},this.enableDebugExceptions=function(){return!1},this.consoleLoggingLevel=function(){return 0},this.telemetryLoggingLevel=function(){return 1},this.maxInternalMessageLimit=function(){return 25},B.isNullOrUndefined(e)||(B.isNullOrUndefined(e.loggingLevelConsole)||(this.consoleLoggingLevel=function(){return e.loggingLevelConsole}),B.isNullOrUndefined(e.loggingLevelTelemetry)||(this.telemetryLoggingLevel=function(){return e.loggingLevelTelemetry}),B.isNullOrUndefined(e.maxMessageLimit)||(this.maxInternalMessageLimit=function(){return e.maxMessageLimit}),B.isNullOrUndefined(e.enableDebugExceptions)||(this.enableDebugExceptions=function(){return e.enableDebugExceptions}))}var Y=B.isFunction,X=function(r,o){var a=this,s=null,l=Y(r.processTelemetry),u=Y(r.setNextPlugin);a._hasRun=!1,a.getPlugin=function(){return r},a.getNext=function(){return s},a.setNext=function(e){s=e},a.processTelemetry=function(e,t){if(t=t||o,r&&l){a._hasRun=!0;try{t.setNext(s),u&&r.setNextPlugin(s),s&&(s._hasRun=!1),r.processTelemetry(e,t)}catch(i){var n=s&&s._hasRun;s&&n||t.diagLog().throwInternal(c.LoggingSeverity.CRITICAL,K.PluginException,"Plugin ["+r.identifier+"] failed during processTelemetry - "+i),s&&!n&&s.processTelemetry(e,t)}}else s&&(a._hasRun=!0,s.processTelemetry(e,t))}},ee=B.isNullOrUndefined;function te(e,t){var n=[];if(e&&0<e.length)for(var i=null,r=0;r<e.length;r++){var o,a=e[r];a&&B.isFunction(a.processTelemetry)&&(o=new X(a,t),n.push(o),i&&i.setNext(o),i=o)}return 0<n.length?n[0]:null}var ne=function Re(e,o,n,t){var i,r,a,s,l=this,u=null;null!==t&&(e&&B.isFunction(e.getPlugin)?u=function(e,t,n){var i=[],r=!n;if(e)for(;e;){var o=e.getPlugin();!r&&o!==n||(r=!0,i.push(o)),e=e.getNext()}return r||i.push(n),te(i,t)}(e,l,t||e.getPlugin()):t?(i=l,a=e,s=!1,(r=t)&&e&&(a=[],B.arrForEach(e,function(e){!s&&e!==r||(s=!0,a.push(e))})),r&&!s&&(a=a||[]).push(r),u=te(a,i)):B.isUndefined(t)&&(u=te(e,l))),l.core=function(){return n},l.diagLog=function(){return(n||{}).logger||new Z(o||{})},l.getCfg=function(){return o},l.getExtCfg=function(e,t){var n,i;return void 0===t&&(t={}),!o||(i=o.extensionConfig)&&e&&(n=i[e]),n||t},l.getConfig=function(e,t,n){var i;void 0===n&&(n=!1);var r=l.getExtCfg(e,null);return r&&!ee(r[t])?i=r[t]:o&&!ee(o[t])&&(i=o[t]),ee(i)?n:i},l.hasNext=function(){return null!=u},l.getNext=function(){return u},l.setNext=function(e){u=e},l.processNext=function(e){var t=u;t&&(u=t.getNext(),t.processTelemetry(e,l))},l.createNew=function(e,t){return void 0===e&&(e=null),new Re(e||u,o,n,t)}},ie=B.isFunction,re="getPlugin",oe=(ae.prototype.initialize=function(e,t,n,i){this._baseTelInit(e,t,n,i)},ae);function ae(){var o=this,a=!1,s=null,l=null;o.core=null,o.diagLog=function(e){return o._getTelCtx(e).diagLog()},o.isInitialized=function(){return a},o.setInitialized=function(e){a=e},o.setNextPlugin=function(e){l=e},o.processNext=function(e,t){t?t.processNext(e):l&&ie(l.processTelemetry)&&l.processTelemetry(e,null)},o._getTelCtx=function(e){void 0===e&&(e=null);var t,n=e;return n||(t=s||new ne(null,{},o.core),n=l&&l[re]?t.createNew(null,l[re]):t.createNew(null,l)),n},o._baseTelInit=function(e,t,n,i){e&&(e.extensionConfig=e.extensionConfig||[]),!i&&t&&(i=t.getProcessTelContext().getNext());var r=l;l&&l[re]&&(r=l[re]()),o.core=t,s=new ne(i,e,t,r),a=!0}}var se=B.isFunction,le="processTelemetry",ue="priority",ce="setNextPlugin",fe="isInitialized";function ge(t,n){for(var e=[],i=null,r=t.getNext();r;){var o=r.getPlugin();o&&(i&&se(i[ce])&&se(o[le])&&i[ce](o),se(o[fe])&&o[fe]()||e.push(o),i=o,r=r.getNext())}B.arrForEach(e,function(e){e.initialize(t.getCfg(),t.core(),n,t.getNext())})}function de(e){return e.sort(function(e,t){var n=0,i=se(t[le]);return se(e[le])?n=i?e[ue]-t[ue]:1:i&&(n=-1),n})}var he=B.arrForEach,pe=B.objDefineAccessors;function ve(e,t){t&&0<t.length&&(t=t.sort(function(e,t){return e.priority-t.priority}),he(t,function(e){if(e.priority<500)throw Error("Channel has invalid priority"+e.identifier)}),e.push(t))}var ye,me=(ye=oe,__extends(xe,ye),xe.prototype.processTelemetry=function(t,n){var i=this;this._channelQueue&&he(this._channelQueue,function(e){0<e.length&&i._getTelCtx(n).createNew(e).processNext(t)})},xe.prototype.getChannelControls=function(){return this._channelQueue},xe.prototype.initialize=function(t,n,i){var e,r,o,a,s;this.isInitialized()||(ye.prototype.initialize.call(this,t,n,i),t.isCookieUseDisabled&&B.disableCookies(),e=this._channelQueue=(o=i,s=[],(r=(t||{}).channels)&&he(r,function(e){return ve(s,e)}),o&&(a=[],he(o,function(e){500<e.priority&&a.push(e)}),ve(s,a)),s),he(e,function(e){return ge(new ne(e,t,n),i)}))},xe._staticInit=(pe(xe.prototype,"ChannelControls",xe.prototype.getChannelControls),void pe(xe.prototype,"channelQueue",xe.prototype.getChannelControls)),xe);function xe(){var e=null!==ye&&ye.apply(this,arguments)||this;return e.identifier="ChannelControllerPlugin",e.priority=500,e}var Ce=B.arrForEach,Te=B.isNullOrUndefined,Ie=(_e.prototype.initialize=function(e,t,i,n){var r=this;if(r.isInitialized())throw Error("Core should not be initialized more than once");if(!e||Te(e.instrumentationKey))throw Error("Please provide instrumentation key");r.config=e;var o=r._channelController;n=n||B.objCreate({addNotificationListener:function(e){},removeNotificationListener:function(e){},eventsSent:function(e){},eventsDiscarded:function(e,t){},eventsSendRequest:function(e,t){}}),r._notificationManager=n,e.extensions=Te(e.extensions)?[]:e.extensions,(e.extensionConfig=Te(e.extensionConfig)?{}:e.extensionConfig).NotificationManager=n,i=i||B.objCreate({throwInternal:function(e,t,n,i,r){void 0===r&&(r=!1)},warnToConsole:function(e){},resetInternalMessageCount:function(){}}),r.logger=i;var a=[];a.push.apply(a,t.concat(e.extensions)),a=de(a);var s=[],l={};if(Ce(a,function(e){if(Te(e)||Te(e.initialize))throw Error("Extensions must provide callback to initialize");var t=e.priority,n=e.identifier;e&&t&&(Te(l[t])?l[t]=n:i.warnToConsole("Two extensions have same priority #"+t+" - "+l[t]+", "+n)),(!t||t<o.priority)&&s.push(e)}),a.push(o),s.push(o),a=de(a),r._extensions=a,ge(new ne([o],e,r),a),ge(new ne(s,e,r),a),r._extensions=s,0===r.getTransmissionControls().length)throw Error("No channels available");r._setInit(!0),r.releaseQueue()},_e.prototype.getTransmissionControls=function(){return this._channelController.getChannelControls()},_e.prototype.track=function(e){e.iKey||(e.iKey=this.config.instrumentationKey),e.time||(e.time=B.toISOString(new Date)),Te(e.ver)&&(e.ver="4.0"),this.isInitialized()?this.getProcessTelContext().processNext(e):this._eventQueue.push(e)},_e.prototype.getProcessTelContext=function(){var e=this._extensions,t=e;return e&&0!==e.length||(t=[this._channelController]),new ne(t,this.config,this)},_e.prototype.releaseQueue=function(){var t=this;0<t._eventQueue.length&&(Ce(t._eventQueue,function(e){t.getProcessTelContext().processNext(e)}),t._eventQueue=[])},_e);function _e(){var t=!1,e=this;e._extensions=[],e._channelController=new me,e.isInitialized=function(){return t},e._setInit=function(e){t=e},e._eventQueue=[]}var we=(Se.prototype.addNotificationListener=function(e){this.listeners.push(e)},Se.prototype.removeNotificationListener=function(e){for(var t=B.arrIndexOf(this.listeners,e);-1<t;)this.listeners.splice(t,1),t=B.arrIndexOf(this.listeners,e)},Se.prototype.eventsSent=function(t){for(var n=this,i=this,e=0;e<this.listeners.length;++e)!function(e){i.listeners[e].eventsSent&&setTimeout(function(){return n.listeners[e].eventsSent(t)},0)}(e)},Se.prototype.eventsDiscarded=function(t,n){for(var i=this,r=this,e=0;e<this.listeners.length;++e)!function(e){r.listeners[e].eventsDiscarded&&setTimeout(function(){return i.listeners[e].eventsDiscarded(t,n)},0)}(e)},Se.prototype.eventsSendRequest=function(n,i){for(var r=this,o=this,e=0;e<this.listeners.length;++e)!function(e){if(o.listeners[e].eventsSendRequest)if(i)setTimeout(function(){return r.listeners[e].eventsSendRequest(n,i)},0);else try{o.listeners[e].eventsSendRequest(n,i)}catch(t){}}(e)},Se);function Se(){this.listeners=[]}var Ne,be=(Ne=Ie,__extends(Le,Ne),Le.prototype.initialize=function(e,t){var n=this;n._notificationManager=new we,n.logger=new Z(e),n.config=e,Ne.prototype.initialize.call(this,e,t,n.logger,n._notificationManager)},Le.prototype.getTransmissionControls=function(){return Ne.prototype.getTransmissionControls.call(this)},Le.prototype.track=function(e){if(null===e)throw this._notifyInvalidEvent(e),Error("Invalid telemetry item");this._validateTelemetryItem(e),Ne.prototype.track.call(this,e)},Le.prototype.addNotificationListener=function(e){this._notificationManager&&this._notificationManager.addNotificationListener(e)},Le.prototype.removeNotificationListener=function(e){this._notificationManager&&this._notificationManager.removeNotificationListener(e)},Le.prototype.pollInternalLogs=function(i){var t=this,e=this.config.diagnosticLogInterval;return e&&0<e||(e=1e4),setInterval(function(){var n=t,e=n.logger?n.logger.queue:[];B.arrForEach(e,function(e){var t={name:i||"InternalMessageId: "+e.messageId,iKey:n.config.instrumentationKey,time:B.toISOString(new Date),baseType:G.dataType,baseData:{message:e.message}};n.track(t)}),e.length=0},e)},Le.prototype._validateTelemetryItem=function(e){if(B.isNullOrUndefined(e.name))throw this._notifyInvalidEvent(e),Error("telemetry name required")},Le.prototype._notifyInvalidEvent=function(e){this._notificationManager&&this._notificationManager.eventsDiscarded([e],u.InvalidEvent)},Le);function Le(){return Ne.call(this)||this}var Ee="_aiHooks",Fe=["req","rsp","hkErr","fnErr"];function Me(e,t){if(e)for(var n=0;n<e.length&&!t(e[n],n);n++);}function Pe(e,l,u,c,f){0<=f&&f<=2&&Me(e,function(e,t){var n=e.cbks,i=n[Fe[f]];if(i){l.ctx=function(){return c[t]=c[t]||{}};try{i.apply(l.inst,u)}catch(a){var r=l.err;try{var o=n[Fe[2]];o&&(l.err=a,o.apply(l.inst,u))}catch(s){}finally{l.err=r}}}})}function Ae(e,t,n,i){if(void 0===i&&(i=!0),e&&t&&n){var r=function c(e,t,n){var i=null;return e&&(B.hasOwnProperty(e,t)?i=e:n&&(i=c(e[d],t,!1))),i}(e,t,i),o=r[t];if(typeof o===h){var a,s=o[Ee];s||(u=s={i:0,n:t,f:o,h:[]},(a=function(){var n=arguments,e=u.h,i={name:u.n,inst:this,ctx:null,set:function(e,t){(n=o([],n))[e]=t,r=o([i],n)}},t=[],r=o([i],n);function o(t,e){return Me(e,function(e){t.push(e)}),t}Pe(e,i,r,t,0);var a=u.f;try{i.rslt=a.apply(this,n)}catch(s){throw i.err=s,Pe(e,i,r,t,3),s}return Pe(e,i,r,t,1),i.rslt})[Ee]=s,r[t]=a);var l={id:s.i,cbks:n,rm:function(){var n=this.id;Me(s.h,function(e,t){return e.id===n&&(s.h.splice(t,1),1)})}};return s.i++,s.h.push(l),l}}var u;return null}function Oe(n,e,i,r){void 0===r&&(r=!0);var o=null;return Me(e,function(e){var t=Ae(n,e,i,r);t&&(o=o||[]).push(t)}),o}c.MinChannelPriorty=100,c.EventsDiscardedReason=u,c.AppInsightsCore=be,c.BaseCore=Ie,c.BaseTelemetryPlugin=oe,c.CoreUtils=B,c.EventHelper=W,c.Undefined=L,c.normalizeJsName=function(e){var t=e,n=/([^\w\d_$])/g;return n.test(e)&&(t=e.replace(n,"_")),t},c.getGlobal=y,c.getGlobalInst=m,c.hasWindow=x,c.getWindow=C,c.hasDocument=T,c.getDocument=I,c.hasNavigator=_,c.getNavigator=w,c.hasHistory=S,c.getHistory=function(){return S()?history:m("history")},c.getLocation=function(){return typeof location===g&&location?location:m("location")},c.getPerformance=function(){return m("performance")},c.hasJSON=N,c.getJSON=b,c.isReactNative=function(){var e=w();return!(!e||!e.product)&&"ReactNative"===e.product},c.strUndefined=f,c.strObject=g,c.strPrototype=d,c.strFunction=h,c.NotificationManager=we,c.DiagnosticLogger=Z,c._InternalLogMessage=G,c.ProcessTelemetryContext=ne,c.initializePlugins=ge,c.sortPlugins=de,c._InternalMessageId=K,c.InstrumentProto=function(e,t,n){return e?Ae(e[d],t,n,!1):null},c.InstrumentProtos=function(e,t,n){return e?Oe(e[d],t,n,!1):null},c.InstrumentFunc=Ae,c.InstrumentFuncs=Oe,function(e,t,n){var i=Object.defineProperty;if(i)try{return i(e,t,n)}catch(r){}typeof n.value!==undefined&&(e[t]=n.value)}(c,"__esModule",{value:!0})});
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e.Microsoft=e.Microsoft||{},e.Microsoft.ApplicationInsights=e.Microsoft.ApplicationInsights||{}))}(this,function(l){"use strict";var i="function",o="object",n="undefined",a="prototype",s="hasOwnProperty";function e(){return typeof globalThis!==n&&globalThis?globalThis:typeof self!==n&&self?self:typeof window!==n&&window?window:typeof global!==n&&global?global:null}function r(e){var n=Object.create;if(n)return n(e);if(null==e)return{};var t=typeof e;if(t!=o&&t!=i)throw new TypeError("Object prototype may only be an Object:"+e);function r(){}return r[a]=e,new r}var u=function(e,n){return(u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var t in n)n[s](t)&&(e[t]=n[t])})(e,n)},t=e()||{};__assign=t.__assign=t.__assign||Object.assign||function(e){for(var n,t=1,r=arguments.length;t<r;t++)for(var i in n=arguments[t])Object[a][s].call(n,i)&&(e[i]=n[i]);return e},__extends=t.__extends=t.__extends||function(e,n){function t(){this.constructor=e}u(e,n),e[a]=null===n?r(n):(t[a]=n[a],new t)};var c={Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5},f=n,g=o,d=a,v=i,p="window",h="JSON",y=e;function x(e){var n=y();return n&&n[e]?n[e]:e===p&&C()?window:null}function C(){return!(typeof window!==g||!window)}function m(){return C()?window:x(p)}function T(){return!(typeof document!==g||!document)}function w(){return T()?document:x("document")}function S(){return!(typeof navigator!==g||!navigator)}function I(){return S()?navigator:x("navigator")}function N(){return!(typeof history!==g||!history)}function b(){return typeof console!==f?console:x("console")}function E(){return!!(typeof JSON===g&&JSON||null!==x(h))}function P(){return E()?JSON||x(h):null}var F="constructor",_="prototype",L="function",M="_dynInstFuncs",O="_isDynProxy",A="_dynClass",j="_dynCls$",D="_unknown_",R="__proto__",k=Object.getPrototypeOf,U=0;function z(e,n){return e&&Object[_].hasOwnProperty.call(e,n)}function K(e){return typeof e===L}function B(e){return e&&(e===Object[_]||e===Array[_])}function q(e){return B(e)||e===Function[_]}function V(e){if(e){if(k)return k(e);var n=e[R]||e[_]||e[F];if(n)return n}return null}function W(e,n,t){return n!==F&&K(e[n])&&(t||z(e,n))}function H(e){throw new TypeError("DynamicProto: "+e)}function G(e,n){return z(e,_)?e.name||n||D:((e||{})[F]||{}).name||n||D}function J(e,t,n){z(e,_)||H("theClass is an invalid class definition.");var r=e[_];!function(e){for(var n=V(t);n&&!q(n);){if(n===e)return 1;n=V(n)}}(r)&&H("["+G(e)+"] is not in class heirarchy of ["+G(t)+"]");var i=null;z(r,A)?i=r[A]:(i=j+G(e,"_")+"$"+U,U++,r[A]=i);var o=function(e){var n={};for(var t in e)!n[t]&&W(e,t,!1)&&(n[t]=e[t]);return n}(t);n(t,function(e,n,t){function r(e,n){return function(){return n.apply(e,arguments)}}var i={};for(var o in t)i[o]=r(n,t[o]);for(var a=V(e),s=[];a&&!q(a)&&!function(e,n){for(var t=e.length-1;0<=t;t--)if(e[t]===n)return 1}(s,a);){for(var o in a)!i[o]&&W(a,o,!k)&&(i[o]=r(n,a[o]));s.push(a),a=V(a)}return i}(r,t,o)),function(e,n,t,r){if(!B(e)){var i=t[M]=t[M]||{},o=i[n]=i[n]||{};for(var a in t)W(t,a,!1)&&t[a]!==r[a]&&(o[a]=t[a],delete t[a],z(e,a)&&(!e[a]||e[a][O])||(e[a]=function(t,r){var i=function(){if(this&&z(t,A)){var e=((this[M]||{})[t[A]]||{})[r];if(e)return e.apply(this,arguments);H("Missing ["+r+"] "+L)}var n=t[r];return n===i&&(n=V(t)[r]),K(n)||H("["+r+"] is not a "+L),n.apply(this,arguments)};return i[O]=1,i}(e,a)))}}(r,i,t,o)}var Q="ctx",$=(Z.ParentContextKey="parent",Z.ChildrenContextKey="childEvts",Z);function Z(e,i,n){var t,o=this,a=!1;o.start=Date.now(),o.name=e,o.isAsync=n,o.isChildEvt=function(){return!1},ge.isFunction(i)&&(a=ge.objDefineAccessors(o,"payload",function(){return!t&&ge.isFunction(i)&&(t=i(),i=null),t})),o.getCtx=function(e){return e?e===Z.ParentContextKey||e===Z.ChildrenContextKey?o[e]:(o[Q]||{})[e]:null},o.setCtx=function(e,n){e&&(e===Z.ParentContextKey?(o[e]||(o.isChildEvt=function(){return!0}),o[e]=n):e===Z.ChildrenContextKey?o[e]=n:(o[Q]=o[Q]||{})[e]=n)},o.complete=function(){var e=0,n=o.getCtx(Z.ChildrenContextKey);if(ge.isArray(n))for(var t=0;t<n.length;t++){var r=n[t];r&&(e+=r.time)}o.time=Date.now()-o.start,o.exTime=o.time-e,o.complete=function(){},!a&&ge.isFunction(i)&&(o.payload=i())}}var Y=function fn(n){this.ctx={},J(fn,this,function(t){t.create=function(e,n,t){return new $(e,n,t)},t.fire=function(e){e&&e.complete(),n&&n.perfEvent(e)},t.setCtx=function(e,n){e&&((t[Q]=t[Q]||{})[e]=n)},t.getCtx=function(e){return(t[Q]||{})[e]}})},X=n,ee="attachEvent",ne="addEventListener",te="detachEvent",re="removeEventListener";function ie(e,n){return typeof e===n}function oe(e){return ie(e,n)||e===undefined}function ae(e){return oe(e)||null===e}function se(e,n){return e&&Object[a].hasOwnProperty.call(e,n)}function ue(e){return ie(e,o)}function ce(e){return ie(e,i)}function le(e,n,t,r){void 0===r&&(r=!1);var i=!1;if(!ae(e))try{ae(e[ne])?ae(e[ee])||(e[ee]("on"+n,t),i=!0):(e[ne](n,t,r),i=!0)}catch(o){}return i}function fe(e,n,t,r){if(void 0===r&&(r=!1),!ae(e))try{ae(e[re])?ae(e[te])||e[te]("on"+n,t):e[re](n,t,r)}catch(i){}}var ge=(de.isDate=function(e){return"[object Date]"===Object[a].toString.call(e)},de.isArray=function(e){return"[object Array]"===Object[a].toString.call(e)},de.isError=function(e){return"[object Error]"===Object[a].toString.call(e)},de.isString=function(e){return ie(e,"string")},de.isNumber=function(e){return ie(e,"number")},de.isBoolean=function(e){return ie(e,"boolean")},de.disableCookies=function(){de._canUseCookies=!1},de.newGuid=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(ve,function(e){var n,t=0|((n=x("crypto"))?n.getRandomValues(new Uint8Array(1))[0]%16:16*Math.random());return("x"===e?t:3&t|8).toString(16)})},de.toISOString=function(e){if(de.isDate(e)){var n=function(e){var n=e+"";return 1===n.length&&(n="0"+n),n};return e.getUTCFullYear()+"-"+n(1+e.getUTCMonth())+"-"+n(e.getUTCDate())+"T"+n(e.getUTCHours())+":"+n(e.getUTCMinutes())+":"+n(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}},de.arrForEach=function(e,n,t){for(var r=e.length,i=0;i<r;i++)i in e&&n.call(t||e,e[i],i,e)},de.arrIndexOf=function(e,n,t){for(var r=e.length,i=t||0,o=Math.max(0<=i?i:r-Math.abs(i),0);o<r;o++)if(o in e&&e[o]===n)return o;return-1},de.arrMap=function(e,n,t){for(var r=e.length,i=t||e,o=Array(r),a=0;a<r;a++)a in e&&(o[a]=n.call(i,e[a],e));return o},de.arrReduce=function(e,n,t){var r,i=e.length,o=0;if(3<=arguments.length)r=t;else{for(;o<i&&!(o in e);)o++;r=e[o++]}for(;o<i;)o in e&&(r=n(r,e[o],o,e)),o++;return r},de.strTrim=function(e){return de.isString(e)?e.replace(/^\s+|\s+$/g,""):e},de.objKeys=function(e){var n=!{toString:null}.propertyIsEnumerable("toString");if(!(ce(e)||ue(e)&&null!==e))throw new TypeError("objKeys called on non-object");var t=[];for(var r in e)se(e,r)&&t.push(r);if(n)for(var i=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=i.length,a=0;a<o;a++)se(e,i[a])&&t.push(i[a]);return t},de.objDefineAccessors=function(e,n,t,r){var i=Object.defineProperty;if(i)try{var o={enumerable:!0,configurable:!0};return t&&(o.get=t),r&&(o.set=r),i(e,n,o),!0}catch(a){}return!1},de.addEventHandler=function(e,n){var t=!1,r=m();r&&(t=le(r,e,n),t=le(r.body,e,n)||t);var i=w();return i&&(t=pe.Attach(i,e,n)||t),t},de.isTypeof=ie,de.isUndefined=oe,de.isNullOrUndefined=ae,de.hasOwnProperty=se,de.isFunction=ce,de.isObject=ue,de.objCreate=r,de);function de(){}var ve=/[xy]/g,pe=(he.Attach=le,he.AttachEvent=le,he.Detach=fe,he.DetachEvent=fe,he);function he(){}var ye,xe="CoreUtils.doPerf";function Ce(e,n,t,r,i){if(e){var o=e;if(o&&ge.isFunction(o.getPerfMgr)&&(o=o.getPerfMgr()),o){var a,s=void 0,u=o.getCtx(xe);try{if(s=o.create(n(),r,i))return u&&s.setCtx&&(s.setCtx($.ParentContextKey,u),u.getCtx&&u.setCtx&&((a=u.getCtx($.ChildrenContextKey))||(a=[],u.setCtx($.ChildrenContextKey,a)),a.push(s))),o.setCtx(xe,s),t(s)}catch(c){s&&s.setCtx&&s.setCtx("exception",c)}finally{s&&o.fire(s),o.setCtx(xe,u)}}}return t()}(ye=l.LoggingSeverity||(l.LoggingSeverity={}))[ye.CRITICAL=1]="CRITICAL",ye[ye.WARNING=2]="WARNING";var me={BrowserDoesNotSupportLocalStorage:0,BrowserCannotReadLocalStorage:1,BrowserCannotReadSessionStorage:2,BrowserCannotWriteLocalStorage:3,BrowserCannotWriteSessionStorage:4,BrowserFailedRemovalFromLocalStorage:5,BrowserFailedRemovalFromSessionStorage:6,CannotSendEmptyTelemetry:7,ClientPerformanceMathError:8,ErrorParsingAISessionCookie:9,ErrorPVCalc:10,ExceptionWhileLoggingError:11,FailedAddingTelemetryToBuffer:12,FailedMonitorAjaxAbort:13,FailedMonitorAjaxDur:14,FailedMonitorAjaxOpen:15,FailedMonitorAjaxRSC:16,FailedMonitorAjaxSend:17,FailedMonitorAjaxGetCorrelationHeader:18,FailedToAddHandlerForOnBeforeUnload:19,FailedToSendQueuedTelemetry:20,FailedToReportDataLoss:21,FlushFailed:22,MessageLimitPerPVExceeded:23,MissingRequiredFieldSpecification:24,NavigationTimingNotSupported:25,OnError:26,SessionRenewalDateIsZero:27,SenderNotInitialized:28,StartTrackEventFailed:29,StopTrackEventFailed:30,StartTrackFailed:31,StopTrackFailed:32,TelemetrySampledAndNotSent:33,TrackEventFailed:34,TrackExceptionFailed:35,TrackMetricFailed:36,TrackPVFailed:37,TrackPVFailedCalc:38,TrackTraceFailed:39,TransmissionFailed:40,FailedToSetStorageBuffer:41,FailedToRestoreStorageBuffer:42,InvalidBackendResponse:43,FailedToFixDepricatedValues:44,InvalidDurationValue:45,TelemetryEnvelopeInvalid:46,CreateEnvelopeError:47,CannotSerializeObject:48,CannotSerializeObjectNonSerializable:49,CircularReferenceDetected:50,ClearAuthContextFailed:51,ExceptionTruncated:52,IllegalCharsInName:53,ItemNotInArray:54,MaxAjaxPerPVExceeded:55,MessageTruncated:56,NameTooLong:57,SampleRateOutOfRange:58,SetAuthContextFailed:59,SetAuthContextFailedAccountName:60,StringValueTooLong:61,StartCalledMoreThanOnce:62,StopCalledWithoutStart:63,TelemetryInitializerFailed:64,TrackArgumentsNotSpecified:65,UrlTooLong:66,SessionStorageBufferFull:67,CannotAccessCookie:68,IdTooLong:69,InvalidEvent:70,FailedMonitorAjaxSetRequestHeader:71,SendBrowserInfoOnUserInit:72,PluginException:73,NotificationException:74,SnippetScriptLoadFailure:99};function Te(e){return e?'"'+e.replace(/\"/g,"")+'"':""}var we=(Se.dataType="MessageData",Se);function Se(e,n,t,r){void 0===t&&(t=!1),this.messageId=e,this.message=(t?"AI: ":"AI (Internal): ")+e;var i="";E()&&(i=P().stringify(r));var o=(n?" message:"+Te(n):"")+(r?" props:"+Te(i):"");this.message+=o}var Ie=function gn(o){this.identifier="DiagnosticLogger",this.queue=[];var a=0,c={};J(gn,this,function(s){var r=ge.isNullOrUndefined,u=ge.isUndefined,i=ge.isFunction;function e(e,n){var t=o[e];return r(t)?n:t}r(o)&&(o={}),s.consoleLoggingLevel=function(){return e("loggingLevelConsole",0)},s.telemetryLoggingLevel=function(){return e("loggingLevelTelemetry",1)},s.maxInternalMessageLimit=function(){return e("maxMessageLimit",25)},s.enableDebugExceptions=function(){return e("enableDebugExceptions",!1)},s.throwInternal=function(e,n,t,r,i){void 0===i&&(i=!1);var o,a=new we(n,t,i,r);if(s.enableDebugExceptions())throw a;!u(a)&&a&&(u(a.message)||(i?(o=+a.messageId,!c[o]&&s.consoleLoggingLevel()>=l.LoggingSeverity.WARNING&&(s.warnToConsole(a.message),c[o]=!0)):s.consoleLoggingLevel()>=l.LoggingSeverity.WARNING&&s.warnToConsole(a.message),s.logInternalMessage(e,a)))},s.warnToConsole=function(e){var n,t=b();t&&(n="log",t.warn&&(n="warn"),i(t[n])&&t[n](e))},s.resetInternalMessageCount=function(){a=0,c={}},s.logInternalMessage=function(e,n){var t,r,i;a>=s.maxInternalMessageLimit()||(t=!0,r="AITR_"+n.messageId,c[r]?t=!1:c[r]=!0,t&&(e<=s.telemetryLoggingLevel()&&(s.queue.push(n),a++),a===s.maxInternalMessageLimit()&&(i=new we(me.MessageLimitPerPVExceeded,"Internal events throttle limit per PageView reached for this app.",!1),s.queue.push(i),s.warnToConsole("Internal events throttle limit per PageView reached for this app."))))}})},Ne=ge.isFunction,be=function(i,n){var o=this,a=null,s=Ne(i.processTelemetry),u=Ne(i.setNextPlugin);o._hasRun=!1,o.getPlugin=function(){return i},o.getNext=function(){return a},o.setNext=function(e){a=e},o.processTelemetry=function(t,r){r=r||n;var e=i?i.identifier:"TelemetryPluginChain";Ce(r?r.core():null,function(){return e+":processTelemetry"},function(){if(i&&s){o._hasRun=!0;try{r.setNext(a),u&&i.setNextPlugin(a),a&&(a._hasRun=!1),i.processTelemetry(t,r)}catch(n){var e=a&&a._hasRun;a&&e||r.diagLog().throwInternal(l.LoggingSeverity.CRITICAL,me.PluginException,"Plugin ["+i.identifier+"] failed during processTelemetry - "+n),a&&!e&&a.processTelemetry(t,r)}}else a&&(o._hasRun=!0,a.processTelemetry(t,r))},function(){return{item:t}},!t.sync)}},Ee=ge.isNullOrUndefined;function Pe(e,n){var t=[];if(e&&0<e.length)for(var r=null,i=0;i<e.length;i++){var o,a=e[i];a&&ge.isFunction(a.processTelemetry)&&(o=new be(a,n),t.push(o),r&&r.setNext(o),r=o)}return 0<t.length?t[0]:null}var Fe=function dn(e,o,t,n){var r,i,a,s,u=this,c=null;null!==n&&(e&&ge.isFunction(e.getPlugin)?c=function(e,n,t){var r=[],i=!t;if(e)for(;e;){var o=e.getPlugin();!i&&o!==t||(i=!0,r.push(o)),e=e.getNext()}return i||r.push(t),Pe(r,n)}(e,u,n||e.getPlugin()):n?(r=u,a=e,s=!1,(i=n)&&e&&(a=[],ge.arrForEach(e,function(e){!s&&e!==i||(s=!0,a.push(e))})),i&&!s&&(a=a||[]).push(i),c=Pe(a,r)):ge.isUndefined(n)&&(c=Pe(e,u))),u.core=function(){return t},u.diagLog=function(){return(t||{}).logger||new Ie(o||{})},u.getCfg=function(){return o},u.getExtCfg=function(e,n){var t,r;return void 0===n&&(n={}),!o||(r=o.extensionConfig)&&e&&(t=r[e]),t||n},u.getConfig=function(e,n,t){var r;void 0===t&&(t=!1);var i=u.getExtCfg(e,null);return i&&!Ee(i[n])?r=i[n]:o&&!Ee(o[n])&&(r=o[n]),Ee(r)?t:r},u.hasNext=function(){return null!=c},u.getNext=function(){return c},u.setNext=function(e){c=e},u.processNext=function(e){var n=c;n&&(c=n.getNext(),n.processTelemetry(e,u))},u.createNew=function(e,n){return void 0===e&&(e=null),new dn(e||c,o,t,n)}},_e=ge.isFunction,Le="getPlugin",Me=(Oe.prototype.initialize=function(e,n,t,r){this._baseTelInit(e,n,t,r)},Oe);function Oe(){var o=this,a=!1,s=null,u=null;o.core=null,o.diagLog=function(e){return o._getTelCtx(e).diagLog()},o.isInitialized=function(){return a},o.setInitialized=function(e){a=e},o.setNextPlugin=function(e){u=e},o.processNext=function(e,n){n?n.processNext(e):u&&_e(u.processTelemetry)&&u.processTelemetry(e,null)},o._getTelCtx=function(e){void 0===e&&(e=null);var n,t=e;return t||(n=s||new Fe(null,{},o.core),t=u&&u[Le]?n.createNew(null,u[Le]):n.createNew(null,u)),t},o._baseTelInit=function(e,n,t,r){e&&(e.extensionConfig=e.extensionConfig||[]),!r&&n&&(r=n.getProcessTelContext().getNext());var i=u;u&&u[Le]&&(i=u[Le]()),o.core=n,s=new Fe(r,e,n,i),a=!0}}var Ae=ge.isFunction,je="processTelemetry",De="priority",Re="setNextPlugin",ke="isInitialized";function Ue(n,t){for(var e=[],r=null,i=n.getNext();i;){var o=i.getPlugin();o&&(r&&Ae(r[Re])&&Ae(o[je])&&r[Re](o),Ae(o[ke])&&o[ke]()||e.push(o),r=o,i=i.getNext())}ge.arrForEach(e,function(e){e.initialize(n.getCfg(),n.core(),t,n.getNext())})}function ze(e){return e.sort(function(e,n){var t=0,r=Ae(n[je]);return Ae(e[je])?t=r?e[De]-n[De]:1:r&&(t=-1),t})}var Ke,Be=500,qe="Channel has invalid priority",Ve=ge.objDefineAccessors,We=(Ke=Me,__extends(He,Ke),He._staticInit=(Ve(He.prototype,"ChannelControls",He.prototype.getChannelControls),void Ve(He.prototype,"channelQueue",He.prototype.getChannelControls)),He);function He(){var r=Ke.call(this)||this;r.identifier="ChannelControllerPlugin",r.priority=Be;var u,c=ge.arrForEach;function l(e){e&&0<e.length&&(e=e.sort(function(e,n){return e.priority-n.priority}),c(e,function(e){if(e.priority<Be)throw Error(qe+e.identifier)}),u.push(e))}return J(He,r,function(a,s){a.setNextPlugin=function(e){},a.processTelemetry=function(n,t){u&&c(u,function(e){0<e.length&&r._getTelCtx(t).createNew(e).processNext(n)})},a.getChannelControls=function(){return u},a.initialize=function(n,t,r){var e,i,o;a.isInitialized()||(s.initialize(n,t,r),n.isCookieUseDisabled&&ge.disableCookies(),i=r,u=[],(e=(n||{}).channels)&&c(e,l),i&&(o=[],c(i,function(e){e.priority>Be&&o.push(e)}),l(o)),c(u,function(e){return Ue(new Fe(e,n,t),r)}))}}),r}var Ge,Je=ge.arrForEach,Qe=ge.isNullOrUndefined,$e="_notificationManager",Ze=function vn(){var n,u,c,t,l=!1;J(vn,this,function(s){s._extensions=[],u=new We,n=[],s.isInitialized=function(){return l},s.initialize=function(e,n,r,t){if(s.isInitialized())throw Error("Core should not be initialized more than once");if(!e||Qe(e.instrumentationKey))throw Error("Please provide instrumentation key");c=t,s[$e]=t,s.config=e||{},e.extensions=Qe(e.extensions)?[]:e.extensions,(e.extensionConfig=Qe(e.extensionConfig)?{}:e.extensionConfig).NotificationManager=t,r=r||ge.objCreate({throwInternal:function(e,n,t,r,i){void 0===i&&(i=!1)},warnToConsole:function(e){},resetInternalMessageCount:function(){}}),s.logger=r;var i=[];i.push.apply(i,n.concat(e.extensions)),i=ze(i);var o=[],a={};if(Je(i,function(e){if(Qe(e)||Qe(e.initialize))throw Error("Extensions must provide callback to initialize");var n=e.priority,t=e.identifier;e&&n&&(Qe(a[n])?a[n]=t:r.warnToConsole("Two extensions have same priority #"+n+" - "+a[n]+", "+t)),(!n||n<u.priority)&&o.push(e)}),i.push(u),o.push(u),i=ze(i),s._extensions=i,Ue(new Fe([u],e,s),i),Ue(new Fe(o,e,s),i),s._extensions=o,0===s.getTransmissionControls().length)throw Error("No channels available");l=!0,s.releaseQueue()},s.getTransmissionControls=function(){return u.getChannelControls()},s.track=function(e){e.iKey||(e.iKey=s.config.instrumentationKey),e.time||(e.time=ge.toISOString(new Date)),Qe(e.ver)&&(e.ver="4.0"),s.isInitialized()?s.getProcessTelContext().processNext(e):n.push(e)},s.getProcessTelContext=function(){var e=s._extensions,n=e;return e&&0!==e.length||(n=[u]),new Fe(n,s.config,s)},s.getNotifyMgr=function(){return c||(c=ge.objCreate({addNotificationListener:function(e){},removeNotificationListener:function(e){},eventsSent:function(e){},eventsDiscarded:function(e,n){},eventsSendRequest:function(e,n){}}),s[$e]=c),c},s.getPerfMgr=function(){return t||s.config&&s.config.enablePerfMgr&&(t=new Y(s.getNotifyMgr())),t},s.setPerfMgr=function(e){t=e},s.eventCnt=function(){return n.length},s.releaseQueue=function(){0<n.length&&(Je(n,function(e){s.getProcessTelContext().processNext(e)}),n=[])}})},Ye=function pn(e){this.listeners=[];var o=ge.arrForEach,n=!!(e||{}).perfEvtsSendAll;J(pn,this,function(i){i.addNotificationListener=function(e){i.listeners.push(e)},i.removeNotificationListener=function(e){for(var n=ge.arrIndexOf(i.listeners,e);-1<n;)i.listeners.splice(n,1),n=ge.arrIndexOf(i.listeners,e)},i.eventsSent=function(n){o(i.listeners,function(e){e&&e.eventsSent&&setTimeout(function(){return e.eventsSent(n)},0)})},i.eventsDiscarded=function(n,t){o(i.listeners,function(e){e&&e.eventsDiscarded&&setTimeout(function(){return e.eventsDiscarded(n,t)},0)})},i.eventsSendRequest=function(t,r){o(i.listeners,function(e){if(e&&e.eventsSendRequest)if(r)setTimeout(function(){return e.eventsSendRequest(t,r)},0);else try{e.eventsSendRequest(t,r)}catch(n){}})},i.perfEvent=function(t){t&&(!n&&t.isChildEvt()||o(i.listeners,function(e){if(e&&e.perfEvent)if(t.isAsync)setTimeout(function(){return e.perfEvent(t)},0);else try{e.perfEvent(t)}catch(n){}}))}})},Xe=(Ge=Ze,__extends(en,Ge),en);function en(){var e=Ge.call(this)||this;return J(en,e,function(r,i){function n(e){var n=r.getNotifyMgr();n&&n.eventsDiscarded([e],c.InvalidEvent)}r.initialize=function(e,n,t,r){i.initialize(e,n,t||new Ie(e),r||new Ye(e))},r.track=function(e){Ce(r.getPerfMgr(),function(){return"AppInsightsCore:track"},function(){if(null===e)throw n(e),Error("Invalid telemetry item");!function(e){if(ge.isNullOrUndefined(e.name))throw n(e),Error("telemetry name required")}(e),i.track(e)},function(){return{item:e}},!e.sync)},r.addNotificationListener=function(e){var n=r.getNotifyMgr();n&&n.addNotificationListener(e)},r.removeNotificationListener=function(e){var n=r.getNotifyMgr();n&&n.removeNotificationListener(e)},r.pollInternalLogs=function(t){var e=r.config.diagnosticLogInterval;return e&&0<e||(e=1e4),setInterval(function(){var e=r.logger?r.logger.queue:[];ge.arrForEach(e,function(e){var n={name:t||"InternalMessageId: "+e.messageId,iKey:r.config.instrumentationKey,time:ge.toISOString(new Date),baseType:we.dataType,baseData:{message:e.message}};r.track(n)}),e.length=0},e)}}),e}var nn="_aiHooks",tn=["req","rsp","hkErr","fnErr"],rn="__proto__",on="constructor";function an(e,n){if(e)for(var t=0;t<e.length&&!n(e[t],t);t++);}function sn(e,u,c,l,f){0<=f&&f<=2&&an(e,function(e,n){var t=e.cbks,r=t[tn[f]];if(r){u.ctx=function(){return l[n]=l[n]||{}};try{r.apply(u.inst,c)}catch(a){var i=u.err;try{var o=t[tn[2]];o&&(u.err=a,o.apply(u.inst,c))}catch(s){}finally{u.err=i}}}})}var un=Object.getPrototypeOf;function cn(e,n,t,r){if(void 0===r&&(r=!0),e&&n&&t){var i=function l(e,n,t){var r=null;return e&&(ge.hasOwnProperty(e,n)?r=e:t&&(r=l(function(e){if(e){if(un)return un(e);var n=e[rn]||e[d]||e[on];if(n)return n}return null}(e),n,!1))),r}(e,n,r);if(i){var o=i[n];if(typeof o===v){var a,s=o[nn];s||(c=s={i:0,n:n,f:o,h:[]},(a=function(){var t=arguments,e=c.h,r={name:c.n,inst:this,ctx:null,set:function(e,n){(t=o([],t))[e]=n,i=o([r],t)}},n=[],i=o([r],t);function o(n,e){return an(e,function(e){n.push(e)}),n}sn(e,r,i,n,0);var a=c.f;try{r.rslt=a.apply(this,t)}catch(s){throw r.err=s,sn(e,r,i,n,3),s}return sn(e,r,i,n,1),r.rslt})[nn]=s,i[n]=a);var u={id:s.i,cbks:t,rm:function(){var t=this.id;an(s.h,function(e,n){return e.id===t&&(s.h.splice(n,1),1)})}};return s.i++,s.h.push(u),u}}}var c;return null}function ln(t,e,r,i){void 0===i&&(i=!0);var o=null;return an(e,function(e){var n=cn(t,e,r,i);n&&(o=o||[]).push(n)}),o}l.MinChannelPriorty=100,l.EventsDiscardedReason=c,l.AppInsightsCore=Xe,l.BaseCore=Ze,l.BaseTelemetryPlugin=Me,l.CoreUtils=ge,l.EventHelper=pe,l.Undefined=X,l.normalizeJsName=function(e){var n=e,t=/([^\w\d_$])/g;return t.test(e)&&(n=e.replace(t,"_")),n},l.doPerf=Ce,l.getGlobal=y,l.getGlobalInst=x,l.hasWindow=C,l.getWindow=m,l.hasDocument=T,l.getDocument=w,l.hasNavigator=S,l.getNavigator=I,l.hasHistory=N,l.getHistory=function(){return N()?history:x("history")},l.getLocation=function(){return typeof location===g&&location?location:x("location")},l.getPerformance=function(){return x("performance")},l.hasJSON=E,l.getJSON=P,l.isReactNative=function(){var e=I();return!(!e||!e.product)&&"ReactNative"===e.product},l.getConsole=b,l.strUndefined=f,l.strObject=g,l.strPrototype=d,l.strFunction=v,l.NotificationManager=Ye,l.PerfEvent=$,l.PerfManager=Y,l.DiagnosticLogger=Ie,l._InternalLogMessage=we,l.ProcessTelemetryContext=Fe,l.initializePlugins=Ue,l.sortPlugins=ze,l._InternalMessageId=me,l.InstrumentProto=function(e,n,t){return e?cn(e[d],n,t,!1):null},l.InstrumentProtos=function(e,n,t){return e?ln(e[d],n,t,!1):null},l.InstrumentFunc=cn,l.InstrumentFuncs=ln,function(e,n,t){var r=Object.defineProperty;if(r)try{return r(e,n,t)}catch(i){}typeof t.value!==undefined&&(e[n]=t.value)}(l,"__esModule",{value:!0})});
//# sourceMappingURL=applicationinsights-core-js.min.js.map
{
"name": "@microsoft/applicationinsights-core-js",
"author": "Microsoft Corporation",
"version": "2.5.6",
"version": "2.5.7",
"description": "Microsoft Application Insights Core Javascript SDK",

@@ -36,3 +36,3 @@ "keywords": [

"grunt-contrib-clean": "^1.1.0",
"grunt-contrib-qunit": "2.0.0",
"grunt-contrib-qunit": "^3.1.0",
"grunt-ts": "^6.0.0-beta.15",

@@ -51,4 +51,4 @@ "grunt-tslint": "^5.0.2",

"@microsoft/applicationinsights-shims" : "1.0.1",
"@microsoft/dynamicproto-js": "^0.5.2"
"@microsoft/dynamicproto-js": "^1.0.0"
}
}

@@ -38,2 +38,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

/**
* The event(s) being sent as a retry
*/
Retry = 5,
/**
* Maximum batch size would be exceeded

@@ -40,0 +45,0 @@ */

@@ -7,9 +7,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { IConfiguration } from "./IConfiguration";
import { INotificationManager } from "./INotificationManager";
import { INotificationListener } from "./INotificationListener";
import { IDiagnosticLogger } from './IDiagnosticLogger';
import { IProcessTelemetryContext } from './IProcessTelemetryContext';
import { IPerfManagerProvider } from "./IPerfManager";
"use strict";
export interface IAppInsightsCore {
export interface IAppInsightsCore extends IPerfManagerProvider {

@@ -44,2 +46,7 @@ /*

/**
* Get the current notification manager
*/
getNotifyMgr(): INotificationManager;
/**
* Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.

@@ -46,0 +53,0 @@ * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be

@@ -83,2 +83,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

channels?: IChannelControls[][];
/**
* [Optional] When enabled this will create local perfEvents based on sections of the code that have been instrumented
* to emit perfEvents (via the doPerf()) when this is enabled. This can be used to identify performance issues within
* the SDK, the way you are using it or optionally your own instrumented code.
* The provided IPerfManager implementation does NOT send any additional telemetry events to the server it will only fire
* the new perfEvent() on the INotificationManager which you can listen to.
* This also does not use the window.performance API, so it will work in environments where this API is not supported.
*/
enablePerfMgr?: boolean;
/**
* [Optional] Fire every single performance event not just the top level root performance event. Defaults to false.
*/
perfEvtsSendAll?: boolean;
}

@@ -6,2 +6,3 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { ITelemetryItem } from "./ITelemetryItem";
import { IPerfEvent } from "./IPerfEvent";

@@ -32,2 +33,9 @@ /**

eventsSendRequest?: (sendReason: number, isAsync?: boolean) => void;
/**
* [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging
* the event can be displayed via the debug plugin extension.
* @param perfEvent
*/
perfEvent?: (perfEvent: IPerfEvent) => void;
}

@@ -5,3 +5,3 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { INotificationListener } from "../JavaScriptSDK.Interfaces/INotificationListener";
import { SendRequestReason } from "../JavaScriptSDK.Enums/SendRequestReason";
import { IPerfEvent } from "./IPerfEvent";

@@ -46,2 +46,9 @@ /**

eventsSendRequest?(sendReason: number, isAsync: boolean): void;
/**
* [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging
* the event can be displayed via the debug plugin extension.
* @param perfEvent
*/
perfEvent?(perfEvent: IPerfEvent): void;
}

@@ -7,3 +7,2 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { IPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin";
import { IChannelControls } from "../JavaScriptSDK.Interfaces/IChannelControls";
import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem";

@@ -13,5 +12,7 @@ import { INotificationListener } from "../JavaScriptSDK.Interfaces/INotificationListener";

import { NotificationManager } from "./NotificationManager";
import { CoreUtils } from "./CoreUtils";
import { CoreUtils, doPerf } from "./CoreUtils";
import { INotificationManager } from '../JavaScriptSDK.Interfaces/INotificationManager';
import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger";
import { _InternalLogMessage, DiagnosticLogger } from "./DiagnosticLogger";
import dynamicProto from '@microsoft/dynamicproto-js';

@@ -21,35 +22,99 @@ "use strict";

export class AppInsightsCore extends BaseCore implements IAppInsightsCore {
public config: IConfiguration;
public logger: IDiagnosticLogger;
protected _notificationManager: NotificationManager;
constructor() {
super();
}
initialize(config: IConfiguration, extensions: IPlugin[]): void {
let _self = this;
_self._notificationManager = new NotificationManager();
_self.logger = new DiagnosticLogger(config);
_self.config = config;
dynamicProto(AppInsightsCore, this, (_self, _base) => {
_self.initialize = (config: IConfiguration, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void => {
_base.initialize(config, extensions, logger || new DiagnosticLogger(config), notificationManager || new NotificationManager(config));
};
super.initialize(config, extensions, _self.logger, _self._notificationManager);
_self.track = (telemetryItem: ITelemetryItem) => {
doPerf(_self.getPerfMgr(), () => "AppInsightsCore:track", () => {
if (telemetryItem === null) {
_notifyInvalidEvent(telemetryItem);
// throw error
throw Error("Invalid telemetry item");
}
// do basic validation before sending it through the pipeline
_validateTelemetryItem(telemetryItem);
_base.track(telemetryItem);
}, () => ({ item: telemetryItem }), !((telemetryItem as any).sync));
};
/**
* Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.
* The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be
* called.
* @param {INotificationListener} listener - An INotificationListener object.
*/
_self.addNotificationListener = (listener: INotificationListener): void => {
let manager = _self.getNotifyMgr();
if (manager) {
manager.addNotificationListener(listener);
}
};
/**
* Removes all instances of the listener.
* @param {INotificationListener} listener - INotificationListener to remove.
*/
_self.removeNotificationListener = (listener: INotificationListener): void => {
let manager = _self.getNotifyMgr();
if (manager) {
manager.removeNotificationListener(listener);
}
}
/**
* Periodically check logger.queue for
*/
_self.pollInternalLogs = (eventName?: string): number => {
let interval = _self.config.diagnosticLogInterval;
if (!interval || !(interval > 0)) {
interval = 10000;
}
return setInterval(() => {
const queue: _InternalLogMessage[] = _self.logger ? _self.logger.queue : [];
CoreUtils.arrForEach(queue, (logMessage: _InternalLogMessage) => {
const item: ITelemetryItem = {
name: eventName ? eventName : "InternalMessageId: " + logMessage.messageId,
iKey: _self.config.instrumentationKey,
time: CoreUtils.toISOString(new Date()),
baseType: _InternalLogMessage.dataType,
baseData: { message: logMessage.message }
};
_self.track(item);
});
queue.length = 0;
}, interval) as any;
}
function _validateTelemetryItem(telemetryItem: ITelemetryItem) {
if (CoreUtils.isNullOrUndefined(telemetryItem.name)) {
_notifyInvalidEvent(telemetryItem);
throw Error("telemetry name required");
}
}
function _notifyInvalidEvent(telemetryItem: ITelemetryItem): void {
let manager = _self.getNotifyMgr();
if (manager) {
manager.eventsDiscarded([telemetryItem], EventsDiscardedReason.InvalidEvent);
}
}
});
}
getTransmissionControls(): IChannelControls[][] {
return super.getTransmissionControls();
public initialize(config: IConfiguration, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
track(telemetryItem: ITelemetryItem) {
if (telemetryItem === null) {
this._notifyInvalidEvent(telemetryItem);
// throw error
throw Error("Invalid telemetry item");
}
// do basic validation before sending it through the pipeline
this._validateTelemetryItem(telemetryItem);
super.track(telemetryItem);
public track(telemetryItem: ITelemetryItem) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -63,6 +128,4 @@

*/
addNotificationListener(listener: INotificationListener): void {
if (this._notificationManager) {
this._notificationManager.addNotificationListener(listener);
}
public addNotificationListener(listener: INotificationListener): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -74,6 +137,4 @@

*/
removeNotificationListener(listener: INotificationListener): void {
if (this._notificationManager) {
this._notificationManager.removeNotificationListener(listener);
}
public removeNotificationListener(listener: INotificationListener): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -84,40 +145,6 @@

*/
pollInternalLogs(eventName?: string): number {
let interval = this.config.diagnosticLogInterval;
if (!interval || !(interval > 0)) {
interval = 10000;
}
return setInterval(() => {
let _self = this;
const queue: _InternalLogMessage[] = _self.logger ? _self.logger.queue : [];
CoreUtils.arrForEach(queue, (logMessage: _InternalLogMessage) => {
const item: ITelemetryItem = {
name: eventName ? eventName : "InternalMessageId: " + logMessage.messageId,
iKey: _self.config.instrumentationKey,
time: CoreUtils.toISOString(new Date()),
baseType: _InternalLogMessage.dataType,
baseData: { message: logMessage.message }
};
_self.track(item);
});
queue.length = 0;
}, interval) as any;
public pollInternalLogs(eventName?: string): number {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 0;
}
private _validateTelemetryItem(telemetryItem: ITelemetryItem) {
if (CoreUtils.isNullOrUndefined(telemetryItem.name)) {
this._notifyInvalidEvent(telemetryItem);
throw Error("telemetry name required");
}
}
private _notifyInvalidEvent(telemetryItem: ITelemetryItem): void {
if (this._notificationManager) {
this._notificationManager.eventsDiscarded([telemetryItem], EventsDiscardedReason.InvalidEvent);
}
}
}

@@ -19,3 +19,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { _InternalMessageId, LoggingSeverity } from "../JavaScriptSDK.Enums/LoggingEnums";
import { SendRequestReason } from "../JavaScriptSDK.Enums/SendRequestReason";
import dynamicProto from '@microsoft/dynamicproto-js';
import { IPerfManager } from "../JavaScriptSDK.Interfaces/IPerfManager";
import { PerfManager } from "./PerfManager";

@@ -26,2 +28,3 @@ const validationError = "Extensions must provide callback to initialize";

const _isNullOrUndefined = CoreUtils.isNullOrUndefined;
const strNotificationManager = "_notificationManager";

@@ -35,175 +38,244 @@ export class BaseCore implements IAppInsightsCore {

public isInitialized: () => boolean;
protected _notificationManager: INotificationManager;
private _eventQueue: ITelemetryItem[];
private _channelController: ChannelController;
private _setInit: (value: boolean) => void;
constructor() {
let _isInitialized = false;
let _this = this;
_this._extensions = new Array<IPlugin>();
_this._channelController = new ChannelController();
_this.isInitialized = () => _isInitialized;
_this._setInit = (value: boolean) => { _isInitialized = value; }
_this._eventQueue = [];
}
let _eventQueue: ITelemetryItem[];
let _channelController: ChannelController;
let _notificationManager: INotificationManager;
let _perfManager: IPerfManager;
dynamicProto(BaseCore, this, (_self) => {
_self._extensions = new Array<IPlugin>();
_channelController = new ChannelController();
_eventQueue = [];
_self.isInitialized = () => _isInitialized;
initialize(config: IConfiguration, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void {
let _this = this;
_self.initialize = (config: IConfiguration, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void => {
// Make sure core is only initialized once
if (_self.isInitialized()) {
throw Error("Core should not be initialized more than once");
}
if (!config || _isNullOrUndefined(config.instrumentationKey)) {
throw Error("Please provide instrumentation key");
}
_notificationManager = notificationManager;
// Make sure core is only initialized once
if (_this.isInitialized()) {
throw Error("Core should not be initialized more than once");
}
// For backward compatibility only
_self[strNotificationManager] = notificationManager;
_self.config = config || {};
config.extensions = _isNullOrUndefined(config.extensions) ? [] : config.extensions;
// add notification to the extensions in the config so other plugins can access it
let extConfig = config.extensionConfig = _isNullOrUndefined(config.extensionConfig) ? {} : config.extensionConfig;
extConfig.NotificationManager = notificationManager;
if (!config || _isNullOrUndefined(config.instrumentationKey)) {
throw Error("Please provide instrumentation key");
}
if (!logger) {
logger = CoreUtils.objCreate({
throwInternal: (severity: LoggingSeverity, msgId: _InternalMessageId, msg: string, properties?: Object, isUserAct = false) => { },
warnToConsole: (message: string) => { },
resetInternalMessageCount: () => { }
});
}
_this.config = config;
let channelController = _this._channelController;
_self.logger = logger;
// Concat all available extensions
let allExtensions = [];
allExtensions.push(...extensions, ...config.extensions);
allExtensions = sortPlugins(allExtensions);
let coreExtensions: any[] = [];
let channelExtensions: any[] = [];
// Check if any two extensions have the same priority, then warn to console
// And extract the local extensions from the
const extPriorities = {};
// Extension validation
_arrForEach(allExtensions, (ext: ITelemetryPlugin) => {
if (_isNullOrUndefined(ext) || _isNullOrUndefined(ext.initialize)) {
throw Error(validationError);
}
const extPriority = ext.priority;
const identifier = ext.identifier;
if (ext && extPriority) {
if (!_isNullOrUndefined(extPriorities[extPriority])) {
logger.warnToConsole("Two extensions have same priority #" + extPriority + " - " + extPriorities[extPriority] + ", " + identifier);
} else {
// set a value
extPriorities[extPriority] = identifier;
}
}
// Split extensions to core and channelController
if (!extPriority || extPriority < _channelController.priority) {
// Add to core extension that will be managed by BaseCore
coreExtensions.push(ext);
} else {
// Add all other extensions to be managed by the channel controller
channelExtensions.push(ext);
}
});
// Validation complete
// Add the channelController to the complete extension collection and
// to the end of the core extensions
allExtensions.push(_channelController);
coreExtensions.push(_channelController);
// Sort the complete set of extensions by priority
allExtensions = sortPlugins(allExtensions);
_self._extensions = allExtensions;
// initialize channel controller first, this will initialize all channel plugins
initializePlugins(new ProcessTelemetryContext([_channelController], config, _self), allExtensions);
initializePlugins(new ProcessTelemetryContext(coreExtensions, config, _self), allExtensions);
// Now reset the extensions to just those being managed by Basecore
_self._extensions = coreExtensions;
if (_self.getTransmissionControls().length === 0) {
throw new Error("No channels available");
}
_isInitialized = true;
_self.releaseQueue();
};
_self.getTransmissionControls = (): IChannelControls[][] => {
return _channelController.getChannelControls();
};
_self.track = (telemetryItem: ITelemetryItem) => {
if (!telemetryItem.iKey) {
// setup default iKey if not passed in
telemetryItem.iKey = _self.config.instrumentationKey;
}
if (!telemetryItem.time) {
// add default timestamp if not passed in
telemetryItem.time = CoreUtils.toISOString(new Date());
}
if (_isNullOrUndefined(telemetryItem.ver)) {
// CommonSchema 4.0
telemetryItem.ver = "4.0";
}
if (_self.isInitialized()) {
// Process the telemetry plugin chain
_self.getProcessTelContext().processNext(telemetryItem);
} else {
// Queue events until all extensions are initialized
_eventQueue.push(telemetryItem);
}
};
_self.getProcessTelContext = (): IProcessTelemetryContext => {
let extensions = _self._extensions;
let thePlugins: IPlugin[] = extensions;
// invoke any common telemetry processors before sending through pipeline
if (!extensions || extensions.length === 0) {
// Pass to Channel controller so data is sent to correct channel queues
thePlugins = [_channelController];
}
return new ProcessTelemetryContext(thePlugins, _self.config, _self);
};
if (!notificationManager) {
// Create Dummy notification manager
notificationManager = CoreUtils.objCreate({
addNotificationListener: (listener: INotificationListener) => { },
removeNotificationListener: (listener: INotificationListener) => { },
eventsSent: (events: ITelemetryItem[]) => { },
eventsDiscarded: (events: ITelemetryItem[], reason: number) => { },
eventsSendRequest: (sendReason: number, isAsync: boolean) => { }
});
}
_self.getNotifyMgr = (): INotificationManager => {
if (!_notificationManager) {
// Create Dummy notification manager
_notificationManager = CoreUtils.objCreate({
addNotificationListener: (listener: INotificationListener) => { },
removeNotificationListener: (listener: INotificationListener) => { },
eventsSent: (events: ITelemetryItem[]) => { },
eventsDiscarded: (events: ITelemetryItem[], reason: number) => { },
eventsSendRequest: (sendReason: number, isAsync: boolean) => { }
});
_this._notificationManager = notificationManager as INotificationManager;
config.extensions = _isNullOrUndefined(config.extensions) ? [] : config.extensions;
// For backward compatibility only
_self[strNotificationManager] = _notificationManager;
}
// add notification to the extensions in the config so other plugins can access it
let extConfig = config.extensionConfig = _isNullOrUndefined(config.extensionConfig) ? {} : config.extensionConfig;
extConfig.NotificationManager = notificationManager;
return _notificationManager;
};
_self.getPerfMgr = (): IPerfManager => {
if (!_perfManager) {
if (_self.config && _self.config.enablePerfMgr) {
_perfManager = new PerfManager(_self.getNotifyMgr());
}
}
if (!logger) {
logger = CoreUtils.objCreate({
throwInternal: (severity: LoggingSeverity, msgId: _InternalMessageId, msg: string, properties?: Object, isUserAct = false) => { },
warnToConsole: (message: string) => { },
resetInternalMessageCount: () => { }
});
}
_this.logger = logger;
return _perfManager;
};
// Concat all available extensions
let allExtensions = [];
allExtensions.push(...extensions, ...config.extensions);
allExtensions = sortPlugins(allExtensions);
_self.setPerfMgr = (perfMgr: IPerfManager) => {
_perfManager = perfMgr;
};
let coreExtensions: any[] = [];
let channelExtensions: any[] = [];
_self.eventCnt = (): number => {
return _eventQueue.length;
};
// Check if any two extensions have the same priority, then warn to console
// And extract the local extensions from the
const extPriorities = {};
_self.releaseQueue = () => {
if (_eventQueue.length > 0) {
_arrForEach(_eventQueue, (event: ITelemetryItem) => {
_self.getProcessTelContext().processNext(event);
});
// Extension validation
_arrForEach(allExtensions, (ext: ITelemetryPlugin) => {
if (_isNullOrUndefined(ext) || _isNullOrUndefined(ext.initialize)) {
throw Error(validationError);
}
const extPriority = ext.priority;
const identifier = ext.identifier;
if (ext && extPriority) {
if (!_isNullOrUndefined(extPriorities[extPriority])) {
logger.warnToConsole("Two extensions have same priority #" + extPriority + " - " + extPriorities[extPriority] + ", " + identifier);
} else {
// set a value
extPriorities[extPriority] = identifier;
_eventQueue = [];
}
}
// Split extensions to core and channelController
if (!extPriority || extPriority < channelController.priority) {
// Add to core extension that will be managed by BaseCore
coreExtensions.push(ext);
} else {
// Add all other extensions to be managed by the channel controller
channelExtensions.push(ext);
}
};
});
// Validation complete
}
// Add the channelController to the complete extension collection and
// to the end of the core extensions
allExtensions.push(channelController);
coreExtensions.push(channelController);
public initialize(config: IConfiguration, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
// Sort the complete set of extensions by priority
allExtensions = sortPlugins(allExtensions);
_this._extensions = allExtensions;
public getTransmissionControls(): IChannelControls[][] {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
// initialize channel controller first, this will initialize all channel plugins
initializePlugins(new ProcessTelemetryContext([channelController], config, _this), allExtensions);
initializePlugins(new ProcessTelemetryContext(coreExtensions, config, _this), allExtensions);
public track(telemetryItem: ITelemetryItem) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
// Now reset the extensions to just those being managed by Basecore
_this._extensions = coreExtensions;
public getProcessTelContext(): IProcessTelemetryContext {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
if (_this.getTransmissionControls().length === 0) {
throw new Error("No channels available");
}
_this._setInit(true);
_this.releaseQueue();
public getNotifyMgr(): INotificationManager {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
getTransmissionControls(): IChannelControls[][] {
return this._channelController.getChannelControls();
public getPerfMgr(): IPerfManager {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
track(telemetryItem: ITelemetryItem) {
let _this = this;
if (!telemetryItem.iKey) {
// setup default iKey if not passed in
telemetryItem.iKey = _this.config.instrumentationKey;
}
if (!telemetryItem.time) {
// add default timestamp if not passed in
telemetryItem.time = CoreUtils.toISOString(new Date());
}
if (_isNullOrUndefined(telemetryItem.ver)) {
// CommonSchema 4.0
telemetryItem.ver = "4.0";
}
if (_this.isInitialized()) {
// Process the telemetry plugin chain
_this.getProcessTelContext().processNext(telemetryItem);
} else {
// Queue events until all extensions are initialized
_this._eventQueue.push(telemetryItem);
}
public setPerfMgr(perfMgr: IPerfManager) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
getProcessTelContext(): IProcessTelemetryContext {
let _this = this;
let extensions = _this._extensions;
let thePlugins: IPlugin[] = extensions;
// invoke any common telemetry processors before sending through pipeline
if (!extensions || extensions.length === 0) {
// Pass to Channel controller so data is sent to correct channel queues
thePlugins = [_this._channelController];
}
return new ProcessTelemetryContext(thePlugins, _this.config, _this);
public eventCnt(): number {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 0;
}
protected releaseQueue() {
let _this = this;
if (_this._eventQueue.length > 0) {
_arrForEach(_this._eventQueue, (event: ITelemetryItem) => {
_this.getProcessTelContext().processNext(event);
});
_this._eventQueue = [];
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}

@@ -8,3 +8,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { IChannelControls } from "../JavaScriptSDK.Interfaces/IChannelControls";
import { IPlugin, ITelemetryPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin";
import { IPlugin, ITelemetryPlugin, } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin";
import { ITelemetryPluginChain } from "../JavaScriptSDK.Interfaces/ITelemetryPluginChain";
import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem";

@@ -17,2 +18,3 @@ import { IProcessTelemetryContext } from "../JavaScriptSDK.Interfaces/IProcessTelemetryContext";

import { initializePlugins } from './TelemetryHelpers';
import dynamicProto from '@microsoft/dynamicproto-js';

@@ -22,92 +24,110 @@ const ChannelControllerPriority = 500;

let _arrForEach = CoreUtils.arrForEach;
let _objDefineAccessors = CoreUtils.objDefineAccessors;
function _checkQueuePriority(queue:IChannelControls[]) {
_arrForEach(queue, queueItem => {
if (queueItem.priority < ChannelControllerPriority) {
throw Error(ChannelValidationMessage + queueItem.identifier);
}
});
}
export class ChannelController extends BaseTelemetryPlugin {
function _addChannelQueue(channelQueues:IChannelControls[][], queue:IChannelControls[]) {
if (queue && queue.length > 0) {
queue = queue.sort((a, b) => { // sort based on priority within each queue
return a.priority - b.priority;
});
identifier: string = "ChannelControllerPlugin";
priority: number = ChannelControllerPriority; // in reserved range 100 to 200
_checkQueuePriority(queue);
channelQueues.push(queue);
}
}
public setNextPlugin: (next: ITelemetryPlugin | ITelemetryPluginChain) => void;
function _createChannelQueues(channels:IChannelControls[][], extensions: IPlugin[]) {
let channelQueues:IChannelControls[][] = [];
constructor() {
super();
let _arrForEach = CoreUtils.arrForEach;
let _channelQueue: IChannelControls[][];
if (channels) {
// Add and sort the configuration channel queues
_arrForEach(channels, queue => _addChannelQueue(channelQueues, queue));
}
dynamicProto(ChannelController, this, (_self, _base) => {
_self.setNextPlugin = (next: ITelemetryPlugin | ITelemetryPluginChain) => {
// The Channel controller is last in pipeline
};
if (extensions) {
// Create a new channel queue for any extensions with a priority > the ChannelControllerPriority
let extensionQueue:IChannelControls[] = [];
_arrForEach(extensions as IChannelControls[], plugin => {
if (plugin.priority > ChannelControllerPriority) {
extensionQueue.push(plugin);
_self.processTelemetry = (item: ITelemetryItem, itemCtx: IProcessTelemetryContext) => {
if (_channelQueue) {
_arrForEach(_channelQueue, queues => {
// pass on to first item in queue
if (queues.length > 0) {
// Copying the item context as we could have mutiple chains that are executing asynchronously
// and calling _getDefTelCtx as it's possible that the caller doesn't pass any context
let chainCtx = this._getTelCtx(itemCtx).createNew(queues);
chainCtx.processNext(item);
}
});
}
};
_self.getChannelControls = (): IChannelControls[][] => {
return _channelQueue;
};
_self.initialize = (config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[]) => {
if (_self.isInitialized()) {
// already initialized
return;
}
_base.initialize(config, core, extensions);
if ((config as any).isCookieUseDisabled) {
CoreUtils.disableCookies();
}
_createChannelQueues((config||{}).channels, extensions);
// Initialize the Queues
_arrForEach(_channelQueue, queue => initializePlugins(new ProcessTelemetryContext(queue, config, core), extensions));
}
});
_addChannelQueue(channelQueues, extensionQueue);
}
return channelQueues;
}
export class ChannelController extends BaseTelemetryPlugin {
identifier: string = "ChannelControllerPlugin";
setNextPlugin: (next: ITelemetryPlugin) => {}; // channel controller is last in pipeline
priority: number = ChannelControllerPriority; // in reserved range 100 to 200
private _channelQueue: IChannelControls[][];
public processTelemetry(item: ITelemetryItem, itemCtx: IProcessTelemetryContext) {
if (this._channelQueue) {
_arrForEach(this._channelQueue, queues => {
// pass on to first item in queue
if (queues.length > 0) {
// Copying the item context as we could have mutiple chains that are executing asynchronously
// and calling _getDefTelCtx as it's possible that the caller doesn't pass any context
let chainCtx = this._getTelCtx(itemCtx).createNew(queues);
chainCtx.processNext(item);
function _checkQueuePriority(queue:IChannelControls[]) {
_arrForEach(queue, queueItem => {
if (queueItem.priority < ChannelControllerPriority) {
throw Error(ChannelValidationMessage + queueItem.identifier);
}
});
}
function _addChannelQueue(queue:IChannelControls[]) {
if (queue && queue.length > 0) {
queue = queue.sort((a, b) => { // sort based on priority within each queue
return a.priority - b.priority;
});
_checkQueuePriority(queue);
_channelQueue.push(queue);
}
}
function _createChannelQueues(channels:IChannelControls[][], extensions: IPlugin[]) {
_channelQueue = [];
if (channels) {
// Add and sort the configuration channel queues
_arrForEach(channels, queue => _addChannelQueue(queue));
}
if (extensions) {
// Create a new channel queue for any extensions with a priority > the ChannelControllerPriority
let extensionQueue:IChannelControls[] = [];
_arrForEach(extensions as IChannelControls[], plugin => {
if (plugin.priority > ChannelControllerPriority) {
extensionQueue.push(plugin);
}
});
_addChannelQueue(extensionQueue);
}
}
}
public processTelemetry(item: ITelemetryItem, itemCtx: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
};
public getChannelControls(): IChannelControls[][] {
return this._channelQueue;
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
public initialize(config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[]) {
let _self = this;
if (_self.isInitialized()) {
// already initialized
return;
}
super.initialize(config, core, extensions);
if ((config as any).isCookieUseDisabled) {
CoreUtils.disableCookies();
}
let channelQueue = _self._channelQueue = _createChannelQueues((config||{}).channels, extensions);
// Initialize the Queues
_arrForEach(channelQueue, queue => initializePlugins(new ProcessTelemetryContext(queue, config, core), extensions));
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -114,0 +134,0 @@

@@ -6,2 +6,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { getWindow, getDocument, getGlobalInst, getCrypto } from './EnvUtils';
import { ITelemetryItem } from '../JavaScriptSDK.Interfaces/ITelemetryItem';
import { IPerfEvent } from '../JavaScriptSDK.Interfaces/IPerfEvent';
import { IPerfManager, IPerfManagerProvider } from '../JavaScriptSDK.Interfaces/IPerfManager';
import { PerfEvent } from '../JavaScriptSDK/PerfManager';

@@ -36,3 +40,3 @@ // Added to help with minfication

function _isFunction(value: any): boolean {
function _isFunction(value: any): value is Function {
return _isTypeof(value, strShimFunction);

@@ -124,3 +128,3 @@ };

*/
public static isFunction: (value: any) => boolean = _isFunction;
public static isFunction: (value: any) => value is Function = _isFunction;

@@ -137,3 +141,3 @@ /**

*/
public static isDate(obj: any): boolean {
public static isDate(obj: any): obj is Date {
return Object[strShimPrototype].toString.call(obj) === "[object Date]";

@@ -143,2 +147,16 @@ }

/**
* Check if an object is of type Array
*/
public static isArray(obj: any): boolean {
return Object[strShimPrototype].toString.call(obj) === "[object Array]";
}
/**
* Check if an object is of type Error
*/
public static isError(obj: any): boolean {
return Object[strShimPrototype].toString.call(obj) === "[object Error]";
}
/**
* Checks if the type of value is a string.

@@ -148,3 +166,3 @@ * @param {any} value - Value to be checked.

*/
public static isString(value: any): boolean {
public static isString(value: any): value is string {
return _isTypeof(value, "string");

@@ -158,3 +176,3 @@ }

*/
public static isNumber(value: any): boolean {
public static isNumber(value: any): value is number {
return _isTypeof(value, "number");

@@ -168,3 +186,3 @@ }

*/
public static isBoolean(value: any): boolean {
public static isBoolean(value: any): value is boolean {
return _isTypeof(value, "boolean");

@@ -477,1 +495,61 @@ }

}
const doPerfActiveKey = "CoreUtils.doPerf";
/**
* Helper function to wrap a function with a perf event
* @param mgrSource - The Performance Manager or a Performance provider source (may be null)
* @param getSource - The callback to create the source name for the event (if perf monitoring is enabled)
* @param func - The function to call and measure
* @param details - A function to return the payload details
* @param isAsync - Is the event / function being call asynchronously or synchronously
*/
export function doPerf<T>(mgrSource: IPerfManagerProvider | IPerfManager, getSource: () => string, func: (perfEvt?: IPerfEvent) => T, details?: () => any, isAsync?: boolean) {
if (mgrSource) {
let perfMgr: IPerfManager = mgrSource as IPerfManager;
if (perfMgr && CoreUtils.isFunction(perfMgr["getPerfMgr"])) {
// Looks like a perf manager provider object
perfMgr = perfMgr["getPerfMgr"]()
}
if (perfMgr) {
let perfEvt: IPerfEvent;
let currentActive: IPerfEvent = perfMgr.getCtx(doPerfActiveKey);
try {
perfEvt = perfMgr.create(getSource(), details, isAsync);
if (perfEvt) {
if (currentActive && perfEvt.setCtx) {
perfEvt.setCtx(PerfEvent.ParentContextKey, currentActive);
if (currentActive.getCtx && currentActive.setCtx) {
let children: IPerfEvent[] = currentActive.getCtx(PerfEvent.ChildrenContextKey);
if (!children) {
children = [];
currentActive.setCtx(PerfEvent.ChildrenContextKey, children);
}
children.push(perfEvt);
}
}
// Set this event as the active event now
perfMgr.setCtx(doPerfActiveKey, perfEvt);
return func(perfEvt);
}
} catch (ex) {
if (perfEvt && perfEvt.setCtx) {
perfEvt.setCtx("exception", ex);
}
} finally {
// fire the perf event
if (perfEvt) {
perfMgr.fire(perfEvt);
}
// Reset the active event to the previous value
perfMgr.setCtx(doPerfActiveKey, currentActive);
}
}
}
return func();
}

@@ -8,26 +8,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { CoreUtils } from "./CoreUtils";
import { hasJSON, getJSON } from "./EnvUtils";
import { AppInsightsCore } from "./AppInsightsCore";
import { hasJSON, getJSON, getConsole } from "./EnvUtils";
import dynamicProto from '@microsoft/dynamicproto-js';
export class _InternalLogMessage{
public static dataType: string = "MessageData";
/**
* For user non actionable traces use AI Internal prefix.
*/
const AiNonUserActionablePrefix = "AI (Internal): ";
/**
* For user non actionable traces use AI Internal prefix.
*/
private static AiNonUserActionablePrefix = "AI (Internal): ";
/**
* Prefix of the traces in portal.
*/
const AiUserActionablePrefix = "AI: ";
/**
* Prefix of the traces in portal.
*/
private static AiUserActionablePrefix = "AI: ";
/**
* Session storage key for the prefix for the key indicating message type already logged
*/
const AIInternalMessagePrefix = "AITR_";
private static sanitizeDiagnosticText(text: string) {
if (text) {
return "\"" + text.replace(/\"/g, "") + "\"";
}
return "";
function _sanitizeDiagnosticText(text: string) {
if (text) {
return "\"" + text.replace(/\"/g, "") + "\"";
}
return "";
}
export class _InternalLogMessage{
public static dataType: string = "MessageData";
public message: string;

@@ -37,6 +43,7 @@ public messageId: _InternalMessageId;

constructor(msgId: _InternalMessageId, msg: string, isUserAct = false, properties?: Object) {
let _self = this;
this.messageId = msgId;
this.message =
(isUserAct ? _InternalLogMessage.AiUserActionablePrefix : _InternalLogMessage.AiNonUserActionablePrefix) +
_self.messageId = msgId;
_self.message =
(isUserAct ? AiUserActionablePrefix : AiNonUserActionablePrefix) +
msgId;

@@ -48,7 +55,8 @@

}
const diagnosticText =
(msg ? " message:" + _InternalLogMessage.sanitizeDiagnosticText(msg) : "") +
(properties ? " props:" + _InternalLogMessage.sanitizeDiagnosticText(strProps) : "");
(msg ? " message:" + _sanitizeDiagnosticText(msg) : "") +
(properties ? " props:" + _sanitizeDiagnosticText(strProps) : "");
this.message += diagnosticText;
_self.message += diagnosticText;
}

@@ -58,3 +66,4 @@ }

export class DiagnosticLogger implements IDiagnosticLogger {
public identifier = 'DiagnosticLogger';
/**

@@ -65,37 +74,142 @@ * The internal logging queue

/**
* Session storage key for the prefix for the key indicating message type already logged
*/
private AIInternalMessagePrefix: string = "AITR_";
constructor(config?: IConfiguration) {
/**
* Count of internal messages sent
*/
let _messageCount = 0;
/**
* Count of internal messages sent
*/
private _messageCount = 0;
/**
* Holds information about what message types were already logged to console or sent to server.
*/
let _messageLogged: { [msg: number]: boolean } = {};
/**
* Holds information about what message types were already logged to console or sent to server.
*/
private _messageLogged: { [msg: number]: boolean } = {};
dynamicProto(DiagnosticLogger, this, (_self) => {
const isNullOrUndefined = CoreUtils.isNullOrUndefined;
const isUndefined = CoreUtils.isUndefined;
const isFunction = CoreUtils.isFunction;
constructor(config?: IConfiguration) {
if (CoreUtils.isNullOrUndefined(config)) {
// TODO: Use default config
// config = AppInsightsCore.defaultConfig;
if (isNullOrUndefined(config)) {
config = {};
}
// For now, use defaults specified in DiagnosticLogger members;
return;
}
if (!CoreUtils.isNullOrUndefined(config.loggingLevelConsole)) {
this.consoleLoggingLevel = () => config.loggingLevelConsole;
}
if (!CoreUtils.isNullOrUndefined(config.loggingLevelTelemetry)) {
this.telemetryLoggingLevel = () => config.loggingLevelTelemetry;
}
if (!CoreUtils.isNullOrUndefined(config.maxMessageLimit)) {
this.maxInternalMessageLimit = () => config.maxMessageLimit
}
if (!CoreUtils.isNullOrUndefined(config.enableDebugExceptions)) {
this.enableDebugExceptions = () => config.enableDebugExceptions;
}
_self.consoleLoggingLevel = () => _getConfigValue('loggingLevelConsole', 0);
_self.telemetryLoggingLevel = () => _getConfigValue('loggingLevelTelemetry', 1);
_self.maxInternalMessageLimit = () => _getConfigValue('maxMessageLimit', 25);
_self.enableDebugExceptions = () => _getConfigValue('enableDebugExceptions', false);
/**
* This method will throw exceptions in debug mode or attempt to log the error as a console warning.
* @param severity {LoggingSeverity} - The severity of the log message
* @param message {_InternalLogMessage} - The log message.
*/
_self.throwInternal = (severity: LoggingSeverity, msgId: _InternalMessageId, msg: string, properties?: Object, isUserAct = false) => {
const message = new _InternalLogMessage(msgId, msg, isUserAct, properties);
if (_self.enableDebugExceptions()) {
throw message;
} else {
if (!isUndefined(message) && !!message) {
if (!isUndefined(message.message)) {
if (isUserAct) {
// check if this message type was already logged to console for this page view and if so, don't log it again
const messageKey: number = +message.messageId;
if (!_messageLogged[messageKey] && _self.consoleLoggingLevel() >= LoggingSeverity.WARNING) {
_self.warnToConsole(message.message);
_messageLogged[messageKey] = true;
}
} else {
// don't log internal AI traces in the console, unless the verbose logging is enabled
if (_self.consoleLoggingLevel() >= LoggingSeverity.WARNING) {
_self.warnToConsole(message.message);
}
}
_self.logInternalMessage(severity, message);
}
}
}
}
/**
* This will write a warning to the console if possible
* @param message {string} - The warning message
*/
_self.warnToConsole = (message: string) => {
let theConsole = getConsole();
if (!!theConsole) {
let logFunc = 'log';
if (theConsole.warn) {
logFunc = 'warn';
}
if (isFunction(theConsole[logFunc])) {
theConsole[logFunc](message);
}
}
}
/**
* Resets the internal message count
*/
_self.resetInternalMessageCount = (): void => {
_messageCount = 0;
_messageLogged = {};
};
/**
* Logs a message to the internal queue.
* @param severity {LoggingSeverity} - The severity of the log message
* @param message {_InternalLogMessage} - The message to log.
*/
_self.logInternalMessage = (severity: LoggingSeverity, message: _InternalLogMessage): void => {
if (_areInternalMessagesThrottled()) {
return;
}
// check if this message type was already logged for this session and if so, don't log it again
let logMessage = true;
const messageKey = AIInternalMessagePrefix + message.messageId;
// if the session storage is not available, limit to only one message type per page view
if (_messageLogged[messageKey]) {
logMessage = false;
} else {
_messageLogged[messageKey] = true;
}
if (logMessage) {
// Push the event in the internal queue
if (severity <= _self.telemetryLoggingLevel()) {
_self.queue.push(message);
_messageCount++;
}
// When throttle limit reached, send a special event
if (_messageCount === _self.maxInternalMessageLimit()) {
const throttleLimitMessage = "Internal events throttle limit per PageView reached for this app.";
const throttleMessage = new _InternalLogMessage(_InternalMessageId.MessageLimitPerPVExceeded, throttleLimitMessage, false);
_self.queue.push(throttleMessage);
_self.warnToConsole(throttleLimitMessage);
}
}
};
function _getConfigValue<T>(name: keyof IConfiguration, defValue: T): T {
let value = config[name] as T;
if (!isNullOrUndefined(value)) {
return value;
}
return defValue;
}
function _areInternalMessagesThrottled(): boolean {
return _messageCount >= _self.maxInternalMessageLimit();
}
});
}

@@ -106,3 +220,6 @@

*/
public enableDebugExceptions = () => false;
public enableDebugExceptions(): boolean {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return false;
}

@@ -114,3 +231,6 @@ /**

*/
public consoleLoggingLevel = () => 0;
public consoleLoggingLevel(): number {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 0;
}

@@ -122,3 +242,6 @@ /**

*/
public telemetryLoggingLevel = () => 1;
public telemetryLoggingLevel(): number {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 1;
}

@@ -128,3 +251,6 @@ /**

*/
public maxInternalMessageLimit = () => 25;
public maxInternalMessageLimit(): number {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 25;
}

@@ -137,29 +263,3 @@ /**

public throwInternal(severity: LoggingSeverity, msgId: _InternalMessageId, msg: string, properties?: Object, isUserAct = false) {
const message = new _InternalLogMessage(msgId, msg, isUserAct, properties);
let _this = this;
if (_this.enableDebugExceptions()) {
throw message;
} else {
if (!CoreUtils.isUndefined(message) && !!message) {
if (!CoreUtils.isUndefined(message.message)) {
if (isUserAct) {
// check if this message type was already logged to console for this page view and if so, don't log it again
const messageKey: number = +message.messageId;
if (!_this._messageLogged[messageKey] && _this.consoleLoggingLevel() >= LoggingSeverity.WARNING) {
_this.warnToConsole(message.message);
_this._messageLogged[messageKey] = true;
}
} else {
// don't log internal AI traces in the console, unless the verbose logging is enabled
if (_this.consoleLoggingLevel() >= LoggingSeverity.WARNING) {
_this.warnToConsole(message.message);
}
}
_this.logInternalMessage(severity, message);
}
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -172,9 +272,3 @@

public warnToConsole(message: string) {
if (!CoreUtils.isUndefined(console) && !!console) {
if (CoreUtils.isFunction(console.warn)) {
console.warn(message);
} else if (CoreUtils.isFunction(console.log)) {
console.log(message);
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -186,4 +280,3 @@

public resetInternalMessageCount(): void {
this._messageCount = 0;
this._messageLogged = {};
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -197,42 +290,4 @@

public logInternalMessage(severity: LoggingSeverity, message: _InternalLogMessage): void {
let _this = this;
if (_this._areInternalMessagesThrottled()) {
return;
}
// check if this message type was already logged for this session and if so, don't log it again
let logMessage = true;
const messageKey = _this.AIInternalMessagePrefix + message.messageId;
// if the session storage is not available, limit to only one message type per page view
if (_this._messageLogged[messageKey]) {
logMessage = false;
} else {
_this._messageLogged[messageKey] = true;
}
if (logMessage) {
// Push the event in the internal queue
if (severity <= _this.telemetryLoggingLevel()) {
_this.queue.push(message);
_this._messageCount++;
}
// When throttle limit reached, send a special event
if (_this._messageCount === _this.maxInternalMessageLimit()) {
const throttleLimitMessage = "Internal events throttle limit per PageView reached for this app.";
const throttleMessage = new _InternalLogMessage(_InternalMessageId.MessageLimitPerPVExceeded, throttleLimitMessage, false);
_this.queue.push(throttleMessage);
_this.warnToConsole(throttleLimitMessage);
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Indicates whether the internal events are throttled
*/
private _areInternalMessagesThrottled(): boolean {
return this._messageCount >= this.maxInternalMessageLimit();
}
}

@@ -26,2 +26,3 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

const strLocation = "location";
const strConsole = "console";
const strPerformance = "performance";

@@ -177,2 +178,13 @@ const strJSON = "JSON";

/**
* Returns the global console object
*/
export function getConsole(): Console | null {
if (typeof console !== strUndefined) {
return console;
}
return getGlobalInst(strConsole);
}
/**
* Returns the performance object if it is present otherwise null.

@@ -179,0 +191,0 @@ * This helper is used to access the performance object from the current

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import {
IInstrumentHooksCallbacks, IInstrumentHooks, IInstrumentHook, IInstrumentCallDetails, InstrumentorHooksCallback
import {
IInstrumentHooksCallbacks, IInstrumentHooks, IInstrumentHook, IInstrumentCallDetails, InstrumentorHooksCallback
} from "../JavaScriptSDK.Interfaces/IInstrumentHooks";

@@ -25,2 +25,15 @@ import {

/**
* Constant string defined to support minimization
* @ignore
*/
const str__Proto = "__proto__";
/**
* Constant string defined to support minimization
* @ignore
*/
const strConstructor = "constructor";
/** @ignore */

@@ -33,3 +46,3 @@ function _arrLoop<T>(arr:T[], fn:(value:T, idx:number) => boolean|number|void) {

}
}
}
}

@@ -45,3 +58,3 @@ }

if (cb) {
// Set the specific hook context implementation using a lazy creation pattern

@@ -78,3 +91,3 @@ callDetails.ctx = () => {

function _createFunctionHook(aiHook:IInstrumentHooks) {
// Define a temporary method that queues-up a the real method call

@@ -134,2 +147,30 @@ return function () {

/**
* Pre-lookup to check if we are running on a modern browser (i.e. not IE8)
* @ignore
*/
let _objGetPrototypeOf = Object["getPrototypeOf"];
/**
* Helper used to get the prototype of the target object as getPrototypeOf is not available in an ES3 environment.
* @ignore
*/
function _getObjProto(target:any) {
if (target) {
// This method doesn't existing in older browsers (e.g. IE8)
if (_objGetPrototypeOf) {
return _objGetPrototypeOf(target);
}
// target[Constructor] May break if the constructor has been changed or removed
let newProto = target[str__Proto] || target[strPrototype] || target[strConstructor];
if(newProto) {
return newProto;
}
}
return null;
}
/** @ignore */

@@ -142,3 +183,3 @@ function _getOwner(target:any, name:string, checkPrototype:boolean): any {

} else if (checkPrototype) {
owner = _getOwner(target[strPrototype], name, false);
owner = _getOwner(_getObjProto(target), name, false);
}

@@ -188,42 +229,44 @@ }

let owner = _getOwner(target, funcName, checkPrototype);
let fn = owner[funcName]
if (typeof fn === strFunction) {
let aiHook:IInstrumentHooks = fn[aiInstrumentHooks];
if (!aiHook) {
// Only hook the function once
aiHook = {
i: 0,
n: funcName,
f: fn,
h: []
};
if (owner) {
let fn = owner[funcName]
if (typeof fn === strFunction) {
let aiHook:IInstrumentHooks = fn[aiInstrumentHooks];
if (!aiHook) {
// Only hook the function once
aiHook = {
i: 0,
n: funcName,
f: fn,
h: []
};
// Override (hook) the original function
let newFunc = _createFunctionHook(aiHook);
newFunc[aiInstrumentHooks] = aiHook; // Tag and store the function hooks
owner[funcName] = newFunc;
}
// Override (hook) the original function
let newFunc = _createFunctionHook(aiHook);
newFunc[aiInstrumentHooks] = aiHook; // Tag and store the function hooks
owner[funcName] = newFunc;
}
const theHook: IInstrumentHook = {
// tslint:disable:object-literal-shorthand
id: aiHook.i,
cbks: callbacks,
rm: function() {
// DO NOT Use () => { shorthand for the function as the this gets replaced
// with the outer this and not the this for theHook instance.
let id = this.id;
_arrLoop(aiHook.h, (hook, idx) => {
if (hook.id === id) {
aiHook.h.splice(idx, 1);
return 1;
}
});
const theHook: IInstrumentHook = {
// tslint:disable:object-literal-shorthand
id: aiHook.i,
cbks: callbacks,
rm: function() {
// DO NOT Use () => { shorthand for the function as the this gets replaced
// with the outer this and not the this for theHook instance.
let id = this.id;
_arrLoop(aiHook.h, (hook, idx) => {
if (hook.id === id) {
aiHook.h.splice(idx, 1);
return 1;
}
});
}
// tslint:enable:object-literal-shorthand
}
// tslint:enable:object-literal-shorthand
}
aiHook.i ++;
aiHook.h.push(theHook);
aiHook.i ++;
aiHook.h.push(theHook);
return theHook;
return theHook;
}
}

@@ -230,0 +273,0 @@ }

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IConfiguration } from '../JavaScriptSDK.Interfaces/IConfiguration';
import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem";
import { INotificationListener } from "../JavaScriptSDK.Interfaces/INotificationListener";
import { INotificationManager } from './../JavaScriptSDK.Interfaces/INotificationManager';
import { SendRequestReason } from '../JavaScriptSDK.Enums/SendRequestReason';
import { CoreUtils } from "./CoreUtils";
import { INotificationManager } from '../JavaScriptSDK.Interfaces/INotificationManager';
import { IPerfEvent } from "../JavaScriptSDK.Interfaces/IPerfEvent";
import { CoreUtils, } from "./CoreUtils";
import dynamicProto from "@microsoft/dynamicproto-js";

@@ -15,2 +17,94 @@ /**

constructor(config?: IConfiguration) {
let arrForEach = CoreUtils.arrForEach;
let perfEvtsSendAll = !!(config ||{}).perfEvtsSendAll;
dynamicProto(NotificationManager, this, (_self) => {
_self.addNotificationListener = (listener: INotificationListener): void => {
_self.listeners.push(listener);
};
/**
* Removes all instances of the listener.
* @param {INotificationListener} listener - AWTNotificationListener to remove.
*/
_self.removeNotificationListener = (listener: INotificationListener): void => {
let index: number = CoreUtils.arrIndexOf(_self.listeners, listener);
while (index > -1) {
_self.listeners.splice(index, 1);
index = CoreUtils.arrIndexOf(_self.listeners, listener);
}
};
/**
* Notification for events sent.
* @param {ITelemetryItem[]} events - The array of events that have been sent.
*/
_self.eventsSent = (events: ITelemetryItem[]): void => {
arrForEach(_self.listeners, (listener) => {
if (listener && listener.eventsSent) {
setTimeout(() => listener.eventsSent(events), 0);
}
});
};
/**
* Notification for events being discarded.
* @param {ITelemetryItem[]} events - The array of events that have been discarded by the SDK.
* @param {number} reason - The reason for which the SDK discarded the events. The EventsDiscardedReason
* constant should be used to check the different values.
*/
_self.eventsDiscarded = (events: ITelemetryItem[], reason: number): void => {
arrForEach(_self.listeners, (listener) => {
if (listener && listener.eventsDiscarded) {
setTimeout(() => listener.eventsDiscarded(events, reason), 0);
}
});
};
/**
* [Optional] A function called when the events have been requested to be sent to the sever.
* @param {number} sendReason - The reason why the event batch is being sent.
* @param {boolean} isAsync - A flag which identifies whether the requests are being sent in an async or sync manner.
*/
_self.eventsSendRequest = (sendReason: number, isAsync: boolean): void => {
arrForEach(_self.listeners, (listener) => {
if (listener && listener.eventsSendRequest) {
if (isAsync) {
setTimeout(() => listener.eventsSendRequest(sendReason, isAsync), 0);
} else {
try {
listener.eventsSendRequest(sendReason, isAsync);
} catch (e) {
// Catch errors to ensure we don't block sending the requests
}
}
}
});
};
_self.perfEvent = (perfEvent?: IPerfEvent): void => {
if (perfEvent) {
// Send all events or only parent events
if (perfEvtsSendAll || !perfEvent.isChildEvt()) {
arrForEach(_self.listeners, (listener) => {
if (listener && listener.perfEvent) {
if (perfEvent.isAsync) {
setTimeout(() => listener.perfEvent(perfEvent), 0);
} else {
try {
listener.perfEvent(perfEvent);
} catch (e) {
// Catch errors to ensure we don't block sending the requests
}
}
}
});
}
}
}
});
}
/**

@@ -21,3 +115,3 @@ * Adds a notification listener.

addNotificationListener(listener: INotificationListener): void {
this.listeners.push(listener);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -30,7 +124,3 @@

removeNotificationListener(listener: INotificationListener): void {
let index: number = CoreUtils.arrIndexOf(this.listeners, listener);
while (index > -1) {
this.listeners.splice(index, 1);
index = CoreUtils.arrIndexOf(this.listeners, listener);
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -43,7 +133,3 @@

eventsSent(events: ITelemetryItem[]): void {
for (let i: number = 0; i < this.listeners.length; ++i) {
if (this.listeners[i].eventsSent) {
setTimeout(() => this.listeners[i].eventsSent(events), 0);
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -58,7 +144,3 @@

eventsDiscarded(events: ITelemetryItem[], reason: number): void {
for (let i: number = 0; i < this.listeners.length; ++i) {
if (this.listeners[i].eventsDiscarded) {
setTimeout(() => this.listeners[i].eventsDiscarded(events, reason), 0);
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}

@@ -72,16 +154,11 @@

eventsSendRequest?(sendReason: number, isAsync: boolean): void {
for (let i: number = 0; i < this.listeners.length; ++i) {
if (this.listeners[i].eventsSendRequest) {
if (isAsync) {
setTimeout(() => this.listeners[i].eventsSendRequest(sendReason, isAsync), 0);
} else {
try {
this.listeners[i].eventsSendRequest(sendReason, isAsync);
} catch (e) {
// Catch errors to ensure we don't block sending the requests
}
}
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging
* the event can be displayed via the debug plugin extension.
* @param perfEvent
*/
perfEvent?(perfEvent: IPerfEvent): void;
}

@@ -9,3 +9,3 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import { IPlugin, ITelemetryPlugin } from '../JavaScriptSDK.Interfaces/ITelemetryPlugin';
import { CoreUtils } from "./CoreUtils";
import { CoreUtils, doPerf } from "./CoreUtils";
import { _InternalLogMessage } from "./DiagnosticLogger";

@@ -74,45 +74,49 @@ import { LoggingSeverity, _InternalMessageId } from '../JavaScriptSDK.Enums/LoggingEnums';

if (plugin && _hasProcessTelemetry) {
_self._hasRun = true;
try {
let identifier = plugin ? plugin.identifier : "TelemetryPluginChain";
// Ensure that we keep the context in sync (for processNext()), just in case a plugin
// doesn't calls processTelemetry() instead of itemContext.processNext() or some
// other form of error occurred
itemCtx.setNext(_nextProxy);
if (_hasSetNext) {
// Backward compatibility setting the next plugin on the instance
plugin.setNextPlugin(_nextProxy);
doPerf(itemCtx ? itemCtx.core() : null, () => identifier + ":processTelemetry", () => {
if (plugin && _hasProcessTelemetry) {
_self._hasRun = true;
try {
// Ensure that we keep the context in sync (for processNext()), just in case a plugin
// doesn't calls processTelemetry() instead of itemContext.processNext() or some
// other form of error occurred
itemCtx.setNext(_nextProxy);
if (_hasSetNext) {
// Backward compatibility setting the next plugin on the instance
plugin.setNextPlugin(_nextProxy);
}
// Set a flag on the next plugin so we know if it was attempted to be executed
_nextProxy && ((_nextProxy as TelemetryPluginChain)._hasRun = false);
plugin.processTelemetry(env, itemCtx);
} catch (error) {
let hasRun = _nextProxy && (_nextProxy as TelemetryPluginChain)._hasRun;
if (!_nextProxy || !hasRun) {
// Either we have no next plugin or the current one did not attempt to call the next plugin
// Which means the current one is the root of the failure so log/report this failure
itemCtx.diagLog().throwInternal(
LoggingSeverity.CRITICAL,
_InternalMessageId.PluginException,
"Plugin [" + plugin.identifier + "] failed during processTelemetry - " + error);
}
if (_nextProxy && !hasRun) {
// As part of the failure the current plugin did not attempt to call the next plugin in the cahin
// So rather than leave the pipeline dead in the water we call the next plugin
_nextProxy.processTelemetry(env, itemCtx);
}
}
// Set a flag on the next plugin so we know if it was attempted to be executed
_nextProxy && ((_nextProxy as TelemetryPluginChain)._hasRun = false);
plugin.processTelemetry(env, itemCtx);
} catch (error) {
let hasRun = _nextProxy && (_nextProxy as TelemetryPluginChain)._hasRun;
if (!_nextProxy || !hasRun) {
// Either we have no next plugin or the current one did not attempt to call the next plugin
// Which means the current one is the root of the failure so log/report this failure
itemCtx.diagLog().throwInternal(
LoggingSeverity.CRITICAL,
_InternalMessageId.PluginException,
"Plugin [" + plugin.identifier + "] failed during processTelemetry - " + error);
}
if (_nextProxy && !hasRun) {
// As part of the failure the current plugin did not attempt to call the next plugin in the cahin
// So rather than leave the pipeline dead in the water we call the next plugin
_nextProxy.processTelemetry(env, itemCtx);
}
} else if (_nextProxy) {
_self._hasRun = true;
// The underlying plugin is either not defined or does not have a processTelemetry implementation
// so we still want the next plugin to be executed.
_nextProxy.processTelemetry(env, itemCtx);
}
} else if (_nextProxy) {
_self._hasRun = true;
// The underlying plugin is either not defined or does not have a processTelemetry implementation
// so we still want the next plugin to be executed.
_nextProxy.processTelemetry(env, itemCtx);
}
}, () => ({ item: env }), !((env as any).sync));
};
}
}

@@ -17,6 +17,9 @@ import '@microsoft/applicationinsights-shims';

export { BaseTelemetryPlugin } from './JavaScriptSDK/BaseTelemetryPlugin';
export { CoreUtils, EventHelper, Undefined, normalizeJsName } from "./JavaScriptSDK/CoreUtils";
export { getGlobal, getGlobalInst, hasWindow, getWindow, hasDocument, getDocument, hasNavigator, getNavigator, hasHistory, getHistory, getLocation, getPerformance, hasJSON, getJSON, isReactNative, strUndefined, strObject, strPrototype, strFunction } from "./JavaScriptSDK/EnvUtils";
export { CoreUtils, EventHelper, Undefined, normalizeJsName, doPerf } from "./JavaScriptSDK/CoreUtils";
export { getGlobal, getGlobalInst, hasWindow, getWindow, hasDocument, getDocument, hasNavigator, getNavigator, hasHistory, getHistory, getLocation, getPerformance, hasJSON, getJSON, isReactNative, getConsole, strUndefined, strObject, strPrototype, strFunction } from "./JavaScriptSDK/EnvUtils";
export { NotificationManager } from "./JavaScriptSDK/NotificationManager";
export { INotificationManager } from "./JavaScriptSDK.Interfaces/INotificationManager";
export { IPerfEvent } from './JavaScriptSDK.Interfaces/IPerfEvent';
export { IPerfManager, IPerfManagerProvider } from './JavaScriptSDK.Interfaces/IPerfManager';
export { PerfEvent, PerfManager } from './JavaScriptSDK/PerfManager';
export { DiagnosticLogger, _InternalLogMessage } from './JavaScriptSDK/DiagnosticLogger';

@@ -23,0 +26,0 @@ export { ProcessTelemetryContext } from './JavaScriptSDK/ProcessTelemetryContext';

@@ -30,2 +30,6 @@ /**

/**
* The event(s) being sent as a retry
*/
Retry = 5,
/**
* Maximum batch size would be exceeded

@@ -32,0 +36,0 @@ */

@@ -5,6 +5,8 @@ import { ITelemetryItem } from "./ITelemetryItem";

import { IConfiguration } from "./IConfiguration";
import { INotificationManager } from "./INotificationManager";
import { INotificationListener } from "./INotificationListener";
import { IDiagnosticLogger } from './IDiagnosticLogger';
import { IProcessTelemetryContext } from './IProcessTelemetryContext';
export interface IAppInsightsCore {
import { IPerfManagerProvider } from "./IPerfManager";
export interface IAppInsightsCore extends IPerfManagerProvider {
config: IConfiguration;

@@ -20,2 +22,6 @@ logger: IDiagnosticLogger;

/**
* Get the current notification manager
*/
getNotifyMgr(): INotificationManager;
/**
* Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.

@@ -22,0 +28,0 @@ * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be

@@ -70,2 +70,15 @@ import { ITelemetryPlugin } from "./ITelemetryPlugin";

channels?: IChannelControls[][];
/**
* [Optional] When enabled this will create local perfEvents based on sections of the code that have been instrumented
* to emit perfEvents (via the doPerf()) when this is enabled. This can be used to identify performance issues within
* the SDK, the way you are using it or optionally your own instrumented code.
* The provided IPerfManager implementation does NOT send any additional telemetry events to the server it will only fire
* the new perfEvent() on the INotificationManager which you can listen to.
* This also does not use the window.performance API, so it will work in environments where this API is not supported.
*/
enablePerfMgr?: boolean;
/**
* [Optional] Fire every single performance event not just the top level root performance event. Defaults to false.
*/
perfEvtsSendAll?: boolean;
}
import { ITelemetryItem } from "./ITelemetryItem";
import { IPerfEvent } from "./IPerfEvent";
/**

@@ -25,2 +26,8 @@ * An interface used for the notification listener.

eventsSendRequest?: (sendReason: number, isAsync?: boolean) => void;
/**
* [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging
* the event can be displayed via the debug plugin extension.
* @param perfEvent
*/
perfEvent?: (perfEvent: IPerfEvent) => void;
}
import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem";
import { INotificationListener } from "../JavaScriptSDK.Interfaces/INotificationListener";
import { IPerfEvent } from "./IPerfEvent";
/**

@@ -36,2 +37,8 @@ * Class to manage sending notifications to all the listeners.

eventsSendRequest?(sendReason: number, isAsync: boolean): void;
/**
* [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging
* the event can be displayed via the debug plugin extension.
* @param perfEvent
*/
perfEvent?(perfEvent: IPerfEvent): void;
}

@@ -5,14 +5,9 @@ import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore";

import { IPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin";
import { IChannelControls } from "../JavaScriptSDK.Interfaces/IChannelControls";
import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem";
import { INotificationListener } from "../JavaScriptSDK.Interfaces/INotificationListener";
import { NotificationManager } from "./NotificationManager";
import { INotificationManager } from '../JavaScriptSDK.Interfaces/INotificationManager';
import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger";
export declare class AppInsightsCore extends BaseCore implements IAppInsightsCore {
config: IConfiguration;
logger: IDiagnosticLogger;
protected _notificationManager: NotificationManager;
constructor();
initialize(config: IConfiguration, extensions: IPlugin[]): void;
getTransmissionControls(): IChannelControls[][];
initialize(config: IConfiguration, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void;
track(telemetryItem: ITelemetryItem): void;

@@ -35,4 +30,2 @@ /**

pollInternalLogs(eventName?: string): number;
private _validateTelemetryItem(telemetryItem);
private _notifyInvalidEvent(telemetryItem);
}

@@ -9,2 +9,3 @@ import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore";

import { IProcessTelemetryContext } from '../JavaScriptSDK.Interfaces/IProcessTelemetryContext';
import { IPerfManager } from "../JavaScriptSDK.Interfaces/IPerfManager";
export declare class BaseCore implements IAppInsightsCore {

@@ -16,6 +17,2 @@ static defaultConfig: IConfiguration;

isInitialized: () => boolean;
protected _notificationManager: INotificationManager;
private _eventQueue;
private _channelController;
private _setInit;
constructor();

@@ -26,3 +23,7 @@ initialize(config: IConfiguration, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void;

getProcessTelContext(): IProcessTelemetryContext;
getNotifyMgr(): INotificationManager;
getPerfMgr(): IPerfManager;
setPerfMgr(perfMgr: IPerfManager): void;
eventCnt(): number;
protected releaseQueue(): void;
}

@@ -5,2 +5,3 @@ import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore";

import { IPlugin, ITelemetryPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin";
import { ITelemetryPluginChain } from "../JavaScriptSDK.Interfaces/ITelemetryPluginChain";
import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem";

@@ -11,5 +12,5 @@ import { IProcessTelemetryContext } from "../JavaScriptSDK.Interfaces/IProcessTelemetryContext";

identifier: string;
setNextPlugin: (next: ITelemetryPlugin) => {};
priority: number;
private _channelQueue;
setNextPlugin: (next: ITelemetryPlugin | ITelemetryPluginChain) => void;
constructor();
processTelemetry(item: ITelemetryItem, itemCtx: IProcessTelemetryContext): void;

@@ -16,0 +17,0 @@ getChannelControls(): IChannelControls[][];

@@ -0,1 +1,3 @@

import { IPerfEvent } from '../JavaScriptSDK.Interfaces/IPerfEvent';
import { IPerfManager, IPerfManagerProvider } from '../JavaScriptSDK.Interfaces/IPerfManager';
export declare const Undefined = "undefined";

@@ -21,3 +23,3 @@ /**

*/
static isFunction: (value: any) => boolean;
static isFunction: (value: any) => value is Function;
/**

@@ -32,4 +34,12 @@ * Checks if the passed of value is a function.

*/
static isDate(obj: any): boolean;
static isDate(obj: any): obj is Date;
/**
* Check if an object is of type Array
*/
static isArray(obj: any): boolean;
/**
* Check if an object is of type Error
*/
static isError(obj: any): boolean;
/**
* Checks if the type of value is a string.

@@ -39,3 +49,3 @@ * @param {any} value - Value to be checked.

*/
static isString(value: any): boolean;
static isString(value: any): value is string;
/**

@@ -46,3 +56,3 @@ * Checks if the type of value is a number.

*/
static isNumber(value: any): boolean;
static isNumber(value: any): value is number;
/**

@@ -53,3 +63,3 @@ * Checks if the type of value is a boolean.

*/
static isBoolean(value: any): boolean;
static isBoolean(value: any): value is boolean;
/**

@@ -172,1 +182,10 @@ * Creates a new GUID.

}
/**
* Helper function to wrap a function with a perf event
* @param mgrSource - The Performance Manager or a Performance provider source (may be null)
* @param getSource - The callback to create the source name for the event (if perf monitoring is enabled)
* @param func - The function to call and measure
* @param details - A function to return the payload details
* @param isAsync - Is the event / function being call asynchronously or synchronously
*/
export declare function doPerf<T>(mgrSource: IPerfManagerProvider | IPerfManager, getSource: () => string, func: (perfEvt?: IPerfEvent) => T, details?: () => any, isAsync?: boolean): T;

@@ -6,11 +6,2 @@ import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration";

static dataType: string;
/**
* For user non actionable traces use AI Internal prefix.
*/
private static AiNonUserActionablePrefix;
/**
* Prefix of the traces in portal.
*/
private static AiUserActionablePrefix;
private static sanitizeDiagnosticText(text);
message: string;

@@ -21,2 +12,3 @@ messageId: _InternalMessageId;

export declare class DiagnosticLogger implements IDiagnosticLogger {
identifier: string;
/**

@@ -26,14 +18,2 @@ * The internal logging queue

queue: _InternalLogMessage[];
/**
* Session storage key for the prefix for the key indicating message type already logged
*/
private AIInternalMessagePrefix;
/**
* Count of internal messages sent
*/
private _messageCount;
/**
* Holds information about what message types were already logged to console or sent to server.
*/
private _messageLogged;
constructor(config?: IConfiguration);

@@ -43,3 +23,3 @@ /**

*/
enableDebugExceptions: () => boolean;
enableDebugExceptions(): boolean;
/**

@@ -50,3 +30,3 @@ * 0: OFF (default)

*/
consoleLoggingLevel: () => number;
consoleLoggingLevel(): number;
/**

@@ -57,7 +37,7 @@ * 0: OFF

*/
telemetryLoggingLevel: () => number;
telemetryLoggingLevel(): number;
/**
* The maximum number of internal messages allowed to be sent per page view
*/
maxInternalMessageLimit: () => number;
maxInternalMessageLimit(): number;
/**

@@ -84,6 +64,2 @@ * This method will throw exceptions in debug mode or attempt to log the error as a console warning.

logInternalMessage(severity: LoggingSeverity, message: _InternalLogMessage): void;
/**
* Indicates whether the internal events are throttled
*/
private _areInternalMessagesThrottled();
}

@@ -92,2 +92,6 @@ /**

/**
* Returns the global console object
*/
export declare function getConsole(): Console | null;
/**
* Returns the performance object if it is present otherwise null.

@@ -94,0 +98,0 @@ * This helper is used to access the performance object from the current

@@ -0,4 +1,6 @@

import { IConfiguration } from '../JavaScriptSDK.Interfaces/IConfiguration';
import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem";
import { INotificationListener } from "../JavaScriptSDK.Interfaces/INotificationListener";
import { INotificationManager } from './../JavaScriptSDK.Interfaces/INotificationManager';
import { INotificationManager } from '../JavaScriptSDK.Interfaces/INotificationManager';
import { IPerfEvent } from "../JavaScriptSDK.Interfaces/IPerfEvent";
/**

@@ -9,2 +11,3 @@ * Class to manage sending notifications to all the listeners.

listeners: INotificationListener[];
constructor(config?: IConfiguration);
/**

@@ -38,2 +41,8 @@ * Adds a notification listener.

eventsSendRequest?(sendReason: number, isAsync: boolean): void;
/**
* [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging
* the event can be displayed via the debug plugin extension.
* @param perfEvent
*/
perfEvent?(perfEvent: IPerfEvent): void;
}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc