elements work best with integers. round up to ensure contents fits\n}\nfunction getSectionHasLiquidHeight(props, sectionConfig) {\n return props.liquid && sectionConfig.liquid; // does the section do liquid-height? (need to have whole scrollgrid liquid-height as well)\n}\nfunction getAllowYScrolling(props, sectionConfig) {\n return sectionConfig.maxHeight != null || // if its possible for the height to max out, we might need scrollbars\n getSectionHasLiquidHeight(props, sectionConfig); // if the section is liquid height, it might condense enough to require scrollbars\n}\n// TODO: ONLY use `arg`. force out internal function to use same API\nfunction renderChunkContent(sectionConfig, chunkConfig, arg, isHeader) {\n var expandRows = arg.expandRows;\n var content = typeof chunkConfig.content === 'function' ?\n chunkConfig.content(arg) :\n createElement('table', {\n role: 'presentation',\n className: [\n chunkConfig.tableClassName,\n sectionConfig.syncRowHeights ? 'fc-scrollgrid-sync-table' : '',\n ].join(' '),\n style: {\n minWidth: arg.tableMinWidth,\n width: arg.clientWidth,\n height: expandRows ? arg.clientHeight : '', // css `height` on a
serves as a min-height\n },\n }, arg.tableColGroupNode, createElement(isHeader ? 'thead' : 'tbody', {\n role: 'presentation',\n }, typeof chunkConfig.rowContent === 'function'\n ? chunkConfig.rowContent(arg)\n : chunkConfig.rowContent));\n return content;\n}\nfunction isColPropsEqual(cols0, cols1) {\n return isArraysEqual(cols0, cols1, isPropsEqual);\n}\nfunction renderMicroColGroup(cols, shrinkWidth) {\n var colNodes = [];\n /*\n for ColProps with spans, it would have been great to make a single
\n HOWEVER, Chrome was getting messing up distributing the width to
/
elements with colspans.\n SOLUTION: making individual
elements makes Chrome behave.\n */\n for (var _i = 0, cols_1 = cols; _i < cols_1.length; _i++) {\n var colProps = cols_1[_i];\n var span = colProps.span || 1;\n for (var i = 0; i < span; i += 1) {\n colNodes.push(createElement(\"col\", { style: {\n width: colProps.width === 'shrink' ? sanitizeShrinkWidth(shrinkWidth) : (colProps.width || ''),\n minWidth: colProps.minWidth || '',\n } }));\n }\n }\n return createElement.apply(void 0, __spreadArray(['colgroup', {}], colNodes));\n}\nfunction sanitizeShrinkWidth(shrinkWidth) {\n /* why 4? if we do 0, it will kill any border, which are needed for computeSmallestCellWidth\n 4 accounts for 2 2-pixel borders. TODO: better solution? */\n return shrinkWidth == null ? 4 : shrinkWidth;\n}\nfunction hasShrinkWidth(cols) {\n for (var _i = 0, cols_2 = cols; _i < cols_2.length; _i++) {\n var col = cols_2[_i];\n if (col.width === 'shrink') {\n return true;\n }\n }\n return false;\n}\nfunction getScrollGridClassNames(liquid, context) {\n var classNames = [\n 'fc-scrollgrid',\n context.theme.getClass('table'),\n ];\n if (liquid) {\n classNames.push('fc-scrollgrid-liquid');\n }\n return classNames;\n}\nfunction getSectionClassNames(sectionConfig, wholeTableVGrow) {\n var classNames = [\n 'fc-scrollgrid-section',\n \"fc-scrollgrid-section-\" + sectionConfig.type,\n sectionConfig.className, // used?\n ];\n if (wholeTableVGrow && sectionConfig.liquid && sectionConfig.maxHeight == null) {\n classNames.push('fc-scrollgrid-section-liquid');\n }\n if (sectionConfig.isSticky) {\n classNames.push('fc-scrollgrid-section-sticky');\n }\n return classNames;\n}\nfunction renderScrollShim(arg) {\n return (createElement(\"div\", { className: \"fc-scrollgrid-sticky-shim\", style: {\n width: arg.clientWidth,\n minWidth: arg.tableMinWidth,\n } }));\n}\nfunction getStickyHeaderDates(options) {\n var stickyHeaderDates = options.stickyHeaderDates;\n if (stickyHeaderDates == null || stickyHeaderDates === 'auto') {\n stickyHeaderDates = options.height === 'auto' || options.viewHeight === 'auto';\n }\n return stickyHeaderDates;\n}\nfunction getStickyFooterScrollbar(options) {\n var stickyFooterScrollbar = options.stickyFooterScrollbar;\n if (stickyFooterScrollbar == null || stickyFooterScrollbar === 'auto') {\n stickyFooterScrollbar = options.height === 'auto' || options.viewHeight === 'auto';\n }\n return stickyFooterScrollbar;\n}\n\nvar SimpleScrollGrid = /** @class */ (function (_super) {\n __extends(SimpleScrollGrid, _super);\n function SimpleScrollGrid() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.processCols = memoize(function (a) { return a; }, isColPropsEqual); // so we get same `cols` props every time\n // yucky to memoize VNodes, but much more efficient for consumers\n _this.renderMicroColGroup = memoize(renderMicroColGroup);\n _this.scrollerRefs = new RefMap();\n _this.scrollerElRefs = new RefMap(_this._handleScrollerEl.bind(_this));\n _this.state = {\n shrinkWidth: null,\n forceYScrollbars: false,\n scrollerClientWidths: {},\n scrollerClientHeights: {},\n };\n // TODO: can do a really simple print-view. dont need to join rows\n _this.handleSizing = function () {\n _this.safeSetState(__assign({ shrinkWidth: _this.computeShrinkWidth() }, _this.computeScrollerDims()));\n };\n return _this;\n }\n SimpleScrollGrid.prototype.render = function () {\n var _a = this, props = _a.props, state = _a.state, context = _a.context;\n var sectionConfigs = props.sections || [];\n var cols = this.processCols(props.cols);\n var microColGroupNode = this.renderMicroColGroup(cols, state.shrinkWidth);\n var classNames = getScrollGridClassNames(props.liquid, context);\n if (props.collapsibleWidth) {\n classNames.push('fc-scrollgrid-collapsible');\n }\n // TODO: make DRY\n var configCnt = sectionConfigs.length;\n var configI = 0;\n var currentConfig;\n var headSectionNodes = [];\n var bodySectionNodes = [];\n var footSectionNodes = [];\n while (configI < configCnt && (currentConfig = sectionConfigs[configI]).type === 'header') {\n headSectionNodes.push(this.renderSection(currentConfig, microColGroupNode, true));\n configI += 1;\n }\n while (configI < configCnt && (currentConfig = sectionConfigs[configI]).type === 'body') {\n bodySectionNodes.push(this.renderSection(currentConfig, microColGroupNode, false));\n configI += 1;\n }\n while (configI < configCnt && (currentConfig = sectionConfigs[configI]).type === 'footer') {\n footSectionNodes.push(this.renderSection(currentConfig, microColGroupNode, true));\n configI += 1;\n }\n // firefox bug: when setting height on table and there is a thead or tfoot,\n // the necessary height:100% on the liquid-height body section forces the *whole* table to be taller. (bug #5524)\n // use getCanVGrowWithinCell as a way to detect table-stupid firefox.\n // if so, use a simpler dom structure, jam everything into a lone tbody.\n var isBuggy = !getCanVGrowWithinCell();\n var roleAttrs = { role: 'rowgroup' };\n return createElement('table', {\n role: 'grid',\n className: classNames.join(' '),\n style: { height: props.height },\n }, Boolean(!isBuggy && headSectionNodes.length) && createElement.apply(void 0, __spreadArray(['thead', roleAttrs], headSectionNodes)), Boolean(!isBuggy && bodySectionNodes.length) && createElement.apply(void 0, __spreadArray(['tbody', roleAttrs], bodySectionNodes)), Boolean(!isBuggy && footSectionNodes.length) && createElement.apply(void 0, __spreadArray(['tfoot', roleAttrs], footSectionNodes)), isBuggy && createElement.apply(void 0, __spreadArray(__spreadArray(__spreadArray(['tbody', roleAttrs], headSectionNodes), bodySectionNodes), footSectionNodes)));\n };\n SimpleScrollGrid.prototype.renderSection = function (sectionConfig, microColGroupNode, isHeader) {\n if ('outerContent' in sectionConfig) {\n return (createElement(Fragment, { key: sectionConfig.key }, sectionConfig.outerContent));\n }\n return (createElement(\"tr\", { key: sectionConfig.key, role: \"presentation\", className: getSectionClassNames(sectionConfig, this.props.liquid).join(' ') }, this.renderChunkTd(sectionConfig, microColGroupNode, sectionConfig.chunk, isHeader)));\n };\n SimpleScrollGrid.prototype.renderChunkTd = function (sectionConfig, microColGroupNode, chunkConfig, isHeader) {\n if ('outerContent' in chunkConfig) {\n return chunkConfig.outerContent;\n }\n var props = this.props;\n var _a = this.state, forceYScrollbars = _a.forceYScrollbars, scrollerClientWidths = _a.scrollerClientWidths, scrollerClientHeights = _a.scrollerClientHeights;\n var needsYScrolling = getAllowYScrolling(props, sectionConfig); // TODO: do lazily. do in section config?\n var isLiquid = getSectionHasLiquidHeight(props, sectionConfig);\n // for `!props.liquid` - is WHOLE scrollgrid natural height?\n // TODO: do same thing in advanced scrollgrid? prolly not b/c always has horizontal scrollbars\n var overflowY = !props.liquid ? 'visible' :\n forceYScrollbars ? 'scroll' :\n !needsYScrolling ? 'hidden' :\n 'auto';\n var sectionKey = sectionConfig.key;\n var content = renderChunkContent(sectionConfig, chunkConfig, {\n tableColGroupNode: microColGroupNode,\n tableMinWidth: '',\n clientWidth: (!props.collapsibleWidth && scrollerClientWidths[sectionKey] !== undefined) ? scrollerClientWidths[sectionKey] : null,\n clientHeight: scrollerClientHeights[sectionKey] !== undefined ? scrollerClientHeights[sectionKey] : null,\n expandRows: sectionConfig.expandRows,\n syncRowHeights: false,\n rowSyncHeights: [],\n reportRowHeightChange: function () { },\n }, isHeader);\n return createElement(isHeader ? 'th' : 'td', {\n ref: chunkConfig.elRef,\n role: 'presentation',\n }, createElement(\"div\", { className: \"fc-scroller-harness\" + (isLiquid ? ' fc-scroller-harness-liquid' : '') },\n createElement(Scroller, { ref: this.scrollerRefs.createRef(sectionKey), elRef: this.scrollerElRefs.createRef(sectionKey), overflowY: overflowY, overflowX: !props.liquid ? 'visible' : 'hidden' /* natural height? */, maxHeight: sectionConfig.maxHeight, liquid: isLiquid, liquidIsAbsolute // because its within a harness\n : true }, content)));\n };\n SimpleScrollGrid.prototype._handleScrollerEl = function (scrollerEl, key) {\n var section = getSectionByKey(this.props.sections, key);\n if (section) {\n setRef(section.chunk.scrollerElRef, scrollerEl);\n }\n };\n SimpleScrollGrid.prototype.componentDidMount = function () {\n this.handleSizing();\n this.context.addResizeHandler(this.handleSizing);\n };\n SimpleScrollGrid.prototype.componentDidUpdate = function () {\n // TODO: need better solution when state contains non-sizing things\n this.handleSizing();\n };\n SimpleScrollGrid.prototype.componentWillUnmount = function () {\n this.context.removeResizeHandler(this.handleSizing);\n };\n SimpleScrollGrid.prototype.computeShrinkWidth = function () {\n return hasShrinkWidth(this.props.cols)\n ? computeShrinkWidth(this.scrollerElRefs.getAll())\n : 0;\n };\n SimpleScrollGrid.prototype.computeScrollerDims = function () {\n var scrollbarWidth = getScrollbarWidths();\n var _a = this, scrollerRefs = _a.scrollerRefs, scrollerElRefs = _a.scrollerElRefs;\n var forceYScrollbars = false;\n var scrollerClientWidths = {};\n var scrollerClientHeights = {};\n for (var sectionKey in scrollerRefs.currentMap) {\n var scroller = scrollerRefs.currentMap[sectionKey];\n if (scroller && scroller.needsYScrolling()) {\n forceYScrollbars = true;\n break;\n }\n }\n for (var _i = 0, _b = this.props.sections; _i < _b.length; _i++) {\n var section = _b[_i];\n var sectionKey = section.key;\n var scrollerEl = scrollerElRefs.currentMap[sectionKey];\n if (scrollerEl) {\n var harnessEl = scrollerEl.parentNode; // TODO: weird way to get this. need harness b/c doesn't include table borders\n scrollerClientWidths[sectionKey] = Math.floor(harnessEl.getBoundingClientRect().width - (forceYScrollbars\n ? scrollbarWidth.y // use global because scroller might not have scrollbars yet but will need them in future\n : 0));\n scrollerClientHeights[sectionKey] = Math.floor(harnessEl.getBoundingClientRect().height);\n }\n }\n return { forceYScrollbars: forceYScrollbars, scrollerClientWidths: scrollerClientWidths, scrollerClientHeights: scrollerClientHeights };\n };\n return SimpleScrollGrid;\n}(BaseComponent));\nSimpleScrollGrid.addStateEquality({\n scrollerClientWidths: isPropsEqual,\n scrollerClientHeights: isPropsEqual,\n});\nfunction getSectionByKey(sections, key) {\n for (var _i = 0, sections_1 = sections; _i < sections_1.length; _i++) {\n var section = sections_1[_i];\n if (section.key === key) {\n return section;\n }\n }\n return null;\n}\n\nvar EventRoot = /** @class */ (function (_super) {\n __extends(EventRoot, _super);\n function EventRoot() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.elRef = createRef();\n return _this;\n }\n EventRoot.prototype.render = function () {\n var _a = this, props = _a.props, context = _a.context;\n var options = context.options;\n var seg = props.seg;\n var eventRange = seg.eventRange;\n var ui = eventRange.ui;\n var hookProps = {\n event: new EventApi(context, eventRange.def, eventRange.instance),\n view: context.viewApi,\n timeText: props.timeText,\n textColor: ui.textColor,\n backgroundColor: ui.backgroundColor,\n borderColor: ui.borderColor,\n isDraggable: !props.disableDragging && computeSegDraggable(seg, context),\n isStartResizable: !props.disableResizing && computeSegStartResizable(seg, context),\n isEndResizable: !props.disableResizing && computeSegEndResizable(seg),\n isMirror: Boolean(props.isDragging || props.isResizing || props.isDateSelecting),\n isStart: Boolean(seg.isStart),\n isEnd: Boolean(seg.isEnd),\n isPast: Boolean(props.isPast),\n isFuture: Boolean(props.isFuture),\n isToday: Boolean(props.isToday),\n isSelected: Boolean(props.isSelected),\n isDragging: Boolean(props.isDragging),\n isResizing: Boolean(props.isResizing),\n };\n var standardClassNames = getEventClassNames(hookProps).concat(ui.classNames);\n return (createElement(RenderHook, { hookProps: hookProps, classNames: options.eventClassNames, content: options.eventContent, defaultContent: props.defaultContent, didMount: options.eventDidMount, willUnmount: options.eventWillUnmount, elRef: this.elRef }, function (rootElRef, customClassNames, innerElRef, innerContent) { return props.children(rootElRef, standardClassNames.concat(customClassNames), innerElRef, innerContent, hookProps); }));\n };\n EventRoot.prototype.componentDidMount = function () {\n setElSeg(this.elRef.current, this.props.seg);\n };\n /*\n need to re-assign seg to the element if seg changes, even if the element is the same\n */\n EventRoot.prototype.componentDidUpdate = function (prevProps) {\n var seg = this.props.seg;\n if (seg !== prevProps.seg) {\n setElSeg(this.elRef.current, seg);\n }\n };\n return EventRoot;\n}(BaseComponent));\n\n// should not be a purecomponent\nvar StandardEvent = /** @class */ (function (_super) {\n __extends(StandardEvent, _super);\n function StandardEvent() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n StandardEvent.prototype.render = function () {\n var _a = this, props = _a.props, context = _a.context;\n var seg = props.seg;\n var timeFormat = context.options.eventTimeFormat || props.defaultTimeFormat;\n var timeText = buildSegTimeText(seg, timeFormat, context, props.defaultDisplayEventTime, props.defaultDisplayEventEnd);\n return (createElement(EventRoot, { seg: seg, timeText: timeText, disableDragging: props.disableDragging, disableResizing: props.disableResizing, defaultContent: props.defaultContent || renderInnerContent$1, isDragging: props.isDragging, isResizing: props.isResizing, isDateSelecting: props.isDateSelecting, isSelected: props.isSelected, isPast: props.isPast, isFuture: props.isFuture, isToday: props.isToday }, function (rootElRef, classNames, innerElRef, innerContent, hookProps) { return (createElement(\"a\", __assign({ className: props.extraClassNames.concat(classNames).join(' '), style: {\n borderColor: hookProps.borderColor,\n backgroundColor: hookProps.backgroundColor,\n }, ref: rootElRef }, getSegAnchorAttrs(seg, context)),\n createElement(\"div\", { className: \"fc-event-main\", ref: innerElRef, style: { color: hookProps.textColor } }, innerContent),\n hookProps.isStartResizable &&\n createElement(\"div\", { className: \"fc-event-resizer fc-event-resizer-start\" }),\n hookProps.isEndResizable &&\n createElement(\"div\", { className: \"fc-event-resizer fc-event-resizer-end\" }))); }));\n };\n return StandardEvent;\n}(BaseComponent));\nfunction renderInnerContent$1(innerProps) {\n return (createElement(\"div\", { className: \"fc-event-main-frame\" },\n innerProps.timeText && (createElement(\"div\", { className: \"fc-event-time\" }, innerProps.timeText)),\n createElement(\"div\", { className: \"fc-event-title-container\" },\n createElement(\"div\", { className: \"fc-event-title fc-sticky\" }, innerProps.event.title || createElement(Fragment, null, \"\\u00A0\")))));\n}\n\nvar NowIndicatorRoot = function (props) { return (createElement(ViewContextType.Consumer, null, function (context) {\n var options = context.options;\n var hookProps = {\n isAxis: props.isAxis,\n date: context.dateEnv.toDate(props.date),\n view: context.viewApi,\n };\n return (createElement(RenderHook, { hookProps: hookProps, classNames: options.nowIndicatorClassNames, content: options.nowIndicatorContent, didMount: options.nowIndicatorDidMount, willUnmount: options.nowIndicatorWillUnmount }, props.children));\n})); };\n\nvar DAY_NUM_FORMAT = createFormatter({ day: 'numeric' });\nvar DayCellContent = /** @class */ (function (_super) {\n __extends(DayCellContent, _super);\n function DayCellContent() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n DayCellContent.prototype.render = function () {\n var _a = this, props = _a.props, context = _a.context;\n var options = context.options;\n var hookProps = refineDayCellHookProps({\n date: props.date,\n dateProfile: props.dateProfile,\n todayRange: props.todayRange,\n showDayNumber: props.showDayNumber,\n extraProps: props.extraHookProps,\n viewApi: context.viewApi,\n dateEnv: context.dateEnv,\n });\n return (createElement(ContentHook, { hookProps: hookProps, content: options.dayCellContent, defaultContent: props.defaultContent }, props.children));\n };\n return DayCellContent;\n}(BaseComponent));\nfunction refineDayCellHookProps(raw) {\n var date = raw.date, dateEnv = raw.dateEnv;\n var dayMeta = getDateMeta(date, raw.todayRange, null, raw.dateProfile);\n return __assign(__assign(__assign({ date: dateEnv.toDate(date), view: raw.viewApi }, dayMeta), { dayNumberText: raw.showDayNumber ? dateEnv.format(date, DAY_NUM_FORMAT) : '' }), raw.extraProps);\n}\n\nvar DayCellRoot = /** @class */ (function (_super) {\n __extends(DayCellRoot, _super);\n function DayCellRoot() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.refineHookProps = memoizeObjArg(refineDayCellHookProps);\n _this.normalizeClassNames = buildClassNameNormalizer();\n return _this;\n }\n DayCellRoot.prototype.render = function () {\n var _a = this, props = _a.props, context = _a.context;\n var options = context.options;\n var hookProps = this.refineHookProps({\n date: props.date,\n dateProfile: props.dateProfile,\n todayRange: props.todayRange,\n showDayNumber: props.showDayNumber,\n extraProps: props.extraHookProps,\n viewApi: context.viewApi,\n dateEnv: context.dateEnv,\n });\n var classNames = getDayClassNames(hookProps, context.theme).concat(hookProps.isDisabled\n ? [] // don't use custom classNames if disabled\n : this.normalizeClassNames(options.dayCellClassNames, hookProps));\n var dataAttrs = hookProps.isDisabled ? {} : {\n 'data-date': formatDayString(props.date),\n };\n return (createElement(MountHook, { hookProps: hookProps, didMount: options.dayCellDidMount, willUnmount: options.dayCellWillUnmount, elRef: props.elRef }, function (rootElRef) { return props.children(rootElRef, classNames, dataAttrs, hookProps.isDisabled); }));\n };\n return DayCellRoot;\n}(BaseComponent));\n\nfunction renderFill(fillType) {\n return (createElement(\"div\", { className: \"fc-\" + fillType }));\n}\nvar BgEvent = function (props) { return (createElement(EventRoot, { defaultContent: renderInnerContent, seg: props.seg /* uselesss i think */, timeText: \"\", disableDragging: true, disableResizing: true, isDragging: false, isResizing: false, isDateSelecting: false, isSelected: false, isPast: props.isPast, isFuture: props.isFuture, isToday: props.isToday }, function (rootElRef, classNames, innerElRef, innerContent, hookProps) { return (createElement(\"div\", { ref: rootElRef, className: ['fc-bg-event'].concat(classNames).join(' '), style: {\n backgroundColor: hookProps.backgroundColor,\n } }, innerContent)); })); };\nfunction renderInnerContent(props) {\n var title = props.event.title;\n return title && (createElement(\"div\", { className: \"fc-event-title\" }, props.event.title));\n}\n\nvar WeekNumberRoot = function (props) { return (createElement(ViewContextType.Consumer, null, function (context) {\n var dateEnv = context.dateEnv, options = context.options;\n var date = props.date;\n var format = options.weekNumberFormat || props.defaultFormat;\n var num = dateEnv.computeWeekNumber(date); // TODO: somehow use for formatting as well?\n var text = dateEnv.format(date, format);\n var hookProps = { num: num, text: text, date: date };\n return (createElement(RenderHook, { hookProps: hookProps, classNames: options.weekNumberClassNames, content: options.weekNumberContent, defaultContent: renderInner, didMount: options.weekNumberDidMount, willUnmount: options.weekNumberWillUnmount }, props.children));\n})); };\nfunction renderInner(innerProps) {\n return innerProps.text;\n}\n\nvar PADDING_FROM_VIEWPORT = 10;\nvar Popover = /** @class */ (function (_super) {\n __extends(Popover, _super);\n function Popover() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.state = {\n titleId: getUniqueDomId(),\n };\n _this.handleRootEl = function (el) {\n _this.rootEl = el;\n if (_this.props.elRef) {\n setRef(_this.props.elRef, el);\n }\n };\n // Triggered when the user clicks *anywhere* in the document, for the autoHide feature\n _this.handleDocumentMouseDown = function (ev) {\n // only hide the popover if the click happened outside the popover\n var target = getEventTargetViaRoot(ev);\n if (!_this.rootEl.contains(target)) {\n _this.handleCloseClick();\n }\n };\n _this.handleDocumentKeyDown = function (ev) {\n if (ev.key === 'Escape') {\n _this.handleCloseClick();\n }\n };\n _this.handleCloseClick = function () {\n var onClose = _this.props.onClose;\n if (onClose) {\n onClose();\n }\n };\n return _this;\n }\n Popover.prototype.render = function () {\n var _a = this.context, theme = _a.theme, options = _a.options;\n var _b = this, props = _b.props, state = _b.state;\n var classNames = [\n 'fc-popover',\n theme.getClass('popover'),\n ].concat(props.extraClassNames || []);\n return createPortal(createElement(\"div\", __assign({ id: props.id, className: classNames.join(' '), \"aria-labelledby\": state.titleId }, props.extraAttrs, { ref: this.handleRootEl }),\n createElement(\"div\", { className: 'fc-popover-header ' + theme.getClass('popoverHeader') },\n createElement(\"span\", { className: \"fc-popover-title\", id: state.titleId }, props.title),\n createElement(\"span\", { className: 'fc-popover-close ' + theme.getIconClass('close'), title: options.closeHint, onClick: this.handleCloseClick })),\n createElement(\"div\", { className: 'fc-popover-body ' + theme.getClass('popoverContent') }, props.children)), props.parentEl);\n };\n Popover.prototype.componentDidMount = function () {\n document.addEventListener('mousedown', this.handleDocumentMouseDown);\n document.addEventListener('keydown', this.handleDocumentKeyDown);\n this.updateSize();\n };\n Popover.prototype.componentWillUnmount = function () {\n document.removeEventListener('mousedown', this.handleDocumentMouseDown);\n document.removeEventListener('keydown', this.handleDocumentKeyDown);\n };\n Popover.prototype.updateSize = function () {\n var isRtl = this.context.isRtl;\n var _a = this.props, alignmentEl = _a.alignmentEl, alignGridTop = _a.alignGridTop;\n var rootEl = this.rootEl;\n var alignmentRect = computeClippedClientRect(alignmentEl);\n if (alignmentRect) {\n var popoverDims = rootEl.getBoundingClientRect();\n // position relative to viewport\n var popoverTop = alignGridTop\n ? elementClosest(alignmentEl, '.fc-scrollgrid').getBoundingClientRect().top\n : alignmentRect.top;\n var popoverLeft = isRtl ? alignmentRect.right - popoverDims.width : alignmentRect.left;\n // constrain\n popoverTop = Math.max(popoverTop, PADDING_FROM_VIEWPORT);\n popoverLeft = Math.min(popoverLeft, document.documentElement.clientWidth - PADDING_FROM_VIEWPORT - popoverDims.width);\n popoverLeft = Math.max(popoverLeft, PADDING_FROM_VIEWPORT);\n var origin_1 = rootEl.offsetParent.getBoundingClientRect();\n applyStyle(rootEl, {\n top: popoverTop - origin_1.top,\n left: popoverLeft - origin_1.left,\n });\n }\n };\n return Popover;\n}(BaseComponent));\n\nvar MorePopover = /** @class */ (function (_super) {\n __extends(MorePopover, _super);\n function MorePopover() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.handleRootEl = function (rootEl) {\n _this.rootEl = rootEl;\n if (rootEl) {\n _this.context.registerInteractiveComponent(_this, {\n el: rootEl,\n useEventCenter: false,\n });\n }\n else {\n _this.context.unregisterInteractiveComponent(_this);\n }\n };\n return _this;\n }\n MorePopover.prototype.render = function () {\n var _a = this.context, options = _a.options, dateEnv = _a.dateEnv;\n var props = this.props;\n var startDate = props.startDate, todayRange = props.todayRange, dateProfile = props.dateProfile;\n var title = dateEnv.format(startDate, options.dayPopoverFormat);\n return (createElement(DayCellRoot, { date: startDate, dateProfile: dateProfile, todayRange: todayRange, elRef: this.handleRootEl }, function (rootElRef, dayClassNames, dataAttrs) { return (createElement(Popover, { elRef: rootElRef, id: props.id, title: title, extraClassNames: ['fc-more-popover'].concat(dayClassNames), extraAttrs: dataAttrs /* TODO: make these time-based when not whole-day? */, parentEl: props.parentEl, alignmentEl: props.alignmentEl, alignGridTop: props.alignGridTop, onClose: props.onClose },\n createElement(DayCellContent, { date: startDate, dateProfile: dateProfile, todayRange: todayRange }, function (innerElRef, innerContent) { return (innerContent &&\n createElement(\"div\", { className: \"fc-more-popover-misc\", ref: innerElRef }, innerContent)); }),\n props.children)); }));\n };\n MorePopover.prototype.queryHit = function (positionLeft, positionTop, elWidth, elHeight) {\n var _a = this, rootEl = _a.rootEl, props = _a.props;\n if (positionLeft >= 0 && positionLeft < elWidth &&\n positionTop >= 0 && positionTop < elHeight) {\n return {\n dateProfile: props.dateProfile,\n dateSpan: __assign({ allDay: true, range: {\n start: props.startDate,\n end: props.endDate,\n } }, props.extraDateSpan),\n dayEl: rootEl,\n rect: {\n left: 0,\n top: 0,\n right: elWidth,\n bottom: elHeight,\n },\n layer: 1, // important when comparing with hits from other components\n };\n }\n return null;\n };\n return MorePopover;\n}(DateComponent));\n\nvar MoreLinkRoot = /** @class */ (function (_super) {\n __extends(MoreLinkRoot, _super);\n function MoreLinkRoot() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.linkElRef = createRef();\n _this.state = {\n isPopoverOpen: false,\n popoverId: getUniqueDomId(),\n };\n _this.handleClick = function (ev) {\n var _a = _this, props = _a.props, context = _a.context;\n var moreLinkClick = context.options.moreLinkClick;\n var date = computeRange(props).start;\n function buildPublicSeg(seg) {\n var _a = seg.eventRange, def = _a.def, instance = _a.instance, range = _a.range;\n return {\n event: new EventApi(context, def, instance),\n start: context.dateEnv.toDate(range.start),\n end: context.dateEnv.toDate(range.end),\n isStart: seg.isStart,\n isEnd: seg.isEnd,\n };\n }\n if (typeof moreLinkClick === 'function') {\n moreLinkClick = moreLinkClick({\n date: date,\n allDay: Boolean(props.allDayDate),\n allSegs: props.allSegs.map(buildPublicSeg),\n hiddenSegs: props.hiddenSegs.map(buildPublicSeg),\n jsEvent: ev,\n view: context.viewApi,\n });\n }\n if (!moreLinkClick || moreLinkClick === 'popover') {\n _this.setState({ isPopoverOpen: true });\n }\n else if (typeof moreLinkClick === 'string') { // a view name\n context.calendarApi.zoomTo(date, moreLinkClick);\n }\n };\n _this.handlePopoverClose = function () {\n _this.setState({ isPopoverOpen: false });\n };\n return _this;\n }\n MoreLinkRoot.prototype.render = function () {\n var _this = this;\n var _a = this, props = _a.props, state = _a.state;\n return (createElement(ViewContextType.Consumer, null, function (context) {\n var viewApi = context.viewApi, options = context.options, calendarApi = context.calendarApi;\n var moreLinkText = options.moreLinkText;\n var moreCnt = props.moreCnt;\n var range = computeRange(props);\n var text = typeof moreLinkText === 'function' // TODO: eventually use formatWithOrdinals\n ? moreLinkText.call(calendarApi, moreCnt)\n : \"+\" + moreCnt + \" \" + moreLinkText;\n var title = formatWithOrdinals(options.moreLinkHint, [moreCnt], text);\n var hookProps = {\n num: moreCnt,\n shortText: \"+\" + moreCnt,\n text: text,\n view: viewApi,\n };\n return (createElement(Fragment, null,\n Boolean(props.moreCnt) && (createElement(RenderHook, { elRef: _this.linkElRef, hookProps: hookProps, classNames: options.moreLinkClassNames, content: options.moreLinkContent, defaultContent: props.defaultContent || renderMoreLinkInner, didMount: options.moreLinkDidMount, willUnmount: options.moreLinkWillUnmount }, function (rootElRef, customClassNames, innerElRef, innerContent) { return props.children(rootElRef, ['fc-more-link'].concat(customClassNames), innerElRef, innerContent, _this.handleClick, title, state.isPopoverOpen, state.isPopoverOpen ? state.popoverId : ''); })),\n state.isPopoverOpen && (createElement(MorePopover, { id: state.popoverId, startDate: range.start, endDate: range.end, dateProfile: props.dateProfile, todayRange: props.todayRange, extraDateSpan: props.extraDateSpan, parentEl: _this.parentEl, alignmentEl: props.alignmentElRef.current, alignGridTop: props.alignGridTop, onClose: _this.handlePopoverClose }, props.popoverContent()))));\n }));\n };\n MoreLinkRoot.prototype.componentDidMount = function () {\n this.updateParentEl();\n };\n MoreLinkRoot.prototype.componentDidUpdate = function () {\n this.updateParentEl();\n };\n MoreLinkRoot.prototype.updateParentEl = function () {\n if (this.linkElRef.current) {\n this.parentEl = elementClosest(this.linkElRef.current, '.fc-view-harness');\n }\n };\n return MoreLinkRoot;\n}(BaseComponent));\nfunction renderMoreLinkInner(props) {\n return props.text;\n}\nfunction computeRange(props) {\n if (props.allDayDate) {\n return {\n start: props.allDayDate,\n end: addDays(props.allDayDate, 1),\n };\n }\n var hiddenSegs = props.hiddenSegs;\n return {\n start: computeEarliestSegStart(hiddenSegs),\n end: computeLatestSegEnd(hiddenSegs),\n };\n}\nfunction computeEarliestSegStart(segs) {\n return segs.reduce(pickEarliestStart).eventRange.range.start;\n}\nfunction pickEarliestStart(seg0, seg1) {\n return seg0.eventRange.range.start < seg1.eventRange.range.start ? seg0 : seg1;\n}\nfunction computeLatestSegEnd(segs) {\n return segs.reduce(pickLatestEnd).eventRange.range.end;\n}\nfunction pickLatestEnd(seg0, seg1) {\n return seg0.eventRange.range.end > seg1.eventRange.range.end ? seg0 : seg1;\n}\n\n// exports\n// --------------------------------------------------------------------------------------------------\nvar version = '5.11.4'; // important to type it, so .d.ts has generic string\n\nexport { BASE_OPTION_DEFAULTS, BASE_OPTION_REFINERS, BaseComponent, BgEvent, CalendarApi, CalendarContent, CalendarDataManager, CalendarDataProvider, CalendarRoot, ContentHook, CustomContentRenderContext, DateComponent, DateEnv, DateProfileGenerator, DayCellContent, DayCellRoot, DayHeader, DaySeriesModel, DayTableModel, DelayedRunner, ElementDragging, ElementScrollController, Emitter, EventApi, EventRoot, EventSourceApi, Interaction, MoreLinkRoot, MountHook, NamedTimeZoneImpl, NowIndicatorRoot, NowTimer, PositionCache, RefMap, RenderHook, ScrollController, ScrollResponder, Scroller, SegHierarchy, SimpleScrollGrid, Slicer, Splitter, StandardEvent, TableDateCell, TableDowCell, Theme, ViewApi, ViewContextType, ViewRoot, WeekNumberRoot, WindowScrollController, addDays, addDurations, addMs, addWeeks, allowContextMenu, allowSelection, applyMutationToEventStore, applyStyle, applyStyleProp, asCleanDays, asRoughMinutes, asRoughMs, asRoughSeconds, binarySearch, buildClassNameNormalizer, buildEntryKey, buildEventApis, buildEventRangeKey, buildHashFromArray, buildIsoString, buildNavLinkAttrs, buildSegCompareObj, buildSegTimeText, collectFromHash, combineEventUis, compareByFieldSpec, compareByFieldSpecs, compareNumbers, compareObjs, computeEarliestSegStart, computeEdges, computeFallbackHeaderFormat, computeHeightAndMargins, computeInnerRect, computeRect, computeSegDraggable, computeSegEndResizable, computeSegStartResizable, computeShrinkWidth, computeSmallestCellWidth, computeVisibleDayRange, config, constrainPoint, createAriaClickAttrs, createDuration, createEmptyEventStore, createEventInstance, createEventUi, createFormatter, createPlugin, diffDates, diffDayAndTime, diffDays, diffPoints, diffWeeks, diffWholeDays, diffWholeWeeks, disableCursor, elementClosest, elementMatches, enableCursor, eventTupleToStore, filterEventStoreDefs, filterHash, findDirectChildren, findElements, flexibleCompare, formatDate, formatDayString, formatIsoTimeString, formatRange, getAllowYScrolling, getCanVGrowWithinCell, getClippingParents, getDateMeta, getDayClassNames, getDefaultEventEnd, getElRoot, getElSeg, getEntrySpanEnd, getEventClassNames, getEventTargetViaRoot, getIsRtlScrollbarOnLeft, getRectCenter, getRelevantEvents, getScrollGridClassNames, getScrollbarWidths, getSectionClassNames, getSectionHasLiquidHeight, getSegAnchorAttrs, getSegMeta, getSlotClassNames, getStickyFooterScrollbar, getStickyHeaderDates, getUnequalProps, getUniqueDomId, globalLocales, globalPlugins, greatestDurationDenominator, groupIntersectingEntries, guid, hasBgRendering, hasShrinkWidth, identity, interactionSettingsStore, interactionSettingsToStore, intersectRanges, intersectRects, intersectSpans, isArraysEqual, isColPropsEqual, isDateSelectionValid, isDateSpansEqual, isInt, isInteractionValid, isMultiDayRange, isPropsEqual, isPropsValid, isValidDate, joinSpans, listenBySelector, mapHash, memoize, memoizeArraylike, memoizeHashlike, memoizeObjArg, mergeEventStores, multiplyDuration, padStart, parseBusinessHours, parseClassNames, parseDragMeta, parseEventDef, parseFieldSpecs, parse as parseMarker, pointInsideRect, preventContextMenu, preventDefault, preventSelection, rangeContainsMarker, rangeContainsRange, rangesEqual, rangesIntersect, refineEventDef, refineProps, removeElement, removeExact, renderChunkContent, renderFill, renderMicroColGroup, renderScrollShim, requestJson, sanitizeShrinkWidth, setElSeg, setRef, sliceEventStore, sliceEvents, sortEventSegs, startOfDay, translateRect, triggerDateSelect, unpromisify, version, whenTransitionDone, wholeDivideDurations };\n","/// \nif (typeof FullCalendarVDom === 'undefined') {\n throw new Error('Please import the top-level fullcalendar lib before attempting to import a plugin.');\n}\nvar Component = FullCalendarVDom.Component;\nvar createElement = FullCalendarVDom.createElement;\nvar render = FullCalendarVDom.render;\nvar createRef = FullCalendarVDom.createRef;\nvar Fragment = FullCalendarVDom.Fragment;\nvar createContext = FullCalendarVDom.createContext;\nvar createPortal = FullCalendarVDom.createPortal;\nvar flushSync = FullCalendarVDom.flushSync;\nvar unmountComponentAtNode = FullCalendarVDom.unmountComponentAtNode;\n/* eslint-enable */\n\nexport { Component, Fragment, createContext, createElement, createPortal, createRef, flushSync, render, unmountComponentAtNode };\n","/*!\nFullCalendar v5.11.4\nDocs & License: https://fullcalendar.io/\n(c) 2022 Adam Shaw\n*/\nimport './vdom.js';\nimport { __extends, __assign } from 'tslib';\nimport { flushSync, render, createElement, CalendarRoot, CustomContentRenderContext, CalendarContent, unmountComponentAtNode, DelayedRunner, CalendarDataManager, isArraysEqual, applyStyleProp, CalendarApi } from '@fullcalendar/common';\nexport * from '@fullcalendar/common';\n\nvar Calendar = /** @class */ (function (_super) {\n __extends(Calendar, _super);\n function Calendar(el, optionOverrides) {\n if (optionOverrides === void 0) { optionOverrides = {}; }\n var _this = _super.call(this) || this;\n _this.isRendering = false;\n _this.isRendered = false;\n _this.currentClassNames = [];\n _this.customContentRenderId = 0; // will affect custom generated classNames?\n _this.handleAction = function (action) {\n // actions we know we want to render immediately\n switch (action.type) {\n case 'SET_EVENT_DRAG':\n case 'SET_EVENT_RESIZE':\n _this.renderRunner.tryDrain();\n }\n };\n _this.handleData = function (data) {\n _this.currentData = data;\n _this.renderRunner.request(data.calendarOptions.rerenderDelay);\n };\n _this.handleRenderRequest = function () {\n if (_this.isRendering) {\n _this.isRendered = true;\n var currentData_1 = _this.currentData;\n flushSync(function () {\n render(createElement(CalendarRoot, { options: currentData_1.calendarOptions, theme: currentData_1.theme, emitter: currentData_1.emitter }, function (classNames, height, isHeightAuto, forPrint) {\n _this.setClassNames(classNames);\n _this.setHeight(height);\n return (createElement(CustomContentRenderContext.Provider, { value: _this.customContentRenderId },\n createElement(CalendarContent, __assign({ isHeightAuto: isHeightAuto, forPrint: forPrint }, currentData_1))));\n }), _this.el);\n });\n }\n else if (_this.isRendered) {\n _this.isRendered = false;\n unmountComponentAtNode(_this.el);\n _this.setClassNames([]);\n _this.setHeight('');\n }\n };\n _this.el = el;\n _this.renderRunner = new DelayedRunner(_this.handleRenderRequest);\n new CalendarDataManager({\n optionOverrides: optionOverrides,\n calendarApi: _this,\n onAction: _this.handleAction,\n onData: _this.handleData,\n });\n return _this;\n }\n Object.defineProperty(Calendar.prototype, \"view\", {\n get: function () { return this.currentData.viewApi; } // for public API\n ,\n enumerable: false,\n configurable: true\n });\n Calendar.prototype.render = function () {\n var wasRendering = this.isRendering;\n if (!wasRendering) {\n this.isRendering = true;\n }\n else {\n this.customContentRenderId += 1;\n }\n this.renderRunner.request();\n if (wasRendering) {\n this.updateSize();\n }\n };\n Calendar.prototype.destroy = function () {\n if (this.isRendering) {\n this.isRendering = false;\n this.renderRunner.request();\n }\n };\n Calendar.prototype.updateSize = function () {\n var _this = this;\n flushSync(function () {\n _super.prototype.updateSize.call(_this);\n });\n };\n Calendar.prototype.batchRendering = function (func) {\n this.renderRunner.pause('batchRendering');\n func();\n this.renderRunner.resume('batchRendering');\n };\n Calendar.prototype.pauseRendering = function () {\n this.renderRunner.pause('pauseRendering');\n };\n Calendar.prototype.resumeRendering = function () {\n this.renderRunner.resume('pauseRendering', true);\n };\n Calendar.prototype.resetOptions = function (optionOverrides, append) {\n this.currentDataManager.resetOptions(optionOverrides, append);\n };\n Calendar.prototype.setClassNames = function (classNames) {\n if (!isArraysEqual(classNames, this.currentClassNames)) {\n var classList = this.el.classList;\n for (var _i = 0, _a = this.currentClassNames; _i < _a.length; _i++) {\n var className = _a[_i];\n classList.remove(className);\n }\n for (var _b = 0, classNames_1 = classNames; _b < classNames_1.length; _b++) {\n var className = classNames_1[_b];\n classList.add(className);\n }\n this.currentClassNames = classNames;\n }\n };\n Calendar.prototype.setHeight = function (height) {\n applyStyleProp(this.el, 'height', height);\n };\n return Calendar;\n}(CalendarApi));\n\nexport { Calendar };\n","import { __extends } from 'tslib';\nimport * as preact from 'preact';\nimport * as preactCompat from 'preact/compat';\n\nvar globalObj = typeof globalThis !== 'undefined' ? globalThis : window; // // TODO: streamline when killing IE11 support\nif (globalObj.FullCalendarVDom) {\n console.warn('FullCalendar VDOM already loaded');\n}\nelse {\n globalObj.FullCalendarVDom = {\n Component: preact.Component,\n createElement: preact.createElement,\n render: preact.render,\n createRef: preact.createRef,\n Fragment: preact.Fragment,\n createContext: createContext,\n createPortal: preactCompat.createPortal,\n flushSync: flushSync,\n unmountComponentAtNode: unmountComponentAtNode,\n };\n}\n// HACKS...\n// TODO: lock version\n// TODO: link gh issues\nfunction flushSync(runBeforeFlush) {\n runBeforeFlush();\n var oldDebounceRendering = preact.options.debounceRendering; // orig\n var callbackQ = [];\n function execCallbackSync(callback) {\n callbackQ.push(callback);\n }\n preact.options.debounceRendering = execCallbackSync;\n preact.render(preact.createElement(FakeComponent, {}), document.createElement('div'));\n while (callbackQ.length) {\n callbackQ.shift()();\n }\n preact.options.debounceRendering = oldDebounceRendering;\n}\nvar FakeComponent = /** @class */ (function (_super) {\n __extends(FakeComponent, _super);\n function FakeComponent() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n FakeComponent.prototype.render = function () { return preact.createElement('div', {}); };\n FakeComponent.prototype.componentDidMount = function () { this.setState({}); };\n return FakeComponent;\n}(preact.Component));\nfunction createContext(defaultValue) {\n var ContextType = preact.createContext(defaultValue);\n var origProvider = ContextType.Provider;\n ContextType.Provider = function () {\n var _this = this;\n var isNew = !this.getChildContext;\n var children = origProvider.apply(this, arguments); // eslint-disable-line prefer-rest-params\n if (isNew) {\n var subs_1 = [];\n this.shouldComponentUpdate = function (_props) {\n if (_this.props.value !== _props.value) {\n subs_1.forEach(function (c) {\n c.context = _props.value;\n c.forceUpdate();\n });\n }\n };\n this.sub = function (c) {\n subs_1.push(c);\n var old = c.componentWillUnmount;\n c.componentWillUnmount = function () {\n subs_1.splice(subs_1.indexOf(c), 1);\n old && old.call(c);\n };\n };\n }\n return children;\n };\n return ContextType;\n}\nfunction unmountComponentAtNode(node) {\n preact.render(null, node);\n}\n","/*!\nFullCalendar v5.11.4\nDocs & License: https://fullcalendar.io/\n(c) 2022 Adam Shaw\n*/\nimport './main.css';\n\nimport { createRef, getStickyHeaderDates, createElement, ViewRoot, SimpleScrollGrid, getStickyFooterScrollbar, renderScrollShim, DateComponent, buildNavLinkAttrs, DayCellContent, Fragment, BaseComponent, createFormatter, StandardEvent, buildSegTimeText, EventRoot, getSegAnchorAttrs, memoize, MoreLinkRoot, getSegMeta, createAriaClickAttrs, getUniqueDomId, setRef, DayCellRoot, WeekNumberRoot, buildEntryKey, intersectSpans, SegHierarchy, intersectRanges, addDays, RefMap, sortEventSegs, isPropsEqual, buildEventRangeKey, BgEvent, renderFill, PositionCache, NowTimer, Slicer, DayHeader, DaySeriesModel, DayTableModel, addWeeks, diffWeeks, DateProfileGenerator, createPlugin } from '@fullcalendar/common';\nimport { __extends, __assign, __spreadArray } from 'tslib';\n\n/* An abstract class for the daygrid views, as well as month view. Renders one or more rows of day cells.\n----------------------------------------------------------------------------------------------------------------------*/\n// It is a manager for a Table subcomponent, which does most of the heavy lifting.\n// It is responsible for managing width/height.\nvar TableView = /** @class */ (function (_super) {\n __extends(TableView, _super);\n function TableView() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.headerElRef = createRef();\n return _this;\n }\n TableView.prototype.renderSimpleLayout = function (headerRowContent, bodyContent) {\n var _a = this, props = _a.props, context = _a.context;\n var sections = [];\n var stickyHeaderDates = getStickyHeaderDates(context.options);\n if (headerRowContent) {\n sections.push({\n type: 'header',\n key: 'header',\n isSticky: stickyHeaderDates,\n chunk: {\n elRef: this.headerElRef,\n tableClassName: 'fc-col-header',\n rowContent: headerRowContent,\n },\n });\n }\n sections.push({\n type: 'body',\n key: 'body',\n liquid: true,\n chunk: { content: bodyContent },\n });\n return (createElement(ViewRoot, { viewSpec: context.viewSpec }, function (rootElRef, classNames) { return (createElement(\"div\", { ref: rootElRef, className: ['fc-daygrid'].concat(classNames).join(' ') },\n createElement(SimpleScrollGrid, { liquid: !props.isHeightAuto && !props.forPrint, collapsibleWidth: props.forPrint, cols: [] /* TODO: make optional? */, sections: sections }))); }));\n };\n TableView.prototype.renderHScrollLayout = function (headerRowContent, bodyContent, colCnt, dayMinWidth) {\n var ScrollGrid = this.context.pluginHooks.scrollGridImpl;\n if (!ScrollGrid) {\n throw new Error('No ScrollGrid implementation');\n }\n var _a = this, props = _a.props, context = _a.context;\n var stickyHeaderDates = !props.forPrint && getStickyHeaderDates(context.options);\n var stickyFooterScrollbar = !props.forPrint && getStickyFooterScrollbar(context.options);\n var sections = [];\n if (headerRowContent) {\n sections.push({\n type: 'header',\n key: 'header',\n isSticky: stickyHeaderDates,\n chunks: [{\n key: 'main',\n elRef: this.headerElRef,\n tableClassName: 'fc-col-header',\n rowContent: headerRowContent,\n }],\n });\n }\n sections.push({\n type: 'body',\n key: 'body',\n liquid: true,\n chunks: [{\n key: 'main',\n content: bodyContent,\n }],\n });\n if (stickyFooterScrollbar) {\n sections.push({\n type: 'footer',\n key: 'footer',\n isSticky: true,\n chunks: [{\n key: 'main',\n content: renderScrollShim,\n }],\n });\n }\n return (createElement(ViewRoot, { viewSpec: context.viewSpec }, function (rootElRef, classNames) { return (createElement(\"div\", { ref: rootElRef, className: ['fc-daygrid'].concat(classNames).join(' ') },\n createElement(ScrollGrid, { liquid: !props.isHeightAuto && !props.forPrint, collapsibleWidth: props.forPrint, colGroups: [{ cols: [{ span: colCnt, minWidth: dayMinWidth }] }], sections: sections }))); }));\n };\n return TableView;\n}(DateComponent));\n\nfunction splitSegsByRow(segs, rowCnt) {\n var byRow = [];\n for (var i = 0; i < rowCnt; i += 1) {\n byRow[i] = [];\n }\n for (var _i = 0, segs_1 = segs; _i < segs_1.length; _i++) {\n var seg = segs_1[_i];\n byRow[seg.row].push(seg);\n }\n return byRow;\n}\nfunction splitSegsByFirstCol(segs, colCnt) {\n var byCol = [];\n for (var i = 0; i < colCnt; i += 1) {\n byCol[i] = [];\n }\n for (var _i = 0, segs_2 = segs; _i < segs_2.length; _i++) {\n var seg = segs_2[_i];\n byCol[seg.firstCol].push(seg);\n }\n return byCol;\n}\nfunction splitInteractionByRow(ui, rowCnt) {\n var byRow = [];\n if (!ui) {\n for (var i = 0; i < rowCnt; i += 1) {\n byRow[i] = null;\n }\n }\n else {\n for (var i = 0; i < rowCnt; i += 1) {\n byRow[i] = {\n affectedInstances: ui.affectedInstances,\n isEvent: ui.isEvent,\n segs: [],\n };\n }\n for (var _i = 0, _a = ui.segs; _i < _a.length; _i++) {\n var seg = _a[_i];\n byRow[seg.row].segs.push(seg);\n }\n }\n return byRow;\n}\n\nvar TableCellTop = /** @class */ (function (_super) {\n __extends(TableCellTop, _super);\n function TableCellTop() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n TableCellTop.prototype.render = function () {\n var props = this.props;\n var navLinkAttrs = buildNavLinkAttrs(this.context, props.date);\n return (createElement(DayCellContent, { date: props.date, dateProfile: props.dateProfile, todayRange: props.todayRange, showDayNumber: props.showDayNumber, extraHookProps: props.extraHookProps, defaultContent: renderTopInner }, function (innerElRef, innerContent) { return ((innerContent || props.forceDayTop) && (createElement(\"div\", { className: \"fc-daygrid-day-top\", ref: innerElRef },\n createElement(\"a\", __assign({ id: props.dayNumberId, className: \"fc-daygrid-day-number\" }, navLinkAttrs), innerContent || createElement(Fragment, null, \"\\u00A0\"))))); }));\n };\n return TableCellTop;\n}(BaseComponent));\nfunction renderTopInner(props) {\n return props.dayNumberText;\n}\n\nvar DEFAULT_TABLE_EVENT_TIME_FORMAT = createFormatter({\n hour: 'numeric',\n minute: '2-digit',\n omitZeroMinute: true,\n meridiem: 'narrow',\n});\nfunction hasListItemDisplay(seg) {\n var display = seg.eventRange.ui.display;\n return display === 'list-item' || (display === 'auto' &&\n !seg.eventRange.def.allDay &&\n seg.firstCol === seg.lastCol && // can't be multi-day\n seg.isStart && // \"\n seg.isEnd // \"\n );\n}\n\nvar TableBlockEvent = /** @class */ (function (_super) {\n __extends(TableBlockEvent, _super);\n function TableBlockEvent() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n TableBlockEvent.prototype.render = function () {\n var props = this.props;\n return (createElement(StandardEvent, __assign({}, props, { extraClassNames: ['fc-daygrid-event', 'fc-daygrid-block-event', 'fc-h-event'], defaultTimeFormat: DEFAULT_TABLE_EVENT_TIME_FORMAT, defaultDisplayEventEnd: props.defaultDisplayEventEnd, disableResizing: !props.seg.eventRange.def.allDay })));\n };\n return TableBlockEvent;\n}(BaseComponent));\n\nvar TableListItemEvent = /** @class */ (function (_super) {\n __extends(TableListItemEvent, _super);\n function TableListItemEvent() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n TableListItemEvent.prototype.render = function () {\n var _a = this, props = _a.props, context = _a.context;\n var timeFormat = context.options.eventTimeFormat || DEFAULT_TABLE_EVENT_TIME_FORMAT;\n var timeText = buildSegTimeText(props.seg, timeFormat, context, true, props.defaultDisplayEventEnd);\n return (createElement(EventRoot, { seg: props.seg, timeText: timeText, defaultContent: renderInnerContent, isDragging: props.isDragging, isResizing: false, isDateSelecting: false, isSelected: props.isSelected, isPast: props.isPast, isFuture: props.isFuture, isToday: props.isToday }, function (rootElRef, classNames, innerElRef, innerContent) { return ( // we don't use styles!\n createElement(\"a\", __assign({ className: ['fc-daygrid-event', 'fc-daygrid-dot-event'].concat(classNames).join(' '), ref: rootElRef }, getSegAnchorAttrs(props.seg, context)), innerContent)); }));\n };\n return TableListItemEvent;\n}(BaseComponent));\nfunction renderInnerContent(innerProps) {\n return (createElement(Fragment, null,\n createElement(\"div\", { className: \"fc-daygrid-event-dot\", style: { borderColor: innerProps.borderColor || innerProps.backgroundColor } }),\n innerProps.timeText && (createElement(\"div\", { className: \"fc-event-time\" }, innerProps.timeText)),\n createElement(\"div\", { className: \"fc-event-title\" }, innerProps.event.title || createElement(Fragment, null, \"\\u00A0\"))));\n}\n\nvar TableCellMoreLink = /** @class */ (function (_super) {\n __extends(TableCellMoreLink, _super);\n function TableCellMoreLink() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.compileSegs = memoize(compileSegs);\n return _this;\n }\n TableCellMoreLink.prototype.render = function () {\n var props = this.props;\n var _a = this.compileSegs(props.singlePlacements), allSegs = _a.allSegs, invisibleSegs = _a.invisibleSegs;\n return (createElement(MoreLinkRoot, { dateProfile: props.dateProfile, todayRange: props.todayRange, allDayDate: props.allDayDate, moreCnt: props.moreCnt, allSegs: allSegs, hiddenSegs: invisibleSegs, alignmentElRef: props.alignmentElRef, alignGridTop: props.alignGridTop, extraDateSpan: props.extraDateSpan, popoverContent: function () {\n var isForcedInvisible = (props.eventDrag ? props.eventDrag.affectedInstances : null) ||\n (props.eventResize ? props.eventResize.affectedInstances : null) ||\n {};\n return (createElement(Fragment, null, allSegs.map(function (seg) {\n var instanceId = seg.eventRange.instance.instanceId;\n return (createElement(\"div\", { className: \"fc-daygrid-event-harness\", key: instanceId, style: {\n visibility: isForcedInvisible[instanceId] ? 'hidden' : '',\n } }, hasListItemDisplay(seg) ? (createElement(TableListItemEvent, __assign({ seg: seg, isDragging: false, isSelected: instanceId === props.eventSelection, defaultDisplayEventEnd: false }, getSegMeta(seg, props.todayRange)))) : (createElement(TableBlockEvent, __assign({ seg: seg, isDragging: false, isResizing: false, isDateSelecting: false, isSelected: instanceId === props.eventSelection, defaultDisplayEventEnd: false }, getSegMeta(seg, props.todayRange))))));\n })));\n } }, function (rootElRef, classNames, innerElRef, innerContent, handleClick, title, isExpanded, popoverId) { return (createElement(\"a\", __assign({ ref: rootElRef, className: ['fc-daygrid-more-link'].concat(classNames).join(' '), title: title, \"aria-expanded\": isExpanded, \"aria-controls\": popoverId }, createAriaClickAttrs(handleClick)), innerContent)); }));\n };\n return TableCellMoreLink;\n}(BaseComponent));\nfunction compileSegs(singlePlacements) {\n var allSegs = [];\n var invisibleSegs = [];\n for (var _i = 0, singlePlacements_1 = singlePlacements; _i < singlePlacements_1.length; _i++) {\n var placement = singlePlacements_1[_i];\n allSegs.push(placement.seg);\n if (!placement.isVisible) {\n invisibleSegs.push(placement.seg);\n }\n }\n return { allSegs: allSegs, invisibleSegs: invisibleSegs };\n}\n\nvar DEFAULT_WEEK_NUM_FORMAT = createFormatter({ week: 'narrow' });\nvar TableCell = /** @class */ (function (_super) {\n __extends(TableCell, _super);\n function TableCell() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.rootElRef = createRef();\n _this.state = {\n dayNumberId: getUniqueDomId(),\n };\n _this.handleRootEl = function (el) {\n setRef(_this.rootElRef, el);\n setRef(_this.props.elRef, el);\n };\n return _this;\n }\n TableCell.prototype.render = function () {\n var _a = this, context = _a.context, props = _a.props, state = _a.state, rootElRef = _a.rootElRef;\n var date = props.date, dateProfile = props.dateProfile;\n var navLinkAttrs = buildNavLinkAttrs(context, date, 'week');\n return (createElement(DayCellRoot, { date: date, dateProfile: dateProfile, todayRange: props.todayRange, showDayNumber: props.showDayNumber, extraHookProps: props.extraHookProps, elRef: this.handleRootEl }, function (dayElRef, dayClassNames, rootDataAttrs, isDisabled) { return (createElement(\"td\", __assign({ ref: dayElRef, role: \"gridcell\", className: ['fc-daygrid-day'].concat(dayClassNames, props.extraClassNames || []).join(' ') }, rootDataAttrs, props.extraDataAttrs, (props.showDayNumber ? { 'aria-labelledby': state.dayNumberId } : {})),\n createElement(\"div\", { className: \"fc-daygrid-day-frame fc-scrollgrid-sync-inner\", ref: props.innerElRef /* different from hook system! RENAME */ },\n props.showWeekNumber && (createElement(WeekNumberRoot, { date: date, defaultFormat: DEFAULT_WEEK_NUM_FORMAT }, function (weekElRef, weekClassNames, innerElRef, innerContent) { return (createElement(\"a\", __assign({ ref: weekElRef, className: ['fc-daygrid-week-number'].concat(weekClassNames).join(' ') }, navLinkAttrs), innerContent)); })),\n !isDisabled && (createElement(TableCellTop, { date: date, dateProfile: dateProfile, showDayNumber: props.showDayNumber, dayNumberId: state.dayNumberId, forceDayTop: props.forceDayTop, todayRange: props.todayRange, extraHookProps: props.extraHookProps })),\n createElement(\"div\", { className: \"fc-daygrid-day-events\", ref: props.fgContentElRef },\n props.fgContent,\n createElement(\"div\", { className: \"fc-daygrid-day-bottom\", style: { marginTop: props.moreMarginTop } },\n createElement(TableCellMoreLink, { allDayDate: date, singlePlacements: props.singlePlacements, moreCnt: props.moreCnt, alignmentElRef: rootElRef, alignGridTop: !props.showDayNumber, extraDateSpan: props.extraDateSpan, dateProfile: props.dateProfile, eventSelection: props.eventSelection, eventDrag: props.eventDrag, eventResize: props.eventResize, todayRange: props.todayRange }))),\n createElement(\"div\", { className: \"fc-daygrid-day-bg\" }, props.bgContent)))); }));\n };\n return TableCell;\n}(DateComponent));\n\nfunction computeFgSegPlacement(segs, // assumed already sorted\ndayMaxEvents, dayMaxEventRows, strictOrder, eventInstanceHeights, maxContentHeight, cells) {\n var hierarchy = new DayGridSegHierarchy();\n hierarchy.allowReslicing = true;\n hierarchy.strictOrder = strictOrder;\n if (dayMaxEvents === true || dayMaxEventRows === true) {\n hierarchy.maxCoord = maxContentHeight;\n hierarchy.hiddenConsumes = true;\n }\n else if (typeof dayMaxEvents === 'number') {\n hierarchy.maxStackCnt = dayMaxEvents;\n }\n else if (typeof dayMaxEventRows === 'number') {\n hierarchy.maxStackCnt = dayMaxEventRows;\n hierarchy.hiddenConsumes = true;\n }\n // create segInputs only for segs with known heights\n var segInputs = [];\n var unknownHeightSegs = [];\n for (var i = 0; i < segs.length; i += 1) {\n var seg = segs[i];\n var instanceId = seg.eventRange.instance.instanceId;\n var eventHeight = eventInstanceHeights[instanceId];\n if (eventHeight != null) {\n segInputs.push({\n index: i,\n thickness: eventHeight,\n span: {\n start: seg.firstCol,\n end: seg.lastCol + 1,\n },\n });\n }\n else {\n unknownHeightSegs.push(seg);\n }\n }\n var hiddenEntries = hierarchy.addSegs(segInputs);\n var segRects = hierarchy.toRects();\n var _a = placeRects(segRects, segs, cells), singleColPlacements = _a.singleColPlacements, multiColPlacements = _a.multiColPlacements, leftoverMargins = _a.leftoverMargins;\n var moreCnts = [];\n var moreMarginTops = [];\n // add segs with unknown heights\n for (var _i = 0, unknownHeightSegs_1 = unknownHeightSegs; _i < unknownHeightSegs_1.length; _i++) {\n var seg = unknownHeightSegs_1[_i];\n multiColPlacements[seg.firstCol].push({\n seg: seg,\n isVisible: false,\n isAbsolute: true,\n absoluteTop: 0,\n marginTop: 0,\n });\n for (var col = seg.firstCol; col <= seg.lastCol; col += 1) {\n singleColPlacements[col].push({\n seg: resliceSeg(seg, col, col + 1, cells),\n isVisible: false,\n isAbsolute: false,\n absoluteTop: 0,\n marginTop: 0,\n });\n }\n }\n // add the hidden entries\n for (var col = 0; col < cells.length; col += 1) {\n moreCnts.push(0);\n }\n for (var _b = 0, hiddenEntries_1 = hiddenEntries; _b < hiddenEntries_1.length; _b++) {\n var hiddenEntry = hiddenEntries_1[_b];\n var seg = segs[hiddenEntry.index];\n var hiddenSpan = hiddenEntry.span;\n multiColPlacements[hiddenSpan.start].push({\n seg: resliceSeg(seg, hiddenSpan.start, hiddenSpan.end, cells),\n isVisible: false,\n isAbsolute: true,\n absoluteTop: 0,\n marginTop: 0,\n });\n for (var col = hiddenSpan.start; col < hiddenSpan.end; col += 1) {\n moreCnts[col] += 1;\n singleColPlacements[col].push({\n seg: resliceSeg(seg, col, col + 1, cells),\n isVisible: false,\n isAbsolute: false,\n absoluteTop: 0,\n marginTop: 0,\n });\n }\n }\n // deal with leftover margins\n for (var col = 0; col < cells.length; col += 1) {\n moreMarginTops.push(leftoverMargins[col]);\n }\n return { singleColPlacements: singleColPlacements, multiColPlacements: multiColPlacements, moreCnts: moreCnts, moreMarginTops: moreMarginTops };\n}\n// rects ordered by top coord, then left\nfunction placeRects(allRects, segs, cells) {\n var rectsByEachCol = groupRectsByEachCol(allRects, cells.length);\n var singleColPlacements = [];\n var multiColPlacements = [];\n var leftoverMargins = [];\n for (var col = 0; col < cells.length; col += 1) {\n var rects = rectsByEachCol[col];\n // compute all static segs in singlePlacements\n var singlePlacements = [];\n var currentHeight = 0;\n var currentMarginTop = 0;\n for (var _i = 0, rects_1 = rects; _i < rects_1.length; _i++) {\n var rect = rects_1[_i];\n var seg = segs[rect.index];\n singlePlacements.push({\n seg: resliceSeg(seg, col, col + 1, cells),\n isVisible: true,\n isAbsolute: false,\n absoluteTop: rect.levelCoord,\n marginTop: rect.levelCoord - currentHeight,\n });\n currentHeight = rect.levelCoord + rect.thickness;\n }\n // compute mixed static/absolute segs in multiPlacements\n var multiPlacements = [];\n currentHeight = 0;\n currentMarginTop = 0;\n for (var _a = 0, rects_2 = rects; _a < rects_2.length; _a++) {\n var rect = rects_2[_a];\n var seg = segs[rect.index];\n var isAbsolute = rect.span.end - rect.span.start > 1; // multi-column?\n var isFirstCol = rect.span.start === col;\n currentMarginTop += rect.levelCoord - currentHeight; // amount of space since bottom of previous seg\n currentHeight = rect.levelCoord + rect.thickness; // height will now be bottom of current seg\n if (isAbsolute) {\n currentMarginTop += rect.thickness;\n if (isFirstCol) {\n multiPlacements.push({\n seg: resliceSeg(seg, rect.span.start, rect.span.end, cells),\n isVisible: true,\n isAbsolute: true,\n absoluteTop: rect.levelCoord,\n marginTop: 0,\n });\n }\n }\n else if (isFirstCol) {\n multiPlacements.push({\n seg: resliceSeg(seg, rect.span.start, rect.span.end, cells),\n isVisible: true,\n isAbsolute: false,\n absoluteTop: rect.levelCoord,\n marginTop: currentMarginTop, // claim the margin\n });\n currentMarginTop = 0;\n }\n }\n singleColPlacements.push(singlePlacements);\n multiColPlacements.push(multiPlacements);\n leftoverMargins.push(currentMarginTop);\n }\n return { singleColPlacements: singleColPlacements, multiColPlacements: multiColPlacements, leftoverMargins: leftoverMargins };\n}\nfunction groupRectsByEachCol(rects, colCnt) {\n var rectsByEachCol = [];\n for (var col = 0; col < colCnt; col += 1) {\n rectsByEachCol.push([]);\n }\n for (var _i = 0, rects_3 = rects; _i < rects_3.length; _i++) {\n var rect = rects_3[_i];\n for (var col = rect.span.start; col < rect.span.end; col += 1) {\n rectsByEachCol[col].push(rect);\n }\n }\n return rectsByEachCol;\n}\nfunction resliceSeg(seg, spanStart, spanEnd, cells) {\n if (seg.firstCol === spanStart && seg.lastCol === spanEnd - 1) {\n return seg;\n }\n var eventRange = seg.eventRange;\n var origRange = eventRange.range;\n var slicedRange = intersectRanges(origRange, {\n start: cells[spanStart].date,\n end: addDays(cells[spanEnd - 1].date, 1),\n });\n return __assign(__assign({}, seg), { firstCol: spanStart, lastCol: spanEnd - 1, eventRange: {\n def: eventRange.def,\n ui: __assign(__assign({}, eventRange.ui), { durationEditable: false }),\n instance: eventRange.instance,\n range: slicedRange,\n }, isStart: seg.isStart && slicedRange.start.valueOf() === origRange.start.valueOf(), isEnd: seg.isEnd && slicedRange.end.valueOf() === origRange.end.valueOf() });\n}\nvar DayGridSegHierarchy = /** @class */ (function (_super) {\n __extends(DayGridSegHierarchy, _super);\n function DayGridSegHierarchy() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n // config\n _this.hiddenConsumes = false;\n // allows us to keep hidden entries in the hierarchy so they take up space\n _this.forceHidden = {};\n return _this;\n }\n DayGridSegHierarchy.prototype.addSegs = function (segInputs) {\n var _this = this;\n var hiddenSegs = _super.prototype.addSegs.call(this, segInputs);\n var entriesByLevel = this.entriesByLevel;\n var excludeHidden = function (entry) { return !_this.forceHidden[buildEntryKey(entry)]; };\n // remove the forced-hidden segs\n for (var level = 0; level < entriesByLevel.length; level += 1) {\n entriesByLevel[level] = entriesByLevel[level].filter(excludeHidden);\n }\n return hiddenSegs;\n };\n DayGridSegHierarchy.prototype.handleInvalidInsertion = function (insertion, entry, hiddenEntries) {\n var _a = this, entriesByLevel = _a.entriesByLevel, forceHidden = _a.forceHidden;\n var touchingEntry = insertion.touchingEntry, touchingLevel = insertion.touchingLevel, touchingLateral = insertion.touchingLateral;\n if (this.hiddenConsumes && touchingEntry) {\n var touchingEntryId = buildEntryKey(touchingEntry);\n // if not already hidden\n if (!forceHidden[touchingEntryId]) {\n if (this.allowReslicing) {\n var placeholderEntry = __assign(__assign({}, touchingEntry), { span: intersectSpans(touchingEntry.span, entry.span) });\n var placeholderEntryId = buildEntryKey(placeholderEntry);\n forceHidden[placeholderEntryId] = true;\n entriesByLevel[touchingLevel][touchingLateral] = placeholderEntry; // replace touchingEntry with our placeholder\n this.splitEntry(touchingEntry, entry, hiddenEntries); // split up the touchingEntry, reinsert it\n }\n else {\n forceHidden[touchingEntryId] = true;\n hiddenEntries.push(touchingEntry);\n }\n }\n }\n return _super.prototype.handleInvalidInsertion.call(this, insertion, entry, hiddenEntries);\n };\n return DayGridSegHierarchy;\n}(SegHierarchy));\n\nvar TableRow = /** @class */ (function (_super) {\n __extends(TableRow, _super);\n function TableRow() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.cellElRefs = new RefMap(); // the
\n _this.frameElRefs = new RefMap(); // the fc-daygrid-day-frame\n _this.fgElRefs = new RefMap(); // the fc-daygrid-day-events\n _this.segHarnessRefs = new RefMap(); // indexed by \"instanceId:firstCol\"\n _this.rootElRef = createRef();\n _this.state = {\n framePositions: null,\n maxContentHeight: null,\n eventInstanceHeights: {},\n };\n return _this;\n }\n TableRow.prototype.render = function () {\n var _this = this;\n var _a = this, props = _a.props, state = _a.state, context = _a.context;\n var options = context.options;\n var colCnt = props.cells.length;\n var businessHoursByCol = splitSegsByFirstCol(props.businessHourSegs, colCnt);\n var bgEventSegsByCol = splitSegsByFirstCol(props.bgEventSegs, colCnt);\n var highlightSegsByCol = splitSegsByFirstCol(this.getHighlightSegs(), colCnt);\n var mirrorSegsByCol = splitSegsByFirstCol(this.getMirrorSegs(), colCnt);\n var _b = computeFgSegPlacement(sortEventSegs(props.fgEventSegs, options.eventOrder), props.dayMaxEvents, props.dayMaxEventRows, options.eventOrderStrict, state.eventInstanceHeights, state.maxContentHeight, props.cells), singleColPlacements = _b.singleColPlacements, multiColPlacements = _b.multiColPlacements, moreCnts = _b.moreCnts, moreMarginTops = _b.moreMarginTops;\n var isForcedInvisible = // TODO: messy way to compute this\n (props.eventDrag && props.eventDrag.affectedInstances) ||\n (props.eventResize && props.eventResize.affectedInstances) ||\n {};\n return (createElement(\"tr\", { ref: this.rootElRef, role: \"row\" },\n props.renderIntro && props.renderIntro(),\n props.cells.map(function (cell, col) {\n var normalFgNodes = _this.renderFgSegs(col, props.forPrint ? singleColPlacements[col] : multiColPlacements[col], props.todayRange, isForcedInvisible);\n var mirrorFgNodes = _this.renderFgSegs(col, buildMirrorPlacements(mirrorSegsByCol[col], multiColPlacements), props.todayRange, {}, Boolean(props.eventDrag), Boolean(props.eventResize), false);\n return (createElement(TableCell, { key: cell.key, elRef: _this.cellElRefs.createRef(cell.key), innerElRef: _this.frameElRefs.createRef(cell.key) /* FF
problem, but okay to use for left/right. TODO: rename prop */, dateProfile: props.dateProfile, date: cell.date, showDayNumber: props.showDayNumbers, showWeekNumber: props.showWeekNumbers && col === 0, forceDayTop: props.showWeekNumbers /* even displaying weeknum for row, not necessarily day */, todayRange: props.todayRange, eventSelection: props.eventSelection, eventDrag: props.eventDrag, eventResize: props.eventResize, extraHookProps: cell.extraHookProps, extraDataAttrs: cell.extraDataAttrs, extraClassNames: cell.extraClassNames, extraDateSpan: cell.extraDateSpan, moreCnt: moreCnts[col], moreMarginTop: moreMarginTops[col], singlePlacements: singleColPlacements[col], fgContentElRef: _this.fgElRefs.createRef(cell.key), fgContent: ( // Fragment scopes the keys\n createElement(Fragment, null,\n createElement(Fragment, null, normalFgNodes),\n createElement(Fragment, null, mirrorFgNodes))), bgContent: ( // Fragment scopes the keys\n createElement(Fragment, null,\n _this.renderFillSegs(highlightSegsByCol[col], 'highlight'),\n _this.renderFillSegs(businessHoursByCol[col], 'non-business'),\n _this.renderFillSegs(bgEventSegsByCol[col], 'bg-event'))) }));\n })));\n };\n TableRow.prototype.componentDidMount = function () {\n this.updateSizing(true);\n };\n TableRow.prototype.componentDidUpdate = function (prevProps, prevState) {\n var currentProps = this.props;\n this.updateSizing(!isPropsEqual(prevProps, currentProps));\n };\n TableRow.prototype.getHighlightSegs = function () {\n var props = this.props;\n if (props.eventDrag && props.eventDrag.segs.length) { // messy check\n return props.eventDrag.segs;\n }\n if (props.eventResize && props.eventResize.segs.length) { // messy check\n return props.eventResize.segs;\n }\n return props.dateSelectionSegs;\n };\n TableRow.prototype.getMirrorSegs = function () {\n var props = this.props;\n if (props.eventResize && props.eventResize.segs.length) { // messy check\n return props.eventResize.segs;\n }\n return [];\n };\n TableRow.prototype.renderFgSegs = function (col, segPlacements, todayRange, isForcedInvisible, isDragging, isResizing, isDateSelecting) {\n var context = this.context;\n var eventSelection = this.props.eventSelection;\n var framePositions = this.state.framePositions;\n var defaultDisplayEventEnd = this.props.cells.length === 1; // colCnt === 1\n var isMirror = isDragging || isResizing || isDateSelecting;\n var nodes = [];\n if (framePositions) {\n for (var _i = 0, segPlacements_1 = segPlacements; _i < segPlacements_1.length; _i++) {\n var placement = segPlacements_1[_i];\n var seg = placement.seg;\n var instanceId = seg.eventRange.instance.instanceId;\n var key = instanceId + ':' + col;\n var isVisible = placement.isVisible && !isForcedInvisible[instanceId];\n var isAbsolute = placement.isAbsolute;\n var left = '';\n var right = '';\n if (isAbsolute) {\n if (context.isRtl) {\n right = 0;\n left = framePositions.lefts[seg.lastCol] - framePositions.lefts[seg.firstCol];\n }\n else {\n left = 0;\n right = framePositions.rights[seg.firstCol] - framePositions.rights[seg.lastCol];\n }\n }\n /*\n known bug: events that are force to be list-item but span multiple days still take up space in later columns\n todo: in print view, for multi-day events, don't display title within non-start/end segs\n */\n nodes.push(createElement(\"div\", { className: 'fc-daygrid-event-harness' + (isAbsolute ? ' fc-daygrid-event-harness-abs' : ''), key: key, ref: isMirror ? null : this.segHarnessRefs.createRef(key), style: {\n visibility: isVisible ? '' : 'hidden',\n marginTop: isAbsolute ? '' : placement.marginTop,\n top: isAbsolute ? placement.absoluteTop : '',\n left: left,\n right: right,\n } }, hasListItemDisplay(seg) ? (createElement(TableListItemEvent, __assign({ seg: seg, isDragging: isDragging, isSelected: instanceId === eventSelection, defaultDisplayEventEnd: defaultDisplayEventEnd }, getSegMeta(seg, todayRange)))) : (createElement(TableBlockEvent, __assign({ seg: seg, isDragging: isDragging, isResizing: isResizing, isDateSelecting: isDateSelecting, isSelected: instanceId === eventSelection, defaultDisplayEventEnd: defaultDisplayEventEnd }, getSegMeta(seg, todayRange))))));\n }\n }\n return nodes;\n };\n TableRow.prototype.renderFillSegs = function (segs, fillType) {\n var isRtl = this.context.isRtl;\n var todayRange = this.props.todayRange;\n var framePositions = this.state.framePositions;\n var nodes = [];\n if (framePositions) {\n for (var _i = 0, segs_1 = segs; _i < segs_1.length; _i++) {\n var seg = segs_1[_i];\n var leftRightCss = isRtl ? {\n right: 0,\n left: framePositions.lefts[seg.lastCol] - framePositions.lefts[seg.firstCol],\n } : {\n left: 0,\n right: framePositions.rights[seg.firstCol] - framePositions.rights[seg.lastCol],\n };\n nodes.push(createElement(\"div\", { key: buildEventRangeKey(seg.eventRange), className: \"fc-daygrid-bg-harness\", style: leftRightCss }, fillType === 'bg-event' ?\n createElement(BgEvent, __assign({ seg: seg }, getSegMeta(seg, todayRange))) :\n renderFill(fillType)));\n }\n }\n return createElement.apply(void 0, __spreadArray([Fragment, {}], nodes));\n };\n TableRow.prototype.updateSizing = function (isExternalSizingChange) {\n var _a = this, props = _a.props, frameElRefs = _a.frameElRefs;\n if (!props.forPrint &&\n props.clientWidth !== null // positioning ready?\n ) {\n if (isExternalSizingChange) {\n var frameEls = props.cells.map(function (cell) { return frameElRefs.currentMap[cell.key]; });\n if (frameEls.length) {\n var originEl = this.rootElRef.current;\n this.setState({\n framePositions: new PositionCache(originEl, frameEls, true, // isHorizontal\n false),\n });\n }\n }\n var oldInstanceHeights = this.state.eventInstanceHeights;\n var newInstanceHeights = this.queryEventInstanceHeights();\n var limitByContentHeight = props.dayMaxEvents === true || props.dayMaxEventRows === true;\n this.safeSetState({\n // HACK to prevent oscillations of events being shown/hidden from max-event-rows\n // Essentially, once you compute an element's height, never null-out.\n // TODO: always display all events, as visibility:hidden?\n eventInstanceHeights: __assign(__assign({}, oldInstanceHeights), newInstanceHeights),\n maxContentHeight: limitByContentHeight ? this.computeMaxContentHeight() : null,\n });\n }\n };\n TableRow.prototype.queryEventInstanceHeights = function () {\n var segElMap = this.segHarnessRefs.currentMap;\n var eventInstanceHeights = {};\n // get the max height amongst instance segs\n for (var key in segElMap) {\n var height = Math.round(segElMap[key].getBoundingClientRect().height);\n var instanceId = key.split(':')[0]; // deconstruct how renderFgSegs makes the key\n eventInstanceHeights[instanceId] = Math.max(eventInstanceHeights[instanceId] || 0, height);\n }\n return eventInstanceHeights;\n };\n TableRow.prototype.computeMaxContentHeight = function () {\n var firstKey = this.props.cells[0].key;\n var cellEl = this.cellElRefs.currentMap[firstKey];\n var fcContainerEl = this.fgElRefs.currentMap[firstKey];\n return cellEl.getBoundingClientRect().bottom - fcContainerEl.getBoundingClientRect().top;\n };\n TableRow.prototype.getCellEls = function () {\n var elMap = this.cellElRefs.currentMap;\n return this.props.cells.map(function (cell) { return elMap[cell.key]; });\n };\n return TableRow;\n}(DateComponent));\nTableRow.addStateEquality({\n eventInstanceHeights: isPropsEqual,\n});\nfunction buildMirrorPlacements(mirrorSegs, colPlacements) {\n if (!mirrorSegs.length) {\n return [];\n }\n var topsByInstanceId = buildAbsoluteTopHash(colPlacements); // TODO: cache this at first render?\n return mirrorSegs.map(function (seg) { return ({\n seg: seg,\n isVisible: true,\n isAbsolute: true,\n absoluteTop: topsByInstanceId[seg.eventRange.instance.instanceId],\n marginTop: 0,\n }); });\n}\nfunction buildAbsoluteTopHash(colPlacements) {\n var topsByInstanceId = {};\n for (var _i = 0, colPlacements_1 = colPlacements; _i < colPlacements_1.length; _i++) {\n var placements = colPlacements_1[_i];\n for (var _a = 0, placements_1 = placements; _a < placements_1.length; _a++) {\n var placement = placements_1[_a];\n topsByInstanceId[placement.seg.eventRange.instance.instanceId] = placement.absoluteTop;\n }\n }\n return topsByInstanceId;\n}\n\nvar Table = /** @class */ (function (_super) {\n __extends(Table, _super);\n function Table() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.splitBusinessHourSegs = memoize(splitSegsByRow);\n _this.splitBgEventSegs = memoize(splitSegsByRow);\n _this.splitFgEventSegs = memoize(splitSegsByRow);\n _this.splitDateSelectionSegs = memoize(splitSegsByRow);\n _this.splitEventDrag = memoize(splitInteractionByRow);\n _this.splitEventResize = memoize(splitInteractionByRow);\n _this.rowRefs = new RefMap();\n _this.handleRootEl = function (rootEl) {\n _this.rootEl = rootEl;\n if (rootEl) {\n _this.context.registerInteractiveComponent(_this, {\n el: rootEl,\n isHitComboAllowed: _this.props.isHitComboAllowed,\n });\n }\n else {\n _this.context.unregisterInteractiveComponent(_this);\n }\n };\n return _this;\n }\n Table.prototype.render = function () {\n var _this = this;\n var props = this.props;\n var dateProfile = props.dateProfile, dayMaxEventRows = props.dayMaxEventRows, dayMaxEvents = props.dayMaxEvents, expandRows = props.expandRows;\n var rowCnt = props.cells.length;\n var businessHourSegsByRow = this.splitBusinessHourSegs(props.businessHourSegs, rowCnt);\n var bgEventSegsByRow = this.splitBgEventSegs(props.bgEventSegs, rowCnt);\n var fgEventSegsByRow = this.splitFgEventSegs(props.fgEventSegs, rowCnt);\n var dateSelectionSegsByRow = this.splitDateSelectionSegs(props.dateSelectionSegs, rowCnt);\n var eventDragByRow = this.splitEventDrag(props.eventDrag, rowCnt);\n var eventResizeByRow = this.splitEventResize(props.eventResize, rowCnt);\n var limitViaBalanced = dayMaxEvents === true || dayMaxEventRows === true;\n // if rows can't expand to fill fixed height, can't do balanced-height event limit\n // TODO: best place to normalize these options?\n if (limitViaBalanced && !expandRows) {\n limitViaBalanced = false;\n dayMaxEventRows = null;\n dayMaxEvents = null;\n }\n var classNames = [\n 'fc-daygrid-body',\n limitViaBalanced ? 'fc-daygrid-body-balanced' : 'fc-daygrid-body-unbalanced',\n expandRows ? '' : 'fc-daygrid-body-natural', // will height of one row depend on the others?\n ];\n return (createElement(\"div\", { className: classNames.join(' '), ref: this.handleRootEl, style: {\n // these props are important to give this wrapper correct dimensions for interactions\n // TODO: if we set it here, can we avoid giving to inner tables?\n width: props.clientWidth,\n minWidth: props.tableMinWidth,\n } },\n createElement(NowTimer, { unit: \"day\" }, function (nowDate, todayRange) { return (createElement(Fragment, null,\n createElement(\"table\", { role: \"presentation\", className: \"fc-scrollgrid-sync-table\", style: {\n width: props.clientWidth,\n minWidth: props.tableMinWidth,\n height: expandRows ? props.clientHeight : '',\n } },\n props.colGroupNode,\n createElement(\"tbody\", { role: \"presentation\" }, props.cells.map(function (cells, row) { return (createElement(TableRow, { ref: _this.rowRefs.createRef(row), key: cells.length\n ? cells[0].date.toISOString() /* best? or put key on cell? or use diff formatter? */\n : row // in case there are no cells (like when resource view is loading)\n , showDayNumbers: rowCnt > 1, showWeekNumbers: props.showWeekNumbers, todayRange: todayRange, dateProfile: dateProfile, cells: cells, renderIntro: props.renderRowIntro, businessHourSegs: businessHourSegsByRow[row], eventSelection: props.eventSelection, bgEventSegs: bgEventSegsByRow[row].filter(isSegAllDay) /* hack */, fgEventSegs: fgEventSegsByRow[row], dateSelectionSegs: dateSelectionSegsByRow[row], eventDrag: eventDragByRow[row], eventResize: eventResizeByRow[row], dayMaxEvents: dayMaxEvents, dayMaxEventRows: dayMaxEventRows, clientWidth: props.clientWidth, clientHeight: props.clientHeight, forPrint: props.forPrint })); }))))); })));\n };\n // Hit System\n // ----------------------------------------------------------------------------------------------------\n Table.prototype.prepareHits = function () {\n this.rowPositions = new PositionCache(this.rootEl, this.rowRefs.collect().map(function (rowObj) { return rowObj.getCellEls()[0]; }), // first cell el in each row. TODO: not optimal\n false, true);\n this.colPositions = new PositionCache(this.rootEl, this.rowRefs.currentMap[0].getCellEls(), // cell els in first row\n true, // horizontal\n false);\n };\n Table.prototype.queryHit = function (positionLeft, positionTop) {\n var _a = this, colPositions = _a.colPositions, rowPositions = _a.rowPositions;\n var col = colPositions.leftToIndex(positionLeft);\n var row = rowPositions.topToIndex(positionTop);\n if (row != null && col != null) {\n var cell = this.props.cells[row][col];\n return {\n dateProfile: this.props.dateProfile,\n dateSpan: __assign({ range: this.getCellRange(row, col), allDay: true }, cell.extraDateSpan),\n dayEl: this.getCellEl(row, col),\n rect: {\n left: colPositions.lefts[col],\n right: colPositions.rights[col],\n top: rowPositions.tops[row],\n bottom: rowPositions.bottoms[row],\n },\n layer: 0,\n };\n }\n return null;\n };\n Table.prototype.getCellEl = function (row, col) {\n return this.rowRefs.currentMap[row].getCellEls()[col]; // TODO: not optimal\n };\n Table.prototype.getCellRange = function (row, col) {\n var start = this.props.cells[row][col].date;\n var end = addDays(start, 1);\n return { start: start, end: end };\n };\n return Table;\n}(DateComponent));\nfunction isSegAllDay(seg) {\n return seg.eventRange.def.allDay;\n}\n\nvar DayTableSlicer = /** @class */ (function (_super) {\n __extends(DayTableSlicer, _super);\n function DayTableSlicer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.forceDayIfListItem = true;\n return _this;\n }\n DayTableSlicer.prototype.sliceRange = function (dateRange, dayTableModel) {\n return dayTableModel.sliceRange(dateRange);\n };\n return DayTableSlicer;\n}(Slicer));\n\nvar DayTable = /** @class */ (function (_super) {\n __extends(DayTable, _super);\n function DayTable() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.slicer = new DayTableSlicer();\n _this.tableRef = createRef();\n return _this;\n }\n DayTable.prototype.render = function () {\n var _a = this, props = _a.props, context = _a.context;\n return (createElement(Table, __assign({ ref: this.tableRef }, this.slicer.sliceProps(props, props.dateProfile, props.nextDayThreshold, context, props.dayTableModel), { dateProfile: props.dateProfile, cells: props.dayTableModel.cells, colGroupNode: props.colGroupNode, tableMinWidth: props.tableMinWidth, renderRowIntro: props.renderRowIntro, dayMaxEvents: props.dayMaxEvents, dayMaxEventRows: props.dayMaxEventRows, showWeekNumbers: props.showWeekNumbers, expandRows: props.expandRows, headerAlignElRef: props.headerAlignElRef, clientWidth: props.clientWidth, clientHeight: props.clientHeight, forPrint: props.forPrint })));\n };\n return DayTable;\n}(DateComponent));\n\nvar DayTableView = /** @class */ (function (_super) {\n __extends(DayTableView, _super);\n function DayTableView() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.buildDayTableModel = memoize(buildDayTableModel);\n _this.headerRef = createRef();\n _this.tableRef = createRef();\n return _this;\n }\n DayTableView.prototype.render = function () {\n var _this = this;\n var _a = this.context, options = _a.options, dateProfileGenerator = _a.dateProfileGenerator;\n var props = this.props;\n var dayTableModel = this.buildDayTableModel(props.dateProfile, dateProfileGenerator);\n var headerContent = options.dayHeaders && (createElement(DayHeader, { ref: this.headerRef, dateProfile: props.dateProfile, dates: dayTableModel.headerDates, datesRepDistinctDays: dayTableModel.rowCnt === 1 }));\n var bodyContent = function (contentArg) { return (createElement(DayTable, { ref: _this.tableRef, dateProfile: props.dateProfile, dayTableModel: dayTableModel, businessHours: props.businessHours, dateSelection: props.dateSelection, eventStore: props.eventStore, eventUiBases: props.eventUiBases, eventSelection: props.eventSelection, eventDrag: props.eventDrag, eventResize: props.eventResize, nextDayThreshold: options.nextDayThreshold, colGroupNode: contentArg.tableColGroupNode, tableMinWidth: contentArg.tableMinWidth, dayMaxEvents: options.dayMaxEvents, dayMaxEventRows: options.dayMaxEventRows, showWeekNumbers: options.weekNumbers, expandRows: !props.isHeightAuto, headerAlignElRef: _this.headerElRef, clientWidth: contentArg.clientWidth, clientHeight: contentArg.clientHeight, forPrint: props.forPrint })); };\n return options.dayMinWidth\n ? this.renderHScrollLayout(headerContent, bodyContent, dayTableModel.colCnt, options.dayMinWidth)\n : this.renderSimpleLayout(headerContent, bodyContent);\n };\n return DayTableView;\n}(TableView));\nfunction buildDayTableModel(dateProfile, dateProfileGenerator) {\n var daySeries = new DaySeriesModel(dateProfile.renderRange, dateProfileGenerator);\n return new DayTableModel(daySeries, /year|month|week/.test(dateProfile.currentRangeUnit));\n}\n\nvar TableDateProfileGenerator = /** @class */ (function (_super) {\n __extends(TableDateProfileGenerator, _super);\n function TableDateProfileGenerator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n // Computes the date range that will be rendered.\n TableDateProfileGenerator.prototype.buildRenderRange = function (currentRange, currentRangeUnit, isRangeAllDay) {\n var dateEnv = this.props.dateEnv;\n var renderRange = _super.prototype.buildRenderRange.call(this, currentRange, currentRangeUnit, isRangeAllDay);\n var start = renderRange.start;\n var end = renderRange.end;\n var endOfWeek;\n // year and month views should be aligned with weeks. this is already done for week\n if (/^(year|month)$/.test(currentRangeUnit)) {\n start = dateEnv.startOfWeek(start);\n // make end-of-week if not already\n endOfWeek = dateEnv.startOfWeek(end);\n if (endOfWeek.valueOf() !== end.valueOf()) {\n end = addWeeks(endOfWeek, 1);\n }\n }\n // ensure 6 weeks\n if (this.props.monthMode &&\n this.props.fixedWeekCount) {\n var rowCnt = Math.ceil(// could be partial weeks due to hiddenDays\n diffWeeks(start, end));\n end = addWeeks(end, 6 - rowCnt);\n }\n return { start: start, end: end };\n };\n return TableDateProfileGenerator;\n}(DateProfileGenerator));\n\nvar main = createPlugin({\n initialView: 'dayGridMonth',\n views: {\n dayGrid: {\n component: DayTableView,\n dateProfileGeneratorClass: TableDateProfileGenerator,\n },\n dayGridDay: {\n type: 'dayGrid',\n duration: { days: 1 },\n },\n dayGridWeek: {\n type: 'dayGrid',\n duration: { weeks: 1 },\n },\n dayGridMonth: {\n type: 'dayGrid',\n duration: { months: 1 },\n monthMode: true,\n fixedWeekCount: true,\n },\n },\n});\n\nexport default main;\nexport { DayTableView as DayGridView, DayTable, DayTableSlicer, Table, TableView, buildDayTableModel };\n","/*!\nFullCalendar v5.11.4\nDocs & License: https://fullcalendar.io/\n(c) 2022 Adam Shaw\n*/\nimport { config, elementClosest, Emitter, applyStyle, whenTransitionDone, removeElement, ScrollController, ElementScrollController, computeInnerRect, WindowScrollController, getElRoot, preventSelection, preventContextMenu, allowSelection, allowContextMenu, ElementDragging, computeRect, getClippingParents, pointInsideRect, isDateSpansEqual, constrainPoint, intersectRects, getRectCenter, diffPoints, mapHash, rangeContainsRange, interactionSettingsToStore, Interaction, isDateSelectionValid, enableCursor, disableCursor, triggerDateSelect, compareNumbers, getElSeg, getRelevantEvents, EventApi, createEmptyEventStore, applyMutationToEventStore, isInteractionValid, buildEventApis, interactionSettingsStore, startOfDay, diffDates, createDuration, getEventTargetViaRoot, identity, eventTupleToStore, parseDragMeta, elementMatches, refineEventDef, parseEventDef, getDefaultEventEnd, createEventInstance, BASE_OPTION_DEFAULTS, createPlugin } from '@fullcalendar/common';\nimport { __extends, __assign } from 'tslib';\n\nconfig.touchMouseIgnoreWait = 500;\nvar ignoreMouseDepth = 0;\nvar listenerCnt = 0;\nvar isWindowTouchMoveCancelled = false;\n/*\nUses a \"pointer\" abstraction, which monitors UI events for both mouse and touch.\nTracks when the pointer \"drags\" on a certain element, meaning down+move+up.\n\nAlso, tracks if there was touch-scrolling.\nAlso, can prevent touch-scrolling from happening.\nAlso, can fire pointermove events when scrolling happens underneath, even when no real pointer movement.\n\nemits:\n- pointerdown\n- pointermove\n- pointerup\n*/\nvar PointerDragging = /** @class */ (function () {\n function PointerDragging(containerEl) {\n var _this = this;\n this.subjectEl = null;\n // options that can be directly assigned by caller\n this.selector = ''; // will cause subjectEl in all emitted events to be this element\n this.handleSelector = '';\n this.shouldIgnoreMove = false;\n this.shouldWatchScroll = true; // for simulating pointermove on scroll\n // internal states\n this.isDragging = false;\n this.isTouchDragging = false;\n this.wasTouchScroll = false;\n // Mouse\n // ----------------------------------------------------------------------------------------------------\n this.handleMouseDown = function (ev) {\n if (!_this.shouldIgnoreMouse() &&\n isPrimaryMouseButton(ev) &&\n _this.tryStart(ev)) {\n var pev = _this.createEventFromMouse(ev, true);\n _this.emitter.trigger('pointerdown', pev);\n _this.initScrollWatch(pev);\n if (!_this.shouldIgnoreMove) {\n document.addEventListener('mousemove', _this.handleMouseMove);\n }\n document.addEventListener('mouseup', _this.handleMouseUp);\n }\n };\n this.handleMouseMove = function (ev) {\n var pev = _this.createEventFromMouse(ev);\n _this.recordCoords(pev);\n _this.emitter.trigger('pointermove', pev);\n };\n this.handleMouseUp = function (ev) {\n document.removeEventListener('mousemove', _this.handleMouseMove);\n document.removeEventListener('mouseup', _this.handleMouseUp);\n _this.emitter.trigger('pointerup', _this.createEventFromMouse(ev));\n _this.cleanup(); // call last so that pointerup has access to props\n };\n // Touch\n // ----------------------------------------------------------------------------------------------------\n this.handleTouchStart = function (ev) {\n if (_this.tryStart(ev)) {\n _this.isTouchDragging = true;\n var pev = _this.createEventFromTouch(ev, true);\n _this.emitter.trigger('pointerdown', pev);\n _this.initScrollWatch(pev);\n // unlike mouse, need to attach to target, not document\n // https://stackoverflow.com/a/45760014\n var targetEl = ev.target;\n if (!_this.shouldIgnoreMove) {\n targetEl.addEventListener('touchmove', _this.handleTouchMove);\n }\n targetEl.addEventListener('touchend', _this.handleTouchEnd);\n targetEl.addEventListener('touchcancel', _this.handleTouchEnd); // treat it as a touch end\n // attach a handler to get called when ANY scroll action happens on the page.\n // this was impossible to do with normal on/off because 'scroll' doesn't bubble.\n // http://stackoverflow.com/a/32954565/96342\n window.addEventListener('scroll', _this.handleTouchScroll, true);\n }\n };\n this.handleTouchMove = function (ev) {\n var pev = _this.createEventFromTouch(ev);\n _this.recordCoords(pev);\n _this.emitter.trigger('pointermove', pev);\n };\n this.handleTouchEnd = function (ev) {\n if (_this.isDragging) { // done to guard against touchend followed by touchcancel\n var targetEl = ev.target;\n targetEl.removeEventListener('touchmove', _this.handleTouchMove);\n targetEl.removeEventListener('touchend', _this.handleTouchEnd);\n targetEl.removeEventListener('touchcancel', _this.handleTouchEnd);\n window.removeEventListener('scroll', _this.handleTouchScroll, true); // useCaptured=true\n _this.emitter.trigger('pointerup', _this.createEventFromTouch(ev));\n _this.cleanup(); // call last so that pointerup has access to props\n _this.isTouchDragging = false;\n startIgnoringMouse();\n }\n };\n this.handleTouchScroll = function () {\n _this.wasTouchScroll = true;\n };\n this.handleScroll = function (ev) {\n if (!_this.shouldIgnoreMove) {\n var pageX = (window.pageXOffset - _this.prevScrollX) + _this.prevPageX;\n var pageY = (window.pageYOffset - _this.prevScrollY) + _this.prevPageY;\n _this.emitter.trigger('pointermove', {\n origEvent: ev,\n isTouch: _this.isTouchDragging,\n subjectEl: _this.subjectEl,\n pageX: pageX,\n pageY: pageY,\n deltaX: pageX - _this.origPageX,\n deltaY: pageY - _this.origPageY,\n });\n }\n };\n this.containerEl = containerEl;\n this.emitter = new Emitter();\n containerEl.addEventListener('mousedown', this.handleMouseDown);\n containerEl.addEventListener('touchstart', this.handleTouchStart, { passive: true });\n listenerCreated();\n }\n PointerDragging.prototype.destroy = function () {\n this.containerEl.removeEventListener('mousedown', this.handleMouseDown);\n this.containerEl.removeEventListener('touchstart', this.handleTouchStart, { passive: true });\n listenerDestroyed();\n };\n PointerDragging.prototype.tryStart = function (ev) {\n var subjectEl = this.querySubjectEl(ev);\n var downEl = ev.target;\n if (subjectEl &&\n (!this.handleSelector || elementClosest(downEl, this.handleSelector))) {\n this.subjectEl = subjectEl;\n this.isDragging = true; // do this first so cancelTouchScroll will work\n this.wasTouchScroll = false;\n return true;\n }\n return false;\n };\n PointerDragging.prototype.cleanup = function () {\n isWindowTouchMoveCancelled = false;\n this.isDragging = false;\n this.subjectEl = null;\n // keep wasTouchScroll around for later access\n this.destroyScrollWatch();\n };\n PointerDragging.prototype.querySubjectEl = function (ev) {\n if (this.selector) {\n return elementClosest(ev.target, this.selector);\n }\n return this.containerEl;\n };\n PointerDragging.prototype.shouldIgnoreMouse = function () {\n return ignoreMouseDepth || this.isTouchDragging;\n };\n // can be called by user of this class, to cancel touch-based scrolling for the current drag\n PointerDragging.prototype.cancelTouchScroll = function () {\n if (this.isDragging) {\n isWindowTouchMoveCancelled = true;\n }\n };\n // Scrolling that simulates pointermoves\n // ----------------------------------------------------------------------------------------------------\n PointerDragging.prototype.initScrollWatch = function (ev) {\n if (this.shouldWatchScroll) {\n this.recordCoords(ev);\n window.addEventListener('scroll', this.handleScroll, true); // useCapture=true\n }\n };\n PointerDragging.prototype.recordCoords = function (ev) {\n if (this.shouldWatchScroll) {\n this.prevPageX = ev.pageX;\n this.prevPageY = ev.pageY;\n this.prevScrollX = window.pageXOffset;\n this.prevScrollY = window.pageYOffset;\n }\n };\n PointerDragging.prototype.destroyScrollWatch = function () {\n if (this.shouldWatchScroll) {\n window.removeEventListener('scroll', this.handleScroll, true); // useCaptured=true\n }\n };\n // Event Normalization\n // ----------------------------------------------------------------------------------------------------\n PointerDragging.prototype.createEventFromMouse = function (ev, isFirst) {\n var deltaX = 0;\n var deltaY = 0;\n // TODO: repeat code\n if (isFirst) {\n this.origPageX = ev.pageX;\n this.origPageY = ev.pageY;\n }\n else {\n deltaX = ev.pageX - this.origPageX;\n deltaY = ev.pageY - this.origPageY;\n }\n return {\n origEvent: ev,\n isTouch: false,\n subjectEl: this.subjectEl,\n pageX: ev.pageX,\n pageY: ev.pageY,\n deltaX: deltaX,\n deltaY: deltaY,\n };\n };\n PointerDragging.prototype.createEventFromTouch = function (ev, isFirst) {\n var touches = ev.touches;\n var pageX;\n var pageY;\n var deltaX = 0;\n var deltaY = 0;\n // if touch coords available, prefer,\n // because FF would give bad ev.pageX ev.pageY\n if (touches && touches.length) {\n pageX = touches[0].pageX;\n pageY = touches[0].pageY;\n }\n else {\n pageX = ev.pageX;\n pageY = ev.pageY;\n }\n // TODO: repeat code\n if (isFirst) {\n this.origPageX = pageX;\n this.origPageY = pageY;\n }\n else {\n deltaX = pageX - this.origPageX;\n deltaY = pageY - this.origPageY;\n }\n return {\n origEvent: ev,\n isTouch: true,\n subjectEl: this.subjectEl,\n pageX: pageX,\n pageY: pageY,\n deltaX: deltaX,\n deltaY: deltaY,\n };\n };\n return PointerDragging;\n}());\n// Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)\nfunction isPrimaryMouseButton(ev) {\n return ev.button === 0 && !ev.ctrlKey;\n}\n// Ignoring fake mouse events generated by touch\n// ----------------------------------------------------------------------------------------------------\nfunction startIgnoringMouse() {\n ignoreMouseDepth += 1;\n setTimeout(function () {\n ignoreMouseDepth -= 1;\n }, config.touchMouseIgnoreWait);\n}\n// We want to attach touchmove as early as possible for Safari\n// ----------------------------------------------------------------------------------------------------\nfunction listenerCreated() {\n listenerCnt += 1;\n if (listenerCnt === 1) {\n window.addEventListener('touchmove', onWindowTouchMove, { passive: false });\n }\n}\nfunction listenerDestroyed() {\n listenerCnt -= 1;\n if (!listenerCnt) {\n window.removeEventListener('touchmove', onWindowTouchMove, { passive: false });\n }\n}\nfunction onWindowTouchMove(ev) {\n if (isWindowTouchMoveCancelled) {\n ev.preventDefault();\n }\n}\n\n/*\nAn effect in which an element follows the movement of a pointer across the screen.\nThe moving element is a clone of some other element.\nMust call start + handleMove + stop.\n*/\nvar ElementMirror = /** @class */ (function () {\n function ElementMirror() {\n this.isVisible = false; // must be explicitly enabled\n this.sourceEl = null;\n this.mirrorEl = null;\n this.sourceElRect = null; // screen coords relative to viewport\n // options that can be set directly by caller\n this.parentNode = document.body; // HIGHLY SUGGESTED to set this to sidestep ShadowDOM issues\n this.zIndex = 9999;\n this.revertDuration = 0;\n }\n ElementMirror.prototype.start = function (sourceEl, pageX, pageY) {\n this.sourceEl = sourceEl;\n this.sourceElRect = this.sourceEl.getBoundingClientRect();\n this.origScreenX = pageX - window.pageXOffset;\n this.origScreenY = pageY - window.pageYOffset;\n this.deltaX = 0;\n this.deltaY = 0;\n this.updateElPosition();\n };\n ElementMirror.prototype.handleMove = function (pageX, pageY) {\n this.deltaX = (pageX - window.pageXOffset) - this.origScreenX;\n this.deltaY = (pageY - window.pageYOffset) - this.origScreenY;\n this.updateElPosition();\n };\n // can be called before start\n ElementMirror.prototype.setIsVisible = function (bool) {\n if (bool) {\n if (!this.isVisible) {\n if (this.mirrorEl) {\n this.mirrorEl.style.display = '';\n }\n this.isVisible = bool; // needs to happen before updateElPosition\n this.updateElPosition(); // because was not updating the position while invisible\n }\n }\n else if (this.isVisible) {\n if (this.mirrorEl) {\n this.mirrorEl.style.display = 'none';\n }\n this.isVisible = bool;\n }\n };\n // always async\n ElementMirror.prototype.stop = function (needsRevertAnimation, callback) {\n var _this = this;\n var done = function () {\n _this.cleanup();\n callback();\n };\n if (needsRevertAnimation &&\n this.mirrorEl &&\n this.isVisible &&\n this.revertDuration && // if 0, transition won't work\n (this.deltaX || this.deltaY) // if same coords, transition won't work\n ) {\n this.doRevertAnimation(done, this.revertDuration);\n }\n else {\n setTimeout(done, 0);\n }\n };\n ElementMirror.prototype.doRevertAnimation = function (callback, revertDuration) {\n var mirrorEl = this.mirrorEl;\n var finalSourceElRect = this.sourceEl.getBoundingClientRect(); // because autoscrolling might have happened\n mirrorEl.style.transition =\n 'top ' + revertDuration + 'ms,' +\n 'left ' + revertDuration + 'ms';\n applyStyle(mirrorEl, {\n left: finalSourceElRect.left,\n top: finalSourceElRect.top,\n });\n whenTransitionDone(mirrorEl, function () {\n mirrorEl.style.transition = '';\n callback();\n });\n };\n ElementMirror.prototype.cleanup = function () {\n if (this.mirrorEl) {\n removeElement(this.mirrorEl);\n this.mirrorEl = null;\n }\n this.sourceEl = null;\n };\n ElementMirror.prototype.updateElPosition = function () {\n if (this.sourceEl && this.isVisible) {\n applyStyle(this.getMirrorEl(), {\n left: this.sourceElRect.left + this.deltaX,\n top: this.sourceElRect.top + this.deltaY,\n });\n }\n };\n ElementMirror.prototype.getMirrorEl = function () {\n var sourceElRect = this.sourceElRect;\n var mirrorEl = this.mirrorEl;\n if (!mirrorEl) {\n mirrorEl = this.mirrorEl = this.sourceEl.cloneNode(true); // cloneChildren=true\n // we don't want long taps or any mouse interaction causing selection/menus.\n // would use preventSelection(), but that prevents selectstart, causing problems.\n mirrorEl.classList.add('fc-unselectable');\n mirrorEl.classList.add('fc-event-dragging');\n applyStyle(mirrorEl, {\n position: 'fixed',\n zIndex: this.zIndex,\n visibility: '',\n boxSizing: 'border-box',\n width: sourceElRect.right - sourceElRect.left,\n height: sourceElRect.bottom - sourceElRect.top,\n right: 'auto',\n bottom: 'auto',\n margin: 0,\n });\n this.parentNode.appendChild(mirrorEl);\n }\n return mirrorEl;\n };\n return ElementMirror;\n}());\n\n/*\nIs a cache for a given element's scroll information (all the info that ScrollController stores)\nin addition the \"client rectangle\" of the element.. the area within the scrollbars.\n\nThe cache can be in one of two modes:\n- doesListening:false - ignores when the container is scrolled by someone else\n- doesListening:true - watch for scrolling and update the cache\n*/\nvar ScrollGeomCache = /** @class */ (function (_super) {\n __extends(ScrollGeomCache, _super);\n function ScrollGeomCache(scrollController, doesListening) {\n var _this = _super.call(this) || this;\n _this.handleScroll = function () {\n _this.scrollTop = _this.scrollController.getScrollTop();\n _this.scrollLeft = _this.scrollController.getScrollLeft();\n _this.handleScrollChange();\n };\n _this.scrollController = scrollController;\n _this.doesListening = doesListening;\n _this.scrollTop = _this.origScrollTop = scrollController.getScrollTop();\n _this.scrollLeft = _this.origScrollLeft = scrollController.getScrollLeft();\n _this.scrollWidth = scrollController.getScrollWidth();\n _this.scrollHeight = scrollController.getScrollHeight();\n _this.clientWidth = scrollController.getClientWidth();\n _this.clientHeight = scrollController.getClientHeight();\n _this.clientRect = _this.computeClientRect(); // do last in case it needs cached values\n if (_this.doesListening) {\n _this.getEventTarget().addEventListener('scroll', _this.handleScroll);\n }\n return _this;\n }\n ScrollGeomCache.prototype.destroy = function () {\n if (this.doesListening) {\n this.getEventTarget().removeEventListener('scroll', this.handleScroll);\n }\n };\n ScrollGeomCache.prototype.getScrollTop = function () {\n return this.scrollTop;\n };\n ScrollGeomCache.prototype.getScrollLeft = function () {\n return this.scrollLeft;\n };\n ScrollGeomCache.prototype.setScrollTop = function (top) {\n this.scrollController.setScrollTop(top);\n if (!this.doesListening) {\n // we are not relying on the element to normalize out-of-bounds scroll values\n // so we need to sanitize ourselves\n this.scrollTop = Math.max(Math.min(top, this.getMaxScrollTop()), 0);\n this.handleScrollChange();\n }\n };\n ScrollGeomCache.prototype.setScrollLeft = function (top) {\n this.scrollController.setScrollLeft(top);\n if (!this.doesListening) {\n // we are not relying on the element to normalize out-of-bounds scroll values\n // so we need to sanitize ourselves\n this.scrollLeft = Math.max(Math.min(top, this.getMaxScrollLeft()), 0);\n this.handleScrollChange();\n }\n };\n ScrollGeomCache.prototype.getClientWidth = function () {\n return this.clientWidth;\n };\n ScrollGeomCache.prototype.getClientHeight = function () {\n return this.clientHeight;\n };\n ScrollGeomCache.prototype.getScrollWidth = function () {\n return this.scrollWidth;\n };\n ScrollGeomCache.prototype.getScrollHeight = function () {\n return this.scrollHeight;\n };\n ScrollGeomCache.prototype.handleScrollChange = function () {\n };\n return ScrollGeomCache;\n}(ScrollController));\n\nvar ElementScrollGeomCache = /** @class */ (function (_super) {\n __extends(ElementScrollGeomCache, _super);\n function ElementScrollGeomCache(el, doesListening) {\n return _super.call(this, new ElementScrollController(el), doesListening) || this;\n }\n ElementScrollGeomCache.prototype.getEventTarget = function () {\n return this.scrollController.el;\n };\n ElementScrollGeomCache.prototype.computeClientRect = function () {\n return computeInnerRect(this.scrollController.el);\n };\n return ElementScrollGeomCache;\n}(ScrollGeomCache));\n\nvar WindowScrollGeomCache = /** @class */ (function (_super) {\n __extends(WindowScrollGeomCache, _super);\n function WindowScrollGeomCache(doesListening) {\n return _super.call(this, new WindowScrollController(), doesListening) || this;\n }\n WindowScrollGeomCache.prototype.getEventTarget = function () {\n return window;\n };\n WindowScrollGeomCache.prototype.computeClientRect = function () {\n return {\n left: this.scrollLeft,\n right: this.scrollLeft + this.clientWidth,\n top: this.scrollTop,\n bottom: this.scrollTop + this.clientHeight,\n };\n };\n // the window is the only scroll object that changes it's rectangle relative\n // to the document's topleft as it scrolls\n WindowScrollGeomCache.prototype.handleScrollChange = function () {\n this.clientRect = this.computeClientRect();\n };\n return WindowScrollGeomCache;\n}(ScrollGeomCache));\n\n// If available we are using native \"performance\" API instead of \"Date\"\n// Read more about it on MDN:\n// https://developer.mozilla.org/en-US/docs/Web/API/Performance\nvar getTime = typeof performance === 'function' ? performance.now : Date.now;\n/*\nFor a pointer interaction, automatically scrolls certain scroll containers when the pointer\napproaches the edge.\n\nThe caller must call start + handleMove + stop.\n*/\nvar AutoScroller = /** @class */ (function () {\n function AutoScroller() {\n var _this = this;\n // options that can be set by caller\n this.isEnabled = true;\n this.scrollQuery = [window, '.fc-scroller'];\n this.edgeThreshold = 50; // pixels\n this.maxVelocity = 300; // pixels per second\n // internal state\n this.pointerScreenX = null;\n this.pointerScreenY = null;\n this.isAnimating = false;\n this.scrollCaches = null;\n // protect against the initial pointerdown being too close to an edge and starting the scroll\n this.everMovedUp = false;\n this.everMovedDown = false;\n this.everMovedLeft = false;\n this.everMovedRight = false;\n this.animate = function () {\n if (_this.isAnimating) { // wasn't cancelled between animation calls\n var edge = _this.computeBestEdge(_this.pointerScreenX + window.pageXOffset, _this.pointerScreenY + window.pageYOffset);\n if (edge) {\n var now = getTime();\n _this.handleSide(edge, (now - _this.msSinceRequest) / 1000);\n _this.requestAnimation(now);\n }\n else {\n _this.isAnimating = false; // will stop animation\n }\n }\n };\n }\n AutoScroller.prototype.start = function (pageX, pageY, scrollStartEl) {\n if (this.isEnabled) {\n this.scrollCaches = this.buildCaches(scrollStartEl);\n this.pointerScreenX = null;\n this.pointerScreenY = null;\n this.everMovedUp = false;\n this.everMovedDown = false;\n this.everMovedLeft = false;\n this.everMovedRight = false;\n this.handleMove(pageX, pageY);\n }\n };\n AutoScroller.prototype.handleMove = function (pageX, pageY) {\n if (this.isEnabled) {\n var pointerScreenX = pageX - window.pageXOffset;\n var pointerScreenY = pageY - window.pageYOffset;\n var yDelta = this.pointerScreenY === null ? 0 : pointerScreenY - this.pointerScreenY;\n var xDelta = this.pointerScreenX === null ? 0 : pointerScreenX - this.pointerScreenX;\n if (yDelta < 0) {\n this.everMovedUp = true;\n }\n else if (yDelta > 0) {\n this.everMovedDown = true;\n }\n if (xDelta < 0) {\n this.everMovedLeft = true;\n }\n else if (xDelta > 0) {\n this.everMovedRight = true;\n }\n this.pointerScreenX = pointerScreenX;\n this.pointerScreenY = pointerScreenY;\n if (!this.isAnimating) {\n this.isAnimating = true;\n this.requestAnimation(getTime());\n }\n }\n };\n AutoScroller.prototype.stop = function () {\n if (this.isEnabled) {\n this.isAnimating = false; // will stop animation\n for (var _i = 0, _a = this.scrollCaches; _i < _a.length; _i++) {\n var scrollCache = _a[_i];\n scrollCache.destroy();\n }\n this.scrollCaches = null;\n }\n };\n AutoScroller.prototype.requestAnimation = function (now) {\n this.msSinceRequest = now;\n requestAnimationFrame(this.animate);\n };\n AutoScroller.prototype.handleSide = function (edge, seconds) {\n var scrollCache = edge.scrollCache;\n var edgeThreshold = this.edgeThreshold;\n var invDistance = edgeThreshold - edge.distance;\n var velocity = // the closer to the edge, the faster we scroll\n ((invDistance * invDistance) / (edgeThreshold * edgeThreshold)) * // quadratic\n this.maxVelocity * seconds;\n var sign = 1;\n switch (edge.name) {\n case 'left':\n sign = -1;\n // falls through\n case 'right':\n scrollCache.setScrollLeft(scrollCache.getScrollLeft() + velocity * sign);\n break;\n case 'top':\n sign = -1;\n // falls through\n case 'bottom':\n scrollCache.setScrollTop(scrollCache.getScrollTop() + velocity * sign);\n break;\n }\n };\n // left/top are relative to document topleft\n AutoScroller.prototype.computeBestEdge = function (left, top) {\n var edgeThreshold = this.edgeThreshold;\n var bestSide = null;\n var scrollCaches = this.scrollCaches || [];\n for (var _i = 0, scrollCaches_1 = scrollCaches; _i < scrollCaches_1.length; _i++) {\n var scrollCache = scrollCaches_1[_i];\n var rect = scrollCache.clientRect;\n var leftDist = left - rect.left;\n var rightDist = rect.right - left;\n var topDist = top - rect.top;\n var bottomDist = rect.bottom - top;\n // completely within the rect?\n if (leftDist >= 0 && rightDist >= 0 && topDist >= 0 && bottomDist >= 0) {\n if (topDist <= edgeThreshold && this.everMovedUp && scrollCache.canScrollUp() &&\n (!bestSide || bestSide.distance > topDist)) {\n bestSide = { scrollCache: scrollCache, name: 'top', distance: topDist };\n }\n if (bottomDist <= edgeThreshold && this.everMovedDown && scrollCache.canScrollDown() &&\n (!bestSide || bestSide.distance > bottomDist)) {\n bestSide = { scrollCache: scrollCache, name: 'bottom', distance: bottomDist };\n }\n if (leftDist <= edgeThreshold && this.everMovedLeft && scrollCache.canScrollLeft() &&\n (!bestSide || bestSide.distance > leftDist)) {\n bestSide = { scrollCache: scrollCache, name: 'left', distance: leftDist };\n }\n if (rightDist <= edgeThreshold && this.everMovedRight && scrollCache.canScrollRight() &&\n (!bestSide || bestSide.distance > rightDist)) {\n bestSide = { scrollCache: scrollCache, name: 'right', distance: rightDist };\n }\n }\n }\n return bestSide;\n };\n AutoScroller.prototype.buildCaches = function (scrollStartEl) {\n return this.queryScrollEls(scrollStartEl).map(function (el) {\n if (el === window) {\n return new WindowScrollGeomCache(false); // false = don't listen to user-generated scrolls\n }\n return new ElementScrollGeomCache(el, false); // false = don't listen to user-generated scrolls\n });\n };\n AutoScroller.prototype.queryScrollEls = function (scrollStartEl) {\n var els = [];\n for (var _i = 0, _a = this.scrollQuery; _i < _a.length; _i++) {\n var query = _a[_i];\n if (typeof query === 'object') {\n els.push(query);\n }\n else {\n els.push.apply(els, Array.prototype.slice.call(getElRoot(scrollStartEl).querySelectorAll(query)));\n }\n }\n return els;\n };\n return AutoScroller;\n}());\n\n/*\nMonitors dragging on an element. Has a number of high-level features:\n- minimum distance required before dragging\n- minimum wait time (\"delay\") before dragging\n- a mirror element that follows the pointer\n*/\nvar FeaturefulElementDragging = /** @class */ (function (_super) {\n __extends(FeaturefulElementDragging, _super);\n function FeaturefulElementDragging(containerEl, selector) {\n var _this = _super.call(this, containerEl) || this;\n _this.containerEl = containerEl;\n // options that can be directly set by caller\n // the caller can also set the PointerDragging's options as well\n _this.delay = null;\n _this.minDistance = 0;\n _this.touchScrollAllowed = true; // prevents drag from starting and blocks scrolling during drag\n _this.mirrorNeedsRevert = false;\n _this.isInteracting = false; // is the user validly moving the pointer? lasts until pointerup\n _this.isDragging = false; // is it INTENTFULLY dragging? lasts until after revert animation\n _this.isDelayEnded = false;\n _this.isDistanceSurpassed = false;\n _this.delayTimeoutId = null;\n _this.onPointerDown = function (ev) {\n if (!_this.isDragging) { // so new drag doesn't happen while revert animation is going\n _this.isInteracting = true;\n _this.isDelayEnded = false;\n _this.isDistanceSurpassed = false;\n preventSelection(document.body);\n preventContextMenu(document.body);\n // prevent links from being visited if there's an eventual drag.\n // also prevents selection in older browsers (maybe?).\n // not necessary for touch, besides, browser would complain about passiveness.\n if (!ev.isTouch) {\n ev.origEvent.preventDefault();\n }\n _this.emitter.trigger('pointerdown', ev);\n if (_this.isInteracting && // not destroyed via pointerdown handler\n !_this.pointer.shouldIgnoreMove) {\n // actions related to initiating dragstart+dragmove+dragend...\n _this.mirror.setIsVisible(false); // reset. caller must set-visible\n _this.mirror.start(ev.subjectEl, ev.pageX, ev.pageY); // must happen on first pointer down\n _this.startDelay(ev);\n if (!_this.minDistance) {\n _this.handleDistanceSurpassed(ev);\n }\n }\n }\n };\n _this.onPointerMove = function (ev) {\n if (_this.isInteracting) {\n _this.emitter.trigger('pointermove', ev);\n if (!_this.isDistanceSurpassed) {\n var minDistance = _this.minDistance;\n var distanceSq = void 0; // current distance from the origin, squared\n var deltaX = ev.deltaX, deltaY = ev.deltaY;\n distanceSq = deltaX * deltaX + deltaY * deltaY;\n if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem\n _this.handleDistanceSurpassed(ev);\n }\n }\n if (_this.isDragging) {\n // a real pointer move? (not one simulated by scrolling)\n if (ev.origEvent.type !== 'scroll') {\n _this.mirror.handleMove(ev.pageX, ev.pageY);\n _this.autoScroller.handleMove(ev.pageX, ev.pageY);\n }\n _this.emitter.trigger('dragmove', ev);\n }\n }\n };\n _this.onPointerUp = function (ev) {\n if (_this.isInteracting) {\n _this.isInteracting = false;\n allowSelection(document.body);\n allowContextMenu(document.body);\n _this.emitter.trigger('pointerup', ev); // can potentially set mirrorNeedsRevert\n if (_this.isDragging) {\n _this.autoScroller.stop();\n _this.tryStopDrag(ev); // which will stop the mirror\n }\n if (_this.delayTimeoutId) {\n clearTimeout(_this.delayTimeoutId);\n _this.delayTimeoutId = null;\n }\n }\n };\n var pointer = _this.pointer = new PointerDragging(containerEl);\n pointer.emitter.on('pointerdown', _this.onPointerDown);\n pointer.emitter.on('pointermove', _this.onPointerMove);\n pointer.emitter.on('pointerup', _this.onPointerUp);\n if (selector) {\n pointer.selector = selector;\n }\n _this.mirror = new ElementMirror();\n _this.autoScroller = new AutoScroller();\n return _this;\n }\n FeaturefulElementDragging.prototype.destroy = function () {\n this.pointer.destroy();\n // HACK: simulate a pointer-up to end the current drag\n // TODO: fire 'dragend' directly and stop interaction. discourage use of pointerup event (b/c might not fire)\n this.onPointerUp({});\n };\n FeaturefulElementDragging.prototype.startDelay = function (ev) {\n var _this = this;\n if (typeof this.delay === 'number') {\n this.delayTimeoutId = setTimeout(function () {\n _this.delayTimeoutId = null;\n _this.handleDelayEnd(ev);\n }, this.delay); // not assignable to number!\n }\n else {\n this.handleDelayEnd(ev);\n }\n };\n FeaturefulElementDragging.prototype.handleDelayEnd = function (ev) {\n this.isDelayEnded = true;\n this.tryStartDrag(ev);\n };\n FeaturefulElementDragging.prototype.handleDistanceSurpassed = function (ev) {\n this.isDistanceSurpassed = true;\n this.tryStartDrag(ev);\n };\n FeaturefulElementDragging.prototype.tryStartDrag = function (ev) {\n if (this.isDelayEnded && this.isDistanceSurpassed) {\n if (!this.pointer.wasTouchScroll || this.touchScrollAllowed) {\n this.isDragging = true;\n this.mirrorNeedsRevert = false;\n this.autoScroller.start(ev.pageX, ev.pageY, this.containerEl);\n this.emitter.trigger('dragstart', ev);\n if (this.touchScrollAllowed === false) {\n this.pointer.cancelTouchScroll();\n }\n }\n }\n };\n FeaturefulElementDragging.prototype.tryStopDrag = function (ev) {\n // .stop() is ALWAYS asynchronous, which we NEED because we want all pointerup events\n // that come from the document to fire beforehand. much more convenient this way.\n this.mirror.stop(this.mirrorNeedsRevert, this.stopDrag.bind(this, ev));\n };\n FeaturefulElementDragging.prototype.stopDrag = function (ev) {\n this.isDragging = false;\n this.emitter.trigger('dragend', ev);\n };\n // fill in the implementations...\n FeaturefulElementDragging.prototype.setIgnoreMove = function (bool) {\n this.pointer.shouldIgnoreMove = bool;\n };\n FeaturefulElementDragging.prototype.setMirrorIsVisible = function (bool) {\n this.mirror.setIsVisible(bool);\n };\n FeaturefulElementDragging.prototype.setMirrorNeedsRevert = function (bool) {\n this.mirrorNeedsRevert = bool;\n };\n FeaturefulElementDragging.prototype.setAutoScrollEnabled = function (bool) {\n this.autoScroller.isEnabled = bool;\n };\n return FeaturefulElementDragging;\n}(ElementDragging));\n\n/*\nWhen this class is instantiated, it records the offset of an element (relative to the document topleft),\nand continues to monitor scrolling, updating the cached coordinates if it needs to.\nDoes not access the DOM after instantiation, so highly performant.\n\nAlso keeps track of all scrolling/overflow:hidden containers that are parents of the given element\nand an determine if a given point is inside the combined clipping rectangle.\n*/\nvar OffsetTracker = /** @class */ (function () {\n function OffsetTracker(el) {\n this.origRect = computeRect(el);\n // will work fine for divs that have overflow:hidden\n this.scrollCaches = getClippingParents(el).map(function (scrollEl) { return new ElementScrollGeomCache(scrollEl, true); });\n }\n OffsetTracker.prototype.destroy = function () {\n for (var _i = 0, _a = this.scrollCaches; _i < _a.length; _i++) {\n var scrollCache = _a[_i];\n scrollCache.destroy();\n }\n };\n OffsetTracker.prototype.computeLeft = function () {\n var left = this.origRect.left;\n for (var _i = 0, _a = this.scrollCaches; _i < _a.length; _i++) {\n var scrollCache = _a[_i];\n left += scrollCache.origScrollLeft - scrollCache.getScrollLeft();\n }\n return left;\n };\n OffsetTracker.prototype.computeTop = function () {\n var top = this.origRect.top;\n for (var _i = 0, _a = this.scrollCaches; _i < _a.length; _i++) {\n var scrollCache = _a[_i];\n top += scrollCache.origScrollTop - scrollCache.getScrollTop();\n }\n return top;\n };\n OffsetTracker.prototype.isWithinClipping = function (pageX, pageY) {\n var point = { left: pageX, top: pageY };\n for (var _i = 0, _a = this.scrollCaches; _i < _a.length; _i++) {\n var scrollCache = _a[_i];\n if (!isIgnoredClipping(scrollCache.getEventTarget()) &&\n !pointInsideRect(point, scrollCache.clientRect)) {\n return false;\n }\n }\n return true;\n };\n return OffsetTracker;\n}());\n// certain clipping containers should never constrain interactions, like and \n// https://github.com/fullcalendar/fullcalendar/issues/3615\nfunction isIgnoredClipping(node) {\n var tagName = node.tagName;\n return tagName === 'HTML' || tagName === 'BODY';\n}\n\n/*\nTracks movement over multiple droppable areas (aka \"hits\")\nthat exist in one or more DateComponents.\nRelies on an existing draggable.\n\nemits:\n- pointerdown\n- dragstart\n- hitchange - fires initially, even if not over a hit\n- pointerup\n- (hitchange - again, to null, if ended over a hit)\n- dragend\n*/\nvar HitDragging = /** @class */ (function () {\n function HitDragging(dragging, droppableStore) {\n var _this = this;\n // options that can be set by caller\n this.useSubjectCenter = false;\n this.requireInitial = true; // if doesn't start out on a hit, won't emit any events\n this.initialHit = null;\n this.movingHit = null;\n this.finalHit = null; // won't ever be populated if shouldIgnoreMove\n this.handlePointerDown = function (ev) {\n var dragging = _this.dragging;\n _this.initialHit = null;\n _this.movingHit = null;\n _this.finalHit = null;\n _this.prepareHits();\n _this.processFirstCoord(ev);\n if (_this.initialHit || !_this.requireInitial) {\n dragging.setIgnoreMove(false);\n // TODO: fire this before computing processFirstCoord, so listeners can cancel. this gets fired by almost every handler :(\n _this.emitter.trigger('pointerdown', ev);\n }\n else {\n dragging.setIgnoreMove(true);\n }\n };\n this.handleDragStart = function (ev) {\n _this.emitter.trigger('dragstart', ev);\n _this.handleMove(ev, true); // force = fire even if initially null\n };\n this.handleDragMove = function (ev) {\n _this.emitter.trigger('dragmove', ev);\n _this.handleMove(ev);\n };\n this.handlePointerUp = function (ev) {\n _this.releaseHits();\n _this.emitter.trigger('pointerup', ev);\n };\n this.handleDragEnd = function (ev) {\n if (_this.movingHit) {\n _this.emitter.trigger('hitupdate', null, true, ev);\n }\n _this.finalHit = _this.movingHit;\n _this.movingHit = null;\n _this.emitter.trigger('dragend', ev);\n };\n this.droppableStore = droppableStore;\n dragging.emitter.on('pointerdown', this.handlePointerDown);\n dragging.emitter.on('dragstart', this.handleDragStart);\n dragging.emitter.on('dragmove', this.handleDragMove);\n dragging.emitter.on('pointerup', this.handlePointerUp);\n dragging.emitter.on('dragend', this.handleDragEnd);\n this.dragging = dragging;\n this.emitter = new Emitter();\n }\n // sets initialHit\n // sets coordAdjust\n HitDragging.prototype.processFirstCoord = function (ev) {\n var origPoint = { left: ev.pageX, top: ev.pageY };\n var adjustedPoint = origPoint;\n var subjectEl = ev.subjectEl;\n var subjectRect;\n if (subjectEl instanceof HTMLElement) { // i.e. not a Document/ShadowRoot\n subjectRect = computeRect(subjectEl);\n adjustedPoint = constrainPoint(adjustedPoint, subjectRect);\n }\n var initialHit = this.initialHit = this.queryHitForOffset(adjustedPoint.left, adjustedPoint.top);\n if (initialHit) {\n if (this.useSubjectCenter && subjectRect) {\n var slicedSubjectRect = intersectRects(subjectRect, initialHit.rect);\n if (slicedSubjectRect) {\n adjustedPoint = getRectCenter(slicedSubjectRect);\n }\n }\n this.coordAdjust = diffPoints(adjustedPoint, origPoint);\n }\n else {\n this.coordAdjust = { left: 0, top: 0 };\n }\n };\n HitDragging.prototype.handleMove = function (ev, forceHandle) {\n var hit = this.queryHitForOffset(ev.pageX + this.coordAdjust.left, ev.pageY + this.coordAdjust.top);\n if (forceHandle || !isHitsEqual(this.movingHit, hit)) {\n this.movingHit = hit;\n this.emitter.trigger('hitupdate', hit, false, ev);\n }\n };\n HitDragging.prototype.prepareHits = function () {\n this.offsetTrackers = mapHash(this.droppableStore, function (interactionSettings) {\n interactionSettings.component.prepareHits();\n return new OffsetTracker(interactionSettings.el);\n });\n };\n HitDragging.prototype.releaseHits = function () {\n var offsetTrackers = this.offsetTrackers;\n for (var id in offsetTrackers) {\n offsetTrackers[id].destroy();\n }\n this.offsetTrackers = {};\n };\n HitDragging.prototype.queryHitForOffset = function (offsetLeft, offsetTop) {\n var _a = this, droppableStore = _a.droppableStore, offsetTrackers = _a.offsetTrackers;\n var bestHit = null;\n for (var id in droppableStore) {\n var component = droppableStore[id].component;\n var offsetTracker = offsetTrackers[id];\n if (offsetTracker && // wasn't destroyed mid-drag\n offsetTracker.isWithinClipping(offsetLeft, offsetTop)) {\n var originLeft = offsetTracker.computeLeft();\n var originTop = offsetTracker.computeTop();\n var positionLeft = offsetLeft - originLeft;\n var positionTop = offsetTop - originTop;\n var origRect = offsetTracker.origRect;\n var width = origRect.right - origRect.left;\n var height = origRect.bottom - origRect.top;\n if (\n // must be within the element's bounds\n positionLeft >= 0 && positionLeft < width &&\n positionTop >= 0 && positionTop < height) {\n var hit = component.queryHit(positionLeft, positionTop, width, height);\n if (hit && (\n // make sure the hit is within activeRange, meaning it's not a dead cell\n rangeContainsRange(hit.dateProfile.activeRange, hit.dateSpan.range)) &&\n (!bestHit || hit.layer > bestHit.layer)) {\n hit.componentId = id;\n hit.context = component.context;\n // TODO: better way to re-orient rectangle\n hit.rect.left += originLeft;\n hit.rect.right += originLeft;\n hit.rect.top += originTop;\n hit.rect.bottom += originTop;\n bestHit = hit;\n }\n }\n }\n }\n return bestHit;\n };\n return HitDragging;\n}());\nfunction isHitsEqual(hit0, hit1) {\n if (!hit0 && !hit1) {\n return true;\n }\n if (Boolean(hit0) !== Boolean(hit1)) {\n return false;\n }\n return isDateSpansEqual(hit0.dateSpan, hit1.dateSpan);\n}\n\nfunction buildDatePointApiWithContext(dateSpan, context) {\n var props = {};\n for (var _i = 0, _a = context.pluginHooks.datePointTransforms; _i < _a.length; _i++) {\n var transform = _a[_i];\n __assign(props, transform(dateSpan, context));\n }\n __assign(props, buildDatePointApi(dateSpan, context.dateEnv));\n return props;\n}\nfunction buildDatePointApi(span, dateEnv) {\n return {\n date: dateEnv.toDate(span.range.start),\n dateStr: dateEnv.formatIso(span.range.start, { omitTime: span.allDay }),\n allDay: span.allDay,\n };\n}\n\n/*\nMonitors when the user clicks on a specific date/time of a component.\nA pointerdown+pointerup on the same \"hit\" constitutes a click.\n*/\nvar DateClicking = /** @class */ (function (_super) {\n __extends(DateClicking, _super);\n function DateClicking(settings) {\n var _this = _super.call(this, settings) || this;\n _this.handlePointerDown = function (pev) {\n var dragging = _this.dragging;\n var downEl = pev.origEvent.target;\n // do this in pointerdown (not dragend) because DOM might be mutated by the time dragend is fired\n dragging.setIgnoreMove(!_this.component.isValidDateDownEl(downEl));\n };\n // won't even fire if moving was ignored\n _this.handleDragEnd = function (ev) {\n var component = _this.component;\n var pointer = _this.dragging.pointer;\n if (!pointer.wasTouchScroll) {\n var _a = _this.hitDragging, initialHit = _a.initialHit, finalHit = _a.finalHit;\n if (initialHit && finalHit && isHitsEqual(initialHit, finalHit)) {\n var context = component.context;\n var arg = __assign(__assign({}, buildDatePointApiWithContext(initialHit.dateSpan, context)), { dayEl: initialHit.dayEl, jsEvent: ev.origEvent, view: context.viewApi || context.calendarApi.view });\n context.emitter.trigger('dateClick', arg);\n }\n }\n };\n // we DO want to watch pointer moves because otherwise finalHit won't get populated\n _this.dragging = new FeaturefulElementDragging(settings.el);\n _this.dragging.autoScroller.isEnabled = false;\n var hitDragging = _this.hitDragging = new HitDragging(_this.dragging, interactionSettingsToStore(settings));\n hitDragging.emitter.on('pointerdown', _this.handlePointerDown);\n hitDragging.emitter.on('dragend', _this.handleDragEnd);\n return _this;\n }\n DateClicking.prototype.destroy = function () {\n this.dragging.destroy();\n };\n return DateClicking;\n}(Interaction));\n\n/*\nTracks when the user selects a portion of time of a component,\nconstituted by a drag over date cells, with a possible delay at the beginning of the drag.\n*/\nvar DateSelecting = /** @class */ (function (_super) {\n __extends(DateSelecting, _super);\n function DateSelecting(settings) {\n var _this = _super.call(this, settings) || this;\n _this.dragSelection = null;\n _this.handlePointerDown = function (ev) {\n var _a = _this, component = _a.component, dragging = _a.dragging;\n var options = component.context.options;\n var canSelect = options.selectable &&\n component.isValidDateDownEl(ev.origEvent.target);\n // don't bother to watch expensive moves if component won't do selection\n dragging.setIgnoreMove(!canSelect);\n // if touch, require user to hold down\n dragging.delay = ev.isTouch ? getComponentTouchDelay$1(component) : null;\n };\n _this.handleDragStart = function (ev) {\n _this.component.context.calendarApi.unselect(ev); // unselect previous selections\n };\n _this.handleHitUpdate = function (hit, isFinal) {\n var context = _this.component.context;\n var dragSelection = null;\n var isInvalid = false;\n if (hit) {\n var initialHit = _this.hitDragging.initialHit;\n var disallowed = hit.componentId === initialHit.componentId\n && _this.isHitComboAllowed\n && !_this.isHitComboAllowed(initialHit, hit);\n if (!disallowed) {\n dragSelection = joinHitsIntoSelection(initialHit, hit, context.pluginHooks.dateSelectionTransformers);\n }\n if (!dragSelection || !isDateSelectionValid(dragSelection, hit.dateProfile, context)) {\n isInvalid = true;\n dragSelection = null;\n }\n }\n if (dragSelection) {\n context.dispatch({ type: 'SELECT_DATES', selection: dragSelection });\n }\n else if (!isFinal) { // only unselect if moved away while dragging\n context.dispatch({ type: 'UNSELECT_DATES' });\n }\n if (!isInvalid) {\n enableCursor();\n }\n else {\n disableCursor();\n }\n if (!isFinal) {\n _this.dragSelection = dragSelection; // only clear if moved away from all hits while dragging\n }\n };\n _this.handlePointerUp = function (pev) {\n if (_this.dragSelection) {\n // selection is already rendered, so just need to report selection\n triggerDateSelect(_this.dragSelection, pev, _this.component.context);\n _this.dragSelection = null;\n }\n };\n var component = settings.component;\n var options = component.context.options;\n var dragging = _this.dragging = new FeaturefulElementDragging(settings.el);\n dragging.touchScrollAllowed = false;\n dragging.minDistance = options.selectMinDistance || 0;\n dragging.autoScroller.isEnabled = options.dragScroll;\n var hitDragging = _this.hitDragging = new HitDragging(_this.dragging, interactionSettingsToStore(settings));\n hitDragging.emitter.on('pointerdown', _this.handlePointerDown);\n hitDragging.emitter.on('dragstart', _this.handleDragStart);\n hitDragging.emitter.on('hitupdate', _this.handleHitUpdate);\n hitDragging.emitter.on('pointerup', _this.handlePointerUp);\n return _this;\n }\n DateSelecting.prototype.destroy = function () {\n this.dragging.destroy();\n };\n return DateSelecting;\n}(Interaction));\nfunction getComponentTouchDelay$1(component) {\n var options = component.context.options;\n var delay = options.selectLongPressDelay;\n if (delay == null) {\n delay = options.longPressDelay;\n }\n return delay;\n}\nfunction joinHitsIntoSelection(hit0, hit1, dateSelectionTransformers) {\n var dateSpan0 = hit0.dateSpan;\n var dateSpan1 = hit1.dateSpan;\n var ms = [\n dateSpan0.range.start,\n dateSpan0.range.end,\n dateSpan1.range.start,\n dateSpan1.range.end,\n ];\n ms.sort(compareNumbers);\n var props = {};\n for (var _i = 0, dateSelectionTransformers_1 = dateSelectionTransformers; _i < dateSelectionTransformers_1.length; _i++) {\n var transformer = dateSelectionTransformers_1[_i];\n var res = transformer(hit0, hit1);\n if (res === false) {\n return null;\n }\n if (res) {\n __assign(props, res);\n }\n }\n props.range = { start: ms[0], end: ms[3] };\n props.allDay = dateSpan0.allDay;\n return props;\n}\n\nvar EventDragging = /** @class */ (function (_super) {\n __extends(EventDragging, _super);\n function EventDragging(settings) {\n var _this = _super.call(this, settings) || this;\n // internal state\n _this.subjectEl = null;\n _this.subjectSeg = null; // the seg being selected/dragged\n _this.isDragging = false;\n _this.eventRange = null;\n _this.relevantEvents = null; // the events being dragged\n _this.receivingContext = null;\n _this.validMutation = null;\n _this.mutatedRelevantEvents = null;\n _this.handlePointerDown = function (ev) {\n var origTarget = ev.origEvent.target;\n var _a = _this, component = _a.component, dragging = _a.dragging;\n var mirror = dragging.mirror;\n var options = component.context.options;\n var initialContext = component.context;\n _this.subjectEl = ev.subjectEl;\n var subjectSeg = _this.subjectSeg = getElSeg(ev.subjectEl);\n var eventRange = _this.eventRange = subjectSeg.eventRange;\n var eventInstanceId = eventRange.instance.instanceId;\n _this.relevantEvents = getRelevantEvents(initialContext.getCurrentData().eventStore, eventInstanceId);\n dragging.minDistance = ev.isTouch ? 0 : options.eventDragMinDistance;\n dragging.delay =\n // only do a touch delay if touch and this event hasn't been selected yet\n (ev.isTouch && eventInstanceId !== component.props.eventSelection) ?\n getComponentTouchDelay(component) :\n null;\n if (options.fixedMirrorParent) {\n mirror.parentNode = options.fixedMirrorParent;\n }\n else {\n mirror.parentNode = elementClosest(origTarget, '.fc');\n }\n mirror.revertDuration = options.dragRevertDuration;\n var isValid = component.isValidSegDownEl(origTarget) &&\n !elementClosest(origTarget, '.fc-event-resizer'); // NOT on a resizer\n dragging.setIgnoreMove(!isValid);\n // disable dragging for elements that are resizable (ie, selectable)\n // but are not draggable\n _this.isDragging = isValid &&\n ev.subjectEl.classList.contains('fc-event-draggable');\n };\n _this.handleDragStart = function (ev) {\n var initialContext = _this.component.context;\n var eventRange = _this.eventRange;\n var eventInstanceId = eventRange.instance.instanceId;\n if (ev.isTouch) {\n // need to select a different event?\n if (eventInstanceId !== _this.component.props.eventSelection) {\n initialContext.dispatch({ type: 'SELECT_EVENT', eventInstanceId: eventInstanceId });\n }\n }\n else {\n // if now using mouse, but was previous touch interaction, clear selected event\n initialContext.dispatch({ type: 'UNSELECT_EVENT' });\n }\n if (_this.isDragging) {\n initialContext.calendarApi.unselect(ev); // unselect *date* selection\n initialContext.emitter.trigger('eventDragStart', {\n el: _this.subjectEl,\n event: new EventApi(initialContext, eventRange.def, eventRange.instance),\n jsEvent: ev.origEvent,\n view: initialContext.viewApi,\n });\n }\n };\n _this.handleHitUpdate = function (hit, isFinal) {\n if (!_this.isDragging) {\n return;\n }\n var relevantEvents = _this.relevantEvents;\n var initialHit = _this.hitDragging.initialHit;\n var initialContext = _this.component.context;\n // states based on new hit\n var receivingContext = null;\n var mutation = null;\n var mutatedRelevantEvents = null;\n var isInvalid = false;\n var interaction = {\n affectedEvents: relevantEvents,\n mutatedEvents: createEmptyEventStore(),\n isEvent: true,\n };\n if (hit) {\n receivingContext = hit.context;\n var receivingOptions = receivingContext.options;\n if (initialContext === receivingContext ||\n (receivingOptions.editable && receivingOptions.droppable)) {\n mutation = computeEventMutation(initialHit, hit, receivingContext.getCurrentData().pluginHooks.eventDragMutationMassagers);\n if (mutation) {\n mutatedRelevantEvents = applyMutationToEventStore(relevantEvents, receivingContext.getCurrentData().eventUiBases, mutation, receivingContext);\n interaction.mutatedEvents = mutatedRelevantEvents;\n if (!isInteractionValid(interaction, hit.dateProfile, receivingContext)) {\n isInvalid = true;\n mutation = null;\n mutatedRelevantEvents = null;\n interaction.mutatedEvents = createEmptyEventStore();\n }\n }\n }\n else {\n receivingContext = null;\n }\n }\n _this.displayDrag(receivingContext, interaction);\n if (!isInvalid) {\n enableCursor();\n }\n else {\n disableCursor();\n }\n if (!isFinal) {\n if (initialContext === receivingContext && // TODO: write test for this\n isHitsEqual(initialHit, hit)) {\n mutation = null;\n }\n _this.dragging.setMirrorNeedsRevert(!mutation);\n // render the mirror if no already-rendered mirror\n // TODO: wish we could somehow wait for dispatch to guarantee render\n _this.dragging.setMirrorIsVisible(!hit || !getElRoot(_this.subjectEl).querySelector('.fc-event-mirror'));\n // assign states based on new hit\n _this.receivingContext = receivingContext;\n _this.validMutation = mutation;\n _this.mutatedRelevantEvents = mutatedRelevantEvents;\n }\n };\n _this.handlePointerUp = function () {\n if (!_this.isDragging) {\n _this.cleanup(); // because handleDragEnd won't fire\n }\n };\n _this.handleDragEnd = function (ev) {\n if (_this.isDragging) {\n var initialContext_1 = _this.component.context;\n var initialView = initialContext_1.viewApi;\n var _a = _this, receivingContext_1 = _a.receivingContext, validMutation = _a.validMutation;\n var eventDef = _this.eventRange.def;\n var eventInstance = _this.eventRange.instance;\n var eventApi = new EventApi(initialContext_1, eventDef, eventInstance);\n var relevantEvents_1 = _this.relevantEvents;\n var mutatedRelevantEvents_1 = _this.mutatedRelevantEvents;\n var finalHit = _this.hitDragging.finalHit;\n _this.clearDrag(); // must happen after revert animation\n initialContext_1.emitter.trigger('eventDragStop', {\n el: _this.subjectEl,\n event: eventApi,\n jsEvent: ev.origEvent,\n view: initialView,\n });\n if (validMutation) {\n // dropped within same calendar\n if (receivingContext_1 === initialContext_1) {\n var updatedEventApi = new EventApi(initialContext_1, mutatedRelevantEvents_1.defs[eventDef.defId], eventInstance ? mutatedRelevantEvents_1.instances[eventInstance.instanceId] : null);\n initialContext_1.dispatch({\n type: 'MERGE_EVENTS',\n eventStore: mutatedRelevantEvents_1,\n });\n var eventChangeArg = {\n oldEvent: eventApi,\n event: updatedEventApi,\n relatedEvents: buildEventApis(mutatedRelevantEvents_1, initialContext_1, eventInstance),\n revert: function () {\n initialContext_1.dispatch({\n type: 'MERGE_EVENTS',\n eventStore: relevantEvents_1, // the pre-change data\n });\n },\n };\n var transformed = {};\n for (var _i = 0, _b = initialContext_1.getCurrentData().pluginHooks.eventDropTransformers; _i < _b.length; _i++) {\n var transformer = _b[_i];\n __assign(transformed, transformer(validMutation, initialContext_1));\n }\n initialContext_1.emitter.trigger('eventDrop', __assign(__assign(__assign({}, eventChangeArg), transformed), { el: ev.subjectEl, delta: validMutation.datesDelta, jsEvent: ev.origEvent, view: initialView }));\n initialContext_1.emitter.trigger('eventChange', eventChangeArg);\n // dropped in different calendar\n }\n else if (receivingContext_1) {\n var eventRemoveArg = {\n event: eventApi,\n relatedEvents: buildEventApis(relevantEvents_1, initialContext_1, eventInstance),\n revert: function () {\n initialContext_1.dispatch({\n type: 'MERGE_EVENTS',\n eventStore: relevantEvents_1,\n });\n },\n };\n initialContext_1.emitter.trigger('eventLeave', __assign(__assign({}, eventRemoveArg), { draggedEl: ev.subjectEl, view: initialView }));\n initialContext_1.dispatch({\n type: 'REMOVE_EVENTS',\n eventStore: relevantEvents_1,\n });\n initialContext_1.emitter.trigger('eventRemove', eventRemoveArg);\n var addedEventDef = mutatedRelevantEvents_1.defs[eventDef.defId];\n var addedEventInstance = mutatedRelevantEvents_1.instances[eventInstance.instanceId];\n var addedEventApi = new EventApi(receivingContext_1, addedEventDef, addedEventInstance);\n receivingContext_1.dispatch({\n type: 'MERGE_EVENTS',\n eventStore: mutatedRelevantEvents_1,\n });\n var eventAddArg = {\n event: addedEventApi,\n relatedEvents: buildEventApis(mutatedRelevantEvents_1, receivingContext_1, addedEventInstance),\n revert: function () {\n receivingContext_1.dispatch({\n type: 'REMOVE_EVENTS',\n eventStore: mutatedRelevantEvents_1,\n });\n },\n };\n receivingContext_1.emitter.trigger('eventAdd', eventAddArg);\n if (ev.isTouch) {\n receivingContext_1.dispatch({\n type: 'SELECT_EVENT',\n eventInstanceId: eventInstance.instanceId,\n });\n }\n receivingContext_1.emitter.trigger('drop', __assign(__assign({}, buildDatePointApiWithContext(finalHit.dateSpan, receivingContext_1)), { draggedEl: ev.subjectEl, jsEvent: ev.origEvent, view: finalHit.context.viewApi }));\n receivingContext_1.emitter.trigger('eventReceive', __assign(__assign({}, eventAddArg), { draggedEl: ev.subjectEl, view: finalHit.context.viewApi }));\n }\n }\n else {\n initialContext_1.emitter.trigger('_noEventDrop');\n }\n }\n _this.cleanup();\n };\n var component = _this.component;\n var options = component.context.options;\n var dragging = _this.dragging = new FeaturefulElementDragging(settings.el);\n dragging.pointer.selector = EventDragging.SELECTOR;\n dragging.touchScrollAllowed = false;\n dragging.autoScroller.isEnabled = options.dragScroll;\n var hitDragging = _this.hitDragging = new HitDragging(_this.dragging, interactionSettingsStore);\n hitDragging.useSubjectCenter = settings.useEventCenter;\n hitDragging.emitter.on('pointerdown', _this.handlePointerDown);\n hitDragging.emitter.on('dragstart', _this.handleDragStart);\n hitDragging.emitter.on('hitupdate', _this.handleHitUpdate);\n hitDragging.emitter.on('pointerup', _this.handlePointerUp);\n hitDragging.emitter.on('dragend', _this.handleDragEnd);\n return _this;\n }\n EventDragging.prototype.destroy = function () {\n this.dragging.destroy();\n };\n // render a drag state on the next receivingCalendar\n EventDragging.prototype.displayDrag = function (nextContext, state) {\n var initialContext = this.component.context;\n var prevContext = this.receivingContext;\n // does the previous calendar need to be cleared?\n if (prevContext && prevContext !== nextContext) {\n // does the initial calendar need to be cleared?\n // if so, don't clear all the way. we still need to to hide the affectedEvents\n if (prevContext === initialContext) {\n prevContext.dispatch({\n type: 'SET_EVENT_DRAG',\n state: {\n affectedEvents: state.affectedEvents,\n mutatedEvents: createEmptyEventStore(),\n isEvent: true,\n },\n });\n // completely clear the old calendar if it wasn't the initial\n }\n else {\n prevContext.dispatch({ type: 'UNSET_EVENT_DRAG' });\n }\n }\n if (nextContext) {\n nextContext.dispatch({ type: 'SET_EVENT_DRAG', state: state });\n }\n };\n EventDragging.prototype.clearDrag = function () {\n var initialCalendar = this.component.context;\n var receivingContext = this.receivingContext;\n if (receivingContext) {\n receivingContext.dispatch({ type: 'UNSET_EVENT_DRAG' });\n }\n // the initial calendar might have an dummy drag state from displayDrag\n if (initialCalendar !== receivingContext) {\n initialCalendar.dispatch({ type: 'UNSET_EVENT_DRAG' });\n }\n };\n EventDragging.prototype.cleanup = function () {\n this.subjectSeg = null;\n this.isDragging = false;\n this.eventRange = null;\n this.relevantEvents = null;\n this.receivingContext = null;\n this.validMutation = null;\n this.mutatedRelevantEvents = null;\n };\n // TODO: test this in IE11\n // QUESTION: why do we need it on the resizable???\n EventDragging.SELECTOR = '.fc-event-draggable, .fc-event-resizable';\n return EventDragging;\n}(Interaction));\nfunction computeEventMutation(hit0, hit1, massagers) {\n var dateSpan0 = hit0.dateSpan;\n var dateSpan1 = hit1.dateSpan;\n var date0 = dateSpan0.range.start;\n var date1 = dateSpan1.range.start;\n var standardProps = {};\n if (dateSpan0.allDay !== dateSpan1.allDay) {\n standardProps.allDay = dateSpan1.allDay;\n standardProps.hasEnd = hit1.context.options.allDayMaintainDuration;\n if (dateSpan1.allDay) {\n // means date1 is already start-of-day,\n // but date0 needs to be converted\n date0 = startOfDay(date0);\n }\n }\n var delta = diffDates(date0, date1, hit0.context.dateEnv, hit0.componentId === hit1.componentId ?\n hit0.largeUnit :\n null);\n if (delta.milliseconds) { // has hours/minutes/seconds\n standardProps.allDay = false;\n }\n var mutation = {\n datesDelta: delta,\n standardProps: standardProps,\n };\n for (var _i = 0, massagers_1 = massagers; _i < massagers_1.length; _i++) {\n var massager = massagers_1[_i];\n massager(mutation, hit0, hit1);\n }\n return mutation;\n}\nfunction getComponentTouchDelay(component) {\n var options = component.context.options;\n var delay = options.eventLongPressDelay;\n if (delay == null) {\n delay = options.longPressDelay;\n }\n return delay;\n}\n\nvar EventResizing = /** @class */ (function (_super) {\n __extends(EventResizing, _super);\n function EventResizing(settings) {\n var _this = _super.call(this, settings) || this;\n // internal state\n _this.draggingSegEl = null;\n _this.draggingSeg = null; // TODO: rename to resizingSeg? subjectSeg?\n _this.eventRange = null;\n _this.relevantEvents = null;\n _this.validMutation = null;\n _this.mutatedRelevantEvents = null;\n _this.handlePointerDown = function (ev) {\n var component = _this.component;\n var segEl = _this.querySegEl(ev);\n var seg = getElSeg(segEl);\n var eventRange = _this.eventRange = seg.eventRange;\n _this.dragging.minDistance = component.context.options.eventDragMinDistance;\n // if touch, need to be working with a selected event\n _this.dragging.setIgnoreMove(!_this.component.isValidSegDownEl(ev.origEvent.target) ||\n (ev.isTouch && _this.component.props.eventSelection !== eventRange.instance.instanceId));\n };\n _this.handleDragStart = function (ev) {\n var context = _this.component.context;\n var eventRange = _this.eventRange;\n _this.relevantEvents = getRelevantEvents(context.getCurrentData().eventStore, _this.eventRange.instance.instanceId);\n var segEl = _this.querySegEl(ev);\n _this.draggingSegEl = segEl;\n _this.draggingSeg = getElSeg(segEl);\n context.calendarApi.unselect();\n context.emitter.trigger('eventResizeStart', {\n el: segEl,\n event: new EventApi(context, eventRange.def, eventRange.instance),\n jsEvent: ev.origEvent,\n view: context.viewApi,\n });\n };\n _this.handleHitUpdate = function (hit, isFinal, ev) {\n var context = _this.component.context;\n var relevantEvents = _this.relevantEvents;\n var initialHit = _this.hitDragging.initialHit;\n var eventInstance = _this.eventRange.instance;\n var mutation = null;\n var mutatedRelevantEvents = null;\n var isInvalid = false;\n var interaction = {\n affectedEvents: relevantEvents,\n mutatedEvents: createEmptyEventStore(),\n isEvent: true,\n };\n if (hit) {\n var disallowed = hit.componentId === initialHit.componentId\n && _this.isHitComboAllowed\n && !_this.isHitComboAllowed(initialHit, hit);\n if (!disallowed) {\n mutation = computeMutation(initialHit, hit, ev.subjectEl.classList.contains('fc-event-resizer-start'), eventInstance.range);\n }\n }\n if (mutation) {\n mutatedRelevantEvents = applyMutationToEventStore(relevantEvents, context.getCurrentData().eventUiBases, mutation, context);\n interaction.mutatedEvents = mutatedRelevantEvents;\n if (!isInteractionValid(interaction, hit.dateProfile, context)) {\n isInvalid = true;\n mutation = null;\n mutatedRelevantEvents = null;\n interaction.mutatedEvents = null;\n }\n }\n if (mutatedRelevantEvents) {\n context.dispatch({\n type: 'SET_EVENT_RESIZE',\n state: interaction,\n });\n }\n else {\n context.dispatch({ type: 'UNSET_EVENT_RESIZE' });\n }\n if (!isInvalid) {\n enableCursor();\n }\n else {\n disableCursor();\n }\n if (!isFinal) {\n if (mutation && isHitsEqual(initialHit, hit)) {\n mutation = null;\n }\n _this.validMutation = mutation;\n _this.mutatedRelevantEvents = mutatedRelevantEvents;\n }\n };\n _this.handleDragEnd = function (ev) {\n var context = _this.component.context;\n var eventDef = _this.eventRange.def;\n var eventInstance = _this.eventRange.instance;\n var eventApi = new EventApi(context, eventDef, eventInstance);\n var relevantEvents = _this.relevantEvents;\n var mutatedRelevantEvents = _this.mutatedRelevantEvents;\n context.emitter.trigger('eventResizeStop', {\n el: _this.draggingSegEl,\n event: eventApi,\n jsEvent: ev.origEvent,\n view: context.viewApi,\n });\n if (_this.validMutation) {\n var updatedEventApi = new EventApi(context, mutatedRelevantEvents.defs[eventDef.defId], eventInstance ? mutatedRelevantEvents.instances[eventInstance.instanceId] : null);\n context.dispatch({\n type: 'MERGE_EVENTS',\n eventStore: mutatedRelevantEvents,\n });\n var eventChangeArg = {\n oldEvent: eventApi,\n event: updatedEventApi,\n relatedEvents: buildEventApis(mutatedRelevantEvents, context, eventInstance),\n revert: function () {\n context.dispatch({\n type: 'MERGE_EVENTS',\n eventStore: relevantEvents, // the pre-change events\n });\n },\n };\n context.emitter.trigger('eventResize', __assign(__assign({}, eventChangeArg), { el: _this.draggingSegEl, startDelta: _this.validMutation.startDelta || createDuration(0), endDelta: _this.validMutation.endDelta || createDuration(0), jsEvent: ev.origEvent, view: context.viewApi }));\n context.emitter.trigger('eventChange', eventChangeArg);\n }\n else {\n context.emitter.trigger('_noEventResize');\n }\n // reset all internal state\n _this.draggingSeg = null;\n _this.relevantEvents = null;\n _this.validMutation = null;\n // okay to keep eventInstance around. useful to set it in handlePointerDown\n };\n var component = settings.component;\n var dragging = _this.dragging = new FeaturefulElementDragging(settings.el);\n dragging.pointer.selector = '.fc-event-resizer';\n dragging.touchScrollAllowed = false;\n dragging.autoScroller.isEnabled = component.context.options.dragScroll;\n var hitDragging = _this.hitDragging = new HitDragging(_this.dragging, interactionSettingsToStore(settings));\n hitDragging.emitter.on('pointerdown', _this.handlePointerDown);\n hitDragging.emitter.on('dragstart', _this.handleDragStart);\n hitDragging.emitter.on('hitupdate', _this.handleHitUpdate);\n hitDragging.emitter.on('dragend', _this.handleDragEnd);\n return _this;\n }\n EventResizing.prototype.destroy = function () {\n this.dragging.destroy();\n };\n EventResizing.prototype.querySegEl = function (ev) {\n return elementClosest(ev.subjectEl, '.fc-event');\n };\n return EventResizing;\n}(Interaction));\nfunction computeMutation(hit0, hit1, isFromStart, instanceRange) {\n var dateEnv = hit0.context.dateEnv;\n var date0 = hit0.dateSpan.range.start;\n var date1 = hit1.dateSpan.range.start;\n var delta = diffDates(date0, date1, dateEnv, hit0.largeUnit);\n if (isFromStart) {\n if (dateEnv.add(instanceRange.start, delta) < instanceRange.end) {\n return { startDelta: delta };\n }\n }\n else if (dateEnv.add(instanceRange.end, delta) > instanceRange.start) {\n return { endDelta: delta };\n }\n return null;\n}\n\nvar UnselectAuto = /** @class */ (function () {\n function UnselectAuto(context) {\n var _this = this;\n this.context = context;\n this.isRecentPointerDateSelect = false; // wish we could use a selector to detect date selection, but uses hit system\n this.matchesCancel = false;\n this.matchesEvent = false;\n this.onSelect = function (selectInfo) {\n if (selectInfo.jsEvent) {\n _this.isRecentPointerDateSelect = true;\n }\n };\n this.onDocumentPointerDown = function (pev) {\n var unselectCancel = _this.context.options.unselectCancel;\n var downEl = getEventTargetViaRoot(pev.origEvent);\n _this.matchesCancel = !!elementClosest(downEl, unselectCancel);\n _this.matchesEvent = !!elementClosest(downEl, EventDragging.SELECTOR); // interaction started on an event?\n };\n this.onDocumentPointerUp = function (pev) {\n var context = _this.context;\n var documentPointer = _this.documentPointer;\n var calendarState = context.getCurrentData();\n // touch-scrolling should never unfocus any type of selection\n if (!documentPointer.wasTouchScroll) {\n if (calendarState.dateSelection && // an existing date selection?\n !_this.isRecentPointerDateSelect // a new pointer-initiated date selection since last onDocumentPointerUp?\n ) {\n var unselectAuto = context.options.unselectAuto;\n if (unselectAuto && (!unselectAuto || !_this.matchesCancel)) {\n context.calendarApi.unselect(pev);\n }\n }\n if (calendarState.eventSelection && // an existing event selected?\n !_this.matchesEvent // interaction DIDN'T start on an event\n ) {\n context.dispatch({ type: 'UNSELECT_EVENT' });\n }\n }\n _this.isRecentPointerDateSelect = false;\n };\n var documentPointer = this.documentPointer = new PointerDragging(document);\n documentPointer.shouldIgnoreMove = true;\n documentPointer.shouldWatchScroll = false;\n documentPointer.emitter.on('pointerdown', this.onDocumentPointerDown);\n documentPointer.emitter.on('pointerup', this.onDocumentPointerUp);\n /*\n TODO: better way to know about whether there was a selection with the pointer\n */\n context.emitter.on('select', this.onSelect);\n }\n UnselectAuto.prototype.destroy = function () {\n this.context.emitter.off('select', this.onSelect);\n this.documentPointer.destroy();\n };\n return UnselectAuto;\n}());\n\nvar OPTION_REFINERS = {\n fixedMirrorParent: identity,\n};\nvar LISTENER_REFINERS = {\n dateClick: identity,\n eventDragStart: identity,\n eventDragStop: identity,\n eventDrop: identity,\n eventResizeStart: identity,\n eventResizeStop: identity,\n eventResize: identity,\n drop: identity,\n eventReceive: identity,\n eventLeave: identity,\n};\n\n/*\nGiven an already instantiated draggable object for one-or-more elements,\nInterprets any dragging as an attempt to drag an events that lives outside\nof a calendar onto a calendar.\n*/\nvar ExternalElementDragging = /** @class */ (function () {\n function ExternalElementDragging(dragging, suppliedDragMeta) {\n var _this = this;\n this.receivingContext = null;\n this.droppableEvent = null; // will exist for all drags, even if create:false\n this.suppliedDragMeta = null;\n this.dragMeta = null;\n this.handleDragStart = function (ev) {\n _this.dragMeta = _this.buildDragMeta(ev.subjectEl);\n };\n this.handleHitUpdate = function (hit, isFinal, ev) {\n var dragging = _this.hitDragging.dragging;\n var receivingContext = null;\n var droppableEvent = null;\n var isInvalid = false;\n var interaction = {\n affectedEvents: createEmptyEventStore(),\n mutatedEvents: createEmptyEventStore(),\n isEvent: _this.dragMeta.create,\n };\n if (hit) {\n receivingContext = hit.context;\n if (_this.canDropElOnCalendar(ev.subjectEl, receivingContext)) {\n droppableEvent = computeEventForDateSpan(hit.dateSpan, _this.dragMeta, receivingContext);\n interaction.mutatedEvents = eventTupleToStore(droppableEvent);\n isInvalid = !isInteractionValid(interaction, hit.dateProfile, receivingContext);\n if (isInvalid) {\n interaction.mutatedEvents = createEmptyEventStore();\n droppableEvent = null;\n }\n }\n }\n _this.displayDrag(receivingContext, interaction);\n // show mirror if no already-rendered mirror element OR if we are shutting down the mirror (?)\n // TODO: wish we could somehow wait for dispatch to guarantee render\n dragging.setMirrorIsVisible(isFinal || !droppableEvent || !document.querySelector('.fc-event-mirror'));\n if (!isInvalid) {\n enableCursor();\n }\n else {\n disableCursor();\n }\n if (!isFinal) {\n dragging.setMirrorNeedsRevert(!droppableEvent);\n _this.receivingContext = receivingContext;\n _this.droppableEvent = droppableEvent;\n }\n };\n this.handleDragEnd = function (pev) {\n var _a = _this, receivingContext = _a.receivingContext, droppableEvent = _a.droppableEvent;\n _this.clearDrag();\n if (receivingContext && droppableEvent) {\n var finalHit = _this.hitDragging.finalHit;\n var finalView = finalHit.context.viewApi;\n var dragMeta = _this.dragMeta;\n receivingContext.emitter.trigger('drop', __assign(__assign({}, buildDatePointApiWithContext(finalHit.dateSpan, receivingContext)), { draggedEl: pev.subjectEl, jsEvent: pev.origEvent, view: finalView }));\n if (dragMeta.create) {\n var addingEvents_1 = eventTupleToStore(droppableEvent);\n receivingContext.dispatch({\n type: 'MERGE_EVENTS',\n eventStore: addingEvents_1,\n });\n if (pev.isTouch) {\n receivingContext.dispatch({\n type: 'SELECT_EVENT',\n eventInstanceId: droppableEvent.instance.instanceId,\n });\n }\n // signal that an external event landed\n receivingContext.emitter.trigger('eventReceive', {\n event: new EventApi(receivingContext, droppableEvent.def, droppableEvent.instance),\n relatedEvents: [],\n revert: function () {\n receivingContext.dispatch({\n type: 'REMOVE_EVENTS',\n eventStore: addingEvents_1,\n });\n },\n draggedEl: pev.subjectEl,\n view: finalView,\n });\n }\n }\n _this.receivingContext = null;\n _this.droppableEvent = null;\n };\n var hitDragging = this.hitDragging = new HitDragging(dragging, interactionSettingsStore);\n hitDragging.requireInitial = false; // will start outside of a component\n hitDragging.emitter.on('dragstart', this.handleDragStart);\n hitDragging.emitter.on('hitupdate', this.handleHitUpdate);\n hitDragging.emitter.on('dragend', this.handleDragEnd);\n this.suppliedDragMeta = suppliedDragMeta;\n }\n ExternalElementDragging.prototype.buildDragMeta = function (subjectEl) {\n if (typeof this.suppliedDragMeta === 'object') {\n return parseDragMeta(this.suppliedDragMeta);\n }\n if (typeof this.suppliedDragMeta === 'function') {\n return parseDragMeta(this.suppliedDragMeta(subjectEl));\n }\n return getDragMetaFromEl(subjectEl);\n };\n ExternalElementDragging.prototype.displayDrag = function (nextContext, state) {\n var prevContext = this.receivingContext;\n if (prevContext && prevContext !== nextContext) {\n prevContext.dispatch({ type: 'UNSET_EVENT_DRAG' });\n }\n if (nextContext) {\n nextContext.dispatch({ type: 'SET_EVENT_DRAG', state: state });\n }\n };\n ExternalElementDragging.prototype.clearDrag = function () {\n if (this.receivingContext) {\n this.receivingContext.dispatch({ type: 'UNSET_EVENT_DRAG' });\n }\n };\n ExternalElementDragging.prototype.canDropElOnCalendar = function (el, receivingContext) {\n var dropAccept = receivingContext.options.dropAccept;\n if (typeof dropAccept === 'function') {\n return dropAccept.call(receivingContext.calendarApi, el);\n }\n if (typeof dropAccept === 'string' && dropAccept) {\n return Boolean(elementMatches(el, dropAccept));\n }\n return true;\n };\n return ExternalElementDragging;\n}());\n// Utils for computing event store from the DragMeta\n// ----------------------------------------------------------------------------------------------------\nfunction computeEventForDateSpan(dateSpan, dragMeta, context) {\n var defProps = __assign({}, dragMeta.leftoverProps);\n for (var _i = 0, _a = context.pluginHooks.externalDefTransforms; _i < _a.length; _i++) {\n var transform = _a[_i];\n __assign(defProps, transform(dateSpan, dragMeta));\n }\n var _b = refineEventDef(defProps, context), refined = _b.refined, extra = _b.extra;\n var def = parseEventDef(refined, extra, dragMeta.sourceId, dateSpan.allDay, context.options.forceEventDuration || Boolean(dragMeta.duration), // hasEnd\n context);\n var start = dateSpan.range.start;\n // only rely on time info if drop zone is all-day,\n // otherwise, we already know the time\n if (dateSpan.allDay && dragMeta.startTime) {\n start = context.dateEnv.add(start, dragMeta.startTime);\n }\n var end = dragMeta.duration ?\n context.dateEnv.add(start, dragMeta.duration) :\n getDefaultEventEnd(dateSpan.allDay, start, context);\n var instance = createEventInstance(def.defId, { start: start, end: end });\n return { def: def, instance: instance };\n}\n// Utils for extracting data from element\n// ----------------------------------------------------------------------------------------------------\nfunction getDragMetaFromEl(el) {\n var str = getEmbeddedElData(el, 'event');\n var obj = str ?\n JSON.parse(str) :\n { create: false }; // if no embedded data, assume no event creation\n return parseDragMeta(obj);\n}\nconfig.dataAttrPrefix = '';\nfunction getEmbeddedElData(el, name) {\n var prefix = config.dataAttrPrefix;\n var prefixedName = (prefix ? prefix + '-' : '') + name;\n return el.getAttribute('data-' + prefixedName) || '';\n}\n\n/*\nMakes an element (that is *external* to any calendar) draggable.\nCan pass in data that determines how an event will be created when dropped onto a calendar.\nLeverages FullCalendar's internal drag-n-drop functionality WITHOUT a third-party drag system.\n*/\nvar ExternalDraggable = /** @class */ (function () {\n function ExternalDraggable(el, settings) {\n var _this = this;\n if (settings === void 0) { settings = {}; }\n this.handlePointerDown = function (ev) {\n var dragging = _this.dragging;\n var _a = _this.settings, minDistance = _a.minDistance, longPressDelay = _a.longPressDelay;\n dragging.minDistance =\n minDistance != null ?\n minDistance :\n (ev.isTouch ? 0 : BASE_OPTION_DEFAULTS.eventDragMinDistance);\n dragging.delay =\n ev.isTouch ? // TODO: eventually read eventLongPressDelay instead vvv\n (longPressDelay != null ? longPressDelay : BASE_OPTION_DEFAULTS.longPressDelay) :\n 0;\n };\n this.handleDragStart = function (ev) {\n if (ev.isTouch &&\n _this.dragging.delay &&\n ev.subjectEl.classList.contains('fc-event')) {\n _this.dragging.mirror.getMirrorEl().classList.add('fc-event-selected');\n }\n };\n this.settings = settings;\n var dragging = this.dragging = new FeaturefulElementDragging(el);\n dragging.touchScrollAllowed = false;\n if (settings.itemSelector != null) {\n dragging.pointer.selector = settings.itemSelector;\n }\n if (settings.appendTo != null) {\n dragging.mirror.parentNode = settings.appendTo; // TODO: write tests\n }\n dragging.emitter.on('pointerdown', this.handlePointerDown);\n dragging.emitter.on('dragstart', this.handleDragStart);\n new ExternalElementDragging(dragging, settings.eventData); // eslint-disable-line no-new\n }\n ExternalDraggable.prototype.destroy = function () {\n this.dragging.destroy();\n };\n return ExternalDraggable;\n}());\n\n/*\nDetects when a *THIRD-PARTY* drag-n-drop system interacts with elements.\nThe third-party system is responsible for drawing the visuals effects of the drag.\nThis class simply monitors for pointer movements and fires events.\nIt also has the ability to hide the moving element (the \"mirror\") during the drag.\n*/\nvar InferredElementDragging = /** @class */ (function (_super) {\n __extends(InferredElementDragging, _super);\n function InferredElementDragging(containerEl) {\n var _this = _super.call(this, containerEl) || this;\n _this.shouldIgnoreMove = false;\n _this.mirrorSelector = '';\n _this.currentMirrorEl = null;\n _this.handlePointerDown = function (ev) {\n _this.emitter.trigger('pointerdown', ev);\n if (!_this.shouldIgnoreMove) {\n // fire dragstart right away. does not support delay or min-distance\n _this.emitter.trigger('dragstart', ev);\n }\n };\n _this.handlePointerMove = function (ev) {\n if (!_this.shouldIgnoreMove) {\n _this.emitter.trigger('dragmove', ev);\n }\n };\n _this.handlePointerUp = function (ev) {\n _this.emitter.trigger('pointerup', ev);\n if (!_this.shouldIgnoreMove) {\n // fire dragend right away. does not support a revert animation\n _this.emitter.trigger('dragend', ev);\n }\n };\n var pointer = _this.pointer = new PointerDragging(containerEl);\n pointer.emitter.on('pointerdown', _this.handlePointerDown);\n pointer.emitter.on('pointermove', _this.handlePointerMove);\n pointer.emitter.on('pointerup', _this.handlePointerUp);\n return _this;\n }\n InferredElementDragging.prototype.destroy = function () {\n this.pointer.destroy();\n };\n InferredElementDragging.prototype.setIgnoreMove = function (bool) {\n this.shouldIgnoreMove = bool;\n };\n InferredElementDragging.prototype.setMirrorIsVisible = function (bool) {\n if (bool) {\n // restore a previously hidden element.\n // use the reference in case the selector class has already been removed.\n if (this.currentMirrorEl) {\n this.currentMirrorEl.style.visibility = '';\n this.currentMirrorEl = null;\n }\n }\n else {\n var mirrorEl = this.mirrorSelector\n // TODO: somehow query FullCalendars WITHIN shadow-roots\n ? document.querySelector(this.mirrorSelector)\n : null;\n if (mirrorEl) {\n this.currentMirrorEl = mirrorEl;\n mirrorEl.style.visibility = 'hidden';\n }\n }\n };\n return InferredElementDragging;\n}(ElementDragging));\n\n/*\nBridges third-party drag-n-drop systems with FullCalendar.\nMust be instantiated and destroyed by caller.\n*/\nvar ThirdPartyDraggable = /** @class */ (function () {\n function ThirdPartyDraggable(containerOrSettings, settings) {\n var containerEl = document;\n if (\n // wish we could just test instanceof EventTarget, but doesn't work in IE11\n containerOrSettings === document ||\n containerOrSettings instanceof Element) {\n containerEl = containerOrSettings;\n settings = settings || {};\n }\n else {\n settings = (containerOrSettings || {});\n }\n var dragging = this.dragging = new InferredElementDragging(containerEl);\n if (typeof settings.itemSelector === 'string') {\n dragging.pointer.selector = settings.itemSelector;\n }\n else if (containerEl === document) {\n dragging.pointer.selector = '[data-event]';\n }\n if (typeof settings.mirrorSelector === 'string') {\n dragging.mirrorSelector = settings.mirrorSelector;\n }\n new ExternalElementDragging(dragging, settings.eventData); // eslint-disable-line no-new\n }\n ThirdPartyDraggable.prototype.destroy = function () {\n this.dragging.destroy();\n };\n return ThirdPartyDraggable;\n}());\n\nvar main = createPlugin({\n componentInteractions: [DateClicking, DateSelecting, EventDragging, EventResizing],\n calendarInteractions: [UnselectAuto],\n elementDraggingImpl: FeaturefulElementDragging,\n optionRefiners: OPTION_REFINERS,\n listenerRefiners: LISTENER_REFINERS,\n});\n\nexport default main;\nexport { ExternalDraggable as Draggable, FeaturefulElementDragging, PointerDragging, ThirdPartyDraggable };\n","/*!\nFullCalendar v5.11.4\nDocs & License: https://fullcalendar.io/\n(c) 2022 Adam Shaw\n*/\nimport './main.css';\n\nimport { hasBgRendering, Splitter, createFormatter, createElement, ViewContextType, RenderHook, BaseComponent, createRef, diffDays, buildNavLinkAttrs, WeekNumberRoot, getStickyHeaderDates, ViewRoot, SimpleScrollGrid, getStickyFooterScrollbar, NowTimer, NowIndicatorRoot, renderScrollShim, DateComponent, rangeContainsMarker, startOfDay, asRoughMs, createDuration, RefMap, PositionCache, MoreLinkRoot, setRef, SegHierarchy, groupIntersectingEntries, buildEntryKey, binarySearch, getEntrySpanEnd, StandardEvent, DayCellContent, Fragment, getSegMeta, memoize, sortEventSegs, DayCellRoot, buildIsoString, computeEarliestSegStart, buildEventRangeKey, BgEvent, renderFill, addDurations, multiplyDuration, wholeDivideDurations, intersectRanges, Slicer, formatIsoTimeString, DayHeader, DaySeriesModel, DayTableModel, createPlugin } from '@fullcalendar/common';\nimport { __extends, __assign } from 'tslib';\nimport { DayTable } from '@fullcalendar/daygrid';\n\nvar AllDaySplitter = /** @class */ (function (_super) {\n __extends(AllDaySplitter, _super);\n function AllDaySplitter() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n AllDaySplitter.prototype.getKeyInfo = function () {\n return {\n allDay: {},\n timed: {},\n };\n };\n AllDaySplitter.prototype.getKeysForDateSpan = function (dateSpan) {\n if (dateSpan.allDay) {\n return ['allDay'];\n }\n return ['timed'];\n };\n AllDaySplitter.prototype.getKeysForEventDef = function (eventDef) {\n if (!eventDef.allDay) {\n return ['timed'];\n }\n if (hasBgRendering(eventDef)) {\n return ['timed', 'allDay'];\n }\n return ['allDay'];\n };\n return AllDaySplitter;\n}(Splitter));\n\nvar DEFAULT_SLAT_LABEL_FORMAT = createFormatter({\n hour: 'numeric',\n minute: '2-digit',\n omitZeroMinute: true,\n meridiem: 'short',\n});\nfunction TimeColsAxisCell(props) {\n var classNames = [\n 'fc-timegrid-slot',\n 'fc-timegrid-slot-label',\n props.isLabeled ? 'fc-scrollgrid-shrink' : 'fc-timegrid-slot-minor',\n ];\n return (createElement(ViewContextType.Consumer, null, function (context) {\n if (!props.isLabeled) {\n return (createElement(\"td\", { className: classNames.join(' '), \"data-time\": props.isoTimeStr }));\n }\n var dateEnv = context.dateEnv, options = context.options, viewApi = context.viewApi;\n var labelFormat = // TODO: fully pre-parse\n options.slotLabelFormat == null ? DEFAULT_SLAT_LABEL_FORMAT :\n Array.isArray(options.slotLabelFormat) ? createFormatter(options.slotLabelFormat[0]) :\n createFormatter(options.slotLabelFormat);\n var hookProps = {\n level: 0,\n time: props.time,\n date: dateEnv.toDate(props.date),\n view: viewApi,\n text: dateEnv.format(props.date, labelFormat),\n };\n return (createElement(RenderHook, { hookProps: hookProps, classNames: options.slotLabelClassNames, content: options.slotLabelContent, defaultContent: renderInnerContent, didMount: options.slotLabelDidMount, willUnmount: options.slotLabelWillUnmount }, function (rootElRef, customClassNames, innerElRef, innerContent) { return (createElement(\"td\", { ref: rootElRef, className: classNames.concat(customClassNames).join(' '), \"data-time\": props.isoTimeStr },\n createElement(\"div\", { className: \"fc-timegrid-slot-label-frame fc-scrollgrid-shrink-frame\" },\n createElement(\"div\", { className: \"fc-timegrid-slot-label-cushion fc-scrollgrid-shrink-cushion\", ref: innerElRef }, innerContent)))); }));\n }));\n}\nfunction renderInnerContent(props) {\n return props.text;\n}\n\nvar TimeBodyAxis = /** @class */ (function (_super) {\n __extends(TimeBodyAxis, _super);\n function TimeBodyAxis() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n TimeBodyAxis.prototype.render = function () {\n return this.props.slatMetas.map(function (slatMeta) { return (createElement(\"tr\", { key: slatMeta.key },\n createElement(TimeColsAxisCell, __assign({}, slatMeta)))); });\n };\n return TimeBodyAxis;\n}(BaseComponent));\n\nvar DEFAULT_WEEK_NUM_FORMAT = createFormatter({ week: 'short' });\nvar AUTO_ALL_DAY_MAX_EVENT_ROWS = 5;\nvar TimeColsView = /** @class */ (function (_super) {\n __extends(TimeColsView, _super);\n function TimeColsView() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.allDaySplitter = new AllDaySplitter(); // for use by subclasses\n _this.headerElRef = createRef();\n _this.rootElRef = createRef();\n _this.scrollerElRef = createRef();\n _this.state = {\n slatCoords: null,\n };\n _this.handleScrollTopRequest = function (scrollTop) {\n var scrollerEl = _this.scrollerElRef.current;\n if (scrollerEl) { // TODO: not sure how this could ever be null. weirdness with the reducer\n scrollerEl.scrollTop = scrollTop;\n }\n };\n /* Header Render Methods\n ------------------------------------------------------------------------------------------------------------------*/\n _this.renderHeadAxis = function (rowKey, frameHeight) {\n if (frameHeight === void 0) { frameHeight = ''; }\n var options = _this.context.options;\n var dateProfile = _this.props.dateProfile;\n var range = dateProfile.renderRange;\n var dayCnt = diffDays(range.start, range.end);\n var navLinkAttrs = (dayCnt === 1) // only do in day views (to avoid doing in week views that dont need it)\n ? buildNavLinkAttrs(_this.context, range.start, 'week')\n : {};\n if (options.weekNumbers && rowKey === 'day') {\n return (createElement(WeekNumberRoot, { date: range.start, defaultFormat: DEFAULT_WEEK_NUM_FORMAT }, function (rootElRef, classNames, innerElRef, innerContent) { return (createElement(\"th\", { ref: rootElRef, \"aria-hidden\": true, className: [\n 'fc-timegrid-axis',\n 'fc-scrollgrid-shrink',\n ].concat(classNames).join(' ') },\n createElement(\"div\", { className: \"fc-timegrid-axis-frame fc-scrollgrid-shrink-frame fc-timegrid-axis-frame-liquid\", style: { height: frameHeight } },\n createElement(\"a\", __assign({ ref: innerElRef, className: \"fc-timegrid-axis-cushion fc-scrollgrid-shrink-cushion fc-scrollgrid-sync-inner\" }, navLinkAttrs), innerContent)))); }));\n }\n return (createElement(\"th\", { \"aria-hidden\": true, className: \"fc-timegrid-axis\" },\n createElement(\"div\", { className: \"fc-timegrid-axis-frame\", style: { height: frameHeight } })));\n };\n /* Table Component Render Methods\n ------------------------------------------------------------------------------------------------------------------*/\n // only a one-way height sync. we don't send the axis inner-content height to the DayGrid,\n // but DayGrid still needs to have classNames on inner elements in order to measure.\n _this.renderTableRowAxis = function (rowHeight) {\n var _a = _this.context, options = _a.options, viewApi = _a.viewApi;\n var hookProps = {\n text: options.allDayText,\n view: viewApi,\n };\n return (\n // TODO: make reusable hook. used in list view too\n createElement(RenderHook, { hookProps: hookProps, classNames: options.allDayClassNames, content: options.allDayContent, defaultContent: renderAllDayInner, didMount: options.allDayDidMount, willUnmount: options.allDayWillUnmount }, function (rootElRef, classNames, innerElRef, innerContent) { return (createElement(\"td\", { ref: rootElRef, \"aria-hidden\": true, className: [\n 'fc-timegrid-axis',\n 'fc-scrollgrid-shrink',\n ].concat(classNames).join(' ') },\n createElement(\"div\", { className: 'fc-timegrid-axis-frame fc-scrollgrid-shrink-frame' + (rowHeight == null ? ' fc-timegrid-axis-frame-liquid' : ''), style: { height: rowHeight } },\n createElement(\"span\", { className: \"fc-timegrid-axis-cushion fc-scrollgrid-shrink-cushion fc-scrollgrid-sync-inner\", ref: innerElRef }, innerContent)))); }));\n };\n _this.handleSlatCoords = function (slatCoords) {\n _this.setState({ slatCoords: slatCoords });\n };\n return _this;\n }\n // rendering\n // ----------------------------------------------------------------------------------------------------\n TimeColsView.prototype.renderSimpleLayout = function (headerRowContent, allDayContent, timeContent) {\n var _a = this, context = _a.context, props = _a.props;\n var sections = [];\n var stickyHeaderDates = getStickyHeaderDates(context.options);\n if (headerRowContent) {\n sections.push({\n type: 'header',\n key: 'header',\n isSticky: stickyHeaderDates,\n chunk: {\n elRef: this.headerElRef,\n tableClassName: 'fc-col-header',\n rowContent: headerRowContent,\n },\n });\n }\n if (allDayContent) {\n sections.push({\n type: 'body',\n key: 'all-day',\n chunk: { content: allDayContent },\n });\n sections.push({\n type: 'body',\n key: 'all-day-divider',\n outerContent: ( // TODO: rename to cellContent so don't need to define
?\n createElement(\"tr\", { role: \"presentation\", className: \"fc-scrollgrid-section\" },\n createElement(\"td\", { colSpan: 2, className: 'fc-timegrid-divider ' + context.theme.getClass('tableCellShaded') }))),\n });\n }\n var isNowIndicator = context.options.nowIndicator;\n sections.push({\n type: 'body',\n key: 'body',\n liquid: true,\n expandRows: Boolean(context.options.expandRows),\n chunks: [\n {\n key: 'axis',\n content: function (arg) { return (\n // TODO: make this now-indicator arrow more DRY with TimeColsContent\n createElement(\"div\", { className: \"fc-timegrid-axis-chunk\" },\n createElement(\"table\", { \"aria-hidden\": true, style: { height: arg.expandRows ? arg.clientHeight : '' } },\n arg.tableColGroupNode,\n createElement(\"tbody\", null,\n createElement(TimeBodyAxis, { slatMetas: slatMetas }))),\n createElement(\"div\", { className: \"fc-timegrid-now-indicator-container\" },\n createElement(NowTimer, { unit: isNowIndicator ? 'minute' : 'day' /* hacky */ }, function (nowDate) {\n var nowIndicatorTop = isNowIndicator &&\n slatCoords &&\n slatCoords.safeComputeTop(nowDate); // might return void\n if (typeof nowIndicatorTop === 'number') {\n return (createElement(NowIndicatorRoot, { isAxis: true, date: nowDate }, function (rootElRef, classNames, innerElRef, innerContent) { return (createElement(\"div\", { ref: rootElRef, className: ['fc-timegrid-now-indicator-arrow'].concat(classNames).join(' '), style: { top: nowIndicatorTop } }, innerContent)); }));\n }\n return null;\n })))); },\n },\n {\n key: 'cols',\n scrollerElRef: this.scrollerElRef,\n content: timeContent,\n },\n ],\n });\n if (stickyFooterScrollbar) {\n sections.push({\n key: 'footer',\n type: 'footer',\n isSticky: true,\n chunks: [\n {\n key: 'axis',\n content: renderScrollShim,\n },\n {\n key: 'cols',\n content: renderScrollShim,\n },\n ],\n });\n }\n return (createElement(ViewRoot, { viewSpec: context.viewSpec, elRef: this.rootElRef }, function (rootElRef, classNames) { return (createElement(\"div\", { className: ['fc-timegrid'].concat(classNames).join(' '), ref: rootElRef },\n createElement(ScrollGrid, { liquid: !props.isHeightAuto && !props.forPrint, collapsibleWidth: false, colGroups: [\n { width: 'shrink', cols: [{ width: 'shrink' }] },\n { cols: [{ span: colCnt, minWidth: dayMinWidth }] },\n ], sections: sections }))); }));\n };\n /* Dimensions\n ------------------------------------------------------------------------------------------------------------------*/\n TimeColsView.prototype.getAllDayMaxEventProps = function () {\n var _a = this.context.options, dayMaxEvents = _a.dayMaxEvents, dayMaxEventRows = _a.dayMaxEventRows;\n if (dayMaxEvents === true || dayMaxEventRows === true) { // is auto?\n dayMaxEvents = undefined;\n dayMaxEventRows = AUTO_ALL_DAY_MAX_EVENT_ROWS; // make sure \"auto\" goes to a real number\n }\n return { dayMaxEvents: dayMaxEvents, dayMaxEventRows: dayMaxEventRows };\n };\n return TimeColsView;\n}(DateComponent));\nfunction renderAllDayInner(hookProps) {\n return hookProps.text;\n}\n\nvar TimeColsSlatsCoords = /** @class */ (function () {\n function TimeColsSlatsCoords(positions, dateProfile, slotDuration) {\n this.positions = positions;\n this.dateProfile = dateProfile;\n this.slotDuration = slotDuration;\n }\n TimeColsSlatsCoords.prototype.safeComputeTop = function (date) {\n var dateProfile = this.dateProfile;\n if (rangeContainsMarker(dateProfile.currentRange, date)) {\n var startOfDayDate = startOfDay(date);\n var timeMs = date.valueOf() - startOfDayDate.valueOf();\n if (timeMs >= asRoughMs(dateProfile.slotMinTime) &&\n timeMs < asRoughMs(dateProfile.slotMaxTime)) {\n return this.computeTimeTop(createDuration(timeMs));\n }\n }\n return null;\n };\n // Computes the top coordinate, relative to the bounds of the grid, of the given date.\n // A `startOfDayDate` must be given for avoiding ambiguity over how to treat midnight.\n TimeColsSlatsCoords.prototype.computeDateTop = function (when, startOfDayDate) {\n if (!startOfDayDate) {\n startOfDayDate = startOfDay(when);\n }\n return this.computeTimeTop(createDuration(when.valueOf() - startOfDayDate.valueOf()));\n };\n // Computes the top coordinate, relative to the bounds of the grid, of the given time (a Duration).\n // This is a makeshify way to compute the time-top. Assumes all slatMetas dates are uniform.\n // Eventually allow computation with arbirary slat dates.\n TimeColsSlatsCoords.prototype.computeTimeTop = function (duration) {\n var _a = this, positions = _a.positions, dateProfile = _a.dateProfile;\n var len = positions.els.length;\n // floating-point value of # of slots covered\n var slatCoverage = (duration.milliseconds - asRoughMs(dateProfile.slotMinTime)) / asRoughMs(this.slotDuration);\n var slatIndex;\n var slatRemainder;\n // compute a floating-point number for how many slats should be progressed through.\n // from 0 to number of slats (inclusive)\n // constrained because slotMinTime/slotMaxTime might be customized.\n slatCoverage = Math.max(0, slatCoverage);\n slatCoverage = Math.min(len, slatCoverage);\n // an integer index of the furthest whole slat\n // from 0 to number slats (*exclusive*, so len-1)\n slatIndex = Math.floor(slatCoverage);\n slatIndex = Math.min(slatIndex, len - 1);\n // how much further through the slatIndex slat (from 0.0-1.0) must be covered in addition.\n // could be 1.0 if slatCoverage is covering *all* the slots\n slatRemainder = slatCoverage - slatIndex;\n return positions.tops[slatIndex] +\n positions.getHeight(slatIndex) * slatRemainder;\n };\n return TimeColsSlatsCoords;\n}());\n\nvar TimeColsSlatsBody = /** @class */ (function (_super) {\n __extends(TimeColsSlatsBody, _super);\n function TimeColsSlatsBody() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n TimeColsSlatsBody.prototype.render = function () {\n var _a = this, props = _a.props, context = _a.context;\n var options = context.options;\n var slatElRefs = props.slatElRefs;\n return (createElement(\"tbody\", null, props.slatMetas.map(function (slatMeta, i) {\n var hookProps = {\n time: slatMeta.time,\n date: context.dateEnv.toDate(slatMeta.date),\n view: context.viewApi,\n };\n var classNames = [\n 'fc-timegrid-slot',\n 'fc-timegrid-slot-lane',\n slatMeta.isLabeled ? '' : 'fc-timegrid-slot-minor',\n ];\n return (createElement(\"tr\", { key: slatMeta.key, ref: slatElRefs.createRef(slatMeta.key) },\n props.axis && (createElement(TimeColsAxisCell, __assign({}, slatMeta))),\n createElement(RenderHook, { hookProps: hookProps, classNames: options.slotLaneClassNames, content: options.slotLaneContent, didMount: options.slotLaneDidMount, willUnmount: options.slotLaneWillUnmount }, function (rootElRef, customClassNames, innerElRef, innerContent) { return (createElement(\"td\", { ref: rootElRef, className: classNames.concat(customClassNames).join(' '), \"data-time\": slatMeta.isoTimeStr }, innerContent)); })));\n })));\n };\n return TimeColsSlatsBody;\n}(BaseComponent));\n\n/*\nfor the horizontal \"slats\" that run width-wise. Has a time axis on a side. Depends on RTL.\n*/\nvar TimeColsSlats = /** @class */ (function (_super) {\n __extends(TimeColsSlats, _super);\n function TimeColsSlats() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.rootElRef = createRef();\n _this.slatElRefs = new RefMap();\n return _this;\n }\n TimeColsSlats.prototype.render = function () {\n var _a = this, props = _a.props, context = _a.context;\n return (createElement(\"div\", { ref: this.rootElRef, className: \"fc-timegrid-slots\" },\n createElement(\"table\", { \"aria-hidden\": true, className: context.theme.getClass('table'), style: {\n minWidth: props.tableMinWidth,\n width: props.clientWidth,\n height: props.minHeight,\n } },\n props.tableColGroupNode /* relies on there only being a single
for the axis */,\n createElement(TimeColsSlatsBody, { slatElRefs: this.slatElRefs, axis: props.axis, slatMetas: props.slatMetas }))));\n };\n TimeColsSlats.prototype.componentDidMount = function () {\n this.updateSizing();\n };\n TimeColsSlats.prototype.componentDidUpdate = function () {\n this.updateSizing();\n };\n TimeColsSlats.prototype.componentWillUnmount = function () {\n if (this.props.onCoords) {\n this.props.onCoords(null);\n }\n };\n TimeColsSlats.prototype.updateSizing = function () {\n var _a = this, context = _a.context, props = _a.props;\n if (props.onCoords &&\n props.clientWidth !== null // means sizing has stabilized\n ) {\n var rootEl = this.rootElRef.current;\n if (rootEl.offsetHeight) { // not hidden by css\n props.onCoords(new TimeColsSlatsCoords(new PositionCache(this.rootElRef.current, collectSlatEls(this.slatElRefs.currentMap, props.slatMetas), false, true), this.props.dateProfile, context.options.slotDuration));\n }\n }\n };\n return TimeColsSlats;\n}(BaseComponent));\nfunction collectSlatEls(elMap, slatMetas) {\n return slatMetas.map(function (slatMeta) { return elMap[slatMeta.key]; });\n}\n\nfunction splitSegsByCol(segs, colCnt) {\n var segsByCol = [];\n var i;\n for (i = 0; i < colCnt; i += 1) {\n segsByCol.push([]);\n }\n if (segs) {\n for (i = 0; i < segs.length; i += 1) {\n segsByCol[segs[i].col].push(segs[i]);\n }\n }\n return segsByCol;\n}\nfunction splitInteractionByCol(ui, colCnt) {\n var byRow = [];\n if (!ui) {\n for (var i = 0; i < colCnt; i += 1) {\n byRow[i] = null;\n }\n }\n else {\n for (var i = 0; i < colCnt; i += 1) {\n byRow[i] = {\n affectedInstances: ui.affectedInstances,\n isEvent: ui.isEvent,\n segs: [],\n };\n }\n for (var _i = 0, _a = ui.segs; _i < _a.length; _i++) {\n var seg = _a[_i];\n byRow[seg.col].segs.push(seg);\n }\n }\n return byRow;\n}\n\nvar TimeColMoreLink = /** @class */ (function (_super) {\n __extends(TimeColMoreLink, _super);\n function TimeColMoreLink() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.rootElRef = createRef();\n return _this;\n }\n TimeColMoreLink.prototype.render = function () {\n var _this = this;\n var props = this.props;\n return (createElement(MoreLinkRoot, { allDayDate: null, moreCnt: props.hiddenSegs.length, allSegs: props.hiddenSegs, hiddenSegs: props.hiddenSegs, alignmentElRef: this.rootElRef, defaultContent: renderMoreLinkInner, extraDateSpan: props.extraDateSpan, dateProfile: props.dateProfile, todayRange: props.todayRange, popoverContent: function () { return renderPlainFgSegs(props.hiddenSegs, props); } }, function (rootElRef, classNames, innerElRef, innerContent, handleClick, title, isExpanded, popoverId) { return (createElement(\"a\", { ref: function (el) {\n setRef(rootElRef, el);\n setRef(_this.rootElRef, el);\n }, className: ['fc-timegrid-more-link'].concat(classNames).join(' '), style: { top: props.top, bottom: props.bottom }, onClick: handleClick, title: title, \"aria-expanded\": isExpanded, \"aria-controls\": popoverId },\n createElement(\"div\", { ref: innerElRef, className: \"fc-timegrid-more-link-inner fc-sticky\" }, innerContent))); }));\n };\n return TimeColMoreLink;\n}(BaseComponent));\nfunction renderMoreLinkInner(props) {\n return props.shortText;\n}\n\n// segInputs assumed sorted\nfunction buildPositioning(segInputs, strictOrder, maxStackCnt) {\n var hierarchy = new SegHierarchy();\n if (strictOrder != null) {\n hierarchy.strictOrder = strictOrder;\n }\n if (maxStackCnt != null) {\n hierarchy.maxStackCnt = maxStackCnt;\n }\n var hiddenEntries = hierarchy.addSegs(segInputs);\n var hiddenGroups = groupIntersectingEntries(hiddenEntries);\n var web = buildWeb(hierarchy);\n web = stretchWeb(web, 1); // all levelCoords/thickness will have 0.0-1.0\n var segRects = webToRects(web);\n return { segRects: segRects, hiddenGroups: hiddenGroups };\n}\nfunction buildWeb(hierarchy) {\n var entriesByLevel = hierarchy.entriesByLevel;\n var buildNode = cacheable(function (level, lateral) { return level + ':' + lateral; }, function (level, lateral) {\n var siblingRange = findNextLevelSegs(hierarchy, level, lateral);\n var nextLevelRes = buildNodes(siblingRange, buildNode);\n var entry = entriesByLevel[level][lateral];\n return [\n __assign(__assign({}, entry), { nextLevelNodes: nextLevelRes[0] }),\n entry.thickness + nextLevelRes[1], // the pressure builds\n ];\n });\n return buildNodes(entriesByLevel.length\n ? { level: 0, lateralStart: 0, lateralEnd: entriesByLevel[0].length }\n : null, buildNode)[0];\n}\nfunction buildNodes(siblingRange, buildNode) {\n if (!siblingRange) {\n return [[], 0];\n }\n var level = siblingRange.level, lateralStart = siblingRange.lateralStart, lateralEnd = siblingRange.lateralEnd;\n var lateral = lateralStart;\n var pairs = [];\n while (lateral < lateralEnd) {\n pairs.push(buildNode(level, lateral));\n lateral += 1;\n }\n pairs.sort(cmpDescPressures);\n return [\n pairs.map(extractNode),\n pairs[0][1], // first item's pressure\n ];\n}\nfunction cmpDescPressures(a, b) {\n return b[1] - a[1];\n}\nfunction extractNode(a) {\n return a[0];\n}\nfunction findNextLevelSegs(hierarchy, subjectLevel, subjectLateral) {\n var levelCoords = hierarchy.levelCoords, entriesByLevel = hierarchy.entriesByLevel;\n var subjectEntry = entriesByLevel[subjectLevel][subjectLateral];\n var afterSubject = levelCoords[subjectLevel] + subjectEntry.thickness;\n var levelCnt = levelCoords.length;\n var level = subjectLevel;\n // skip past levels that are too high up\n for (; level < levelCnt && levelCoords[level] < afterSubject; level += 1)\n ; // do nothing\n for (; level < levelCnt; level += 1) {\n var entries = entriesByLevel[level];\n var entry = void 0;\n var searchIndex = binarySearch(entries, subjectEntry.span.start, getEntrySpanEnd);\n var lateralStart = searchIndex[0] + searchIndex[1]; // if exact match (which doesn't collide), go to next one\n var lateralEnd = lateralStart;\n while ( // loop through entries that horizontally intersect\n (entry = entries[lateralEnd]) && // but not past the whole seg list\n entry.span.start < subjectEntry.span.end) {\n lateralEnd += 1;\n }\n if (lateralStart < lateralEnd) {\n return { level: level, lateralStart: lateralStart, lateralEnd: lateralEnd };\n }\n }\n return null;\n}\nfunction stretchWeb(topLevelNodes, totalThickness) {\n var stretchNode = cacheable(function (node, startCoord, prevThickness) { return buildEntryKey(node); }, function (node, startCoord, prevThickness) {\n var nextLevelNodes = node.nextLevelNodes, thickness = node.thickness;\n var allThickness = thickness + prevThickness;\n var thicknessFraction = thickness / allThickness;\n var endCoord;\n var newChildren = [];\n if (!nextLevelNodes.length) {\n endCoord = totalThickness;\n }\n else {\n for (var _i = 0, nextLevelNodes_1 = nextLevelNodes; _i < nextLevelNodes_1.length; _i++) {\n var childNode = nextLevelNodes_1[_i];\n if (endCoord === undefined) {\n var res = stretchNode(childNode, startCoord, allThickness);\n endCoord = res[0];\n newChildren.push(res[1]);\n }\n else {\n var res = stretchNode(childNode, endCoord, 0);\n newChildren.push(res[1]);\n }\n }\n }\n var newThickness = (endCoord - startCoord) * thicknessFraction;\n return [endCoord - newThickness, __assign(__assign({}, node), { thickness: newThickness, nextLevelNodes: newChildren })];\n });\n return topLevelNodes.map(function (node) { return stretchNode(node, 0, 0)[1]; });\n}\n// not sorted in any particular order\nfunction webToRects(topLevelNodes) {\n var rects = [];\n var processNode = cacheable(function (node, levelCoord, stackDepth) { return buildEntryKey(node); }, function (node, levelCoord, stackDepth) {\n var rect = __assign(__assign({}, node), { levelCoord: levelCoord,\n stackDepth: stackDepth, stackForward: 0 });\n rects.push(rect);\n return (rect.stackForward = processNodes(node.nextLevelNodes, levelCoord + node.thickness, stackDepth + 1) + 1);\n });\n function processNodes(nodes, levelCoord, stackDepth) {\n var stackForward = 0;\n for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {\n var node = nodes_1[_i];\n stackForward = Math.max(processNode(node, levelCoord, stackDepth), stackForward);\n }\n return stackForward;\n }\n processNodes(topLevelNodes, 0, 0);\n return rects; // TODO: sort rects by levelCoord to be consistent with toRects?\n}\n// TODO: move to general util\nfunction cacheable(keyFunc, workFunc) {\n var cache = {};\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var key = keyFunc.apply(void 0, args);\n return (key in cache)\n ? cache[key]\n : (cache[key] = workFunc.apply(void 0, args));\n };\n}\n\nfunction computeSegVCoords(segs, colDate, slatCoords, eventMinHeight) {\n if (slatCoords === void 0) { slatCoords = null; }\n if (eventMinHeight === void 0) { eventMinHeight = 0; }\n var vcoords = [];\n if (slatCoords) {\n for (var i = 0; i < segs.length; i += 1) {\n var seg = segs[i];\n var spanStart = slatCoords.computeDateTop(seg.start, colDate);\n var spanEnd = Math.max(spanStart + (eventMinHeight || 0), // :(\n slatCoords.computeDateTop(seg.end, colDate));\n vcoords.push({\n start: Math.round(spanStart),\n end: Math.round(spanEnd), //\n });\n }\n }\n return vcoords;\n}\nfunction computeFgSegPlacements(segs, segVCoords, // might not have for every seg\neventOrderStrict, eventMaxStack) {\n var segInputs = [];\n var dumbSegs = []; // segs without coords\n for (var i = 0; i < segs.length; i += 1) {\n var vcoords = segVCoords[i];\n if (vcoords) {\n segInputs.push({\n index: i,\n thickness: 1,\n span: vcoords,\n });\n }\n else {\n dumbSegs.push(segs[i]);\n }\n }\n var _a = buildPositioning(segInputs, eventOrderStrict, eventMaxStack), segRects = _a.segRects, hiddenGroups = _a.hiddenGroups;\n var segPlacements = [];\n for (var _i = 0, segRects_1 = segRects; _i < segRects_1.length; _i++) {\n var segRect = segRects_1[_i];\n segPlacements.push({\n seg: segs[segRect.index],\n rect: segRect,\n });\n }\n for (var _b = 0, dumbSegs_1 = dumbSegs; _b < dumbSegs_1.length; _b++) {\n var dumbSeg = dumbSegs_1[_b];\n segPlacements.push({ seg: dumbSeg, rect: null });\n }\n return { segPlacements: segPlacements, hiddenGroups: hiddenGroups };\n}\n\nvar DEFAULT_TIME_FORMAT = createFormatter({\n hour: 'numeric',\n minute: '2-digit',\n meridiem: false,\n});\nvar TimeColEvent = /** @class */ (function (_super) {\n __extends(TimeColEvent, _super);\n function TimeColEvent() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n TimeColEvent.prototype.render = function () {\n var classNames = [\n 'fc-timegrid-event',\n 'fc-v-event',\n ];\n if (this.props.isShort) {\n classNames.push('fc-timegrid-event-short');\n }\n return (createElement(StandardEvent, __assign({}, this.props, { defaultTimeFormat: DEFAULT_TIME_FORMAT, extraClassNames: classNames })));\n };\n return TimeColEvent;\n}(BaseComponent));\n\nvar TimeColMisc = /** @class */ (function (_super) {\n __extends(TimeColMisc, _super);\n function TimeColMisc() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n TimeColMisc.prototype.render = function () {\n var props = this.props;\n return (createElement(DayCellContent, { date: props.date, dateProfile: props.dateProfile, todayRange: props.todayRange, extraHookProps: props.extraHookProps }, function (innerElRef, innerContent) { return (innerContent &&\n createElement(\"div\", { className: \"fc-timegrid-col-misc\", ref: innerElRef }, innerContent)); }));\n };\n return TimeColMisc;\n}(BaseComponent));\n\nvar TimeCol = /** @class */ (function (_super) {\n __extends(TimeCol, _super);\n function TimeCol() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.sortEventSegs = memoize(sortEventSegs);\n return _this;\n }\n // TODO: memoize event-placement?\n TimeCol.prototype.render = function () {\n var _this = this;\n var _a = this, props = _a.props, context = _a.context;\n var isSelectMirror = context.options.selectMirror;\n var mirrorSegs = (props.eventDrag && props.eventDrag.segs) ||\n (props.eventResize && props.eventResize.segs) ||\n (isSelectMirror && props.dateSelectionSegs) ||\n [];\n var interactionAffectedInstances = // TODO: messy way to compute this\n (props.eventDrag && props.eventDrag.affectedInstances) ||\n (props.eventResize && props.eventResize.affectedInstances) ||\n {};\n var sortedFgSegs = this.sortEventSegs(props.fgEventSegs, context.options.eventOrder);\n return (createElement(DayCellRoot, { elRef: props.elRef, date: props.date, dateProfile: props.dateProfile, todayRange: props.todayRange, extraHookProps: props.extraHookProps }, function (rootElRef, classNames, dataAttrs) { return (createElement(\"td\", __assign({ ref: rootElRef, role: \"gridcell\", className: ['fc-timegrid-col'].concat(classNames, props.extraClassNames || []).join(' ') }, dataAttrs, props.extraDataAttrs),\n createElement(\"div\", { className: \"fc-timegrid-col-frame\" },\n createElement(\"div\", { className: \"fc-timegrid-col-bg\" },\n _this.renderFillSegs(props.businessHourSegs, 'non-business'),\n _this.renderFillSegs(props.bgEventSegs, 'bg-event'),\n _this.renderFillSegs(props.dateSelectionSegs, 'highlight')),\n createElement(\"div\", { className: \"fc-timegrid-col-events\" }, _this.renderFgSegs(sortedFgSegs, interactionAffectedInstances, false, false, false)),\n createElement(\"div\", { className: \"fc-timegrid-col-events\" }, _this.renderFgSegs(mirrorSegs, {}, Boolean(props.eventDrag), Boolean(props.eventResize), Boolean(isSelectMirror))),\n createElement(\"div\", { className: \"fc-timegrid-now-indicator-container\" }, _this.renderNowIndicator(props.nowIndicatorSegs)),\n createElement(TimeColMisc, { date: props.date, dateProfile: props.dateProfile, todayRange: props.todayRange, extraHookProps: props.extraHookProps })))); }));\n };\n TimeCol.prototype.renderFgSegs = function (sortedFgSegs, segIsInvisible, isDragging, isResizing, isDateSelecting) {\n var props = this.props;\n if (props.forPrint) {\n return renderPlainFgSegs(sortedFgSegs, props);\n }\n return this.renderPositionedFgSegs(sortedFgSegs, segIsInvisible, isDragging, isResizing, isDateSelecting);\n };\n TimeCol.prototype.renderPositionedFgSegs = function (segs, // if not mirror, needs to be sorted\n segIsInvisible, isDragging, isResizing, isDateSelecting) {\n var _this = this;\n var _a = this.context.options, eventMaxStack = _a.eventMaxStack, eventShortHeight = _a.eventShortHeight, eventOrderStrict = _a.eventOrderStrict, eventMinHeight = _a.eventMinHeight;\n var _b = this.props, date = _b.date, slatCoords = _b.slatCoords, eventSelection = _b.eventSelection, todayRange = _b.todayRange, nowDate = _b.nowDate;\n var isMirror = isDragging || isResizing || isDateSelecting;\n var segVCoords = computeSegVCoords(segs, date, slatCoords, eventMinHeight);\n var _c = computeFgSegPlacements(segs, segVCoords, eventOrderStrict, eventMaxStack), segPlacements = _c.segPlacements, hiddenGroups = _c.hiddenGroups;\n return (createElement(Fragment, null,\n this.renderHiddenGroups(hiddenGroups, segs),\n segPlacements.map(function (segPlacement) {\n var seg = segPlacement.seg, rect = segPlacement.rect;\n var instanceId = seg.eventRange.instance.instanceId;\n var isVisible = isMirror || Boolean(!segIsInvisible[instanceId] && rect);\n var vStyle = computeSegVStyle(rect && rect.span);\n var hStyle = (!isMirror && rect) ? _this.computeSegHStyle(rect) : { left: 0, right: 0 };\n var isInset = Boolean(rect) && rect.stackForward > 0;\n var isShort = Boolean(rect) && (rect.span.end - rect.span.start) < eventShortHeight; // look at other places for this problem\n return (createElement(\"div\", { className: 'fc-timegrid-event-harness' +\n (isInset ? ' fc-timegrid-event-harness-inset' : ''), key: instanceId, style: __assign(__assign({ visibility: isVisible ? '' : 'hidden' }, vStyle), hStyle) },\n createElement(TimeColEvent, __assign({ seg: seg, isDragging: isDragging, isResizing: isResizing, isDateSelecting: isDateSelecting, isSelected: instanceId === eventSelection, isShort: isShort }, getSegMeta(seg, todayRange, nowDate)))));\n })));\n };\n // will already have eventMinHeight applied because segInputs already had it\n TimeCol.prototype.renderHiddenGroups = function (hiddenGroups, segs) {\n var _a = this.props, extraDateSpan = _a.extraDateSpan, dateProfile = _a.dateProfile, todayRange = _a.todayRange, nowDate = _a.nowDate, eventSelection = _a.eventSelection, eventDrag = _a.eventDrag, eventResize = _a.eventResize;\n return (createElement(Fragment, null, hiddenGroups.map(function (hiddenGroup) {\n var positionCss = computeSegVStyle(hiddenGroup.span);\n var hiddenSegs = compileSegsFromEntries(hiddenGroup.entries, segs);\n return (createElement(TimeColMoreLink, { key: buildIsoString(computeEarliestSegStart(hiddenSegs)), hiddenSegs: hiddenSegs, top: positionCss.top, bottom: positionCss.bottom, extraDateSpan: extraDateSpan, dateProfile: dateProfile, todayRange: todayRange, nowDate: nowDate, eventSelection: eventSelection, eventDrag: eventDrag, eventResize: eventResize }));\n })));\n };\n TimeCol.prototype.renderFillSegs = function (segs, fillType) {\n var _a = this, props = _a.props, context = _a.context;\n var segVCoords = computeSegVCoords(segs, props.date, props.slatCoords, context.options.eventMinHeight); // don't assume all populated\n var children = segVCoords.map(function (vcoords, i) {\n var seg = segs[i];\n return (createElement(\"div\", { key: buildEventRangeKey(seg.eventRange), className: \"fc-timegrid-bg-harness\", style: computeSegVStyle(vcoords) }, fillType === 'bg-event' ?\n createElement(BgEvent, __assign({ seg: seg }, getSegMeta(seg, props.todayRange, props.nowDate))) :\n renderFill(fillType)));\n });\n return createElement(Fragment, null, children);\n };\n TimeCol.prototype.renderNowIndicator = function (segs) {\n var _a = this.props, slatCoords = _a.slatCoords, date = _a.date;\n if (!slatCoords) {\n return null;\n }\n return segs.map(function (seg, i) { return (createElement(NowIndicatorRoot, { isAxis: false, date: date, \n // key doesn't matter. will only ever be one\n key: i }, function (rootElRef, classNames, innerElRef, innerContent) { return (createElement(\"div\", { ref: rootElRef, className: ['fc-timegrid-now-indicator-line'].concat(classNames).join(' '), style: { top: slatCoords.computeDateTop(seg.start, date) } }, innerContent)); })); });\n };\n TimeCol.prototype.computeSegHStyle = function (segHCoords) {\n var _a = this.context, isRtl = _a.isRtl, options = _a.options;\n var shouldOverlap = options.slotEventOverlap;\n var nearCoord = segHCoords.levelCoord; // the left side if LTR. the right side if RTL. floating-point\n var farCoord = segHCoords.levelCoord + segHCoords.thickness; // the right side if LTR. the left side if RTL. floating-point\n var left; // amount of space from left edge, a fraction of the total width\n var right; // amount of space from right edge, a fraction of the total width\n if (shouldOverlap) {\n // double the width, but don't go beyond the maximum forward coordinate (1.0)\n farCoord = Math.min(1, nearCoord + (farCoord - nearCoord) * 2);\n }\n if (isRtl) {\n left = 1 - farCoord;\n right = nearCoord;\n }\n else {\n left = nearCoord;\n right = 1 - farCoord;\n }\n var props = {\n zIndex: segHCoords.stackDepth + 1,\n left: left * 100 + '%',\n right: right * 100 + '%',\n };\n if (shouldOverlap && !segHCoords.stackForward) {\n // add padding to the edge so that forward stacked events don't cover the resizer's icon\n props[isRtl ? 'marginLeft' : 'marginRight'] = 10 * 2; // 10 is a guesstimate of the icon's width\n }\n return props;\n };\n return TimeCol;\n}(BaseComponent));\nfunction renderPlainFgSegs(sortedFgSegs, _a) {\n var todayRange = _a.todayRange, nowDate = _a.nowDate, eventSelection = _a.eventSelection, eventDrag = _a.eventDrag, eventResize = _a.eventResize;\n var hiddenInstances = (eventDrag ? eventDrag.affectedInstances : null) ||\n (eventResize ? eventResize.affectedInstances : null) ||\n {};\n return (createElement(Fragment, null, sortedFgSegs.map(function (seg) {\n var instanceId = seg.eventRange.instance.instanceId;\n return (createElement(\"div\", { key: instanceId, style: { visibility: hiddenInstances[instanceId] ? 'hidden' : '' } },\n createElement(TimeColEvent, __assign({ seg: seg, isDragging: false, isResizing: false, isDateSelecting: false, isSelected: instanceId === eventSelection, isShort: false }, getSegMeta(seg, todayRange, nowDate)))));\n })));\n}\nfunction computeSegVStyle(segVCoords) {\n if (!segVCoords) {\n return { top: '', bottom: '' };\n }\n return {\n top: segVCoords.start,\n bottom: -segVCoords.end,\n };\n}\nfunction compileSegsFromEntries(segEntries, allSegs) {\n return segEntries.map(function (segEntry) { return allSegs[segEntry.index]; });\n}\n\nvar TimeColsContent = /** @class */ (function (_super) {\n __extends(TimeColsContent, _super);\n function TimeColsContent() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.splitFgEventSegs = memoize(splitSegsByCol);\n _this.splitBgEventSegs = memoize(splitSegsByCol);\n _this.splitBusinessHourSegs = memoize(splitSegsByCol);\n _this.splitNowIndicatorSegs = memoize(splitSegsByCol);\n _this.splitDateSelectionSegs = memoize(splitSegsByCol);\n _this.splitEventDrag = memoize(splitInteractionByCol);\n _this.splitEventResize = memoize(splitInteractionByCol);\n _this.rootElRef = createRef();\n _this.cellElRefs = new RefMap();\n return _this;\n }\n TimeColsContent.prototype.render = function () {\n var _this = this;\n var _a = this, props = _a.props, context = _a.context;\n var nowIndicatorTop = context.options.nowIndicator &&\n props.slatCoords &&\n props.slatCoords.safeComputeTop(props.nowDate); // might return void\n var colCnt = props.cells.length;\n var fgEventSegsByRow = this.splitFgEventSegs(props.fgEventSegs, colCnt);\n var bgEventSegsByRow = this.splitBgEventSegs(props.bgEventSegs, colCnt);\n var businessHourSegsByRow = this.splitBusinessHourSegs(props.businessHourSegs, colCnt);\n var nowIndicatorSegsByRow = this.splitNowIndicatorSegs(props.nowIndicatorSegs, colCnt);\n var dateSelectionSegsByRow = this.splitDateSelectionSegs(props.dateSelectionSegs, colCnt);\n var eventDragByRow = this.splitEventDrag(props.eventDrag, colCnt);\n var eventResizeByRow = this.splitEventResize(props.eventResize, colCnt);\n return (createElement(\"div\", { className: \"fc-timegrid-cols\", ref: this.rootElRef },\n createElement(\"table\", { role: \"presentation\", style: {\n minWidth: props.tableMinWidth,\n width: props.clientWidth,\n } },\n props.tableColGroupNode,\n createElement(\"tbody\", { role: \"presentation\" },\n createElement(\"tr\", { role: \"row\" },\n props.axis && (createElement(\"td\", { \"aria-hidden\": true, className: \"fc-timegrid-col fc-timegrid-axis\" },\n createElement(\"div\", { className: \"fc-timegrid-col-frame\" },\n createElement(\"div\", { className: \"fc-timegrid-now-indicator-container\" }, typeof nowIndicatorTop === 'number' && (createElement(NowIndicatorRoot, { isAxis: true, date: props.nowDate }, function (rootElRef, classNames, innerElRef, innerContent) { return (createElement(\"div\", { ref: rootElRef, className: ['fc-timegrid-now-indicator-arrow'].concat(classNames).join(' '), style: { top: nowIndicatorTop } }, innerContent)); })))))),\n props.cells.map(function (cell, i) { return (createElement(TimeCol, { key: cell.key, elRef: _this.cellElRefs.createRef(cell.key), dateProfile: props.dateProfile, date: cell.date, nowDate: props.nowDate, todayRange: props.todayRange, extraHookProps: cell.extraHookProps, extraDataAttrs: cell.extraDataAttrs, extraClassNames: cell.extraClassNames, extraDateSpan: cell.extraDateSpan, fgEventSegs: fgEventSegsByRow[i], bgEventSegs: bgEventSegsByRow[i], businessHourSegs: businessHourSegsByRow[i], nowIndicatorSegs: nowIndicatorSegsByRow[i], dateSelectionSegs: dateSelectionSegsByRow[i], eventDrag: eventDragByRow[i], eventResize: eventResizeByRow[i], slatCoords: props.slatCoords, eventSelection: props.eventSelection, forPrint: props.forPrint })); }))))));\n };\n TimeColsContent.prototype.componentDidMount = function () {\n this.updateCoords();\n };\n TimeColsContent.prototype.componentDidUpdate = function () {\n this.updateCoords();\n };\n TimeColsContent.prototype.updateCoords = function () {\n var props = this.props;\n if (props.onColCoords &&\n props.clientWidth !== null // means sizing has stabilized\n ) {\n props.onColCoords(new PositionCache(this.rootElRef.current, collectCellEls(this.cellElRefs.currentMap, props.cells), true, // horizontal\n false));\n }\n };\n return TimeColsContent;\n}(BaseComponent));\nfunction collectCellEls(elMap, cells) {\n return cells.map(function (cell) { return elMap[cell.key]; });\n}\n\n/* A component that renders one or more columns of vertical time slots\n----------------------------------------------------------------------------------------------------------------------*/\nvar TimeCols = /** @class */ (function (_super) {\n __extends(TimeCols, _super);\n function TimeCols() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.processSlotOptions = memoize(processSlotOptions);\n _this.state = {\n slatCoords: null,\n };\n _this.handleRootEl = function (el) {\n if (el) {\n _this.context.registerInteractiveComponent(_this, {\n el: el,\n isHitComboAllowed: _this.props.isHitComboAllowed,\n });\n }\n else {\n _this.context.unregisterInteractiveComponent(_this);\n }\n };\n _this.handleScrollRequest = function (request) {\n var onScrollTopRequest = _this.props.onScrollTopRequest;\n var slatCoords = _this.state.slatCoords;\n if (onScrollTopRequest && slatCoords) {\n if (request.time) {\n var top_1 = slatCoords.computeTimeTop(request.time);\n top_1 = Math.ceil(top_1); // zoom can give weird floating-point values. rather scroll a little bit further\n if (top_1) {\n top_1 += 1; // to overcome top border that slots beyond the first have. looks better\n }\n onScrollTopRequest(top_1);\n }\n return true;\n }\n return false;\n };\n _this.handleColCoords = function (colCoords) {\n _this.colCoords = colCoords;\n };\n _this.handleSlatCoords = function (slatCoords) {\n _this.setState({ slatCoords: slatCoords });\n if (_this.props.onSlatCoords) {\n _this.props.onSlatCoords(slatCoords);\n }\n };\n return _this;\n }\n TimeCols.prototype.render = function () {\n var _a = this, props = _a.props, state = _a.state;\n return (createElement(\"div\", { className: \"fc-timegrid-body\", ref: this.handleRootEl, style: {\n // these props are important to give this wrapper correct dimensions for interactions\n // TODO: if we set it here, can we avoid giving to inner tables?\n width: props.clientWidth,\n minWidth: props.tableMinWidth,\n } },\n createElement(TimeColsSlats, { axis: props.axis, dateProfile: props.dateProfile, slatMetas: props.slatMetas, clientWidth: props.clientWidth, minHeight: props.expandRows ? props.clientHeight : '', tableMinWidth: props.tableMinWidth, tableColGroupNode: props.axis ? props.tableColGroupNode : null /* axis depends on the colgroup's shrinking */, onCoords: this.handleSlatCoords }),\n createElement(TimeColsContent, { cells: props.cells, axis: props.axis, dateProfile: props.dateProfile, businessHourSegs: props.businessHourSegs, bgEventSegs: props.bgEventSegs, fgEventSegs: props.fgEventSegs, dateSelectionSegs: props.dateSelectionSegs, eventSelection: props.eventSelection, eventDrag: props.eventDrag, eventResize: props.eventResize, todayRange: props.todayRange, nowDate: props.nowDate, nowIndicatorSegs: props.nowIndicatorSegs, clientWidth: props.clientWidth, tableMinWidth: props.tableMinWidth, tableColGroupNode: props.tableColGroupNode, slatCoords: state.slatCoords, onColCoords: this.handleColCoords, forPrint: props.forPrint })));\n };\n TimeCols.prototype.componentDidMount = function () {\n this.scrollResponder = this.context.createScrollResponder(this.handleScrollRequest);\n };\n TimeCols.prototype.componentDidUpdate = function (prevProps) {\n this.scrollResponder.update(prevProps.dateProfile !== this.props.dateProfile);\n };\n TimeCols.prototype.componentWillUnmount = function () {\n this.scrollResponder.detach();\n };\n TimeCols.prototype.queryHit = function (positionLeft, positionTop) {\n var _a = this.context, dateEnv = _a.dateEnv, options = _a.options;\n var colCoords = this.colCoords;\n var dateProfile = this.props.dateProfile;\n var slatCoords = this.state.slatCoords;\n var _b = this.processSlotOptions(this.props.slotDuration, options.snapDuration), snapDuration = _b.snapDuration, snapsPerSlot = _b.snapsPerSlot;\n var colIndex = colCoords.leftToIndex(positionLeft);\n var slatIndex = slatCoords.positions.topToIndex(positionTop);\n if (colIndex != null && slatIndex != null) {\n var cell = this.props.cells[colIndex];\n var slatTop = slatCoords.positions.tops[slatIndex];\n var slatHeight = slatCoords.positions.getHeight(slatIndex);\n var partial = (positionTop - slatTop) / slatHeight; // floating point number between 0 and 1\n var localSnapIndex = Math.floor(partial * snapsPerSlot); // the snap # relative to start of slat\n var snapIndex = slatIndex * snapsPerSlot + localSnapIndex;\n var dayDate = this.props.cells[colIndex].date;\n var time = addDurations(dateProfile.slotMinTime, multiplyDuration(snapDuration, snapIndex));\n var start = dateEnv.add(dayDate, time);\n var end = dateEnv.add(start, snapDuration);\n return {\n dateProfile: dateProfile,\n dateSpan: __assign({ range: { start: start, end: end }, allDay: false }, cell.extraDateSpan),\n dayEl: colCoords.els[colIndex],\n rect: {\n left: colCoords.lefts[colIndex],\n right: colCoords.rights[colIndex],\n top: slatTop,\n bottom: slatTop + slatHeight,\n },\n layer: 0,\n };\n }\n return null;\n };\n return TimeCols;\n}(DateComponent));\nfunction processSlotOptions(slotDuration, snapDurationOverride) {\n var snapDuration = snapDurationOverride || slotDuration;\n var snapsPerSlot = wholeDivideDurations(slotDuration, snapDuration);\n if (snapsPerSlot === null) {\n snapDuration = slotDuration;\n snapsPerSlot = 1;\n // TODO: say warning?\n }\n return { snapDuration: snapDuration, snapsPerSlot: snapsPerSlot };\n}\n\nvar DayTimeColsSlicer = /** @class */ (function (_super) {\n __extends(DayTimeColsSlicer, _super);\n function DayTimeColsSlicer() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n DayTimeColsSlicer.prototype.sliceRange = function (range, dayRanges) {\n var segs = [];\n for (var col = 0; col < dayRanges.length; col += 1) {\n var segRange = intersectRanges(range, dayRanges[col]);\n if (segRange) {\n segs.push({\n start: segRange.start,\n end: segRange.end,\n isStart: segRange.start.valueOf() === range.start.valueOf(),\n isEnd: segRange.end.valueOf() === range.end.valueOf(),\n col: col,\n });\n }\n }\n return segs;\n };\n return DayTimeColsSlicer;\n}(Slicer));\n\nvar DayTimeCols = /** @class */ (function (_super) {\n __extends(DayTimeCols, _super);\n function DayTimeCols() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.buildDayRanges = memoize(buildDayRanges);\n _this.slicer = new DayTimeColsSlicer();\n _this.timeColsRef = createRef();\n return _this;\n }\n DayTimeCols.prototype.render = function () {\n var _this = this;\n var _a = this, props = _a.props, context = _a.context;\n var dateProfile = props.dateProfile, dayTableModel = props.dayTableModel;\n var isNowIndicator = context.options.nowIndicator;\n var dayRanges = this.buildDayRanges(dayTableModel, dateProfile, context.dateEnv);\n // give it the first row of cells\n // TODO: would move this further down hierarchy, but sliceNowDate needs it\n return (createElement(NowTimer, { unit: isNowIndicator ? 'minute' : 'day' }, function (nowDate, todayRange) { return (createElement(TimeCols, __assign({ ref: _this.timeColsRef }, _this.slicer.sliceProps(props, dateProfile, null, context, dayRanges), { forPrint: props.forPrint, axis: props.axis, dateProfile: dateProfile, slatMetas: props.slatMetas, slotDuration: props.slotDuration, cells: dayTableModel.cells[0], tableColGroupNode: props.tableColGroupNode, tableMinWidth: props.tableMinWidth, clientWidth: props.clientWidth, clientHeight: props.clientHeight, expandRows: props.expandRows, nowDate: nowDate, nowIndicatorSegs: isNowIndicator && _this.slicer.sliceNowDate(nowDate, context, dayRanges), todayRange: todayRange, onScrollTopRequest: props.onScrollTopRequest, onSlatCoords: props.onSlatCoords }))); }));\n };\n return DayTimeCols;\n}(DateComponent));\nfunction buildDayRanges(dayTableModel, dateProfile, dateEnv) {\n var ranges = [];\n for (var _i = 0, _a = dayTableModel.headerDates; _i < _a.length; _i++) {\n var date = _a[_i];\n ranges.push({\n start: dateEnv.add(date, dateProfile.slotMinTime),\n end: dateEnv.add(date, dateProfile.slotMaxTime),\n });\n }\n return ranges;\n}\n\n// potential nice values for the slot-duration and interval-duration\n// from largest to smallest\nvar STOCK_SUB_DURATIONS = [\n { hours: 1 },\n { minutes: 30 },\n { minutes: 15 },\n { seconds: 30 },\n { seconds: 15 },\n];\nfunction buildSlatMetas(slotMinTime, slotMaxTime, explicitLabelInterval, slotDuration, dateEnv) {\n var dayStart = new Date(0);\n var slatTime = slotMinTime;\n var slatIterator = createDuration(0);\n var labelInterval = explicitLabelInterval || computeLabelInterval(slotDuration);\n var metas = [];\n while (asRoughMs(slatTime) < asRoughMs(slotMaxTime)) {\n var date = dateEnv.add(dayStart, slatTime);\n var isLabeled = wholeDivideDurations(slatIterator, labelInterval) !== null;\n metas.push({\n date: date,\n time: slatTime,\n key: date.toISOString(),\n isoTimeStr: formatIsoTimeString(date),\n isLabeled: isLabeled,\n });\n slatTime = addDurations(slatTime, slotDuration);\n slatIterator = addDurations(slatIterator, slotDuration);\n }\n return metas;\n}\n// Computes an automatic value for slotLabelInterval\nfunction computeLabelInterval(slotDuration) {\n var i;\n var labelInterval;\n var slotsPerLabel;\n // find the smallest stock label interval that results in more than one slots-per-label\n for (i = STOCK_SUB_DURATIONS.length - 1; i >= 0; i -= 1) {\n labelInterval = createDuration(STOCK_SUB_DURATIONS[i]);\n slotsPerLabel = wholeDivideDurations(labelInterval, slotDuration);\n if (slotsPerLabel !== null && slotsPerLabel > 1) {\n return labelInterval;\n }\n }\n return slotDuration; // fall back\n}\n\nvar DayTimeColsView = /** @class */ (function (_super) {\n __extends(DayTimeColsView, _super);\n function DayTimeColsView() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.buildTimeColsModel = memoize(buildTimeColsModel);\n _this.buildSlatMetas = memoize(buildSlatMetas);\n return _this;\n }\n DayTimeColsView.prototype.render = function () {\n var _this = this;\n var _a = this.context, options = _a.options, dateEnv = _a.dateEnv, dateProfileGenerator = _a.dateProfileGenerator;\n var props = this.props;\n var dateProfile = props.dateProfile;\n var dayTableModel = this.buildTimeColsModel(dateProfile, dateProfileGenerator);\n var splitProps = this.allDaySplitter.splitProps(props);\n var slatMetas = this.buildSlatMetas(dateProfile.slotMinTime, dateProfile.slotMaxTime, options.slotLabelInterval, options.slotDuration, dateEnv);\n var dayMinWidth = options.dayMinWidth;\n var hasAttachedAxis = !dayMinWidth;\n var hasDetachedAxis = dayMinWidth;\n var headerContent = options.dayHeaders && (createElement(DayHeader, { dates: dayTableModel.headerDates, dateProfile: dateProfile, datesRepDistinctDays: true, renderIntro: hasAttachedAxis ? this.renderHeadAxis : null }));\n var allDayContent = (options.allDaySlot !== false) && (function (contentArg) { return (createElement(DayTable, __assign({}, splitProps.allDay, { dateProfile: dateProfile, dayTableModel: dayTableModel, nextDayThreshold: options.nextDayThreshold, tableMinWidth: contentArg.tableMinWidth, colGroupNode: contentArg.tableColGroupNode, renderRowIntro: hasAttachedAxis ? _this.renderTableRowAxis : null, showWeekNumbers: false, expandRows: false, headerAlignElRef: _this.headerElRef, clientWidth: contentArg.clientWidth, clientHeight: contentArg.clientHeight, forPrint: props.forPrint }, _this.getAllDayMaxEventProps()))); });\n var timeGridContent = function (contentArg) { return (createElement(DayTimeCols, __assign({}, splitProps.timed, { dayTableModel: dayTableModel, dateProfile: dateProfile, axis: hasAttachedAxis, slotDuration: options.slotDuration, slatMetas: slatMetas, forPrint: props.forPrint, tableColGroupNode: contentArg.tableColGroupNode, tableMinWidth: contentArg.tableMinWidth, clientWidth: contentArg.clientWidth, clientHeight: contentArg.clientHeight, onSlatCoords: _this.handleSlatCoords, expandRows: contentArg.expandRows, onScrollTopRequest: _this.handleScrollTopRequest }))); };\n return hasDetachedAxis\n ? this.renderHScrollLayout(headerContent, allDayContent, timeGridContent, dayTableModel.colCnt, dayMinWidth, slatMetas, this.state.slatCoords)\n : this.renderSimpleLayout(headerContent, allDayContent, timeGridContent);\n };\n return DayTimeColsView;\n}(TimeColsView));\nfunction buildTimeColsModel(dateProfile, dateProfileGenerator) {\n var daySeries = new DaySeriesModel(dateProfile.renderRange, dateProfileGenerator);\n return new DayTableModel(daySeries, false);\n}\n\nvar OPTION_REFINERS = {\n allDaySlot: Boolean,\n};\n\nvar main = createPlugin({\n initialView: 'timeGridWeek',\n optionRefiners: OPTION_REFINERS,\n views: {\n timeGrid: {\n component: DayTimeColsView,\n usesMinMaxTime: true,\n allDaySlot: true,\n slotDuration: '00:30:00',\n slotEventOverlap: true, // a bad name. confused with overlap/constraint system\n },\n timeGridDay: {\n type: 'timeGrid',\n duration: { days: 1 },\n },\n timeGridWeek: {\n type: 'timeGrid',\n duration: { weeks: 1 },\n },\n },\n});\n\nexport default main;\nexport { DayTimeCols, DayTimeColsSlicer, DayTimeColsView, TimeCols, TimeColsSlatsCoords, TimeColsView, buildDayRanges, buildSlatMetas, buildTimeColsModel };\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n/**\r\n* ApplicationInsights.ts\r\n* @copyright Microsoft 2018\r\n*/\r\nimport { __assignFn as __assign, __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { AnalyticsPluginIdentifier, Event as EventTelemetry, Exception, Metric, PageView, PageViewPerformance, PropertiesPluginIdentifier, RemoteDependencyData, Trace, createDistributedTraceContextFromTrace, createDomEvent, createTelemetryItem, dataSanitizeString, isCrossOriginError, strNotSpecified, stringToBoolOrDefault, utlDisableStorage, utlEnableStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { BaseTelemetryPlugin, InstrumentEvent, arrForEach, createProcessTelemetryContext, createUniqueNamespace, dumpObj, eventOff, eventOn, generateW3CId, getDocument, getExceptionName, getHistory, getLocation, getWindow, hasHistory, hasWindow, isError, isFunction, isNullOrUndefined, isString, isUndefined, mergeEvtNamespace, objDefineAccessors, objForEachKey, safeGetCookieMgr, strUndefined, throwError } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_ADD_TELEMETRY_INITIA15, _DYN_AUTO_TRACK_PAGE_VISI1, _DYN_COLUMN_NUMBER, _DYN_CORE, _DYN_DATA_TYPE, _DYN_DIAG_LOG, _DYN_DISABLE_EXCEPTION_TR0, _DYN_DISABLE_FLUSH_ON_BEF7, _DYN_ENABLE_AUTO_ROUTE_TR6, _DYN_ENABLE_UNHANDLED_PRO3, _DYN_ENVELOPE_TYPE, _DYN_ERROR, _DYN_ERROR_SRC, _DYN_EXCEPTION, _DYN_HREF, _DYN_IS_BROWSER_LINK_TRAC5, _DYN_IS_STORAGE_USE_DISAB4, _DYN_LENGTH, _DYN_LINE_NUMBER, _DYN_MESSAGE, _DYN_NAME_PREFIX, _DYN_OVERRIDE_PAGE_VIEW_D2, _DYN_POPULATE_PAGE_VIEW_P12, _DYN_SAMPLING_PERCENTAGE, _DYN_SEND_EXCEPTION_INTER13, _DYN_SEND_PAGE_VIEW_INTER10, _DYN_SEND_PAGE_VIEW_PERFO11, _DYN_TO_STRING, _DYN_TRACK, _DYN_TRACK_PAGE_VIEW, _DYN_TRACK_PREVIOUS_PAGE_9, _DYN__CREATE_AUTO_EXCEPTI14, _DYN__ONERROR } from \"../__DynamicConstants\";\r\nimport { PageViewManager } from \"./Telemetry/PageViewManager\";\r\nimport { PageViewPerformanceManager } from \"./Telemetry/PageViewPerformanceManager\";\r\nimport { PageVisitTimeManager } from \"./Telemetry/PageVisitTimeManager\";\r\nimport { Timing } from \"./Timing\";\r\nvar strEvent = \"event\";\r\nfunction _dispatchEvent(target, evnt) {\r\n if (target && target.dispatchEvent && evnt) {\r\n target.dispatchEvent(evnt);\r\n }\r\n}\r\nfunction _getReason(error) {\r\n if (error && error.reason) {\r\n var reason = error.reason;\r\n if (!isString(reason) && isFunction(reason[_DYN_TO_STRING /* @min:%2etoString */])) {\r\n return reason[_DYN_TO_STRING /* @min:%2etoString */]();\r\n }\r\n return dumpObj(reason);\r\n }\r\n // Pass the original object down which will eventually get evaluated for any message or description\r\n return error || \"\";\r\n}\r\nvar MinMilliSeconds = 60000;\r\nfunction _configMilliseconds(value, defValue) {\r\n value = value || defValue;\r\n if (value < MinMilliSeconds) {\r\n value = MinMilliSeconds;\r\n }\r\n return value;\r\n}\r\nfunction _getDefaultConfig(config) {\r\n if (!config) {\r\n config = {};\r\n }\r\n // set default values\r\n config.sessionRenewalMs = _configMilliseconds(config.sessionRenewalMs, 30 * 60 * 1000);\r\n config.sessionExpirationMs = _configMilliseconds(config.sessionExpirationMs, 24 * 60 * 60 * 1000);\r\n config[_DYN_DISABLE_EXCEPTION_TR0 /* @min:%2edisableExceptionTracking */] = stringToBoolOrDefault(config[_DYN_DISABLE_EXCEPTION_TR0 /* @min:%2edisableExceptionTracking */]);\r\n config[_DYN_AUTO_TRACK_PAGE_VISI1 /* @min:%2eautoTrackPageVisitTime */] = stringToBoolOrDefault(config[_DYN_AUTO_TRACK_PAGE_VISI1 /* @min:%2eautoTrackPageVisitTime */]);\r\n config[_DYN_OVERRIDE_PAGE_VIEW_D2 /* @min:%2eoverridePageViewDuration */] = stringToBoolOrDefault(config[_DYN_OVERRIDE_PAGE_VIEW_D2 /* @min:%2eoverridePageViewDuration */]);\r\n config[_DYN_ENABLE_UNHANDLED_PRO3 /* @min:%2eenableUnhandledPromiseRejectionTracking */] = stringToBoolOrDefault(config[_DYN_ENABLE_UNHANDLED_PRO3 /* @min:%2eenableUnhandledPromiseRejectionTracking */]);\r\n if (isNaN(config[_DYN_SAMPLING_PERCENTAGE /* @min:%2esamplingPercentage */]) || config[_DYN_SAMPLING_PERCENTAGE /* @min:%2esamplingPercentage */] <= 0 || config[_DYN_SAMPLING_PERCENTAGE /* @min:%2esamplingPercentage */] >= 100) {\r\n config[_DYN_SAMPLING_PERCENTAGE /* @min:%2esamplingPercentage */] = 100;\r\n }\r\n config[_DYN_IS_STORAGE_USE_DISAB4 /* @min:%2eisStorageUseDisabled */] = stringToBoolOrDefault(config[_DYN_IS_STORAGE_USE_DISAB4 /* @min:%2eisStorageUseDisabled */]);\r\n config[_DYN_IS_BROWSER_LINK_TRAC5 /* @min:%2eisBrowserLinkTrackingEnabled */] = stringToBoolOrDefault(config[_DYN_IS_BROWSER_LINK_TRAC5 /* @min:%2eisBrowserLinkTrackingEnabled */]);\r\n config[_DYN_ENABLE_AUTO_ROUTE_TR6 /* @min:%2eenableAutoRouteTracking */] = stringToBoolOrDefault(config[_DYN_ENABLE_AUTO_ROUTE_TR6 /* @min:%2eenableAutoRouteTracking */]);\r\n config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */] = config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */] || \"\";\r\n config.enableDebug = stringToBoolOrDefault(config.enableDebug);\r\n config[_DYN_DISABLE_FLUSH_ON_BEF7 /* @min:%2edisableFlushOnBeforeUnload */] = stringToBoolOrDefault(config[_DYN_DISABLE_FLUSH_ON_BEF7 /* @min:%2edisableFlushOnBeforeUnload */]);\r\n config.disableFlushOnUnload = stringToBoolOrDefault(config.disableFlushOnUnload, config[_DYN_DISABLE_FLUSH_ON_BEF7 /* @min:%2edisableFlushOnBeforeUnload */]);\r\n return config;\r\n}\r\nfunction _updateStorageUsage(extConfig) {\r\n // Not resetting the storage usage as someone may have manually called utlDisableStorage, so this will only\r\n // reset based if the configuration option is provided\r\n if (!isUndefined(extConfig[_DYN_IS_STORAGE_USE_DISAB4 /* @min:%2eisStorageUseDisabled */])) {\r\n if (extConfig[_DYN_IS_STORAGE_USE_DISAB4 /* @min:%2eisStorageUseDisabled */]) {\r\n utlDisableStorage();\r\n }\r\n else {\r\n utlEnableStorage();\r\n }\r\n }\r\n}\r\nvar AnalyticsPlugin = /** @class */ (function (_super) {\r\n __extends(AnalyticsPlugin, _super);\r\n function AnalyticsPlugin() {\r\n var _this = _super.call(this) || this;\r\n _this.identifier = AnalyticsPluginIdentifier; // do not change name or priority\r\n _this.priority = 180; // take from reserved priority range 100- 200\r\n _this.autoRoutePVDelay = 500; // ms; Time to wait after a route change before triggering a pageview to allow DOM changes to take place\r\n var _eventTracking;\r\n var _pageTracking;\r\n var _pageViewManager;\r\n var _pageViewPerformanceManager;\r\n var _pageVisitTimeManager;\r\n var _preInitTelemetryInitializers;\r\n var _isBrowserLinkTrackingEnabled;\r\n var _browserLinkInitializerAdded;\r\n var _enableAutoRouteTracking;\r\n var _historyListenerAdded;\r\n var _disableExceptionTracking;\r\n var _autoExceptionInstrumented;\r\n var _enableUnhandledPromiseRejectionTracking;\r\n var _autoUnhandledPromiseInstrumented;\r\n // Counts number of trackAjax invocations.\r\n // By default we only monitor X ajax call per view to avoid too much load.\r\n // Default value is set in config.\r\n // This counter keeps increasing even after the limit is reached.\r\n var _trackAjaxAttempts = 0;\r\n // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.\r\n var _prevUri; // Assigned in the constructor\r\n var _currUri;\r\n var _evtNamespace;\r\n dynamicProto(AnalyticsPlugin, _this, function (_self, _base) {\r\n var _addHook = _base._addHook;\r\n _initDefaults();\r\n _self.getCookieMgr = function () {\r\n return safeGetCookieMgr(_self[_DYN_CORE /* @min:%2ecore */]);\r\n };\r\n _self.processTelemetry = function (env, itemCtx) {\r\n _self.processNext(env, itemCtx);\r\n };\r\n _self.trackEvent = function (event, customProperties) {\r\n try {\r\n var telemetryItem = createTelemetryItem(event, EventTelemetry[_DYN_DATA_TYPE /* @min:%2edataType */], EventTelemetry[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n }\r\n catch (e) {\r\n _throwInternal(2 /* eLoggingSeverity.WARNING */, 39 /* _eInternalMessageId.TrackTraceFailed */, \"trackTrace failed, trace will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * Start timing an extended event. Call `stopTrackEvent` to log the event when it ends.\r\n * @param name A string that identifies this event uniquely within the document.\r\n */\r\n _self.startTrackEvent = function (name) {\r\n try {\r\n _eventTracking.start(name);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 29 /* _eInternalMessageId.StartTrackEventFailed */, \"startTrackEvent failed, event will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * Log an extended event that you started timing with `startTrackEvent`.\r\n * @param name The string you used to identify this event in `startTrackEvent`.\r\n * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.\r\n * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.\r\n */\r\n _self.stopTrackEvent = function (name, properties, measurements) {\r\n try {\r\n _eventTracking.stop(name, undefined, properties, measurements);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 30 /* _eInternalMessageId.StopTrackEventFailed */, \"stopTrackEvent failed, event will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * @description Log a diagnostic message\r\n * @param {ITraceTelemetry} trace\r\n * @param ICustomProperties.\r\n * @memberof ApplicationInsights\r\n */\r\n _self.trackTrace = function (trace, customProperties) {\r\n try {\r\n var telemetryItem = createTelemetryItem(trace, Trace[_DYN_DATA_TYPE /* @min:%2edataType */], Trace[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n }\r\n catch (e) {\r\n _throwInternal(2 /* eLoggingSeverity.WARNING */, 39 /* _eInternalMessageId.TrackTraceFailed */, \"trackTrace failed, trace will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * @description Log a numeric value that is not associated with a specific event. Typically\r\n * used to send regular reports of performance indicators. To send single measurement, just\r\n * use the name and average fields of {@link IMetricTelemetry}. If you take measurements\r\n * frequently, you can reduce the telemetry bandwidth by aggregating multiple measurements\r\n * and sending the resulting average at intervals\r\n * @param {IMetricTelemetry} metric input object argument. Only name and average are mandatory.\r\n * @param {{[key: string]: any}} customProperties additional data used to filter metrics in the\r\n * portal. Defaults to empty.\r\n * @memberof ApplicationInsights\r\n */\r\n _self.trackMetric = function (metric, customProperties) {\r\n try {\r\n var telemetryItem = createTelemetryItem(metric, Metric[_DYN_DATA_TYPE /* @min:%2edataType */], Metric[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 36 /* _eInternalMessageId.TrackMetricFailed */, \"trackMetric failed, metric will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * Logs that a page or other item was viewed.\r\n * @param IPageViewTelemetry The string you used as the name in startTrackPage. Defaults to the document title.\r\n * @param customProperties Additional data used to filter events and metrics. Defaults to empty.\r\n * If a user wants to provide duration for pageLoad, it'll have to be in pageView.properties.duration\r\n */\r\n _self[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */] = function (pageView, customProperties) {\r\n try {\r\n var inPv = pageView || {};\r\n _pageViewManager[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */](inPv, __assign(__assign(__assign({}, inPv.properties), inPv.measurements), customProperties));\r\n if (_self.config[_DYN_AUTO_TRACK_PAGE_VISI1 /* @min:%2eautoTrackPageVisitTime */]) {\r\n _pageVisitTimeManager[_DYN_TRACK_PREVIOUS_PAGE_9 /* @min:%2etrackPreviousPageVisit */](inPv.name, inPv.uri);\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 37 /* _eInternalMessageId.TrackPVFailed */, \"trackPageView failed, page view will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * Create a page view telemetry item and send it to the SDK pipeline through the core.track API\r\n * @param pageView Page view item to be sent\r\n * @param properties Custom properties (Part C) that a user can add to the telemetry item\r\n * @param systemProperties System level properties (Part A) that a user can add to the telemetry item\r\n */\r\n _self[_DYN_SEND_PAGE_VIEW_INTER10 /* @min:%2esendPageViewInternal */] = function (pageView, properties, systemProperties) {\r\n var doc = getDocument();\r\n if (doc) {\r\n pageView.refUri = pageView.refUri === undefined ? doc.referrer : pageView.refUri;\r\n }\r\n var telemetryItem = createTelemetryItem(pageView, PageView[_DYN_DATA_TYPE /* @min:%2edataType */], PageView[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), properties, systemProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n // reset ajaxes counter\r\n _trackAjaxAttempts = 0;\r\n };\r\n /**\r\n * @ignore INTERNAL ONLY\r\n * @param pageViewPerformance\r\n * @param properties\r\n */\r\n _self[_DYN_SEND_PAGE_VIEW_PERFO11 /* @min:%2esendPageViewPerformanceInternal */] = function (pageViewPerformance, properties, systemProperties) {\r\n var telemetryItem = createTelemetryItem(pageViewPerformance, PageViewPerformance[_DYN_DATA_TYPE /* @min:%2edataType */], PageViewPerformance[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), properties, systemProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n };\r\n /**\r\n * Send browser performance metrics.\r\n * @param pageViewPerformance\r\n * @param customProperties\r\n */\r\n _self.trackPageViewPerformance = function (pageViewPerformance, customProperties) {\r\n var inPvp = pageViewPerformance || {};\r\n try {\r\n _pageViewPerformanceManager[_DYN_POPULATE_PAGE_VIEW_P12 /* @min:%2epopulatePageViewPerformanceEvent */](inPvp);\r\n _self[_DYN_SEND_PAGE_VIEW_PERFO11 /* @min:%2esendPageViewPerformanceInternal */](inPvp, customProperties);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 37 /* _eInternalMessageId.TrackPVFailed */, \"trackPageViewPerformance failed, page view will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops,\r\n * but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view\r\n * and send the event.\r\n * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.\r\n */\r\n _self.startTrackPage = function (name) {\r\n try {\r\n if (typeof name !== \"string\") {\r\n var doc = getDocument();\r\n name = doc && doc.title || \"\";\r\n }\r\n _pageTracking.start(name);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 31 /* _eInternalMessageId.StartTrackFailed */, \"startTrackPage failed, page view may not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements.\r\n * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`.\r\n * @param name The string you used as the name in startTrackPage. Defaults to the document title.\r\n * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.\r\n * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.\r\n * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.\r\n */\r\n _self.stopTrackPage = function (name, url, properties, measurement) {\r\n try {\r\n if (typeof name !== \"string\") {\r\n var doc = getDocument();\r\n name = doc && doc.title || \"\";\r\n }\r\n if (typeof url !== \"string\") {\r\n var loc = getLocation();\r\n url = loc && loc[_DYN_HREF /* @min:%2ehref */] || \"\";\r\n }\r\n _pageTracking.stop(name, url, properties, measurement);\r\n if (_self.config[_DYN_AUTO_TRACK_PAGE_VISI1 /* @min:%2eautoTrackPageVisitTime */]) {\r\n _pageVisitTimeManager[_DYN_TRACK_PREVIOUS_PAGE_9 /* @min:%2etrackPreviousPageVisit */](name, url);\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 32 /* _eInternalMessageId.StopTrackFailed */, \"stopTrackPage failed, page view will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * @ignore INTERNAL ONLY\r\n * @param exception\r\n * @param properties\r\n * @param systemProperties\r\n */\r\n _self[_DYN_SEND_EXCEPTION_INTER13 /* @min:%2esendExceptionInternal */] = function (exception, customProperties, systemProperties) {\r\n // Adding additional edge cases to handle\r\n // - Not passing anything (null / undefined)\r\n var theError = (exception && (exception[_DYN_EXCEPTION /* @min:%2eexception */] || exception[_DYN_ERROR /* @min:%2eerror */])) ||\r\n // - Handle someone calling trackException based of v1 API where the exception was the Error\r\n isError(exception) && exception ||\r\n // - Handles no error being defined and instead of creating a new Error() instance attempt to map so any stacktrace\r\n // is preserved and does not list ApplicationInsights code as the source\r\n { name: (exception && typeof exception), message: exception || strNotSpecified };\r\n // If no exception object was passed assign to an empty object to avoid internal exceptions\r\n exception = exception || {};\r\n var exceptionPartB = new Exception(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), theError, exception.properties || customProperties, exception.measurements, exception.severityLevel, exception.id).toInterface();\r\n var telemetryItem = createTelemetryItem(exceptionPartB, Exception[_DYN_DATA_TYPE /* @min:%2edataType */], Exception[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties, systemProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n };\r\n /**\r\n * Log an exception you have caught.\r\n *\r\n * @param {IExceptionTelemetry} exception Object which contains exception to be sent\r\n * @param {{[key: string]: any}} customProperties Additional data used to filter pages and metrics in the portal. Defaults to empty.\r\n *\r\n * Any property of type double will be considered a measurement, and will be treated by Application Insights as a metric.\r\n * @memberof ApplicationInsights\r\n */\r\n _self.trackException = function (exception, customProperties) {\r\n if (exception && !exception[_DYN_EXCEPTION /* @min:%2eexception */] && exception[_DYN_ERROR /* @min:%2eerror */]) {\r\n exception[_DYN_EXCEPTION /* @min:%2eexception */] = exception[_DYN_ERROR /* @min:%2eerror */];\r\n }\r\n try {\r\n _self[_DYN_SEND_EXCEPTION_INTER13 /* @min:%2esendExceptionInternal */](exception, customProperties);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 35 /* _eInternalMessageId.TrackExceptionFailed */, \"trackException failed, exception will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * @description Custom error handler for Application Insights Analytics\r\n * @param {IAutoExceptionTelemetry} exception\r\n * @memberof ApplicationInsights\r\n */\r\n _self[_DYN__ONERROR /* @min:%2e_onerror */] = function (exception) {\r\n var error = exception && exception[_DYN_ERROR /* @min:%2eerror */];\r\n var evt = exception && exception.evt;\r\n try {\r\n if (!evt) {\r\n var _window = getWindow();\r\n if (_window) {\r\n evt = _window[strEvent];\r\n }\r\n }\r\n var url = (exception && exception.url) || (getDocument() || {}).URL;\r\n // If no error source is provided assume the default window.onerror handler\r\n var errorSrc = exception[_DYN_ERROR_SRC /* @min:%2eerrorSrc */] || \"window.onerror@\" + url + \":\" + (exception[_DYN_LINE_NUMBER /* @min:%2elineNumber */] || 0) + \":\" + (exception[_DYN_COLUMN_NUMBER /* @min:%2ecolumnNumber */] || 0);\r\n var properties = {\r\n errorSrc: errorSrc,\r\n url: url,\r\n lineNumber: exception[_DYN_LINE_NUMBER /* @min:%2elineNumber */] || 0,\r\n columnNumber: exception[_DYN_COLUMN_NUMBER /* @min:%2ecolumnNumber */] || 0,\r\n message: exception[_DYN_MESSAGE /* @min:%2emessage */]\r\n };\r\n if (isCrossOriginError(exception.message, exception.url, exception.lineNumber, exception.columnNumber, exception[_DYN_ERROR /* @min:%2eerror */])) {\r\n _sendCORSException(Exception[_DYN__CREATE_AUTO_EXCEPTI14 /* @min:%2eCreateAutoException */](\"Script error: The browser's same-origin policy prevents us from getting the details of this exception. Consider using the 'crossorigin' attribute.\", url, exception[_DYN_LINE_NUMBER /* @min:%2elineNumber */] || 0, exception[_DYN_COLUMN_NUMBER /* @min:%2ecolumnNumber */] || 0, error, evt, null, errorSrc), properties);\r\n }\r\n else {\r\n if (!exception[_DYN_ERROR_SRC /* @min:%2eerrorSrc */]) {\r\n exception[_DYN_ERROR_SRC /* @min:%2eerrorSrc */] = errorSrc;\r\n }\r\n _self.trackException({ exception: exception, severityLevel: 3 /* eSeverityLevel.Error */ }, properties);\r\n }\r\n }\r\n catch (e) {\r\n var errorString = error ? (error.name + \", \" + error[_DYN_MESSAGE /* @min:%2emessage */]) : \"null\";\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 11 /* _eInternalMessageId.ExceptionWhileLoggingError */, \"_onError threw exception while logging error, error will not be collected: \"\r\n + getExceptionName(e), { exception: dumpObj(e), errorString: errorString });\r\n }\r\n };\r\n _self[_DYN_ADD_TELEMETRY_INITIA15 /* @min:%2eaddTelemetryInitializer */] = function (telemetryInitializer) {\r\n if (_self[_DYN_CORE /* @min:%2ecore */]) {\r\n // Just add to the core\r\n return _self[_DYN_CORE /* @min:%2ecore */][_DYN_ADD_TELEMETRY_INITIA15 /* @min:%2eaddTelemetryInitializer */](telemetryInitializer);\r\n }\r\n // Handle \"pre-initialization\" telemetry initializers (for backward compatibility)\r\n if (!_preInitTelemetryInitializers) {\r\n _preInitTelemetryInitializers = [];\r\n }\r\n _preInitTelemetryInitializers.push(telemetryInitializer);\r\n };\r\n _self.initialize = function (config, core, extensions, pluginChain) {\r\n if (_self.isInitialized()) {\r\n return;\r\n }\r\n if (isNullOrUndefined(core)) {\r\n throwError(\"Error initializing\");\r\n }\r\n _base.initialize(config, core, extensions, pluginChain);\r\n try {\r\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(_self.identifier), core.evtNamespace && core.evtNamespace());\r\n if (_preInitTelemetryInitializers) {\r\n arrForEach(_preInitTelemetryInitializers, function (initializer) {\r\n core[_DYN_ADD_TELEMETRY_INITIA15 /* @min:%2eaddTelemetryInitializer */](initializer);\r\n });\r\n _preInitTelemetryInitializers = null;\r\n }\r\n var extConfig = _populateDefaults(config);\r\n _updateStorageUsage(extConfig);\r\n _pageViewPerformanceManager = new PageViewPerformanceManager(_self[_DYN_CORE /* @min:%2ecore */]);\r\n _pageViewManager = new PageViewManager(_this, extConfig[_DYN_OVERRIDE_PAGE_VIEW_D2 /* @min:%2eoverridePageViewDuration */], _self[_DYN_CORE /* @min:%2ecore */], _pageViewPerformanceManager);\r\n _pageVisitTimeManager = new PageVisitTimeManager(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), function (pageName, pageUrl, pageVisitTime) { return trackPageVisitTime(pageName, pageUrl, pageVisitTime); });\r\n _updateBrowserLinkTracking(extConfig, config);\r\n _eventTracking = new Timing(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), \"trackEvent\");\r\n _eventTracking.action =\r\n function (name, url, duration, properties, measurements) {\r\n if (!properties) {\r\n properties = {};\r\n }\r\n if (!measurements) {\r\n measurements = {};\r\n }\r\n properties.duration = duration[_DYN_TO_STRING /* @min:%2etoString */]();\r\n _self.trackEvent({ name: name, properties: properties, measurements: measurements });\r\n };\r\n // initialize page view timing\r\n _pageTracking = new Timing(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), \"trackPageView\");\r\n _pageTracking.action = function (name, url, duration, properties, measurements) {\r\n // duration must be a custom property in order for the collector to extract it\r\n if (isNullOrUndefined(properties)) {\r\n properties = {};\r\n }\r\n properties.duration = duration[_DYN_TO_STRING /* @min:%2etoString */]();\r\n var pageViewItem = {\r\n name: name,\r\n uri: url,\r\n properties: properties,\r\n measurements: measurements\r\n };\r\n _self[_DYN_SEND_PAGE_VIEW_INTER10 /* @min:%2esendPageViewInternal */](pageViewItem, properties);\r\n };\r\n if (hasWindow()) {\r\n _updateExceptionTracking(extConfig);\r\n _updateLocationChange(extConfig);\r\n }\r\n }\r\n catch (e) {\r\n // resetting the initialized state because of failure\r\n _self.setInitialized(false);\r\n throw e;\r\n }\r\n };\r\n _self._doTeardown = function (unloadCtx, unloadState) {\r\n _pageViewManager && _pageViewManager.teardown(unloadCtx, unloadState);\r\n // Just register to remove all events associated with this namespace\r\n eventOff(window, null, null, _evtNamespace);\r\n _initDefaults();\r\n };\r\n function _populateDefaults(config) {\r\n var ctx = createProcessTelemetryContext(null, config, _self[_DYN_CORE /* @min:%2ecore */]);\r\n var identifier = _self.identifier;\r\n // load default values if specified\r\n var defaults = _getDefaultConfig(config);\r\n var extConfig = _self.config = ctx.getExtCfg(identifier);\r\n if (defaults !== undefined) {\r\n objForEachKey(defaults, function (field, value) {\r\n // for each unspecified field, set the default value\r\n extConfig[field] = ctx.getConfig(identifier, field, value);\r\n if (extConfig[field] === undefined) {\r\n extConfig = value;\r\n }\r\n });\r\n }\r\n return extConfig;\r\n }\r\n function _updateBrowserLinkTracking(extConfig, config) {\r\n _isBrowserLinkTrackingEnabled = extConfig[_DYN_IS_BROWSER_LINK_TRAC5 /* @min:%2eisBrowserLinkTrackingEnabled */] || config[_DYN_IS_BROWSER_LINK_TRAC5 /* @min:%2eisBrowserLinkTrackingEnabled */];\r\n _addDefaultTelemetryInitializers();\r\n }\r\n /**\r\n * Log a page visit time\r\n * @param pageName Name of page\r\n * @param pageVisitDuration Duration of visit to the page in milleseconds\r\n */\r\n function trackPageVisitTime(pageName, pageUrl, pageVisitTime) {\r\n var properties = { PageName: pageName, PageUrl: pageUrl };\r\n _self.trackMetric({\r\n name: \"PageVisitTime\",\r\n average: pageVisitTime,\r\n max: pageVisitTime,\r\n min: pageVisitTime,\r\n sampleCount: 1\r\n }, properties);\r\n }\r\n function _addDefaultTelemetryInitializers() {\r\n if (!_browserLinkInitializerAdded && _isBrowserLinkTrackingEnabled) {\r\n var browserLinkPaths_1 = [\"/browserLinkSignalR/\", \"/__browserLink/\"];\r\n var dropBrowserLinkRequests = function (envelope) {\r\n if (_isBrowserLinkTrackingEnabled && envelope.baseType === RemoteDependencyData[_DYN_DATA_TYPE /* @min:%2edataType */]) {\r\n var remoteData = envelope.baseData;\r\n if (remoteData) {\r\n for (var i = 0; i < browserLinkPaths_1[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n if (remoteData.target && remoteData.target.indexOf(browserLinkPaths_1[i]) >= 0) {\r\n return false;\r\n }\r\n }\r\n }\r\n }\r\n return true;\r\n };\r\n _self[_DYN_ADD_TELEMETRY_INITIA15 /* @min:%2eaddTelemetryInitializer */](dropBrowserLinkRequests);\r\n _browserLinkInitializerAdded = true;\r\n }\r\n }\r\n function _sendCORSException(exception, properties) {\r\n var telemetryItem = createTelemetryItem(exception, Exception[_DYN_DATA_TYPE /* @min:%2edataType */], Exception[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), properties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n }\r\n function _updateExceptionTracking(extConfig) {\r\n var _window = getWindow();\r\n var locn = getLocation(true);\r\n _disableExceptionTracking = extConfig[_DYN_DISABLE_EXCEPTION_TR0 /* @min:%2edisableExceptionTracking */];\r\n if (!_disableExceptionTracking && !_autoExceptionInstrumented && !extConfig.autoExceptionInstrumented) {\r\n // We want to enable exception auto collection and it has not been done so yet\r\n _addHook(InstrumentEvent(_window, \"onerror\", {\r\n ns: _evtNamespace,\r\n rsp: function (callDetails, message, url, lineNumber, columnNumber, error) {\r\n if (!_disableExceptionTracking && callDetails.rslt !== true) {\r\n _self[_DYN__ONERROR /* @min:%2e_onerror */](Exception[_DYN__CREATE_AUTO_EXCEPTI14 /* @min:%2eCreateAutoException */](message, url, lineNumber, columnNumber, error, callDetails.evt));\r\n }\r\n }\r\n }, false));\r\n _autoExceptionInstrumented = true;\r\n }\r\n _addUnhandledPromiseRejectionTracking(extConfig, _window, locn);\r\n }\r\n function _updateLocationChange(extConfig) {\r\n var win = getWindow();\r\n var locn = getLocation(true);\r\n _enableAutoRouteTracking = extConfig[_DYN_ENABLE_AUTO_ROUTE_TR6 /* @min:%2eenableAutoRouteTracking */] === true;\r\n /**\r\n * Create a custom \"locationchange\" event which is triggered each time the history object is changed\r\n */\r\n if (win && _enableAutoRouteTracking && hasHistory()) {\r\n var _history = getHistory();\r\n if (isFunction(_history.pushState) && isFunction(_history.replaceState) && typeof Event !== strUndefined) {\r\n _addHistoryListener(extConfig, win, _history, locn);\r\n }\r\n }\r\n }\r\n function _getDistributedTraceCtx() {\r\n var distributedTraceCtx = null;\r\n if (_self[_DYN_CORE /* @min:%2ecore */] && _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx) {\r\n distributedTraceCtx = _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx(false);\r\n }\r\n if (!distributedTraceCtx) {\r\n // Fallback when using an older Core and PropertiesPlugin\r\n var properties = _self[_DYN_CORE /* @min:%2ecore */].getPlugin(PropertiesPluginIdentifier);\r\n if (properties) {\r\n var context = properties.plugin.context;\r\n if (context) {\r\n distributedTraceCtx = createDistributedTraceContextFromTrace(context.telemetryTrace);\r\n }\r\n }\r\n }\r\n return distributedTraceCtx;\r\n }\r\n /**\r\n * Create a custom \"locationchange\" event which is triggered each time the history object is changed\r\n */\r\n function _addHistoryListener(extConfig, win, history, locn) {\r\n var namePrefix = extConfig[_DYN_NAME_PREFIX /* @min:%2enamePrefix */] || \"\";\r\n function _popstateHandler() {\r\n if (_enableAutoRouteTracking) {\r\n _dispatchEvent(win, createDomEvent(namePrefix + \"locationchange\"));\r\n }\r\n }\r\n function _locationChangeHandler() {\r\n // We always track the changes (if the handler is installed) to handle the feature being disabled between location changes\r\n if (_currUri) {\r\n _prevUri = _currUri;\r\n _currUri = locn && locn[_DYN_HREF /* @min:%2ehref */] || \"\";\r\n }\r\n else {\r\n _currUri = locn && locn[_DYN_HREF /* @min:%2ehref */] || \"\";\r\n }\r\n if (_enableAutoRouteTracking) {\r\n var distributedTraceCtx = _getDistributedTraceCtx();\r\n if (distributedTraceCtx) {\r\n distributedTraceCtx.setTraceId(generateW3CId());\r\n var traceLocationName = \"_unknown_\";\r\n if (locn && locn.pathname) {\r\n traceLocationName = locn.pathname + (locn.hash || \"\");\r\n }\r\n // This populates the ai.operation.name which has a maximum size of 1024 so we need to sanitize it\r\n distributedTraceCtx.setName(dataSanitizeString(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), traceLocationName));\r\n }\r\n setTimeout((function (uri) {\r\n // todo: override start time so that it is not affected by autoRoutePVDelay\r\n _self[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */]({ refUri: uri, properties: { duration: 0 } }); // SPA route change loading durations are undefined, so send 0\r\n }).bind(this, _prevUri), _self.autoRoutePVDelay);\r\n }\r\n }\r\n if (!_historyListenerAdded) {\r\n _addHook(InstrumentEvent(history, \"pushState\", {\r\n ns: _evtNamespace,\r\n rsp: function () {\r\n if (_enableAutoRouteTracking) {\r\n _dispatchEvent(win, createDomEvent(namePrefix + \"pushState\"));\r\n _dispatchEvent(win, createDomEvent(namePrefix + \"locationchange\"));\r\n }\r\n }\r\n }, true));\r\n _addHook(InstrumentEvent(history, \"replaceState\", {\r\n ns: _evtNamespace,\r\n rsp: function () {\r\n if (_enableAutoRouteTracking) {\r\n _dispatchEvent(win, createDomEvent(namePrefix + \"replaceState\"));\r\n _dispatchEvent(win, createDomEvent(namePrefix + \"locationchange\"));\r\n }\r\n }\r\n }, true));\r\n eventOn(win, namePrefix + \"popstate\", _popstateHandler, _evtNamespace);\r\n eventOn(win, namePrefix + \"locationchange\", _locationChangeHandler, _evtNamespace);\r\n _historyListenerAdded = true;\r\n }\r\n }\r\n function _addUnhandledPromiseRejectionTracking(extConfig, _window, _location) {\r\n _enableUnhandledPromiseRejectionTracking = extConfig[_DYN_ENABLE_UNHANDLED_PRO3 /* @min:%2eenableUnhandledPromiseRejectionTracking */] === true;\r\n if (_enableUnhandledPromiseRejectionTracking && !_autoUnhandledPromiseInstrumented) {\r\n // We want to enable exception auto collection and it has not been done so yet\r\n _addHook(InstrumentEvent(_window, \"onunhandledrejection\", {\r\n ns: _evtNamespace,\r\n rsp: function (callDetails, error) {\r\n if (_enableUnhandledPromiseRejectionTracking && callDetails.rslt !== true) { // handled could be typeof function\r\n _self[_DYN__ONERROR /* @min:%2e_onerror */](Exception[_DYN__CREATE_AUTO_EXCEPTI14 /* @min:%2eCreateAutoException */](_getReason(error), _location ? _location[_DYN_HREF /* @min:%2ehref */] : \"\", 0, 0, error, callDetails.evt));\r\n }\r\n }\r\n }, false));\r\n _autoUnhandledPromiseInstrumented = true;\r\n extConfig.autoUnhandledPromiseInstrumented = _autoUnhandledPromiseInstrumented;\r\n }\r\n }\r\n /**\r\n * This method will throw exceptions in debug mode or attempt to log the error as a console warning.\r\n * @param severity {eLoggingSeverity} - The severity of the log message\r\n * @param message {_InternalLogMessage} - The log message.\r\n */\r\n function _throwInternal(severity, msgId, msg, properties, isUserAct) {\r\n _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]().throwInternal(severity, msgId, msg, properties, isUserAct);\r\n }\r\n function _initDefaults() {\r\n _eventTracking = null;\r\n _pageTracking = null;\r\n _pageViewManager = null;\r\n _pageViewPerformanceManager = null;\r\n _pageVisitTimeManager = null;\r\n _preInitTelemetryInitializers = null;\r\n _isBrowserLinkTrackingEnabled = false;\r\n _browserLinkInitializerAdded = false;\r\n _enableAutoRouteTracking = false;\r\n _historyListenerAdded = false;\r\n _disableExceptionTracking = false;\r\n _autoExceptionInstrumented = false;\r\n _enableUnhandledPromiseRejectionTracking = false;\r\n _autoUnhandledPromiseInstrumented = false;\r\n // Counts number of trackAjax invocations.\r\n // By default we only monitor X ajax call per view to avoid too much load.\r\n // Default value is set in config.\r\n // This counter keeps increasing even after the limit is reached.\r\n _trackAjaxAttempts = 0;\r\n // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.\r\n var location = getLocation(true);\r\n _prevUri = location && location[_DYN_HREF /* @min:%2ehref */] || \"\";\r\n _currUri = null;\r\n _evtNamespace = null;\r\n }\r\n // For backward compatibility\r\n objDefineAccessors(_self, \"_pageViewManager\", function () { return _pageViewManager; });\r\n objDefineAccessors(_self, \"_pageViewPerformanceManager\", function () { return _pageViewPerformanceManager; });\r\n objDefineAccessors(_self, \"_pageVisitTimeManager\", function () { return _pageVisitTimeManager; });\r\n objDefineAccessors(_self, \"_evtNamespace\", function () { return \".\" + _evtNamespace; });\r\n });\r\n return _this;\r\n }\r\n// Removed Stub for AnalyticsPlugin.prototype.getCookieMgr.\r\n// Removed Stub for AnalyticsPlugin.prototype.processTelemetry.\r\n// Removed Stub for AnalyticsPlugin.prototype.trackEvent.\r\n// Removed Stub for AnalyticsPlugin.prototype.startTrackEvent.\r\n// Removed Stub for AnalyticsPlugin.prototype.stopTrackEvent.\r\n// Removed Stub for AnalyticsPlugin.prototype.trackTrace.\r\n// Removed Stub for AnalyticsPlugin.prototype.trackMetric.\r\n// Removed Stub for AnalyticsPlugin.prototype.trackPageView.\r\n// Removed Stub for AnalyticsPlugin.prototype.sendPageViewInternal.\r\n// Removed Stub for AnalyticsPlugin.prototype.sendPageViewPerformanceInternal.\r\n// Removed Stub for AnalyticsPlugin.prototype.trackPageViewPerformance.\r\n// Removed Stub for AnalyticsPlugin.prototype.startTrackPage.\r\n// Removed Stub for AnalyticsPlugin.prototype.stopTrackPage.\r\n// Removed Stub for AnalyticsPlugin.prototype.sendExceptionInternal.\r\n// Removed Stub for AnalyticsPlugin.prototype.trackException.\r\n// Removed Stub for AnalyticsPlugin.prototype._onerror.\r\n// Removed Stub for AnalyticsPlugin.prototype.addTelemetryInitializer.\r\n// Removed Stub for AnalyticsPlugin.prototype.initialize.\r\n AnalyticsPlugin.Version = '2.8.11'; // Not currently used anywhere\r\n AnalyticsPlugin.getDefaultConfig = _getDefaultConfig;\r\n return AnalyticsPlugin;\r\n}(BaseTelemetryPlugin));\r\nexport { AnalyticsPlugin };\r\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { dateTimeUtilsDuration } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, arrForEach, dumpObj, getDocument, getExceptionName, getLocation, isNullOrUndefined } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_DURATION, _DYN_GET_PERFORMANCE_TIMI17, _DYN_HREF, _DYN_IS_PERFORMANCE_TIMIN16, _DYN_IS_PERFORMANCE_TIMIN19, _DYN_LENGTH, _DYN_NAVIGATION_START, _DYN_POPULATE_PAGE_VIEW_P12, _DYN_SEND_PAGE_VIEW_INTER10, _DYN_SEND_PAGE_VIEW_PERFO11, _DYN_SHOULD_COLLECT_DURAT18, _DYN_TRACK_PAGE_VIEW } from \"../../__DynamicConstants\";\r\nvar _isWebWorker = null;\r\nfunction isWebWorker() {\r\n if (_isWebWorker == null) {\r\n try {\r\n _isWebWorker = !!(self && self instanceof WorkerGlobalScope);\r\n }\r\n catch (e) {\r\n _isWebWorker = false;\r\n }\r\n }\r\n return _isWebWorker;\r\n}\r\n/**\r\n * Class encapsulates sending page views and page view performance telemetry.\r\n */\r\nvar PageViewManager = /** @class */ (function () {\r\n function PageViewManager(appInsights, overridePageViewDuration, core, pageViewPerformanceManager) {\r\n dynamicProto(PageViewManager, this, function (_self) {\r\n var intervalHandle = null;\r\n var itemQueue = [];\r\n var pageViewPerformanceSent = false;\r\n var _logger;\r\n if (core) {\r\n _logger = core.logger;\r\n }\r\n function _flushChannels(isAsync) {\r\n if (core) {\r\n core.flush(isAsync);\r\n }\r\n }\r\n function _addQueue(cb) {\r\n itemQueue.push(cb);\r\n if (!intervalHandle) {\r\n intervalHandle = setInterval((function () {\r\n var allItems = itemQueue.slice(0);\r\n var doFlush = false;\r\n itemQueue = [];\r\n arrForEach(allItems, function (item) {\r\n if (!item()) {\r\n // Not processed so rescheduled\r\n itemQueue.push(item);\r\n }\r\n else {\r\n doFlush = true;\r\n }\r\n });\r\n if (itemQueue[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n clearInterval(intervalHandle);\r\n intervalHandle = null;\r\n }\r\n if (doFlush) {\r\n // We process at least one item so flush the queue\r\n _flushChannels(true);\r\n }\r\n }), 100);\r\n }\r\n }\r\n _self[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */] = function (pageView, customProperties) {\r\n var name = pageView.name;\r\n if (isNullOrUndefined(name) || typeof name !== \"string\") {\r\n var doc = getDocument();\r\n name = pageView.name = doc && doc.title || \"\";\r\n }\r\n var uri = pageView.uri;\r\n if (isNullOrUndefined(uri) || typeof uri !== \"string\") {\r\n var location_1 = getLocation();\r\n uri = pageView.uri = location_1 && location_1[_DYN_HREF /* @min:%2ehref */] || \"\";\r\n }\r\n // case 1a. if performance timing is not supported by the browser, send the page view telemetry with the duration provided by the user. If the user\r\n // do not provide the duration, set duration to undefined\r\n // Also this is case 4\r\n if (!pageViewPerformanceManager[_DYN_IS_PERFORMANCE_TIMIN16 /* @min:%2eisPerformanceTimingSupported */]()) {\r\n appInsights[_DYN_SEND_PAGE_VIEW_INTER10 /* @min:%2esendPageViewInternal */](pageView, customProperties);\r\n _flushChannels(true);\r\n if (!isWebWorker()) {\r\n // no navigation timing (IE 8, iOS Safari 8.4, Opera Mini 8 - see http://caniuse.com/#feat=nav-timing)\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 25 /* _eInternalMessageId.NavigationTimingNotSupported */, \"trackPageView: navigation timing API used for calculation of page duration is not supported in this browser. This page view will be collected without duration and timing info.\");\r\n }\r\n return;\r\n }\r\n var pageViewSent = false;\r\n var customDuration;\r\n // if the performance timing is supported by the browser, calculate the custom duration\r\n var start = pageViewPerformanceManager[_DYN_GET_PERFORMANCE_TIMI17 /* @min:%2egetPerformanceTiming */]()[_DYN_NAVIGATION_START /* @min:%2enavigationStart */];\r\n if (start > 0) {\r\n customDuration = dateTimeUtilsDuration(start, +new Date);\r\n if (!pageViewPerformanceManager[_DYN_SHOULD_COLLECT_DURAT18 /* @min:%2eshouldCollectDuration */](customDuration)) {\r\n customDuration = undefined;\r\n }\r\n }\r\n // if the user has provided duration, send a page view telemetry with the provided duration. Otherwise, if\r\n // overridePageViewDuration is set to true, send a page view telemetry with the custom duration calculated earlier\r\n var duration;\r\n if (!isNullOrUndefined(customProperties) &&\r\n !isNullOrUndefined(customProperties[_DYN_DURATION /* @min:%2eduration */])) {\r\n duration = customProperties[_DYN_DURATION /* @min:%2eduration */];\r\n }\r\n if (overridePageViewDuration || !isNaN(duration)) {\r\n if (isNaN(duration)) {\r\n // case 3\r\n if (!customProperties) {\r\n customProperties = {};\r\n }\r\n customProperties[_DYN_DURATION /* @min:%2eduration */] = customDuration;\r\n }\r\n // case 2\r\n appInsights[_DYN_SEND_PAGE_VIEW_INTER10 /* @min:%2esendPageViewInternal */](pageView, customProperties);\r\n _flushChannels(true);\r\n pageViewSent = true;\r\n }\r\n // now try to send the page view performance telemetry\r\n var maxDurationLimit = 60000;\r\n if (!customProperties) {\r\n customProperties = {};\r\n }\r\n // Queue the event for processing\r\n _addQueue(function () {\r\n var processed = false;\r\n try {\r\n if (pageViewPerformanceManager[_DYN_IS_PERFORMANCE_TIMIN19 /* @min:%2eisPerformanceTimingDataReady */]()) {\r\n processed = true;\r\n var pageViewPerformance = {\r\n name: name,\r\n uri: uri\r\n };\r\n pageViewPerformanceManager[_DYN_POPULATE_PAGE_VIEW_P12 /* @min:%2epopulatePageViewPerformanceEvent */](pageViewPerformance);\r\n if (!pageViewPerformance.isValid && !pageViewSent) {\r\n // If navigation timing gives invalid numbers, then go back to \"override page view duration\" mode.\r\n // That's the best value we can get that makes sense.\r\n customProperties[_DYN_DURATION /* @min:%2eduration */] = customDuration;\r\n appInsights[_DYN_SEND_PAGE_VIEW_INTER10 /* @min:%2esendPageViewInternal */](pageView, customProperties);\r\n }\r\n else {\r\n if (!pageViewSent) {\r\n customProperties[_DYN_DURATION /* @min:%2eduration */] = pageViewPerformance.durationMs;\r\n appInsights[_DYN_SEND_PAGE_VIEW_INTER10 /* @min:%2esendPageViewInternal */](pageView, customProperties);\r\n }\r\n if (!pageViewPerformanceSent) {\r\n appInsights[_DYN_SEND_PAGE_VIEW_PERFO11 /* @min:%2esendPageViewPerformanceInternal */](pageViewPerformance, customProperties);\r\n pageViewPerformanceSent = true;\r\n }\r\n }\r\n }\r\n else if (start > 0 && dateTimeUtilsDuration(start, +new Date) > maxDurationLimit) {\r\n // if performance timings are not ready but we exceeded the maximum duration limit, just log a page view telemetry\r\n // with the maximum duration limit. Otherwise, keep waiting until performance timings are ready\r\n processed = true;\r\n if (!pageViewSent) {\r\n customProperties[_DYN_DURATION /* @min:%2eduration */] = maxDurationLimit;\r\n appInsights[_DYN_SEND_PAGE_VIEW_INTER10 /* @min:%2esendPageViewInternal */](pageView, customProperties);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 38 /* _eInternalMessageId.TrackPVFailedCalc */, \"trackPageView failed on page load calculation: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n return processed;\r\n });\r\n };\r\n _self.teardown = function (unloadCtx, unloadState) {\r\n if (intervalHandle) {\r\n clearInterval(intervalHandle);\r\n intervalHandle = null;\r\n var allItems = itemQueue.slice(0);\r\n var doFlush_1 = false;\r\n itemQueue = [];\r\n arrForEach(allItems, function (item) {\r\n if (item()) {\r\n doFlush_1 = true;\r\n }\r\n });\r\n }\r\n };\r\n });\r\n }\r\n// Removed Stub for PageViewManager.prototype.trackPageView.\r\n// Removed Stub for PageViewManager.prototype.teardown.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n PageViewManager.__ieDyn=1;\n\n return PageViewManager;\r\n}());\r\nexport { PageViewManager };\r\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { dateTimeUtilsDuration, msToTimeSpan } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, getNavigator, getPerformance, safeGetLogger } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_CONNECT_END, _DYN_DURATION, _DYN_GET_ENTRIES_BY_TYPE, _DYN_GET_PERFORMANCE_TIMI17, _DYN_IS_PERFORMANCE_TIMIN16, _DYN_IS_PERFORMANCE_TIMIN19, _DYN_LENGTH, _DYN_LOAD_EVENT_END, _DYN_NAVIGATION_START, _DYN_POPULATE_PAGE_VIEW_P12, _DYN_REQUEST_START, _DYN_RESPONSE_END, _DYN_RESPONSE_START, _DYN_SHOULD_COLLECT_DURAT18 } from \"../../__DynamicConstants\";\r\nvar MAX_DURATION_ALLOWED = 3600000; // 1h\r\nvar botAgentNames = [\"googlebot\", \"adsbot-google\", \"apis-google\", \"mediapartners-google\"];\r\nfunction _isPerformanceTimingSupported() {\r\n var perf = getPerformance();\r\n return perf && !!perf.timing;\r\n}\r\nfunction _isPerformanceNavigationTimingSupported() {\r\n var perf = getPerformance();\r\n return perf && perf.getEntriesByType && perf.getEntriesByType(\"navigation\")[_DYN_LENGTH /* @min:%2elength */] > 0;\r\n}\r\nfunction _isPerformanceTimingDataReady() {\r\n var perf = getPerformance();\r\n var timing = perf ? perf.timing : 0;\r\n return timing\r\n && timing.domainLookupStart > 0\r\n && timing[_DYN_NAVIGATION_START /* @min:%2enavigationStart */] > 0\r\n && timing[_DYN_RESPONSE_START /* @min:%2eresponseStart */] > 0\r\n && timing[_DYN_REQUEST_START /* @min:%2erequestStart */] > 0\r\n && timing[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */] > 0\r\n && timing[_DYN_RESPONSE_END /* @min:%2eresponseEnd */] > 0\r\n && timing[_DYN_CONNECT_END /* @min:%2econnectEnd */] > 0\r\n && timing.domLoading > 0;\r\n}\r\nfunction _getPerformanceTiming() {\r\n if (_isPerformanceTimingSupported()) {\r\n return getPerformance().timing;\r\n }\r\n return null;\r\n}\r\nfunction _getPerformanceNavigationTiming() {\r\n if (_isPerformanceNavigationTimingSupported()) {\r\n return getPerformance()[_DYN_GET_ENTRIES_BY_TYPE /* @min:%2egetEntriesByType */](\"navigation\")[0];\r\n }\r\n return null;\r\n}\r\n/**\r\n* This method tells if given durations should be excluded from collection.\r\n*/\r\nfunction _shouldCollectDuration() {\r\n var durations = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n durations[_i] = arguments[_i];\r\n }\r\n var _navigator = getNavigator() || {};\r\n // a full list of Google crawlers user agent strings - https://support.google.com/webmasters/answer/1061943?hl=en\r\n var userAgent = _navigator.userAgent;\r\n var isGoogleBot = false;\r\n if (userAgent) {\r\n for (var i = 0; i < botAgentNames[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n isGoogleBot = isGoogleBot || userAgent.toLowerCase().indexOf(botAgentNames[i]) !== -1;\r\n }\r\n }\r\n if (isGoogleBot) {\r\n // Don't report durations for GoogleBot, it is returning invalid values in performance.timing API.\r\n return false;\r\n }\r\n else {\r\n // for other page views, don't report if it's outside of a reasonable range\r\n for (var i = 0; i < durations[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n if (durations[i] < 0 || durations[i] >= MAX_DURATION_ALLOWED) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n}\r\n/**\r\n * Class encapsulates sending page view performance telemetry.\r\n */\r\nvar PageViewPerformanceManager = /** @class */ (function () {\r\n function PageViewPerformanceManager(core) {\r\n var _this = this;\r\n var _logger = safeGetLogger(core);\r\n dynamicProto(PageViewPerformanceManager, this, function (_self) {\r\n _self[_DYN_POPULATE_PAGE_VIEW_P12 /* @min:%2epopulatePageViewPerformanceEvent */] = function (pageViewPerformance) {\r\n pageViewPerformance.isValid = false;\r\n /*\r\n * http://www.w3.org/TR/navigation-timing/#processing-model\r\n * |-navigationStart\r\n * | |-connectEnd\r\n * | ||-requestStart\r\n * | || |-responseStart\r\n * | || | |-responseEnd\r\n * | || | |\r\n * | || | | |-loadEventEnd\r\n * |---network---||---request---|---response---|---dom---|\r\n * |--------------------------total----------------------|\r\n *\r\n * total = The difference between the load event of the current document is completed and the first recorded timestamp of the performance entry : https://developer.mozilla.org/en-US/docs/Web/Performance/Navigation_and_resource_timings#duration\r\n * network = Redirect time + App Cache + DNS lookup time + TCP connection time\r\n * request = Request time : https://developer.mozilla.org/en-US/docs/Web/Performance/Navigation_and_resource_timings#request_time\r\n * response = Response time\r\n * dom = Document load time : https://html.spec.whatwg.org/multipage/dom.html#document-load-timing-info\r\n * = Document processing time : https://developers.google.com/web/fundamentals/performance/navigation-and-resource-timing/#document_processing\r\n * + Loading time : https://developers.google.com/web/fundamentals/performance/navigation-and-resource-timing/#loading\r\n */\r\n var navigationTiming = _getPerformanceNavigationTiming();\r\n var timing = _getPerformanceTiming();\r\n var total = 0;\r\n var network = 0;\r\n var request = 0;\r\n var response = 0;\r\n var dom = 0;\r\n if (navigationTiming || timing) {\r\n if (navigationTiming) {\r\n total = navigationTiming[_DYN_DURATION /* @min:%2eduration */];\r\n /**\r\n * support both cases:\r\n * - startTime is always zero: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming\r\n * - for older browsers where the startTime is not zero\r\n */\r\n network = navigationTiming.startTime === 0 ? navigationTiming[_DYN_CONNECT_END /* @min:%2econnectEnd */] : dateTimeUtilsDuration(navigationTiming.startTime, navigationTiming[_DYN_CONNECT_END /* @min:%2econnectEnd */]);\r\n request = dateTimeUtilsDuration(navigationTiming.requestStart, navigationTiming[_DYN_RESPONSE_START /* @min:%2eresponseStart */]);\r\n response = dateTimeUtilsDuration(navigationTiming[_DYN_RESPONSE_START /* @min:%2eresponseStart */], navigationTiming[_DYN_RESPONSE_END /* @min:%2eresponseEnd */]);\r\n dom = dateTimeUtilsDuration(navigationTiming.responseEnd, navigationTiming[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */]);\r\n }\r\n else {\r\n total = dateTimeUtilsDuration(timing[_DYN_NAVIGATION_START /* @min:%2enavigationStart */], timing[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */]);\r\n network = dateTimeUtilsDuration(timing[_DYN_NAVIGATION_START /* @min:%2enavigationStart */], timing[_DYN_CONNECT_END /* @min:%2econnectEnd */]);\r\n request = dateTimeUtilsDuration(timing.requestStart, timing[_DYN_RESPONSE_START /* @min:%2eresponseStart */]);\r\n response = dateTimeUtilsDuration(timing[_DYN_RESPONSE_START /* @min:%2eresponseStart */], timing[_DYN_RESPONSE_END /* @min:%2eresponseEnd */]);\r\n dom = dateTimeUtilsDuration(timing.responseEnd, timing[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */]);\r\n }\r\n if (total === 0) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 10 /* _eInternalMessageId.ErrorPVCalc */, \"error calculating page view performance.\", { total: total, network: network, request: request, response: response, dom: dom });\r\n }\r\n else if (!_this[_DYN_SHOULD_COLLECT_DURAT18 /* @min:%2eshouldCollectDuration */](total, network, request, response, dom)) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 45 /* _eInternalMessageId.InvalidDurationValue */, \"Invalid page load duration value. Browser perf data won't be sent.\", { total: total, network: network, request: request, response: response, dom: dom });\r\n }\r\n else if (total < Math.floor(network) + Math.floor(request) + Math.floor(response) + Math.floor(dom)) {\r\n // some browsers may report individual components incorrectly so that the sum of the parts will be bigger than total PLT\r\n // in this case, don't report client performance from this page\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 8 /* _eInternalMessageId.ClientPerformanceMathError */, \"client performance math error.\", { total: total, network: network, request: request, response: response, dom: dom });\r\n }\r\n else {\r\n pageViewPerformance.durationMs = total;\r\n // // convert to timespans\r\n pageViewPerformance.perfTotal = pageViewPerformance[_DYN_DURATION /* @min:%2eduration */] = msToTimeSpan(total);\r\n pageViewPerformance.networkConnect = msToTimeSpan(network);\r\n pageViewPerformance.sentRequest = msToTimeSpan(request);\r\n pageViewPerformance.receivedResponse = msToTimeSpan(response);\r\n pageViewPerformance.domProcessing = msToTimeSpan(dom);\r\n pageViewPerformance.isValid = true;\r\n }\r\n }\r\n };\r\n _self[_DYN_GET_PERFORMANCE_TIMI17 /* @min:%2egetPerformanceTiming */] = _getPerformanceTiming;\r\n _self[_DYN_IS_PERFORMANCE_TIMIN16 /* @min:%2eisPerformanceTimingSupported */] = _isPerformanceTimingSupported;\r\n _self[_DYN_IS_PERFORMANCE_TIMIN19 /* @min:%2eisPerformanceTimingDataReady */] = _isPerformanceTimingDataReady;\r\n _self[_DYN_SHOULD_COLLECT_DURAT18 /* @min:%2eshouldCollectDuration */] = _shouldCollectDuration;\r\n });\r\n }\r\n// Removed Stub for PageViewPerformanceManager.prototype.populatePageViewPerformanceEvent.\r\n// Removed Stub for PageViewPerformanceManager.prototype.getPerformanceTiming.\r\n// Removed Stub for PageViewPerformanceManager.prototype.isPerformanceTimingSupported.\r\n// Removed Stub for PageViewPerformanceManager.prototype.isPerformanceTimingDataReady.\r\n// Removed Stub for PageViewPerformanceManager.prototype.shouldCollectDuration.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n PageViewPerformanceManager.__ieDyn=1;\n\n return PageViewPerformanceManager;\r\n}());\r\nexport { PageViewPerformanceManager };\r\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { utlCanUseSessionStorage, utlGetSessionStorage, utlRemoveSessionStorage, utlSetSessionStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { _warnToConsole, dateNow, dumpObj, getJSON, hasJSON, objDefineAccessors, throwError } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_PAGE_VISIT_START_TIM20, _DYN_TRACK_PREVIOUS_PAGE_9 } from \"../../__DynamicConstants\";\r\n/**\r\n * Used to track page visit durations\r\n */\r\nvar PageVisitTimeManager = /** @class */ (function () {\r\n /**\r\n * Creates a new instance of PageVisitTimeManager\r\n * @param pageVisitTimeTrackingHandler Delegate that will be called to send telemetry data to AI (when trackPreviousPageVisit is called)\r\n * @returns {}\r\n */\r\n function PageVisitTimeManager(logger, pageVisitTimeTrackingHandler) {\r\n var prevPageVisitDataKeyName = \"prevPageVisitData\";\r\n dynamicProto(PageVisitTimeManager, this, function (_self) {\r\n _self[_DYN_TRACK_PREVIOUS_PAGE_9 /* @min:%2etrackPreviousPageVisit */] = function (currentPageName, currentPageUrl) {\r\n try {\r\n // Restart timer for new page view\r\n var prevPageVisitTimeData = restartPageVisitTimer(currentPageName, currentPageUrl);\r\n // If there was a page already being timed, track the visit time for it now.\r\n if (prevPageVisitTimeData) {\r\n pageVisitTimeTrackingHandler(prevPageVisitTimeData.pageName, prevPageVisitTimeData.pageUrl, prevPageVisitTimeData.pageVisitTime);\r\n }\r\n }\r\n catch (e) {\r\n _warnToConsole(logger, \"Auto track page visit time failed, metric will not be collected: \" + dumpObj(e));\r\n }\r\n };\r\n /**\r\n * Stops timing of current page (if exists) and starts timing for duration of visit to pageName\r\n * @param pageName Name of page to begin timing visit duration\r\n * @returns {PageVisitData} Page visit data (including duration) of pageName from last call to start or restart, if exists. Null if not.\r\n */\r\n function restartPageVisitTimer(pageName, pageUrl) {\r\n var prevPageVisitData = null;\r\n try {\r\n prevPageVisitData = stopPageVisitTimer();\r\n startPageVisitTimer(pageName, pageUrl);\r\n }\r\n catch (e) {\r\n _warnToConsole(logger, \"Call to restart failed: \" + dumpObj(e));\r\n prevPageVisitData = null;\r\n }\r\n return prevPageVisitData;\r\n }\r\n /**\r\n * Starts timing visit duration of pageName\r\n * @param pageName\r\n * @returns {}\r\n */\r\n function startPageVisitTimer(pageName, pageUrl) {\r\n try {\r\n if (utlCanUseSessionStorage()) {\r\n if (utlGetSessionStorage(logger, prevPageVisitDataKeyName) != null) {\r\n throwError(\"Cannot call startPageVisit consecutively without first calling stopPageVisit\");\r\n }\r\n var currPageVisitData = new PageVisitData(pageName, pageUrl);\r\n var currPageVisitDataStr = getJSON().stringify(currPageVisitData);\r\n utlSetSessionStorage(logger, prevPageVisitDataKeyName, currPageVisitDataStr);\r\n }\r\n }\r\n catch (e) {\r\n // TODO: Remove this catch in next phase, since if start is called twice in a row the exception needs to be propagated out\r\n _warnToConsole(logger, \"Call to start failed: \" + dumpObj(e));\r\n }\r\n }\r\n /**\r\n * Stops timing of current page, if exists.\r\n * @returns {PageVisitData} Page visit data (including duration) of pageName from call to start, if exists. Null if not.\r\n */\r\n function stopPageVisitTimer() {\r\n var prevPageVisitData = null;\r\n try {\r\n if (utlCanUseSessionStorage()) {\r\n // Define end time of page's visit\r\n var pageVisitEndTime = dateNow();\r\n // Try to retrieve page name and start time from session storage\r\n var pageVisitDataJsonStr = utlGetSessionStorage(logger, prevPageVisitDataKeyName);\r\n if (pageVisitDataJsonStr && hasJSON()) {\r\n // if previous page data exists, set end time of visit\r\n prevPageVisitData = getJSON().parse(pageVisitDataJsonStr);\r\n prevPageVisitData.pageVisitTime = pageVisitEndTime - prevPageVisitData[_DYN_PAGE_VISIT_START_TIM20 /* @min:%2epageVisitStartTime */];\r\n // Remove data from storage since we already used it\r\n utlRemoveSessionStorage(logger, prevPageVisitDataKeyName);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _warnToConsole(logger, \"Stop page visit timer failed: \" + dumpObj(e));\r\n prevPageVisitData = null;\r\n }\r\n return prevPageVisitData;\r\n }\r\n // For backward compatibility\r\n objDefineAccessors(_self, \"_logger\", function () { return logger; });\r\n objDefineAccessors(_self, \"pageVisitTimeTrackingHandler\", function () { return pageVisitTimeTrackingHandler; });\r\n });\r\n }\r\n// Removed Stub for PageVisitTimeManager.prototype.trackPreviousPageVisit.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n PageVisitTimeManager.__ieDyn=1;\n\n return PageVisitTimeManager;\r\n}());\r\nexport { PageVisitTimeManager };\r\nvar PageVisitData = /** @class */ (function () {\r\n function PageVisitData(pageName, pageUrl) {\r\n this[_DYN_PAGE_VISIT_START_TIM20 /* @min:%2epageVisitStartTime */] = dateNow();\r\n this.pageName = pageName;\r\n this.pageUrl = pageUrl;\r\n }\r\n return PageVisitData;\r\n}());\r\nexport { PageVisitData };\r\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { dateTimeUtilsDuration } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal } from \"@microsoft/applicationinsights-core-js\";\r\n/**\r\n * Used to record timed events and page views.\r\n */\r\nvar Timing = /** @class */ (function () {\r\n function Timing(logger, name) {\r\n var _self = this;\r\n var _events = {};\r\n _self.start = function (name) {\r\n if (typeof _events[name] !== \"undefined\") {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 62 /* _eInternalMessageId.StartCalledMoreThanOnce */, \"start was called more than once for this event without calling stop.\", { name: name, key: name }, true);\r\n }\r\n _events[name] = +new Date;\r\n };\r\n _self.stop = function (name, url, properties, measurements) {\r\n var start = _events[name];\r\n if (isNaN(start)) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 63 /* _eInternalMessageId.StopCalledWithoutStart */, \"stop was called without a corresponding start.\", { name: name, key: name }, true);\r\n }\r\n else {\r\n var end = +new Date;\r\n var duration = dateTimeUtilsDuration(start, end);\r\n _self.action(name, url, duration, properties, measurements);\r\n }\r\n delete _events[name];\r\n _events[name] = undefined;\r\n };\r\n }\r\n return Timing;\r\n}());\r\nexport { Timing };\r\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_TO_STRING = \"toString\"; // Count: 4\r\nexport var _DYN_DISABLE_EXCEPTION_TR0 = \"disableExceptionTracking\"; // Count: 3\r\nexport var _DYN_AUTO_TRACK_PAGE_VISI1 = \"autoTrackPageVisitTime\"; // Count: 4\r\nexport var _DYN_OVERRIDE_PAGE_VIEW_D2 = \"overridePageViewDuration\"; // Count: 3\r\nexport var _DYN_ENABLE_UNHANDLED_PRO3 = \"enableUnhandledPromiseRejectionTracking\"; // Count: 3\r\nexport var _DYN_SAMPLING_PERCENTAGE = \"samplingPercentage\"; // Count: 4\r\nexport var _DYN_IS_STORAGE_USE_DISAB4 = \"isStorageUseDisabled\"; // Count: 4\r\nexport var _DYN_IS_BROWSER_LINK_TRAC5 = \"isBrowserLinkTrackingEnabled\"; // Count: 4\r\nexport var _DYN_ENABLE_AUTO_ROUTE_TR6 = \"enableAutoRouteTracking\"; // Count: 3\r\nexport var _DYN_NAME_PREFIX = \"namePrefix\"; // Count: 3\r\nexport var _DYN_DISABLE_FLUSH_ON_BEF7 = \"disableFlushOnBeforeUnload\"; // Count: 3\r\nexport var _DYN_DISABLE_FLUSH_ON_UNL8 = \"disableFlushOnUnload\"; // Count: 2\r\nexport var _DYN_CORE = \"core\"; // Count: 7\r\nexport var _DYN_DATA_TYPE = \"dataType\"; // Count: 8\r\nexport var _DYN_ENVELOPE_TYPE = \"envelopeType\"; // Count: 7\r\nexport var _DYN_DIAG_LOG = \"diagLog\"; // Count: 13\r\nexport var _DYN_TRACK = \"track\"; // Count: 7\r\nexport var _DYN_TRACK_PAGE_VIEW = \"trackPageView\"; // Count: 4\r\nexport var _DYN_TRACK_PREVIOUS_PAGE_9 = \"trackPreviousPageVisit\"; // Count: 3\r\nexport var _DYN_SEND_PAGE_VIEW_INTER10 = \"sendPageViewInternal\"; // Count: 7\r\nexport var _DYN_SEND_PAGE_VIEW_PERFO11 = \"sendPageViewPerformanceInternal\"; // Count: 3\r\nexport var _DYN_POPULATE_PAGE_VIEW_P12 = \"populatePageViewPerformanceEvent\"; // Count: 3\r\nexport var _DYN_HREF = \"href\"; // Count: 6\r\nexport var _DYN_SEND_EXCEPTION_INTER13 = \"sendExceptionInternal\"; // Count: 2\r\nexport var _DYN_EXCEPTION = \"exception\"; // Count: 3\r\nexport var _DYN_ERROR = \"error\"; // Count: 5\r\nexport var _DYN__ONERROR = \"_onerror\"; // Count: 3\r\nexport var _DYN_ERROR_SRC = \"errorSrc\"; // Count: 3\r\nexport var _DYN_LINE_NUMBER = \"lineNumber\"; // Count: 5\r\nexport var _DYN_COLUMN_NUMBER = \"columnNumber\"; // Count: 5\r\nexport var _DYN_MESSAGE = \"message\"; // Count: 4\r\nexport var _DYN__CREATE_AUTO_EXCEPTI14 = \"CreateAutoException\"; // Count: 3\r\nexport var _DYN_ADD_TELEMETRY_INITIA15 = \"addTelemetryInitializer\"; // Count: 4\r\nexport var _DYN_DURATION = \"duration\"; // Count: 10\r\nexport var _DYN_LENGTH = \"length\"; // Count: 5\r\nexport var _DYN_IS_PERFORMANCE_TIMIN16 = \"isPerformanceTimingSupported\"; // Count: 2\r\nexport var _DYN_GET_PERFORMANCE_TIMI17 = \"getPerformanceTiming\"; // Count: 2\r\nexport var _DYN_NAVIGATION_START = \"navigationStart\"; // Count: 4\r\nexport var _DYN_SHOULD_COLLECT_DURAT18 = \"shouldCollectDuration\"; // Count: 3\r\nexport var _DYN_IS_PERFORMANCE_TIMIN19 = \"isPerformanceTimingDataReady\"; // Count: 2\r\nexport var _DYN_GET_ENTRIES_BY_TYPE = \"getEntriesByType\"; // Count: 3\r\nexport var _DYN_RESPONSE_START = \"responseStart\"; // Count: 5\r\nexport var _DYN_REQUEST_START = \"requestStart\"; // Count: 3\r\nexport var _DYN_LOAD_EVENT_END = \"loadEventEnd\"; // Count: 4\r\nexport var _DYN_RESPONSE_END = \"responseEnd\"; // Count: 5\r\nexport var _DYN_CONNECT_END = \"connectEnd\"; // Count: 4\r\nexport var _DYN_PAGE_VISIT_START_TIM20 = \"pageVisitStartTime\"; // Count: 2\r\n","/*\n * Application Insights JavaScript SDK - Channel, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { __assignFn as __assign } from \"@microsoft/applicationinsights-shims\";\r\nimport { CtxTagKeys, Data, Envelope, Event, Exception, HttpMethod, Metric, PageView, PageViewPerformance, RemoteDependencyData, SampleRate, Trace, dataSanitizeString } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, _warnToConsole, getJSON, hasJSON, isNullOrUndefined, isNumber, isString, isTruthy, objForEachKey, optimizeObject, setValue, toISOString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { STR_DURATION } from \"./InternalConstants\";\r\nimport { _DYN_DATA, _DYN_DATA_TYPE, _DYN_DEVICE_TYPE, _DYN_ENVELOPE_TYPE, _DYN_LENGTH, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_STRINGIFY, _DYN_TAGS, _DYN_TO_STRING, _DYN_TRACE_ID } from \"./__DynamicConstants\";\r\n// these two constants are used to filter out properties not needed when trying to extract custom properties and measurements from the incoming payload\r\nvar strBaseType = \"baseType\";\r\nvar strBaseData = \"baseData\";\r\nvar strProperties = \"properties\";\r\nvar strTrue = \"true\";\r\nfunction _setValueIf(target, field, value) {\r\n return setValue(target, field, value, isTruthy);\r\n}\r\n/*\r\n * Maps Part A data from CS 4.0\r\n */\r\nfunction _extractPartAExtensions(logger, item, env) {\r\n // todo: switch to keys from common in this method\r\n var envTags = env[_DYN_TAGS /* @min:%2etags */] = env[_DYN_TAGS /* @min:%2etags */] || {};\r\n var itmExt = item.ext = item.ext || {};\r\n var itmTags = item[_DYN_TAGS /* @min:%2etags */] = item[_DYN_TAGS /* @min:%2etags */] || [];\r\n var extUser = itmExt.user;\r\n if (extUser) {\r\n _setValueIf(envTags, CtxTagKeys.userAuthUserId, extUser.authId);\r\n _setValueIf(envTags, CtxTagKeys.userId, extUser.id || extUser.localId);\r\n }\r\n var extApp = itmExt.app;\r\n if (extApp) {\r\n _setValueIf(envTags, CtxTagKeys.sessionId, extApp.sesId);\r\n }\r\n var extDevice = itmExt.device;\r\n if (extDevice) {\r\n _setValueIf(envTags, CtxTagKeys.deviceId, extDevice.id || extDevice.localId);\r\n _setValueIf(envTags, CtxTagKeys[_DYN_DEVICE_TYPE /* @min:%2edeviceType */], extDevice.deviceClass);\r\n _setValueIf(envTags, CtxTagKeys.deviceIp, extDevice.ip);\r\n _setValueIf(envTags, CtxTagKeys.deviceModel, extDevice.model);\r\n _setValueIf(envTags, CtxTagKeys[_DYN_DEVICE_TYPE /* @min:%2edeviceType */], extDevice[_DYN_DEVICE_TYPE /* @min:%2edeviceType */]);\r\n }\r\n var web = item.ext.web;\r\n if (web) {\r\n _setValueIf(envTags, CtxTagKeys.deviceLanguage, web.browserLang);\r\n _setValueIf(envTags, CtxTagKeys.deviceBrowserVersion, web.browserVer);\r\n _setValueIf(envTags, CtxTagKeys.deviceBrowser, web.browser);\r\n var envData = env[_DYN_DATA /* @min:%2edata */] = env[_DYN_DATA /* @min:%2edata */] || {};\r\n var envBaseData = envData[strBaseData] = envData[strBaseData] || {};\r\n var envProps = envBaseData[strProperties] = envBaseData[strProperties] || {};\r\n _setValueIf(envProps, \"domain\", web.domain);\r\n _setValueIf(envProps, \"isManual\", web.isManual ? strTrue : null);\r\n _setValueIf(envProps, \"screenRes\", web.screenRes);\r\n _setValueIf(envProps, \"userConsent\", web.userConsent ? strTrue : null);\r\n }\r\n var extOs = itmExt.os;\r\n if (extOs) {\r\n _setValueIf(envTags, CtxTagKeys.deviceOS, extOs[_DYN_NAME /* @min:%2ename */]);\r\n }\r\n // No support for mapping Trace.traceState to 2.0 as it is currently empty\r\n var extTrace = itmExt.trace;\r\n if (extTrace) {\r\n _setValueIf(envTags, CtxTagKeys.operationParentId, extTrace.parentID);\r\n _setValueIf(envTags, CtxTagKeys.operationName, dataSanitizeString(logger, extTrace[_DYN_NAME /* @min:%2ename */]));\r\n _setValueIf(envTags, CtxTagKeys.operationId, extTrace[_DYN_TRACE_ID /* @min:%2etraceID */]);\r\n }\r\n // Sample 4.0 schema\r\n // {\r\n // \"time\" : \"2018-09-05T22:51:22.4936Z\",\r\n // \"name\" : \"MetricWithNamespace\",\r\n // \"iKey\" : \"ABC-5a4cbd20-e601-4ef5-a3c6-5d6577e4398e\",\r\n // \"ext\": { \"cloud\": {\r\n // \"role\": \"WATSON3\",\r\n // \"roleInstance\": \"CO4AEAP00000260\"\r\n // },\r\n // \"device\": {}, \"correlation\": {} },\r\n // \"tags\": [\r\n // { \"amazon.region\" : \"east2\" },\r\n // { \"os.expid\" : \"wp:02df239\" }\r\n // ]\r\n // }\r\n var tgs = {};\r\n // deals with tags.push({object})\r\n for (var i = itmTags[_DYN_LENGTH /* @min:%2elength */] - 1; i >= 0; i--) {\r\n var tg = itmTags[i];\r\n objForEachKey(tg, function (key, value) {\r\n tgs[key] = value;\r\n });\r\n itmTags.splice(i, 1);\r\n }\r\n // deals with tags[key]=value (and handles hasOwnProperty)\r\n objForEachKey(itmTags, function (tg, value) {\r\n tgs[tg] = value;\r\n });\r\n var theTags = __assign(__assign({}, envTags), tgs);\r\n if (!theTags[CtxTagKeys.internalSdkVersion]) {\r\n // Append a version in case it is not already set\r\n theTags[CtxTagKeys.internalSdkVersion] = \"javascript:\".concat(EnvelopeCreator.Version);\r\n }\r\n env[_DYN_TAGS /* @min:%2etags */] = optimizeObject(theTags);\r\n}\r\nfunction _extractPropsAndMeasurements(data, properties, measurements) {\r\n if (!isNullOrUndefined(data)) {\r\n objForEachKey(data, function (key, value) {\r\n if (isNumber(value)) {\r\n measurements[key] = value;\r\n }\r\n else if (isString(value)) {\r\n properties[key] = value;\r\n }\r\n else if (hasJSON()) {\r\n properties[key] = getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](value);\r\n }\r\n });\r\n }\r\n}\r\nfunction _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue) {\r\n if (!isNullOrUndefined(properties)) {\r\n objForEachKey(properties, function (key, value) {\r\n properties[key] = value || customUndefinedValue;\r\n });\r\n }\r\n}\r\n// TODO: Do we want this to take logger as arg or use this._logger as nonstatic?\r\nfunction _createEnvelope(logger, envelopeType, telemetryItem, data) {\r\n var envelope = new Envelope(logger, data, envelopeType);\r\n _setValueIf(envelope, \"sampleRate\", telemetryItem[SampleRate]);\r\n if ((telemetryItem[strBaseData] || {}).startTime) {\r\n envelope.time = toISOString(telemetryItem[strBaseData].startTime);\r\n }\r\n envelope.iKey = telemetryItem.iKey;\r\n var iKeyNoDashes = telemetryItem.iKey.replace(/-/g, \"\");\r\n envelope[_DYN_NAME /* @min:%2ename */] = envelope[_DYN_NAME /* @min:%2ename */].replace(\"{0}\", iKeyNoDashes);\r\n // extract all extensions from ctx\r\n _extractPartAExtensions(logger, telemetryItem, envelope);\r\n // loop through the envelope tags (extension of Part A) and pick out the ones that should go in outgoing envelope tags\r\n telemetryItem[_DYN_TAGS /* @min:%2etags */] = telemetryItem[_DYN_TAGS /* @min:%2etags */] || [];\r\n return optimizeObject(envelope);\r\n}\r\nfunction EnvelopeCreatorInit(logger, telemetryItem) {\r\n if (isNullOrUndefined(telemetryItem[strBaseData])) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 46 /* _eInternalMessageId.TelemetryEnvelopeInvalid */, \"telemetryItem.baseData cannot be null.\");\r\n }\r\n}\r\nexport var EnvelopeCreator = {\r\n Version: '2.8.11'\r\n};\r\nexport function DependencyEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n var customProperties = telemetryItem[strBaseData][strProperties] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\r\n }\r\n var bd = telemetryItem[strBaseData];\r\n if (isNullOrUndefined(bd)) {\r\n _warnToConsole(logger, \"Invalid input for dependency data\");\r\n return null;\r\n }\r\n var method = bd[strProperties] && bd[strProperties][HttpMethod] ? bd[strProperties][HttpMethod] : \"GET\";\r\n var remoteDepData = new RemoteDependencyData(logger, bd.id, bd.target, bd[_DYN_NAME /* @min:%2ename */], bd[STR_DURATION /* @min:%2eduration */], bd.success, bd.responseCode, method, bd.type, bd.correlationContext, customProperties, customMeasurements);\r\n var data = new Data(RemoteDependencyData[_DYN_DATA_TYPE /* @min:%2edataType */], remoteDepData);\r\n return _createEnvelope(logger, RemoteDependencyData[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function EventEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var customProperties = {};\r\n var customMeasurements = {};\r\n if (telemetryItem[strBaseType] !== Event[_DYN_DATA_TYPE /* @min:%2edataType */]) {\r\n customProperties[\"baseTypeSource\"] = telemetryItem[strBaseType]; // save the passed in base type as a property\r\n }\r\n if (telemetryItem[strBaseType] === Event[_DYN_DATA_TYPE /* @min:%2edataType */]) { // take collection\r\n customProperties = telemetryItem[strBaseData][strProperties] || {};\r\n customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n }\r\n else { // if its not a known type, convert to custom event\r\n if (telemetryItem[strBaseData]) {\r\n _extractPropsAndMeasurements(telemetryItem[strBaseData], customProperties, customMeasurements);\r\n }\r\n }\r\n // Extract root level properties from part C telemetryItem.data\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\r\n }\r\n var eventName = telemetryItem[strBaseData][_DYN_NAME /* @min:%2ename */];\r\n var eventData = new Event(logger, eventName, customProperties, customMeasurements);\r\n var data = new Data(Event[_DYN_DATA_TYPE /* @min:%2edataType */], eventData);\r\n return _createEnvelope(logger, Event[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function ExceptionEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n // Extract root level properties from part C telemetryItem.data\r\n var customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n var customProperties = telemetryItem[strBaseData][strProperties] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\r\n }\r\n var bd = telemetryItem[strBaseData];\r\n var exData = Exception.CreateFromInterface(logger, bd, customProperties, customMeasurements);\r\n var data = new Data(Exception[_DYN_DATA_TYPE /* @min:%2edataType */], exData);\r\n return _createEnvelope(logger, Exception[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function MetricEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var baseData = telemetryItem[strBaseData];\r\n var props = baseData[strProperties] || {};\r\n var measurements = baseData[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], props, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(props, customUndefinedValue);\r\n }\r\n var baseMetricData = new Metric(logger, baseData[_DYN_NAME /* @min:%2ename */], baseData.average, baseData.sampleCount, baseData.min, baseData.max, baseData.stdDev, props, measurements);\r\n var data = new Data(Metric[_DYN_DATA_TYPE /* @min:%2edataType */], baseMetricData);\r\n return _createEnvelope(logger, Metric[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function PageViewEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n // Since duration is not part of the domain properties in Common Schema, extract it from part C\r\n var duration;\r\n var baseData = telemetryItem[strBaseData];\r\n if (!isNullOrUndefined(baseData) &&\r\n !isNullOrUndefined(baseData[strProperties]) &&\r\n !isNullOrUndefined(baseData[strProperties][STR_DURATION])) { // from part B properties\r\n duration = baseData[strProperties][STR_DURATION];\r\n delete baseData[strProperties][STR_DURATION];\r\n }\r\n else if (!isNullOrUndefined(telemetryItem[_DYN_DATA /* @min:%2edata */]) &&\r\n !isNullOrUndefined(telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION])) { // from custom properties\r\n duration = telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION];\r\n delete telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION];\r\n }\r\n var bd = telemetryItem[strBaseData];\r\n // special case: pageview.id is grabbed from current operation id. Analytics plugin is decoupled from properties plugin, so this is done here instead. This can be made a default telemetry intializer instead if needed to be decoupled from channel\r\n var currentContextId;\r\n if (((telemetryItem.ext || {}).trace || {})[_DYN_TRACE_ID /* @min:%2etraceID */]) {\r\n currentContextId = telemetryItem.ext.trace[_DYN_TRACE_ID /* @min:%2etraceID */];\r\n }\r\n var id = bd.id || currentContextId;\r\n var name = bd[_DYN_NAME /* @min:%2ename */];\r\n var url = bd.uri;\r\n var properties = bd[strProperties] || {};\r\n var measurements = bd[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n // refUri is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\r\n if (!isNullOrUndefined(bd.refUri)) {\r\n properties[\"refUri\"] = bd.refUri;\r\n }\r\n // pageType is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\r\n if (!isNullOrUndefined(bd.pageType)) {\r\n properties[\"pageType\"] = bd.pageType;\r\n }\r\n // isLoggedIn is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\r\n if (!isNullOrUndefined(bd.isLoggedIn)) {\r\n properties[\"isLoggedIn\"] = bd.isLoggedIn[_DYN_TO_STRING /* @min:%2etoString */]();\r\n }\r\n // pageTags is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\r\n if (!isNullOrUndefined(bd[strProperties])) {\r\n var pageTags = bd[strProperties];\r\n objForEachKey(pageTags, function (key, value) {\r\n properties[key] = value;\r\n });\r\n }\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], properties, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue);\r\n }\r\n var pageViewData = new PageView(logger, name, url, duration, properties, measurements, id);\r\n var data = new Data(PageView[_DYN_DATA_TYPE /* @min:%2edataType */], pageViewData);\r\n return _createEnvelope(logger, PageView[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function PageViewPerformanceEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var bd = telemetryItem[strBaseData];\r\n var name = bd[_DYN_NAME /* @min:%2ename */];\r\n var url = bd.uri || bd.url;\r\n var properties = bd[strProperties] || {};\r\n var measurements = bd[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], properties, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue);\r\n }\r\n var baseData = new PageViewPerformance(logger, name, url, undefined, properties, measurements, bd);\r\n var data = new Data(PageViewPerformance[_DYN_DATA_TYPE /* @min:%2edataType */], baseData);\r\n return _createEnvelope(logger, PageViewPerformance[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function TraceEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var message = telemetryItem[strBaseData].message;\r\n var severityLevel = telemetryItem[strBaseData].severityLevel;\r\n var props = telemetryItem[strBaseData][strProperties] || {};\r\n var measurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], props, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(props, customUndefinedValue);\r\n }\r\n var baseData = new Trace(logger, message, severityLevel, props, measurements);\r\n var data = new Data(Trace[_DYN_DATA_TYPE /* @min:%2edataType */], baseData);\r\n return _createEnvelope(logger, Trace[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Channel, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)\r\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\r\nexport var STR_DURATION = \"duration\";\r\n","/*\n * Application Insights JavaScript SDK - Channel, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { createUniqueNamespace, eventOff, eventOn, getDocument, getNavigator, getWindow, isNullOrUndefined, isUndefined, mergeEvtNamespace } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_ON_LINE } from \"./__DynamicConstants\";\r\nfunction _disableEvents(target, evtNamespace) {\r\n eventOff(target, null, null, evtNamespace);\r\n}\r\n/**\r\n * Create a new OfflineListener instance to monitor browser online / offline events\r\n * @param parentEvtNamespace - The parent event namespace to append to any specific events for this instance\r\n */\r\nexport function createOfflineListener(parentEvtNamespace) {\r\n var _document = getDocument();\r\n var _navigator = getNavigator(); // Gets the window.navigator or workerNavigator depending on the global\r\n var _isListening = false;\r\n var _onlineStatus = true;\r\n var _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"OfflineListener\"), parentEvtNamespace);\r\n try {\r\n if (_enableEvents(getWindow())) {\r\n _isListening = true;\r\n }\r\n if (_document) {\r\n // Also attach to the document.body or document\r\n var target = _document.body || _document;\r\n if (target.ononline) {\r\n if (_enableEvents(target)) {\r\n _isListening = true;\r\n }\r\n }\r\n }\r\n if (_isListening) {\r\n // We are listening to events so lets set the current status rather than assuming we are online #1538\r\n if (_navigator && !isNullOrUndefined(_navigator[_DYN_ON_LINE /* @min:%2eonLine */])) { // navigator.onLine is undefined in react-native\r\n _onlineStatus = _navigator[_DYN_ON_LINE /* @min:%2eonLine */];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // this makes react-native less angry\r\n _isListening = false;\r\n }\r\n function _enableEvents(target) {\r\n var enabled = false;\r\n if (target) {\r\n enabled = eventOn(target, \"online\", _setOnline, _evtNamespace);\r\n if (enabled) {\r\n eventOn(target, \"offline\", _setOffline, _evtNamespace);\r\n }\r\n }\r\n return enabled;\r\n }\r\n function _setOnline() {\r\n _onlineStatus = true;\r\n }\r\n function _setOffline() {\r\n _onlineStatus = false;\r\n }\r\n function _isOnline() {\r\n var result = true;\r\n if (_isListening) {\r\n result = _onlineStatus;\r\n }\r\n else if (_navigator && !isNullOrUndefined(_navigator[_DYN_ON_LINE /* @min:%2eonLine */])) { // navigator.onLine is undefined in react-native\r\n result = _navigator[_DYN_ON_LINE /* @min:%2eonLine */];\r\n }\r\n return result;\r\n }\r\n function _unload() {\r\n var win = getWindow();\r\n if (win && _isListening) {\r\n _disableEvents(win, _evtNamespace);\r\n if (_document) {\r\n // Also attach to the document.body or document\r\n var target = _document.body || _document;\r\n if (!isUndefined(target.ononline)) {\r\n _disableEvents(target, _evtNamespace);\r\n }\r\n }\r\n _isListening = false;\r\n }\r\n }\r\n return {\r\n isOnline: _isOnline,\r\n isListening: function () { return _isListening; },\r\n unload: _unload\r\n };\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Channel, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { utlGetSessionStorage, utlSetSessionStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, arrForEach, arrIndexOf, dumpObj, getExceptionName, getJSON, isArray, isFunction, isString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_BATCH_PAYLOADS, _DYN_CLEAR, _DYN_CLEAR_SENT, _DYN_COUNT, _DYN_EMIT_LINE_DELIMITED_0, _DYN_ENQUEUE, _DYN_LENGTH, _DYN_MARK_AS_SENT, _DYN_NAME_PREFIX, _DYN_PUSH, _DYN_STRINGIFY, _DYN__BUFFER__KEY, _DYN__MAX__BUFFER__SIZE, _DYN__SENT__BUFFER__KEY } from \"./__DynamicConstants\";\r\nvar BaseSendBuffer = /** @class */ (function () {\r\n function BaseSendBuffer(logger, config) {\r\n var _buffer = [];\r\n var _bufferFullMessageSent = false;\r\n this._get = function () {\r\n return _buffer;\r\n };\r\n this._set = function (buffer) {\r\n _buffer = buffer;\r\n return _buffer;\r\n };\r\n dynamicProto(BaseSendBuffer, this, function (_self) {\r\n _self[_DYN_ENQUEUE /* @min:%2eenqueue */] = function (payload) {\r\n if (_self[_DYN_COUNT /* @min:%2ecount */]() >= config.eventsLimitInMem()) {\r\n // sent internal log only once per page view\r\n if (!_bufferFullMessageSent) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 105 /* _eInternalMessageId.InMemoryStorageBufferFull */, \"Maximum in-memory buffer size reached: \" + _self[_DYN_COUNT /* @min:%2ecount */](), true);\r\n _bufferFullMessageSent = true;\r\n }\r\n return;\r\n }\r\n _buffer[_DYN_PUSH /* @min:%2epush */](payload);\r\n };\r\n _self[_DYN_COUNT /* @min:%2ecount */] = function () {\r\n return _buffer[_DYN_LENGTH /* @min:%2elength */];\r\n };\r\n _self.size = function () {\r\n var size = _buffer[_DYN_LENGTH /* @min:%2elength */];\r\n for (var lp = 0; lp < _buffer[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n size += _buffer[lp][_DYN_LENGTH /* @min:%2elength */];\r\n }\r\n if (!config[_DYN_EMIT_LINE_DELIMITED_0 /* @min:%2eemitLineDelimitedJson */]()) {\r\n size += 2;\r\n }\r\n return size;\r\n };\r\n _self[_DYN_CLEAR /* @min:%2eclear */] = function () {\r\n _buffer = [];\r\n _bufferFullMessageSent = false;\r\n };\r\n _self.getItems = function () {\r\n return _buffer.slice(0);\r\n };\r\n _self[_DYN_BATCH_PAYLOADS /* @min:%2ebatchPayloads */] = function (payload) {\r\n if (payload && payload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var batch = config[_DYN_EMIT_LINE_DELIMITED_0 /* @min:%2eemitLineDelimitedJson */]() ?\r\n payload.join(\"\\n\") :\r\n \"[\" + payload.join(\",\") + \"]\";\r\n return batch;\r\n }\r\n return null;\r\n };\r\n });\r\n }\r\n// Removed Stub for BaseSendBuffer.prototype.enqueue.\r\n// Removed Stub for BaseSendBuffer.prototype.count.\r\n// Removed Stub for BaseSendBuffer.prototype.size.\r\n// Removed Stub for BaseSendBuffer.prototype.clear.\r\n// Removed Stub for BaseSendBuffer.prototype.getItems.\r\n// Removed Stub for BaseSendBuffer.prototype.batchPayloads.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n BaseSendBuffer.__ieDyn=1;\n\n return BaseSendBuffer;\r\n}());\r\n/*\r\n * An array based send buffer.\r\n */\r\nvar ArraySendBuffer = /** @class */ (function (_super) {\r\n __extends(ArraySendBuffer, _super);\r\n function ArraySendBuffer(logger, config) {\r\n var _this = _super.call(this, logger, config) || this;\r\n dynamicProto(ArraySendBuffer, _this, function (_self, _base) {\r\n _self[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */] = function (payload) {\r\n _base[_DYN_CLEAR /* @min:%2eclear */]();\r\n };\r\n _self[_DYN_CLEAR_SENT /* @min:%2eclearSent */] = function (payload) {\r\n // not supported\r\n };\r\n });\r\n return _this;\r\n }\r\n// Removed Stub for ArraySendBuffer.prototype.markAsSent.\r\n// Removed Stub for ArraySendBuffer.prototype.clearSent.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n ArraySendBuffer.__ieDyn=1;\n\n return ArraySendBuffer;\r\n}(BaseSendBuffer));\r\nexport { ArraySendBuffer };\r\n/*\r\n * Session storage buffer holds a copy of all unsent items in the browser session storage.\r\n */\r\nvar SessionStorageSendBuffer = /** @class */ (function (_super) {\r\n __extends(SessionStorageSendBuffer, _super);\r\n function SessionStorageSendBuffer(logger, config) {\r\n var _this = _super.call(this, logger, config) || this;\r\n var _bufferFullMessageSent = false;\r\n dynamicProto(SessionStorageSendBuffer, _this, function (_self, _base) {\r\n var bufferItems = _getBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */]);\r\n var notDeliveredItems = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\r\n var buffer = _self._set(bufferItems.concat(notDeliveredItems));\r\n // If the buffer has too many items, drop items from the end.\r\n if (buffer[_DYN_LENGTH /* @min:%2elength */] > SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\r\n buffer[_DYN_LENGTH /* @min:%2elength */] = SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */];\r\n }\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], []);\r\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], buffer);\r\n _self[_DYN_ENQUEUE /* @min:%2eenqueue */] = function (payload) {\r\n if (_self[_DYN_COUNT /* @min:%2ecount */]() >= SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\r\n // sent internal log only once per page view\r\n if (!_bufferFullMessageSent) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 67 /* _eInternalMessageId.SessionStorageBufferFull */, \"Maximum buffer size reached: \" + _self[_DYN_COUNT /* @min:%2ecount */](), true);\r\n _bufferFullMessageSent = true;\r\n }\r\n return;\r\n }\r\n _base[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\r\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], _self._get());\r\n };\r\n _self[_DYN_CLEAR /* @min:%2eclear */] = function () {\r\n _base[_DYN_CLEAR /* @min:%2eclear */]();\r\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], _self._get());\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], []);\r\n _bufferFullMessageSent = false;\r\n };\r\n _self[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */] = function (payload) {\r\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], _self._set(_removePayloadsFromBuffer(payload, _self._get())));\r\n var sentElements = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\r\n if (sentElements instanceof Array && payload instanceof Array) {\r\n sentElements = sentElements.concat(payload);\r\n if (sentElements[_DYN_LENGTH /* @min:%2elength */] > SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\r\n // We send telemetry normally. If the SENT_BUFFER is too big we don't add new elements\r\n // until we receive a response from the backend and the buffer has free space again (see clearSent method)\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 67 /* _eInternalMessageId.SessionStorageBufferFull */, \"Sent buffer reached its maximum size: \" + sentElements[_DYN_LENGTH /* @min:%2elength */], true);\r\n sentElements[_DYN_LENGTH /* @min:%2elength */] = SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */];\r\n }\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], sentElements);\r\n }\r\n };\r\n _self[_DYN_CLEAR_SENT /* @min:%2eclearSent */] = function (payload) {\r\n var sentElements = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\r\n sentElements = _removePayloadsFromBuffer(payload, sentElements);\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], sentElements);\r\n };\r\n function _removePayloadsFromBuffer(payloads, buffer) {\r\n var remaining = [];\r\n arrForEach(buffer, function (value) {\r\n if (!isFunction(value) && arrIndexOf(payloads, value) === -1) {\r\n remaining[_DYN_PUSH /* @min:%2epush */](value);\r\n }\r\n });\r\n return remaining;\r\n }\r\n function _getBuffer(key) {\r\n var prefixedKey = key;\r\n try {\r\n prefixedKey = config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */] && config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */]() ? config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */]() + \"_\" + prefixedKey : prefixedKey;\r\n var bufferJson = utlGetSessionStorage(logger, prefixedKey);\r\n if (bufferJson) {\r\n var buffer_1 = getJSON().parse(bufferJson);\r\n if (isString(buffer_1)) {\r\n // When using some version prototype.js the stringify / parse cycle does not decode array's correctly\r\n buffer_1 = getJSON().parse(buffer_1);\r\n }\r\n if (buffer_1 && isArray(buffer_1)) {\r\n return buffer_1;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 42 /* _eInternalMessageId.FailedToRestoreStorageBuffer */, \" storage key: \" + prefixedKey + \", \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n return [];\r\n }\r\n function _setBuffer(key, buffer) {\r\n var prefixedKey = key;\r\n try {\r\n prefixedKey = config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */] && config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */]() ? config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */]() + \"_\" + prefixedKey : prefixedKey;\r\n var bufferJson = JSON[_DYN_STRINGIFY /* @min:%2estringify */](buffer);\r\n utlSetSessionStorage(logger, prefixedKey, bufferJson);\r\n }\r\n catch (e) {\r\n // if there was an error, clear the buffer\r\n // telemetry is stored in the _buffer array so we won't loose any items\r\n utlSetSessionStorage(logger, prefixedKey, JSON[_DYN_STRINGIFY /* @min:%2estringify */]([]));\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 41 /* _eInternalMessageId.FailedToSetStorageBuffer */, \" storage key: \" + prefixedKey + \", \" + getExceptionName(e) + \". Buffer cleared\", { exception: dumpObj(e) });\r\n }\r\n }\r\n });\r\n return _this;\r\n }\r\n// Removed Stub for SessionStorageSendBuffer.prototype.enqueue.\r\n// Removed Stub for SessionStorageSendBuffer.prototype.clear.\r\n// Removed Stub for SessionStorageSendBuffer.prototype.markAsSent.\r\n// Removed Stub for SessionStorageSendBuffer.prototype.clearSent.\r\n SessionStorageSendBuffer.BUFFER_KEY = \"AI_buffer\";\r\n SessionStorageSendBuffer.SENT_BUFFER_KEY = \"AI_sentBuffer\";\r\n // Maximum number of payloads stored in the buffer. If the buffer is full, new elements will be dropped.\r\n SessionStorageSendBuffer.MAX_BUFFER_SIZE = 2000;\r\n return SessionStorageSendBuffer;\r\n}(BaseSendBuffer));\r\nexport { SessionStorageSendBuffer };\r\n","/*\n * Application Insights JavaScript SDK - Channel, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nvar _a;\r\nimport { __assignFn as __assign, __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { BreezeChannelIdentifier, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, DisabledPropertyName, Event, Exception, Metric, PageView, PageViewPerformance, ProcessLegacy, RemoteDependencyData, RequestHeaders, SampleRate, Trace, isInternalApplicationInsightsEndpoint, utlCanUseSessionStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { BaseTelemetryPlugin, _throwInternal, _warnToConsole, arrForEach, createUniqueNamespace, dateNow, dumpObj, getExceptionName, getIEVersion, getJSON, getNavigator, getWindow, isArray, isBeaconsSupported, isFetchSupported, isNullOrUndefined, isXhrSupported, mergeEvtNamespace, objForEachKey, objKeys, useXDomainRequest } from \"@microsoft/applicationinsights-core-js\";\r\nimport { DependencyEnvelopeCreator, EventEnvelopeCreator, ExceptionEnvelopeCreator, MetricEnvelopeCreator, PageViewEnvelopeCreator, PageViewPerformanceEnvelopeCreator, TraceEnvelopeCreator } from \"./EnvelopeCreator\";\r\nimport { createOfflineListener } from \"./Offline\";\r\nimport { ArraySendBuffer, SessionStorageSendBuffer } from \"./SendBuffer\";\r\nimport { Serializer } from \"./Serializer\";\r\nimport { Sample } from \"./TelemetryProcessors/Sample\";\r\nimport { _DYN_BASE_TYPE, _DYN_BATCH_PAYLOADS, _DYN_CLEAR, _DYN_CLEAR_SENT, _DYN_CONVERT_UNDEFINED, _DYN_COUNT, _DYN_CUSTOM_HEADERS, _DYN_DIAG_LOG, _DYN_DISABLE_INSTRUMENTAT7, _DYN_DISABLE_TELEMETRY, _DYN_DISABLE_XHR, _DYN_EMIT_LINE_DELIMITED_0, _DYN_ENABLE_SESSION_STORA4, _DYN_ENDPOINT_URL, _DYN_ENQUEUE, _DYN_EVENTS_SEND_REQUEST, _DYN_INSTRUMENTATION_KEY, _DYN_IS_BEACON_API_DISABL3, _DYN_IS_RETRY_DISABLED, _DYN_ITEMS_ACCEPTED, _DYN_ITEMS_RECEIVED, _DYN_LENGTH, _DYN_MARK_AS_SENT, _DYN_MAX_BATCH_INTERVAL, _DYN_MAX_BATCH_SIZE_IN_BY1, _DYN_NAME_PREFIX, _DYN_ONUNLOAD_DISABLE_BEA2, _DYN_ONUNLOAD_DISABLE_FET5, _DYN_PUSH, _DYN_SAMPLE_RATE, _DYN_SAMPLING_PERCENTAGE, _DYN_SET_REQUEST_HEADER, _DYN_TAGS, _DYN_TRIGGER_SEND, _DYN__BUFFER, _DYN__ON_ERROR, _DYN__ON_PARTIAL_SUCCESS, _DYN__ON_SUCCESS, _DYN__SENDER, _DYN__SENDER_CONFIG, _DYN__XHR_READY_STATE_CHA6 } from \"./__DynamicConstants\";\r\nvar FetchSyncRequestSizeLimitBytes = 65000; // approx 64kb (the current Edge, Firefox and Chrome max limit)\r\nfunction _getResponseText(xhr) {\r\n try {\r\n return xhr.responseText;\r\n }\r\n catch (e) {\r\n // Best effort, as XHR may throw while XDR wont so just ignore\r\n }\r\n return null;\r\n}\r\nfunction _getDefaultAppInsightsChannelConfig() {\r\n var _a;\r\n var defaultValue;\r\n var defaultCustomHeaders;\r\n // set default values\r\n return _a = {\r\n endpointUrl: function () { return DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH; }\r\n },\r\n _a[_DYN_EMIT_LINE_DELIMITED_0 /* @min:emitLineDelimitedJson */] = function () { return false; },\r\n _a[_DYN_MAX_BATCH_INTERVAL /* @min:maxBatchInterval */] = function () { return 15000; },\r\n _a[_DYN_MAX_BATCH_SIZE_IN_BY1 /* @min:maxBatchSizeInBytes */] = function () { return 102400; },\r\n _a[_DYN_DISABLE_TELEMETRY /* @min:disableTelemetry */] = function () { return false; },\r\n _a[_DYN_ENABLE_SESSION_STORA4 /* @min:enableSessionStorageBuffer */] = function () { return true; },\r\n _a[_DYN_IS_RETRY_DISABLED /* @min:isRetryDisabled */] = function () { return false; },\r\n _a[_DYN_IS_BEACON_API_DISABL3 /* @min:isBeaconApiDisabled */] = function () { return true; },\r\n _a[_DYN_DISABLE_XHR /* @min:disableXhr */] = function () { return false; },\r\n _a[_DYN_ONUNLOAD_DISABLE_FET5 /* @min:onunloadDisableFetch */] = function () { return false; },\r\n _a[_DYN_ONUNLOAD_DISABLE_BEA2 /* @min:onunloadDisableBeacon */] = function () { return false; },\r\n _a[_DYN_INSTRUMENTATION_KEY /* @min:instrumentationKey */] = function () { return defaultValue; },\r\n _a[_DYN_NAME_PREFIX /* @min:namePrefix */] = function () { return defaultValue; },\r\n _a[_DYN_SAMPLING_PERCENTAGE /* @min:samplingPercentage */] = function () { return 100; },\r\n _a[_DYN_CUSTOM_HEADERS /* @min:customHeaders */] = function () { return defaultCustomHeaders; },\r\n _a[_DYN_CONVERT_UNDEFINED /* @min:convertUndefined */] = function () { return defaultValue; },\r\n _a.eventsLimitInMem = function () { return 10000; },\r\n _a;\r\n}\r\nvar EnvelopeTypeCreator = (_a = {},\r\n _a[Event.dataType] = EventEnvelopeCreator,\r\n _a[Trace.dataType] = TraceEnvelopeCreator,\r\n _a[PageView.dataType] = PageViewEnvelopeCreator,\r\n _a[PageViewPerformance.dataType] = PageViewPerformanceEnvelopeCreator,\r\n _a[Exception.dataType] = ExceptionEnvelopeCreator,\r\n _a[Metric.dataType] = MetricEnvelopeCreator,\r\n _a[RemoteDependencyData.dataType] = DependencyEnvelopeCreator,\r\n _a);\r\nvar Sender = /** @class */ (function (_super) {\r\n __extends(Sender, _super);\r\n function Sender() {\r\n var _this = _super.call(this) || this;\r\n _this.priority = 1001;\r\n _this.identifier = BreezeChannelIdentifier;\r\n /**\r\n * The configuration for this sender instance\r\n */\r\n _this._senderConfig = _getDefaultAppInsightsChannelConfig();\r\n // Don't set the defaults here, set them in the _initDefaults() as this is also called during unload\r\n var _consecutiveErrors; // How many times in a row a retryable error condition has occurred.\r\n var _retryAt; // The time to retry at in milliseconds from 1970/01/01 (this makes the timer calculation easy).\r\n var _lastSend; // The time of the last send operation.\r\n var _paused; // Flag indicating that the sending should be paused\r\n var _timeoutHandle; // Handle to the timer for delayed sending of batches of data.\r\n var _serializer;\r\n var _stamp_specific_redirects;\r\n var _headers;\r\n var _syncFetchPayload = 0; // Keep track of the outstanding sync fetch payload total (as sync fetch has limits)\r\n var _fallbackSender; // The sender to use if the payload size is too large\r\n var _syncUnloadSender; // The identified sender to use for the synchronous unload stage\r\n var _offlineListener;\r\n var _evtNamespace;\r\n dynamicProto(Sender, _this, function (_self, _base) {\r\n _initDefaults();\r\n _self.pause = function () {\r\n _clearScheduledTimer();\r\n _paused = true;\r\n };\r\n _self.resume = function () {\r\n if (_paused) {\r\n _paused = false;\r\n _retryAt = null;\r\n // flush if we have exceeded the max-size already\r\n if (_self._buffer.size() > _self._senderConfig[_DYN_MAX_BATCH_SIZE_IN_BY1 /* @min:%2emaxBatchSizeInBytes */]()) {\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, null, 10 /* SendRequestReason.MaxBatchSize */);\r\n }\r\n _setupTimer();\r\n }\r\n };\r\n _self.flush = function (isAsync, callBack, sendReason) {\r\n if (isAsync === void 0) { isAsync = true; }\r\n if (!_paused) {\r\n // Clear the normal schedule timer as we are going to try and flush ASAP\r\n _clearScheduledTimer();\r\n try {\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](isAsync, null, sendReason || 1 /* SendRequestReason.ManualFlush */);\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 22 /* _eInternalMessageId.FlushFailed */, \"flush failed, telemetry will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n };\r\n _self.onunloadFlush = function () {\r\n if (!_paused) {\r\n if ((_self._senderConfig[_DYN_ONUNLOAD_DISABLE_BEA2 /* @min:%2eonunloadDisableBeacon */]() === false || _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_IS_BEACON_API_DISABL3 /* @min:%2eisBeaconApiDisabled */]() === false) && isBeaconsSupported()) {\r\n try {\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, _doUnloadSend, 2 /* SendRequestReason.Unload */);\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 20 /* _eInternalMessageId.FailedToSendQueuedTelemetry */, \"failed to flush with beacon sender on page unload, telemetry will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n else {\r\n _self.flush();\r\n }\r\n }\r\n };\r\n _self.addHeader = function (name, value) {\r\n _headers[name] = value;\r\n };\r\n _self.initialize = function (config, core, extensions, pluginChain) {\r\n if (_self.isInitialized()) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"Sender is already initialized\");\r\n }\r\n _base.initialize(config, core, extensions, pluginChain);\r\n var ctx = _self._getTelCtx();\r\n var identifier = _self.identifier;\r\n _serializer = new Serializer(core.logger);\r\n _consecutiveErrors = 0;\r\n _retryAt = null;\r\n _lastSend = 0;\r\n _self[_DYN__SENDER /* @min:%2e_sender */] = null;\r\n _stamp_specific_redirects = 0;\r\n var diagLog = _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\r\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"Sender\"), core.evtNamespace && core.evtNamespace());\r\n _offlineListener = createOfflineListener(_evtNamespace);\r\n // TODO v3.x: Change the ISenderConfig to not be function calls\r\n var defaultConfig = _getDefaultAppInsightsChannelConfig();\r\n objForEachKey(defaultConfig, function (field, value) {\r\n _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][field] = function () {\r\n var theValue = ctx.getConfig(identifier, field, value());\r\n if (!theValue && field === \"endpointUrl\") {\r\n // Use the default value (handles empty string in the configuration)\r\n theValue = value();\r\n }\r\n return theValue;\r\n };\r\n });\r\n _self._buffer = (_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_ENABLE_SESSION_STORA4 /* @min:%2eenableSessionStorageBuffer */]() && utlCanUseSessionStorage())\r\n ? new SessionStorageSendBuffer(diagLog, _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */]) : new ArraySendBuffer(diagLog, _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */]);\r\n _self._sample = new Sample(_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_SAMPLING_PERCENTAGE /* @min:%2esamplingPercentage */](), diagLog);\r\n if (!_validateInstrumentationKey(config)) {\r\n _throwInternal(diagLog, 1 /* eLoggingSeverity.CRITICAL */, 100 /* _eInternalMessageId.InvalidInstrumentationKey */, \"Invalid Instrumentation key \" + config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */]);\r\n }\r\n if (!isInternalApplicationInsightsEndpoint(_self._senderConfig.endpointUrl()) && _self._senderConfig.customHeaders() && _self._senderConfig.customHeaders()[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_CUSTOM_HEADERS /* @min:%2ecustomHeaders */](), function (customHeader) {\r\n _this.addHeader(customHeader.header, customHeader.value);\r\n });\r\n }\r\n var senderConfig = _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */];\r\n var sendPostFunc = null;\r\n if (!senderConfig[_DYN_DISABLE_XHR /* @min:%2edisableXhr */]() && useXDomainRequest()) {\r\n sendPostFunc = _xdrSender; // IE 8 and 9\r\n }\r\n else if (!senderConfig[_DYN_DISABLE_XHR /* @min:%2edisableXhr */]() && isXhrSupported()) {\r\n sendPostFunc = _xhrSender;\r\n }\r\n if (!sendPostFunc && isFetchSupported()) {\r\n sendPostFunc = _fetchSender;\r\n }\r\n // always fallback to XHR\r\n _fallbackSender = sendPostFunc || _xhrSender;\r\n if (!senderConfig[_DYN_IS_BEACON_API_DISABL3 /* @min:%2eisBeaconApiDisabled */]() && isBeaconsSupported()) {\r\n // Config is set to always used beacon sending\r\n sendPostFunc = _beaconSender;\r\n }\r\n _self[_DYN__SENDER /* @min:%2e_sender */] = sendPostFunc || _xhrSender;\r\n if (!senderConfig[_DYN_ONUNLOAD_DISABLE_FET5 /* @min:%2eonunloadDisableFetch */]() && isFetchSupported(true)) {\r\n // Try and use the fetch with keepalive\r\n _syncUnloadSender = _fetchKeepAliveSender;\r\n }\r\n else if (isBeaconsSupported()) {\r\n // Try and use sendBeacon\r\n _syncUnloadSender = _beaconSender;\r\n }\r\n else if (!senderConfig[_DYN_DISABLE_XHR /* @min:%2edisableXhr */]() && useXDomainRequest()) {\r\n _syncUnloadSender = _xdrSender; // IE 8 and 9\r\n }\r\n else if (!senderConfig[_DYN_DISABLE_XHR /* @min:%2edisableXhr */]() && isXhrSupported()) {\r\n _syncUnloadSender = _xhrSender;\r\n }\r\n else {\r\n _syncUnloadSender = _fallbackSender;\r\n }\r\n };\r\n _self.processTelemetry = function (telemetryItem, itemCtx) {\r\n itemCtx = _self._getTelCtx(itemCtx);\r\n var diagLogger = itemCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\r\n try {\r\n // if master off switch is set, don't send any data\r\n if (_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_DISABLE_TELEMETRY /* @min:%2edisableTelemetry */]()) {\r\n // Do not send/save data\r\n return;\r\n }\r\n // validate input\r\n if (!telemetryItem) {\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 7 /* _eInternalMessageId.CannotSendEmptyTelemetry */, \"Cannot send empty telemetry\");\r\n return;\r\n }\r\n // validate event\r\n if (telemetryItem.baseData && !telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */]) {\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 70 /* _eInternalMessageId.InvalidEvent */, \"Cannot send telemetry without baseData and baseType\");\r\n return;\r\n }\r\n if (!telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */]) {\r\n // Default\r\n telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */] = \"EventData\";\r\n }\r\n // ensure a sender was constructed\r\n if (!_self[_DYN__SENDER /* @min:%2e_sender */]) {\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"Sender was not initialized\");\r\n return;\r\n }\r\n // check if this item should be sampled in, else add sampleRate tag\r\n if (!_isSampledIn(telemetryItem)) {\r\n // Item is sampled out, do not send it\r\n _throwInternal(diagLogger, 2 /* eLoggingSeverity.WARNING */, 33 /* _eInternalMessageId.TelemetrySampledAndNotSent */, \"Telemetry item was sampled out and not sent\", { SampleRate: _self._sample[_DYN_SAMPLE_RATE /* @min:%2esampleRate */] });\r\n return;\r\n }\r\n else {\r\n telemetryItem[SampleRate] = _self._sample[_DYN_SAMPLE_RATE /* @min:%2esampleRate */];\r\n }\r\n var convertUndefined = _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_CONVERT_UNDEFINED /* @min:%2econvertUndefined */]() || undefined;\r\n // construct an envelope that Application Insights endpoint can understand\r\n // if ikey of telemetry is provided and not empty, envelope will use this iKey instead of senderConfig iKey\r\n var defaultEnvelopeIkey = telemetryItem.iKey || _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */]();\r\n var aiEnvelope_1 = Sender.constructEnvelope(telemetryItem, defaultEnvelopeIkey, diagLogger, convertUndefined);\r\n if (!aiEnvelope_1) {\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 47 /* _eInternalMessageId.CreateEnvelopeError */, \"Unable to create an AppInsights envelope\");\r\n return;\r\n }\r\n var doNotSendItem_1 = false;\r\n // this is for running in legacy mode, where customer may already have a custom initializer present\r\n if (telemetryItem[_DYN_TAGS /* @min:%2etags */] && telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy]) {\r\n arrForEach(telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy], function (callBack) {\r\n try {\r\n if (callBack && callBack(aiEnvelope_1) === false) {\r\n doNotSendItem_1 = true;\r\n _warnToConsole(diagLogger, \"Telemetry processor check returns false\");\r\n }\r\n }\r\n catch (e) {\r\n // log error but dont stop executing rest of the telemetry initializers\r\n // doNotSendItem = true;\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"One of telemetry initializers failed, telemetry item will not be sent: \" + getExceptionName(e), { exception: dumpObj(e) }, true);\r\n }\r\n });\r\n delete telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy];\r\n }\r\n if (doNotSendItem_1) {\r\n return; // do not send, no need to execute next plugin\r\n }\r\n // check if the incoming payload is too large, truncate if necessary\r\n var payload = _serializer.serialize(aiEnvelope_1);\r\n // flush if we would exceed the max-size limit by adding this item\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n var bufferSize = buffer.size();\r\n if ((bufferSize + payload[_DYN_LENGTH /* @min:%2elength */]) > _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_MAX_BATCH_SIZE_IN_BY1 /* @min:%2emaxBatchSizeInBytes */]()) {\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, null, 10 /* SendRequestReason.MaxBatchSize */);\r\n }\r\n // enqueue the payload\r\n buffer[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\r\n // ensure an invocation timeout is set\r\n _setupTimer();\r\n }\r\n catch (e) {\r\n _throwInternal(diagLogger, 2 /* eLoggingSeverity.WARNING */, 12 /* _eInternalMessageId.FailedAddingTelemetryToBuffer */, \"Failed adding telemetry to the sender's buffer, some telemetry will be lost: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n // hand off the telemetry item to the next plugin\r\n _self.processNext(telemetryItem, itemCtx);\r\n };\r\n /**\r\n * xhr state changes\r\n */\r\n _self[_DYN__XHR_READY_STATE_CHA6 /* @min:%2e_xhrReadyStateChange */] = function (xhr, payload, countOfItemsInPayload) {\r\n if (xhr.readyState === 4) {\r\n _checkResponsStatus(xhr.status, payload, xhr.responseURL, countOfItemsInPayload, _formatErrorMessageXhr(xhr), _getResponseText(xhr) || xhr.response);\r\n }\r\n };\r\n /**\r\n * Immediately send buffered data\r\n * @param async {boolean} - Indicates if the events should be sent asynchronously\r\n * @param forcedSender {SenderFunction} - Indicates the forcedSender, undefined if not passed\r\n */\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */] = function (async, forcedSender, sendReason) {\r\n if (async === void 0) { async = true; }\r\n if (!_paused) {\r\n try {\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n // Send data only if disableTelemetry is false\r\n if (!_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_DISABLE_TELEMETRY /* @min:%2edisableTelemetry */]()) {\r\n if (buffer[_DYN_COUNT /* @min:%2ecount */]() > 0) {\r\n var payload = buffer.getItems();\r\n _notifySendRequest(sendReason || 0 /* SendRequestReason.Undefined */, async);\r\n // invoke send\r\n if (forcedSender) {\r\n forcedSender.call(_this, payload, async);\r\n }\r\n else {\r\n _self[_DYN__SENDER /* @min:%2e_sender */](payload, async);\r\n }\r\n }\r\n // update lastSend time to enable throttling\r\n _lastSend = +new Date;\r\n }\r\n else {\r\n buffer[_DYN_CLEAR /* @min:%2eclear */]();\r\n }\r\n _clearScheduledTimer();\r\n }\r\n catch (e) {\r\n /* Ignore this error for IE under v10 */\r\n var ieVer = getIEVersion();\r\n if (!ieVer || ieVer > 9) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 40 /* _eInternalMessageId.TransmissionFailed */, \"Telemetry transmission failed, some telemetry will be lost: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n }\r\n };\r\n _self._doTeardown = function (unloadCtx, unloadState) {\r\n _self.onunloadFlush();\r\n _offlineListener.unload();\r\n _initDefaults();\r\n };\r\n /**\r\n * error handler\r\n */\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */] = function (payload, message, event) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 26 /* _eInternalMessageId.OnError */, \"Failed to send telemetry.\", { message: message });\r\n _self._buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\r\n };\r\n /**\r\n * partial success handler\r\n */\r\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */] = function (payload, results) {\r\n var failed = [];\r\n var retry = [];\r\n // Iterate through the reversed array of errors so that splicing doesn't have invalid indexes after the first item.\r\n var errors = results.errors.reverse();\r\n for (var _i = 0, errors_1 = errors; _i < errors_1.length; _i++) {\r\n var error = errors_1[_i];\r\n var extracted = payload.splice(error.index, 1)[0];\r\n if (_isRetriable(error.statusCode)) {\r\n retry[_DYN_PUSH /* @min:%2epush */](extracted);\r\n }\r\n else {\r\n // All other errors, including: 402 (Monthly quota exceeded) and 439 (Too many requests and refresh cache).\r\n failed[_DYN_PUSH /* @min:%2epush */](extracted);\r\n }\r\n }\r\n if (payload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */]);\r\n }\r\n if (failed[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](failed, _formatErrorMessageXhr(null, [\"partial success\", results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */], \"of\", results.itemsReceived].join(\" \")));\r\n }\r\n if (retry[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _resendPayload(retry);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \"Partial success. \" +\r\n \"Delivered: \" + payload[_DYN_LENGTH /* @min:%2elength */] + \", Failed: \" + failed[_DYN_LENGTH /* @min:%2elength */] +\r\n \". Will retry to send \" + retry[_DYN_LENGTH /* @min:%2elength */] + \" our of \" + results[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] + \" items\");\r\n }\r\n };\r\n /**\r\n * success handler\r\n */\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */] = function (payload, countOfItemsInPayload) {\r\n _self._buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\r\n };\r\n /**\r\n * xdr state changes\r\n */\r\n _self._xdrOnLoad = function (xdr, payload) {\r\n var responseText = _getResponseText(xdr);\r\n if (xdr && (responseText + \"\" === \"200\" || responseText === \"\")) {\r\n _consecutiveErrors = 0;\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, 0);\r\n }\r\n else {\r\n var results = _parseResponse(responseText);\r\n if (results && results.itemsReceived && results.itemsReceived > results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */]\r\n && !_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_IS_RETRY_DISABLED /* @min:%2eisRetryDisabled */]()) {\r\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */](payload, results);\r\n }\r\n else {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, _formatErrorMessageXdr(xdr));\r\n }\r\n }\r\n };\r\n function _isSampledIn(envelope) {\r\n return _self._sample.isSampledIn(envelope);\r\n }\r\n function _checkResponsStatus(status, payload, responseUrl, countOfItemsInPayload, errorMessage, res) {\r\n var response = null;\r\n if (!_self._appId) {\r\n response = _parseResponse(res);\r\n if (response && response.appId) {\r\n _self._appId = response.appId;\r\n }\r\n }\r\n if ((status < 200 || status >= 300) && status !== 0) {\r\n // Update End Point url if permanent redirect or moved permanently\r\n // Updates the end point url before retry\r\n if (status === 301 || status === 307 || status === 308) {\r\n if (!_checkAndUpdateEndPointUrl(responseUrl)) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\r\n return;\r\n }\r\n }\r\n if (!_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_IS_RETRY_DISABLED /* @min:%2eisRetryDisabled */]() && _isRetriable(status)) {\r\n _resendPayload(payload);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" +\r\n \"Response code \" + status + \". Will retry to send \" + payload[_DYN_LENGTH /* @min:%2elength */] + \" items.\");\r\n }\r\n else {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\r\n }\r\n }\r\n else if (_offlineListener && !_offlineListener.isOnline()) { // offline\r\n // Note: Don't check for status == 0, since adblock gives this code\r\n if (!_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_IS_RETRY_DISABLED /* @min:%2eisRetryDisabled */]()) {\r\n var offlineBackOffMultiplier = 10; // arbritrary number\r\n _resendPayload(payload, offlineBackOffMultiplier);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". Offline - Response Code: \".concat(status, \". Offline status: \").concat(!_offlineListener.isOnline(), \". Will retry to send \").concat(payload.length, \" items.\"));\r\n }\r\n }\r\n else {\r\n // check if the xhr's responseURL or fetch's response.url is same as endpoint url\r\n // TODO after 10 redirects force send telemetry with 'redirect=false' as query parameter.\r\n _checkAndUpdateEndPointUrl(responseUrl);\r\n if (status === 206) {\r\n if (!response) {\r\n response = _parseResponse(res);\r\n }\r\n if (response && !_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_IS_RETRY_DISABLED /* @min:%2eisRetryDisabled */]()) {\r\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */](payload, response);\r\n }\r\n else {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\r\n }\r\n }\r\n else {\r\n _consecutiveErrors = 0;\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, countOfItemsInPayload);\r\n }\r\n }\r\n }\r\n function _checkAndUpdateEndPointUrl(responseUrl) {\r\n // Maximum stamp specific redirects allowed(uncomment this when breeze is ready with not allowing redirects feature)\r\n if (_stamp_specific_redirects >= 10) {\r\n // _self._senderConfig.endpointUrl = () => Sender._getDefaultAppInsightsChannelConfig().endpointUrl()+\"/?redirect=false\";\r\n // _stamp_specific_redirects = 0;\r\n return false;\r\n }\r\n if (!isNullOrUndefined(responseUrl) && responseUrl !== \"\") {\r\n if (responseUrl !== _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */]()) {\r\n _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */] = function () { return responseUrl; };\r\n ++_stamp_specific_redirects;\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n function _doUnloadSend(payload, isAsync) {\r\n if (_syncUnloadSender) {\r\n // We are unloading so always call the sender with sync set to false\r\n _syncUnloadSender(payload, false);\r\n }\r\n else {\r\n // Fallback to the previous beacon Sender (which causes a CORB warning on chrome now)\r\n _beaconSender(payload, isAsync);\r\n }\r\n }\r\n function _doBeaconSend(payload) {\r\n var nav = getNavigator();\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n var url = _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */]();\r\n var batch = _self._buffer[_DYN_BATCH_PAYLOADS /* @min:%2ebatchPayloads */](payload);\r\n // Chrome only allows CORS-safelisted values for the sendBeacon data argument\r\n // see: https://bugs.chromium.org/p/chromium/issues/detail?id=720283\r\n var plainTextBatch = new Blob([batch], { type: \"text/plain;charset=UTF-8\" });\r\n // The sendBeacon method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.\r\n var queued = nav.sendBeacon(url, plainTextBatch);\r\n if (queued) {\r\n buffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](payload);\r\n // no response from beaconSender, clear buffer\r\n _self._onSuccess(payload, payload[_DYN_LENGTH /* @min:%2elength */]);\r\n }\r\n return queued;\r\n }\r\n /**\r\n * Send Beacon API request\r\n * @param payload {string} - The data payload to be sent.\r\n * @param isAsync {boolean} - not used\r\n * Note: Beacon API does not support custom headers and we are not able to get\r\n * appId from the backend for the correct correlation.\r\n */\r\n function _beaconSender(payload, isAsync) {\r\n if (isArray(payload) && payload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n // The sendBeacon method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.\r\n if (!_doBeaconSend(payload)) {\r\n // Failed to send entire payload so try and split data and try to send as much events as possible\r\n var droppedPayload = [];\r\n for (var lp = 0; lp < payload[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n var thePayload = payload[lp];\r\n if (!_doBeaconSend([thePayload])) {\r\n // Can't send anymore, so split the batch and drop the rest\r\n droppedPayload[_DYN_PUSH /* @min:%2epush */](thePayload);\r\n }\r\n }\r\n if (droppedPayload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _fallbackSender && _fallbackSender(droppedPayload, true);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with normal sender.\");\r\n }\r\n }\r\n }\r\n }\r\n /**\r\n * Send XMLHttpRequest\r\n * @param payload {string} - The data payload to be sent.\r\n * @param isAsync {boolean} - Indicates if the request should be sent asynchronously\r\n */\r\n function _xhrSender(payload, isAsync) {\r\n var xhr = new XMLHttpRequest();\r\n var endPointUrl = _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */]();\r\n try {\r\n xhr[DisabledPropertyName] = true;\r\n }\r\n catch (e) {\r\n // If the environment has locked down the XMLHttpRequest (preventExtensions and/or freeze), this would\r\n // cause the request to fail and we no telemetry would be sent\r\n }\r\n xhr.open(\"POST\", endPointUrl, isAsync);\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](\"Content-type\", \"application/json\");\r\n // append Sdk-Context request header only in case of breeze endpoint\r\n if (isInternalApplicationInsightsEndpoint(endPointUrl)) {\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[6 /* eRequestHeaders.sdkContextHeader */], RequestHeaders[7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */]);\r\n }\r\n arrForEach(objKeys(_headers), function (headerName) {\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](headerName, _headers[headerName]);\r\n });\r\n xhr.onreadystatechange = function () { return _self._xhrReadyStateChange(xhr, payload, payload[_DYN_LENGTH /* @min:%2elength */]); };\r\n xhr.onerror = function (event) { return _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, _formatErrorMessageXhr(xhr), event); };\r\n // compose an array of payloads\r\n var batch = _self._buffer[_DYN_BATCH_PAYLOADS /* @min:%2ebatchPayloads */](payload);\r\n xhr.send(batch);\r\n _self._buffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](payload);\r\n }\r\n function _fetchKeepAliveSender(payload, isAsync) {\r\n if (isArray(payload)) {\r\n var payloadSize = payload[_DYN_LENGTH /* @min:%2elength */];\r\n for (var lp = 0; lp < payload[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n payloadSize += payload[lp][_DYN_LENGTH /* @min:%2elength */];\r\n }\r\n if ((_syncFetchPayload + payloadSize) <= FetchSyncRequestSizeLimitBytes) {\r\n _doFetchSender(payload, false);\r\n }\r\n else if (isBeaconsSupported()) {\r\n // Fallback to beacon sender as we at least get told which events can't be scheduled\r\n _beaconSender(payload, isAsync);\r\n }\r\n else {\r\n // Payload is going to be too big so just try and send via XHR\r\n _fallbackSender && _fallbackSender(payload, true);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with xhrSender.\");\r\n }\r\n }\r\n }\r\n /**\r\n * Send fetch API request\r\n * @param payload {string} - The data payload to be sent.\r\n * @param isAsync {boolean} - not used\r\n */\r\n function _fetchSender(payload, isAsync) {\r\n _doFetchSender(payload, true);\r\n }\r\n /**\r\n * Send fetch API request\r\n * @param payload {string} - The data payload to be sent.\r\n * @param isAsync {boolean} - For fetch this identifies whether we are \"unloading\" (false) or a normal request\r\n */\r\n function _doFetchSender(payload, isAsync) {\r\n var _a;\r\n var endPointUrl = _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */]();\r\n var batch = _self._buffer[_DYN_BATCH_PAYLOADS /* @min:%2ebatchPayloads */](payload);\r\n var plainTextBatch = new Blob([batch], { type: \"application/json\" });\r\n var requestHeaders = new Headers();\r\n var batchLength = batch[_DYN_LENGTH /* @min:%2elength */];\r\n var ignoreResponse = false;\r\n var responseHandled = false;\r\n // append Sdk-Context request header only in case of breeze endpoint\r\n if (isInternalApplicationInsightsEndpoint(endPointUrl)) {\r\n requestHeaders.append(RequestHeaders[6 /* eRequestHeaders.sdkContextHeader */], RequestHeaders[7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */]);\r\n }\r\n arrForEach(objKeys(_headers), function (headerName) {\r\n requestHeaders.append(headerName, _headers[headerName]);\r\n });\r\n var init = (_a = {\r\n method: \"POST\",\r\n headers: requestHeaders,\r\n body: plainTextBatch\r\n },\r\n _a[DisabledPropertyName] = true // Mark so we don't attempt to track this request\r\n ,\r\n _a);\r\n if (!isAsync) {\r\n init.keepalive = true;\r\n // As a sync request (during unload), it is unlikely that we will get a chance to process the response so\r\n // just like beacon send assume that the events have been accepted and processed\r\n ignoreResponse = true;\r\n _syncFetchPayload += batchLength;\r\n }\r\n var request = new Request(endPointUrl, init);\r\n try {\r\n // Also try and tag the request (just in case the value in init is not copied over)\r\n request[DisabledPropertyName] = true;\r\n }\r\n catch (e) {\r\n // If the environment has locked down the XMLHttpRequest (preventExtensions and/or freeze), this would\r\n // cause the request to fail and we no telemetry would be sent\r\n }\r\n _self._buffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](payload);\r\n try {\r\n fetch(request).then(function (response) {\r\n if (!isAsync) {\r\n _syncFetchPayload -= batchLength;\r\n batchLength = 0;\r\n }\r\n if (!responseHandled) {\r\n responseHandled = true;\r\n /**\r\n * The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500.\r\n * Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure\r\n * or if anything prevented the request from completing.\r\n */\r\n if (!response.ok) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, response.statusText);\r\n }\r\n else {\r\n response.text().then(function (text) {\r\n _checkResponsStatus(response.status, payload, response.url, payload[_DYN_LENGTH /* @min:%2elength */], response.statusText, text);\r\n });\r\n }\r\n }\r\n })[\"catch\"](function (error) {\r\n if (!isAsync) {\r\n _syncFetchPayload -= batchLength;\r\n batchLength = 0;\r\n }\r\n if (!responseHandled) {\r\n responseHandled = true;\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, error.message);\r\n }\r\n });\r\n }\r\n catch (e) {\r\n if (!responseHandled) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, dumpObj(e));\r\n }\r\n }\r\n if (ignoreResponse && !responseHandled) {\r\n // Assume success during unload processing as we most likely won't get the response\r\n responseHandled = true;\r\n _self._onSuccess(payload, payload[_DYN_LENGTH /* @min:%2elength */]);\r\n }\r\n }\r\n /**\r\n * Parses the response from the backend.\r\n * @param response - XMLHttpRequest or XDomainRequest response\r\n */\r\n function _parseResponse(response) {\r\n try {\r\n if (response && response !== \"\") {\r\n var result = getJSON().parse(response);\r\n if (result && result.itemsReceived && result.itemsReceived >= result[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */] &&\r\n result.itemsReceived - result.itemsAccepted === result.errors[_DYN_LENGTH /* @min:%2elength */]) {\r\n return result;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 43 /* _eInternalMessageId.InvalidBackendResponse */, \"Cannot parse the response. \" + getExceptionName(e), {\r\n response: response\r\n });\r\n }\r\n return null;\r\n }\r\n /**\r\n * Resend payload. Adds payload back to the send buffer and setup a send timer (with exponential backoff).\r\n * @param payload\r\n */\r\n function _resendPayload(payload, linearFactor) {\r\n if (linearFactor === void 0) { linearFactor = 1; }\r\n if (!payload || payload[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n return;\r\n }\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\r\n _consecutiveErrors++;\r\n for (var _i = 0, payload_1 = payload; _i < payload_1.length; _i++) {\r\n var item = payload_1[_i];\r\n buffer[_DYN_ENQUEUE /* @min:%2eenqueue */](item);\r\n }\r\n // setup timer\r\n _setRetryTime(linearFactor);\r\n _setupTimer();\r\n }\r\n /**\r\n * Calculates the time to wait before retrying in case of an error based on\r\n * http://en.wikipedia.org/wiki/Exponential_backoff\r\n */\r\n function _setRetryTime(linearFactor) {\r\n var SlotDelayInSeconds = 10;\r\n var delayInSeconds;\r\n if (_consecutiveErrors <= 1) {\r\n delayInSeconds = SlotDelayInSeconds;\r\n }\r\n else {\r\n var backOffSlot = (Math.pow(2, _consecutiveErrors) - 1) / 2;\r\n // tslint:disable-next-line:insecure-random\r\n var backOffDelay = Math.floor(Math.random() * backOffSlot * SlotDelayInSeconds) + 1;\r\n backOffDelay = linearFactor * backOffDelay;\r\n delayInSeconds = Math.max(Math.min(backOffDelay, 3600), SlotDelayInSeconds);\r\n }\r\n // TODO: Log the backoff time like the C# version does.\r\n var retryAfterTimeSpan = dateNow() + (delayInSeconds * 1000);\r\n // TODO: Log the retry at time like the C# version does.\r\n _retryAt = retryAfterTimeSpan;\r\n }\r\n /**\r\n * Sets up the timer which triggers actually sending the data.\r\n */\r\n function _setupTimer() {\r\n if (!_timeoutHandle && !_paused) {\r\n var retryInterval = _retryAt ? Math.max(0, _retryAt - dateNow()) : 0;\r\n var timerValue = Math.max(_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_MAX_BATCH_INTERVAL /* @min:%2emaxBatchInterval */](), retryInterval);\r\n _timeoutHandle = setTimeout(function () {\r\n _timeoutHandle = null;\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, null, 1 /* SendRequestReason.NormalSchedule */);\r\n }, timerValue);\r\n }\r\n }\r\n function _clearScheduledTimer() {\r\n clearTimeout(_timeoutHandle);\r\n _timeoutHandle = null;\r\n _retryAt = null;\r\n }\r\n /**\r\n * Checks if the SDK should resend the payload after receiving this status code from the backend.\r\n * @param statusCode\r\n */\r\n function _isRetriable(statusCode) {\r\n return statusCode === 401 // Unauthorized\r\n || statusCode === 403 // Forbidden\r\n || statusCode === 408 // Timeout\r\n || statusCode === 429 // Too many requests.\r\n || statusCode === 500 // Internal server error.\r\n || statusCode === 502 // Bad Gateway.\r\n || statusCode === 503 // Service unavailable.\r\n || statusCode === 504; // Gateway timeout.\r\n }\r\n function _formatErrorMessageXhr(xhr, message) {\r\n if (xhr) {\r\n return \"XMLHttpRequest,Status:\" + xhr.status + \",Response:\" + _getResponseText(xhr) || xhr.response || \"\";\r\n }\r\n return message;\r\n }\r\n /**\r\n * Send XDomainRequest\r\n * @param payload {string} - The data payload to be sent.\r\n * @param isAsync {boolean} - Indicates if the request should be sent asynchronously\r\n *\r\n * Note: XDomainRequest does not support sync requests. This 'isAsync' parameter is added\r\n * to maintain consistency with the xhrSender's contract\r\n * Note: XDomainRequest does not support custom headers and we are not able to get\r\n * appId from the backend for the correct correlation.\r\n */\r\n function _xdrSender(payload, isAsync) {\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n var _window = getWindow();\r\n var xdr = new XDomainRequest();\r\n xdr.onload = function () { return _self._xdrOnLoad(xdr, payload); };\r\n xdr.onerror = function (event) { return _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, _formatErrorMessageXdr(xdr), event); };\r\n // XDomainRequest requires the same protocol as the hosting page.\r\n // If the protocol doesn't match, we can't send the telemetry :(.\r\n var hostingProtocol = _window && _window.location && _window.location.protocol || \"\";\r\n if (_self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */]().lastIndexOf(hostingProtocol, 0) !== 0) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" +\r\n \"Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.\");\r\n buffer[_DYN_CLEAR /* @min:%2eclear */]();\r\n return;\r\n }\r\n var endpointUrl = _self[_DYN__SENDER_CONFIG /* @min:%2e_senderConfig */][_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */]().replace(/^(https?:)/, \"\");\r\n xdr.open(\"POST\", endpointUrl);\r\n // compose an array of payloads\r\n var batch = buffer[_DYN_BATCH_PAYLOADS /* @min:%2ebatchPayloads */](payload);\r\n xdr.send(batch);\r\n buffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](payload);\r\n }\r\n function _formatErrorMessageXdr(xdr, message) {\r\n if (xdr) {\r\n return \"XDomainRequest,Response:\" + _getResponseText(xdr) || \"\";\r\n }\r\n return message;\r\n }\r\n // Using function lookups for backward compatibility as the getNotifyMgr() did not exist until after v2.5.6\r\n function _getNotifyMgr() {\r\n var func = \"getNotifyMgr\";\r\n if (_self.core[func]) {\r\n return _self.core[func]();\r\n }\r\n // using _self.core['_notificationManager'] for backward compatibility\r\n return _self.core[\"_notificationManager\"];\r\n }\r\n function _notifySendRequest(sendRequest, isAsync) {\r\n var manager = _getNotifyMgr();\r\n if (manager && manager[_DYN_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */]) {\r\n try {\r\n manager[_DYN_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */](sendRequest, isAsync);\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 74 /* _eInternalMessageId.NotificationException */, \"send request notification failed: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n }\r\n /**\r\n * Validate UUID Format\r\n * Specs taken from https://tools.ietf.org/html/rfc4122 and breeze repo\r\n */\r\n function _validateInstrumentationKey(config) {\r\n var disableIKeyValidationFlag = isNullOrUndefined(config[_DYN_DISABLE_INSTRUMENTAT7 /* @min:%2edisableInstrumentationKeyValidation */]) ? false : config[_DYN_DISABLE_INSTRUMENTAT7 /* @min:%2edisableInstrumentationKeyValidation */];\r\n if (disableIKeyValidationFlag) {\r\n return true;\r\n }\r\n var UUID_Regex = \"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\";\r\n var regexp = new RegExp(UUID_Regex);\r\n return regexp.test(config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */]);\r\n }\r\n function _initDefaults() {\r\n _self[_DYN__SENDER /* @min:%2e_sender */] = null;\r\n _self[_DYN__BUFFER /* @min:%2e_buffer */] = null;\r\n _self._appId = null;\r\n _self._sample = null;\r\n _headers = {};\r\n _offlineListener = null;\r\n _consecutiveErrors = 0;\r\n _retryAt = null;\r\n _lastSend = null;\r\n _paused = false;\r\n _timeoutHandle = null;\r\n _serializer = null;\r\n _stamp_specific_redirects = 0;\r\n _syncFetchPayload = 0;\r\n _fallbackSender = null;\r\n _syncUnloadSender = null;\r\n _evtNamespace = null;\r\n }\r\n });\r\n return _this;\r\n }\r\n Sender.constructEnvelope = function (orig, iKey, logger, convertUndefined) {\r\n var envelope;\r\n if (iKey !== orig.iKey && !isNullOrUndefined(iKey)) {\r\n envelope = __assign(__assign({}, orig), { iKey: iKey });\r\n }\r\n else {\r\n envelope = orig;\r\n }\r\n var creator = EnvelopeTypeCreator[envelope.baseType] || EventEnvelopeCreator;\r\n return creator(logger, envelope, convertUndefined);\r\n };\r\n// Removed Stub for Sender.prototype.pause.\r\n// Removed Stub for Sender.prototype.resume.\r\n// Removed Stub for Sender.prototype.flush.\r\n// Removed Stub for Sender.prototype.onunloadFlush.\r\n// Removed Stub for Sender.prototype.initialize.\r\n// Removed Stub for Sender.prototype.processTelemetry.\r\n// Removed Stub for Sender.prototype._xhrReadyStateChange.\r\n// Removed Stub for Sender.prototype.triggerSend.\r\n// Removed Stub for Sender.prototype._onError.\r\n// Removed Stub for Sender.prototype._onPartialSuccess.\r\n// Removed Stub for Sender.prototype._onSuccess.\r\n// Removed Stub for Sender.prototype._xdrOnLoad.\r\n// Removed Stub for Sender.prototype.addHeader.\r\n return Sender;\r\n}(BaseTelemetryPlugin));\r\nexport { Sender };\r\n","/*\n * Application Insights JavaScript SDK - Channel, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { _throwInternal, getJSON, isArray, isFunction, isObject, objForEachKey } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_LENGTH, _DYN_PUSH, _DYN_STRINGIFY, _DYN_TO_STRING } from \"./__DynamicConstants\";\r\nvar Serializer = /** @class */ (function () {\r\n function Serializer(logger) {\r\n dynamicProto(Serializer, this, function (_self) {\r\n /**\r\n * Serializes the current object to a JSON string.\r\n */\r\n _self.serialize = function (input) {\r\n var output = _serializeObject(input, \"root\");\r\n try {\r\n return getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](output);\r\n }\r\n catch (e) {\r\n // if serialization fails return an empty string\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.CannotSerializeObject */, (e && isFunction(e[_DYN_TO_STRING /* @min:%2etoString */])) ? e[_DYN_TO_STRING /* @min:%2etoString */]() : \"Error serializing object\", null, true);\r\n }\r\n };\r\n function _serializeObject(source, name) {\r\n var circularReferenceCheck = \"__aiCircularRefCheck\";\r\n var output = {};\r\n if (!source) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.CannotSerializeObject */, \"cannot serialize object because it is null or undefined\", { name: name }, true);\r\n return output;\r\n }\r\n if (source[circularReferenceCheck]) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 50 /* _eInternalMessageId.CircularReferenceDetected */, \"Circular reference detected while serializing object\", { name: name }, true);\r\n return output;\r\n }\r\n if (!source.aiDataContract) {\r\n // special case for measurements/properties/tags\r\n if (name === \"measurements\") {\r\n output = _serializeStringMap(source, \"number\", name);\r\n }\r\n else if (name === \"properties\") {\r\n output = _serializeStringMap(source, \"string\", name);\r\n }\r\n else if (name === \"tags\") {\r\n output = _serializeStringMap(source, \"string\", name);\r\n }\r\n else if (isArray(source)) {\r\n output = _serializeArray(source, name);\r\n }\r\n else {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 49 /* _eInternalMessageId.CannotSerializeObjectNonSerializable */, \"Attempting to serialize an object which does not implement ISerializable\", { name: name }, true);\r\n try {\r\n // verify that the object can be stringified\r\n getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](source);\r\n output = source;\r\n }\r\n catch (e) {\r\n // if serialization fails return an empty string\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.CannotSerializeObject */, (e && isFunction(e[_DYN_TO_STRING /* @min:%2etoString */])) ? e[_DYN_TO_STRING /* @min:%2etoString */]() : \"Error serializing object\", null, true);\r\n }\r\n }\r\n return output;\r\n }\r\n source[circularReferenceCheck] = true;\r\n objForEachKey(source.aiDataContract, function (field, contract) {\r\n var isRequired = (isFunction(contract)) ? (contract() & 1 /* FieldType.Required */) : (contract & 1 /* FieldType.Required */);\r\n var isHidden = (isFunction(contract)) ? (contract() & 4 /* FieldType.Hidden */) : (contract & 4 /* FieldType.Hidden */);\r\n var isArray = contract & 2 /* FieldType.Array */;\r\n var isPresent = source[field] !== undefined;\r\n var isObj = isObject(source[field]) && source[field] !== null;\r\n if (isRequired && !isPresent && !isArray) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 24 /* _eInternalMessageId.MissingRequiredFieldSpecification */, \"Missing required field specification. The field is required but not present on source\", { field: field, name: name });\r\n // If not in debug mode, continue and hope the error is permissible\r\n }\r\n else if (!isHidden) { // Don't serialize hidden fields\r\n var value = void 0;\r\n if (isObj) {\r\n if (isArray) {\r\n // special case; recurse on each object in the source array\r\n value = _serializeArray(source[field], field);\r\n }\r\n else {\r\n // recurse on the source object in this field\r\n value = _serializeObject(source[field], field);\r\n }\r\n }\r\n else {\r\n // assign the source field to the output even if undefined or required\r\n value = source[field];\r\n }\r\n // only emit this field if the value is defined\r\n if (value !== undefined) {\r\n output[field] = value;\r\n }\r\n }\r\n });\r\n delete source[circularReferenceCheck];\r\n return output;\r\n }\r\n function _serializeArray(sources, name) {\r\n var output;\r\n if (!!sources) {\r\n if (!isArray(sources)) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 54 /* _eInternalMessageId.ItemNotInArray */, \"This field was specified as an array in the contract but the item is not an array.\\r\\n\", { name: name }, true);\r\n }\r\n else {\r\n output = [];\r\n for (var i = 0; i < sources[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n var source = sources[i];\r\n var item = _serializeObject(source, name + \"[\" + i + \"]\");\r\n output[_DYN_PUSH /* @min:%2epush */](item);\r\n }\r\n }\r\n }\r\n return output;\r\n }\r\n function _serializeStringMap(map, expectedType, name) {\r\n var output;\r\n if (map) {\r\n output = {};\r\n objForEachKey(map, function (field, value) {\r\n if (expectedType === \"string\") {\r\n if (value === undefined) {\r\n output[field] = \"undefined\";\r\n }\r\n else if (value === null) {\r\n output[field] = \"null\";\r\n }\r\n else if (!value[_DYN_TO_STRING /* @min:%2etoString */]) {\r\n output[field] = \"invalid field: toString() is not defined.\";\r\n }\r\n else {\r\n output[field] = value[_DYN_TO_STRING /* @min:%2etoString */]();\r\n }\r\n }\r\n else if (expectedType === \"number\") {\r\n if (value === undefined) {\r\n output[field] = \"undefined\";\r\n }\r\n else if (value === null) {\r\n output[field] = \"null\";\r\n }\r\n else {\r\n var num = parseFloat(value);\r\n if (isNaN(num)) {\r\n output[field] = \"NaN\";\r\n }\r\n else {\r\n output[field] = num;\r\n }\r\n }\r\n }\r\n else {\r\n output[field] = \"invalid field: \" + name + \" is of unknown type.\";\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, output[field], null, true);\r\n }\r\n });\r\n }\r\n return output;\r\n }\r\n });\r\n }\r\n// Removed Stub for Serializer.prototype.serialize.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n Serializer.__ieDyn=1;\n\n return Serializer;\r\n}());\r\nexport { Serializer };\r\n","/*\n * Application Insights JavaScript SDK - Channel, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { Metric } from \"@microsoft/applicationinsights-common\";\r\nimport { safeGetLogger } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_DATA_TYPE, _DYN_GET_SAMPLING_SCORE, _DYN_SAMPLE_RATE } from \"../__DynamicConstants\";\r\nimport { SamplingScoreGenerator } from \"./SamplingScoreGenerators/SamplingScoreGenerator\";\r\nvar Sample = /** @class */ (function () {\r\n function Sample(sampleRate, logger) {\r\n // We're using 32 bit math, hence max value is (2^31 - 1)\r\n this.INT_MAX_VALUE = 2147483647;\r\n var _logger = logger || safeGetLogger(null);\r\n if (sampleRate > 100 || sampleRate < 0) {\r\n _logger.throwInternal(2 /* eLoggingSeverity.WARNING */, 58 /* _eInternalMessageId.SampleRateOutOfRange */, \"Sampling rate is out of range (0..100). Sampling will be disabled, you may be sending too much data which may affect your AI service level.\", { samplingRate: sampleRate }, true);\r\n sampleRate = 100;\r\n }\r\n this[_DYN_SAMPLE_RATE /* @min:%2esampleRate */] = sampleRate;\r\n this.samplingScoreGenerator = new SamplingScoreGenerator();\r\n }\r\n /**\r\n * Determines if an envelope is sampled in (i.e. will be sent) or not (i.e. will be dropped).\r\n */\r\n Sample.prototype.isSampledIn = function (envelope) {\r\n var samplingPercentage = this[_DYN_SAMPLE_RATE /* @min:%2esampleRate */]; // 0 - 100\r\n var isSampledIn = false;\r\n if (samplingPercentage === null || samplingPercentage === undefined || samplingPercentage >= 100) {\r\n return true;\r\n }\r\n else if (envelope.baseType === Metric[_DYN_DATA_TYPE /* @min:%2edataType */]) {\r\n // exclude MetricData telemetry from sampling\r\n return true;\r\n }\r\n isSampledIn = this.samplingScoreGenerator[_DYN_GET_SAMPLING_SCORE /* @min:%2egetSamplingScore */](envelope) < samplingPercentage;\r\n return isSampledIn;\r\n };\r\n return Sample;\r\n}());\r\nexport { Sample };\r\n","/*\n * Application Insights JavaScript SDK - Channel, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { _DYN_LENGTH } from \"../../__DynamicConstants\";\r\n// (Magic number) DJB algorithm can't work on shorter strings (results in poor distribution\r\nvar MIN_INPUT_LENGTH = 8;\r\nvar HashCodeScoreGenerator = /** @class */ (function () {\r\n function HashCodeScoreGenerator() {\r\n }\r\n HashCodeScoreGenerator.prototype.getHashCodeScore = function (key) {\r\n var score = this.getHashCode(key) / HashCodeScoreGenerator.INT_MAX_VALUE;\r\n return score * 100;\r\n };\r\n HashCodeScoreGenerator.prototype.getHashCode = function (input) {\r\n if (input === \"\") {\r\n return 0;\r\n }\r\n while (input[_DYN_LENGTH /* @min:%2elength */] < MIN_INPUT_LENGTH) {\r\n input = input.concat(input);\r\n }\r\n // 5381 is a magic number: http://stackoverflow.com/questions/10696223/reason-for-5381-number-in-djb-hash-function\r\n var hash = 5381;\r\n for (var i = 0; i < input[_DYN_LENGTH /* @min:%2elength */]; ++i) {\r\n hash = ((hash << 5) + hash) + input.charCodeAt(i);\r\n // 'hash' is of number type which means 53 bit integer (http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types-number-type)\r\n // 'hash & hash' will keep it 32 bit integer - just to make it clearer what the result is.\r\n hash = hash & hash;\r\n }\r\n return Math.abs(hash);\r\n };\r\n // We're using 32 bit math, hence max value is (2^31 - 1)\r\n HashCodeScoreGenerator.INT_MAX_VALUE = 2147483647;\r\n return HashCodeScoreGenerator;\r\n}());\r\nexport { HashCodeScoreGenerator };\r\n","/*\n * Application Insights JavaScript SDK - Channel, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { ContextTagKeys } from \"@microsoft/applicationinsights-common\";\r\nimport { _DYN_GET_HASH_CODE_SCORE, _DYN_GET_SAMPLING_SCORE, _DYN_TAGS, _DYN_TRACE_ID } from \"../../__DynamicConstants\";\r\nimport { HashCodeScoreGenerator } from \"./HashCodeScoreGenerator\";\r\nvar SamplingScoreGenerator = /** @class */ (function () {\r\n function SamplingScoreGenerator() {\r\n var _self = this;\r\n var hashCodeGenerator = new HashCodeScoreGenerator();\r\n var keys = new ContextTagKeys();\r\n _self[_DYN_GET_SAMPLING_SCORE /* @min:%2egetSamplingScore */] = function (item) {\r\n var score = 0;\r\n if (item[_DYN_TAGS /* @min:%2etags */] && item[_DYN_TAGS /* @min:%2etags */][keys.userId]) { // search in tags first, then ext\r\n score = hashCodeGenerator.getHashCodeScore(item[_DYN_TAGS /* @min:%2etags */][keys.userId]);\r\n }\r\n else if (item.ext && item.ext.user && item.ext.user.id) {\r\n score = hashCodeGenerator[_DYN_GET_HASH_CODE_SCORE /* @min:%2egetHashCodeScore */](item.ext.user.id);\r\n }\r\n else if (item[_DYN_TAGS /* @min:%2etags */] && item[_DYN_TAGS /* @min:%2etags */][keys.operationId]) { // search in tags first, then ext\r\n score = hashCodeGenerator.getHashCodeScore(item[_DYN_TAGS /* @min:%2etags */][keys.operationId]);\r\n }\r\n else if (item.ext && item.ext.telemetryTrace && item.ext.telemetryTrace[_DYN_TRACE_ID /* @min:%2etraceID */]) {\r\n score = hashCodeGenerator.getHashCodeScore(item.ext.telemetryTrace[_DYN_TRACE_ID /* @min:%2etraceID */]);\r\n }\r\n else {\r\n // tslint:disable-next-line:insecure-random\r\n score = (Math.random() * 100);\r\n }\r\n return score;\r\n };\r\n }\r\n return SamplingScoreGenerator;\r\n}());\r\nexport { SamplingScoreGenerator };\r\n","/*\n * Application Insights JavaScript SDK - Channel, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_TAGS = \"tags\"; // Count: 17\r\nexport var _DYN_DEVICE_TYPE = \"deviceType\"; // Count: 3\r\nexport var _DYN_DATA = \"data\"; // Count: 13\r\nexport var _DYN_NAME = \"name\"; // Count: 8\r\nexport var _DYN_TRACE_ID = \"traceID\"; // Count: 5\r\nexport var _DYN_LENGTH = \"length\"; // Count: 36\r\nexport var _DYN_STRINGIFY = \"stringify\"; // Count: 5\r\nexport var _DYN_MEASUREMENTS = \"measurements\"; // Count: 7\r\nexport var _DYN_DATA_TYPE = \"dataType\"; // Count: 10\r\nexport var _DYN_ENVELOPE_TYPE = \"envelopeType\"; // Count: 7\r\nexport var _DYN_TO_STRING = \"toString\"; // Count: 7\r\nexport var _DYN_ON_LINE = \"onLine\"; // Count: 4\r\nexport var _DYN_ENQUEUE = \"enqueue\"; // Count: 5\r\nexport var _DYN_COUNT = \"count\"; // Count: 6\r\nexport var _DYN_PUSH = \"push\"; // Count: 6\r\nexport var _DYN_EMIT_LINE_DELIMITED_0 = \"emitLineDelimitedJson\"; // Count: 3\r\nexport var _DYN_CLEAR = \"clear\"; // Count: 6\r\nexport var _DYN_BATCH_PAYLOADS = \"batchPayloads\"; // Count: 5\r\nexport var _DYN_MARK_AS_SENT = \"markAsSent\"; // Count: 6\r\nexport var _DYN_CLEAR_SENT = \"clearSent\"; // Count: 5\r\nexport var _DYN__BUFFER__KEY = \"BUFFER_KEY\"; // Count: 5\r\nexport var _DYN__SENT__BUFFER__KEY = \"SENT_BUFFER_KEY\"; // Count: 7\r\nexport var _DYN__MAX__BUFFER__SIZE = \"MAX_BUFFER_SIZE\"; // Count: 5\r\nexport var _DYN_NAME_PREFIX = \"namePrefix\"; // Count: 6\r\nexport var _DYN_MAX_BATCH_SIZE_IN_BY1 = \"maxBatchSizeInBytes\"; // Count: 3\r\nexport var _DYN_TRIGGER_SEND = \"triggerSend\"; // Count: 6\r\nexport var _DYN_DIAG_LOG = \"diagLog\"; // Count: 15\r\nexport var _DYN_ONUNLOAD_DISABLE_BEA2 = \"onunloadDisableBeacon\"; // Count: 2\r\nexport var _DYN_IS_BEACON_API_DISABL3 = \"isBeaconApiDisabled\"; // Count: 3\r\nexport var _DYN__SENDER = \"_sender\"; // Count: 5\r\nexport var _DYN__SENDER_CONFIG = \"_senderConfig\"; // Count: 4\r\nexport var _DYN__BUFFER = \"_buffer\"; // Count: 7\r\nexport var _DYN_ENABLE_SESSION_STORA4 = \"enableSessionStorageBuffer\"; // Count: 2\r\nexport var _DYN_SAMPLING_PERCENTAGE = \"samplingPercentage\"; // Count: 2\r\nexport var _DYN_INSTRUMENTATION_KEY = \"instrumentationKey\"; // Count: 4\r\nexport var _DYN_ENDPOINT_URL = \"endpointUrl\"; // Count: 8\r\nexport var _DYN_CUSTOM_HEADERS = \"customHeaders\"; // Count: 4\r\nexport var _DYN_DISABLE_XHR = \"disableXhr\"; // Count: 5\r\nexport var _DYN_ONUNLOAD_DISABLE_FET5 = \"onunloadDisableFetch\"; // Count: 2\r\nexport var _DYN_DISABLE_TELEMETRY = \"disableTelemetry\"; // Count: 2\r\nexport var _DYN_BASE_TYPE = \"baseType\"; // Count: 4\r\nexport var _DYN_SAMPLE_RATE = \"sampleRate\"; // Count: 4\r\nexport var _DYN_CONVERT_UNDEFINED = \"convertUndefined\"; // Count: 2\r\nexport var _DYN__XHR_READY_STATE_CHA6 = \"_xhrReadyStateChange\"; // Count: 2\r\nexport var _DYN__ON_ERROR = \"_onError\"; // Count: 11\r\nexport var _DYN__ON_PARTIAL_SUCCESS = \"_onPartialSuccess\"; // Count: 3\r\nexport var _DYN__ON_SUCCESS = \"_onSuccess\"; // Count: 6\r\nexport var _DYN_ITEMS_ACCEPTED = \"itemsAccepted\"; // Count: 5\r\nexport var _DYN_ITEMS_RECEIVED = \"itemsReceived\"; // Count: 6\r\nexport var _DYN_IS_RETRY_DISABLED = \"isRetryDisabled\"; // Count: 5\r\nexport var _DYN_SET_REQUEST_HEADER = \"setRequestHeader\"; // Count: 3\r\nexport var _DYN_MAX_BATCH_INTERVAL = \"maxBatchInterval\"; // Count: 2\r\nexport var _DYN_EVENTS_SEND_REQUEST = \"eventsSendRequest\"; // Count: 2\r\nexport var _DYN_DISABLE_INSTRUMENTAT7 = \"disableInstrumentationKeyValidation\"; // Count: 2\r\nexport var _DYN_GET_SAMPLING_SCORE = \"getSamplingScore\"; // Count: 2\r\nexport var _DYN_GET_HASH_CODE_SCORE = \"getHashCodeScore\"; // Count: 4\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { arrReduce, objKeys } from \"@microsoft/applicationinsights-core-js\";\r\nimport { DEFAULT_BREEZE_ENDPOINT } from \"./Constants\";\r\nimport { _DYN_INGESTIONENDPOINT, _DYN_LENGTH, _DYN_SPLIT, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\r\nvar _FIELDS_SEPARATOR = \";\";\r\nvar _FIELD_KEY_VALUE_SEPARATOR = \"=\";\r\nexport function parseConnectionString(connectionString) {\r\n if (!connectionString) {\r\n return {};\r\n }\r\n var kvPairs = connectionString[_DYN_SPLIT /* @min:%2esplit */](_FIELDS_SEPARATOR);\r\n var result = arrReduce(kvPairs, function (fields, kv) {\r\n var kvParts = kv[_DYN_SPLIT /* @min:%2esplit */](_FIELD_KEY_VALUE_SEPARATOR);\r\n if (kvParts[_DYN_LENGTH /* @min:%2elength */] === 2) { // only save fields with valid formats\r\n var key = kvParts[0][_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n var value = kvParts[1];\r\n fields[key] = value;\r\n }\r\n return fields;\r\n }, {});\r\n if (objKeys(result)[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n // this is a valid connection string, so parse the results\r\n if (result.endpointsuffix) {\r\n // use endpoint suffix where overrides are not provided\r\n var locationPrefix = result.location ? result.location + \".\" : \"\";\r\n result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] = result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] || (\"https://\" + locationPrefix + \"dc.\" + result.endpointsuffix);\r\n }\r\n // apply the default endpoints\r\n result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] = result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] || DEFAULT_BREEZE_ENDPOINT;\r\n }\r\n return result;\r\n}\r\nexport var ConnectionStringParser = {\r\n parse: parseConnectionString\r\n};\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n/**\r\n * This is an internal property used to cause internal (reporting) requests to be ignored from reporting\r\n * additional telemetry, to handle polyfil implementations ALL urls used with a disabled request will\r\n * also be ignored for future requests even when this property is not provided.\r\n * Tagging as Ignore as this is an internal value and is not expected to be used outside of the SDK\r\n * @ignore\r\n */\r\nexport var DisabledPropertyName = \"Microsoft_ApplicationInsights_BypassAjaxInstrumentation\";\r\nexport var SampleRate = \"sampleRate\";\r\nexport var ProcessLegacy = \"ProcessLegacy\";\r\nexport var HttpMethod = \"http.method\";\r\nexport var DEFAULT_BREEZE_ENDPOINT = \"https://dc.services.visualstudio.com\";\r\nexport var DEFAULT_BREEZE_PATH = \"/v2/track\";\r\nexport var strNotSpecified = \"not_specified\";\r\nexport var strIkey = \"iKey\";\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { isFunction, getDocument } from \"@microsoft/applicationinsights-core-js\";\r\nexport function createDomEvent(eventName) {\r\n var event = null;\r\n if (isFunction(Event)) { // Use Event constructor when available\r\n event = new Event(eventName);\r\n }\r\n else { // Event has no constructor in IE\r\n var doc = getDocument();\r\n if (doc && doc.createEvent) {\r\n event = doc.createEvent(\"Event\");\r\n event.initEvent(eventName, true, true);\r\n }\r\n }\r\n return event;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { createEnumStyle } from \"@microsoft/applicationinsights-core-js\";\r\nexport var StorageType = createEnumStyle({\r\n LocalStorage: 0 /* eStorageType.LocalStorage */,\r\n SessionStorage: 1 /* eStorageType.SessionStorage */\r\n});\r\nexport var DistributedTracingModes = createEnumStyle({\r\n AI: 0 /* eDistributedTracingModes.AI */,\r\n AI_AND_W3C: 1 /* eDistributedTracingModes.AI_AND_W3C */,\r\n W3C: 2 /* eDistributedTracingModes.W3C */\r\n});\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { arrForEach, isString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_LENGTH, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\r\nvar strEmpty = \"\";\r\nexport function stringToBoolOrDefault(str, defaultValue) {\r\n if (defaultValue === void 0) { defaultValue = false; }\r\n if (str === undefined || str === null) {\r\n return defaultValue;\r\n }\r\n return str.toString()[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === \"true\";\r\n}\r\n/**\r\n * Convert ms to c# time span format\r\n */\r\nexport function msToTimeSpan(totalms) {\r\n if (isNaN(totalms) || totalms < 0) {\r\n totalms = 0;\r\n }\r\n totalms = Math.round(totalms);\r\n var ms = strEmpty + totalms % 1000;\r\n var sec = strEmpty + Math.floor(totalms / 1000) % 60;\r\n var min = strEmpty + Math.floor(totalms / (1000 * 60)) % 60;\r\n var hour = strEmpty + Math.floor(totalms / (1000 * 60 * 60)) % 24;\r\n var days = Math.floor(totalms / (1000 * 60 * 60 * 24));\r\n ms = ms[_DYN_LENGTH /* @min:%2elength */] === 1 ? \"00\" + ms : ms[_DYN_LENGTH /* @min:%2elength */] === 2 ? \"0\" + ms : ms;\r\n sec = sec[_DYN_LENGTH /* @min:%2elength */] < 2 ? \"0\" + sec : sec;\r\n min = min[_DYN_LENGTH /* @min:%2elength */] < 2 ? \"0\" + min : min;\r\n hour = hour[_DYN_LENGTH /* @min:%2elength */] < 2 ? \"0\" + hour : hour;\r\n return (days > 0 ? days + \".\" : strEmpty) + hour + \":\" + min + \":\" + sec + \".\" + ms;\r\n}\r\nexport function getExtensionByName(extensions, identifier) {\r\n var extension = null;\r\n arrForEach(extensions, function (value) {\r\n if (value.identifier === identifier) {\r\n extension = value;\r\n return -1;\r\n }\r\n });\r\n return extension;\r\n}\r\nexport function isCrossOriginError(message, url, lineNumber, columnNumber, error) {\r\n return !error && isString(message) && (message === \"Script error.\" || message === \"Script error\");\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\r\nimport { createClassFromInterface } from \"@microsoft/applicationinsights-core-js\";\r\nfunction _aiNameFunc(baseName) {\r\n var aiName = \"ai.\" + baseName + \".\";\r\n return function (name) {\r\n return aiName + name;\r\n };\r\n}\r\nvar _aiApplication = _aiNameFunc(\"application\");\r\nvar _aiDevice = _aiNameFunc(\"device\");\r\nvar _aiLocation = _aiNameFunc(\"location\");\r\nvar _aiOperation = _aiNameFunc(\"operation\");\r\nvar _aiSession = _aiNameFunc(\"session\");\r\nvar _aiUser = _aiNameFunc(\"user\");\r\nvar _aiCloud = _aiNameFunc(\"cloud\");\r\nvar _aiInternal = _aiNameFunc(\"internal\");\r\nvar ContextTagKeys = /** @class */ (function (_super) {\r\n __extends(ContextTagKeys, _super);\r\n function ContextTagKeys() {\r\n return _super.call(this) || this;\r\n }\r\n return ContextTagKeys;\r\n}(createClassFromInterface({\r\n applicationVersion: _aiApplication(\"ver\"),\r\n applicationBuild: _aiApplication(\"build\"),\r\n applicationTypeId: _aiApplication(\"typeId\"),\r\n applicationId: _aiApplication(\"applicationId\"),\r\n applicationLayer: _aiApplication(\"layer\"),\r\n deviceId: _aiDevice(\"id\"),\r\n deviceIp: _aiDevice(\"ip\"),\r\n deviceLanguage: _aiDevice(\"language\"),\r\n deviceLocale: _aiDevice(\"locale\"),\r\n deviceModel: _aiDevice(\"model\"),\r\n deviceFriendlyName: _aiDevice(\"friendlyName\"),\r\n deviceNetwork: _aiDevice(\"network\"),\r\n deviceNetworkName: _aiDevice(\"networkName\"),\r\n deviceOEMName: _aiDevice(\"oemName\"),\r\n deviceOS: _aiDevice(\"os\"),\r\n deviceOSVersion: _aiDevice(\"osVersion\"),\r\n deviceRoleInstance: _aiDevice(\"roleInstance\"),\r\n deviceRoleName: _aiDevice(\"roleName\"),\r\n deviceScreenResolution: _aiDevice(\"screenResolution\"),\r\n deviceType: _aiDevice(\"type\"),\r\n deviceMachineName: _aiDevice(\"machineName\"),\r\n deviceVMName: _aiDevice(\"vmName\"),\r\n deviceBrowser: _aiDevice(\"browser\"),\r\n deviceBrowserVersion: _aiDevice(\"browserVersion\"),\r\n locationIp: _aiLocation(\"ip\"),\r\n locationCountry: _aiLocation(\"country\"),\r\n locationProvince: _aiLocation(\"province\"),\r\n locationCity: _aiLocation(\"city\"),\r\n operationId: _aiOperation(\"id\"),\r\n operationName: _aiOperation(\"name\"),\r\n operationParentId: _aiOperation(\"parentId\"),\r\n operationRootId: _aiOperation(\"rootId\"),\r\n operationSyntheticSource: _aiOperation(\"syntheticSource\"),\r\n operationCorrelationVector: _aiOperation(\"correlationVector\"),\r\n sessionId: _aiSession(\"id\"),\r\n sessionIsFirst: _aiSession(\"isFirst\"),\r\n sessionIsNew: _aiSession(\"isNew\"),\r\n userAccountAcquisitionDate: _aiUser(\"accountAcquisitionDate\"),\r\n userAccountId: _aiUser(\"accountId\"),\r\n userAgent: _aiUser(\"userAgent\"),\r\n userId: _aiUser(\"id\"),\r\n userStoreRegion: _aiUser(\"storeRegion\"),\r\n userAuthUserId: _aiUser(\"authUserId\"),\r\n userAnonymousUserAcquisitionDate: _aiUser(\"anonUserAcquisitionDate\"),\r\n userAuthenticatedUserAcquisitionDate: _aiUser(\"authUserAcquisitionDate\"),\r\n cloudName: _aiCloud(\"name\"),\r\n cloudRole: _aiCloud(\"role\"),\r\n cloudRoleVer: _aiCloud(\"roleVer\"),\r\n cloudRoleInstance: _aiCloud(\"roleInstance\"),\r\n cloudEnvironment: _aiCloud(\"environment\"),\r\n cloudLocation: _aiCloud(\"location\"),\r\n cloudDeploymentUnit: _aiCloud(\"deploymentUnit\"),\r\n internalNodeName: _aiInternal(\"nodeName\"),\r\n internalSdkVersion: _aiInternal(\"sdkVersion\"),\r\n internalAgentVersion: _aiInternal(\"agentVersion\"),\r\n internalSnippet: _aiInternal(\"snippet\"),\r\n internalSdkSrc: _aiInternal(\"sdkSrc\")\r\n})));\r\nexport { ContextTagKeys };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { createEnumStyle } from \"@microsoft/applicationinsights-core-js\";\r\n/**\r\n * Defines the level of severity for the event.\r\n */\r\nexport var SeverityLevel = createEnumStyle({\r\n Verbose: 0 /* eSeverityLevel.Verbose */,\r\n Information: 1 /* eSeverityLevel.Information */,\r\n Warning: 2 /* eSeverityLevel.Warning */,\r\n Error: 3 /* eSeverityLevel.Error */,\r\n Critical: 4 /* eSeverityLevel.Critical */\r\n});\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { isNullOrUndefined } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_EXTENSION_CONFIG } from \"../__DynamicConstants\";\r\nvar ConfigurationManager = /** @class */ (function () {\r\n function ConfigurationManager() {\r\n }\r\n ConfigurationManager.getConfig = function (config, field, identifier, defaultValue) {\r\n if (defaultValue === void 0) { defaultValue = false; }\r\n var configValue;\r\n if (identifier && config[_DYN_EXTENSION_CONFIG /* @min:%2eextensionConfig */] && config[_DYN_EXTENSION_CONFIG /* @min:%2eextensionConfig */][identifier] && !isNullOrUndefined(config[_DYN_EXTENSION_CONFIG /* @min:%2eextensionConfig */][identifier][field])) {\r\n configValue = config[_DYN_EXTENSION_CONFIG /* @min:%2eextensionConfig */][identifier][field];\r\n }\r\n else {\r\n configValue = config[field];\r\n }\r\n return !isNullOrUndefined(configValue) ? configValue : defaultValue;\r\n };\r\n return ConfigurationManager;\r\n}());\r\nexport { ConfigurationManager };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { ContextTagKeys } from \"./Contracts/ContextTagKeys\";\r\nexport var Extensions = {\r\n UserExt: \"user\",\r\n DeviceExt: \"device\",\r\n TraceExt: \"trace\",\r\n WebExt: \"web\",\r\n AppExt: \"app\",\r\n OSExt: \"os\",\r\n SessionExt: \"ses\",\r\n SDKExt: \"sdk\"\r\n};\r\nexport var CtxTagKeys = new ContextTagKeys();\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { createValueMap } from \"@microsoft/applicationinsights-core-js\";\r\nexport var RequestHeaders = createValueMap({\r\n requestContextHeader: [0 /* eRequestHeaders.requestContextHeader */, \"Request-Context\"],\r\n requestContextTargetKey: [1 /* eRequestHeaders.requestContextTargetKey */, \"appId\"],\r\n requestContextAppIdFormat: [2 /* eRequestHeaders.requestContextAppIdFormat */, \"appId=cid-v1:\"],\r\n requestIdHeader: [3 /* eRequestHeaders.requestIdHeader */, \"Request-Id\"],\r\n traceParentHeader: [4 /* eRequestHeaders.traceParentHeader */, \"traceparent\"],\r\n traceStateHeader: [5 /* eRequestHeaders.traceStateHeader */, \"tracestate\"],\r\n sdkContextHeader: [6 /* eRequestHeaders.sdkContextHeader */, \"Sdk-Context\"],\r\n sdkContextHeaderAppIdRequest: [7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */, \"appId\"],\r\n requestContextHeaderLowerCase: [8 /* eRequestHeaders.requestContextHeaderLowerCase */, \"request-context\"]\r\n});\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { _throwInternal, dumpObj, getExceptionName, getGlobal, getGlobalInst, isNullOrUndefined, objForEachKey } from \"@microsoft/applicationinsights-core-js\";\r\nimport { StorageType } from \"./Enums\";\r\nimport { _DYN_REMOVE_ITEM, _DYN_TO_STRING } from \"./__DynamicConstants\";\r\nvar _canUseLocalStorage = undefined;\r\nvar _canUseSessionStorage = undefined;\r\n/**\r\n * Gets the localStorage object if available\r\n * @return {Storage} - Returns the storage object if available else returns null\r\n */\r\nfunction _getLocalStorageObject() {\r\n if (utlCanUseLocalStorage()) {\r\n return _getVerifiedStorageObject(StorageType.LocalStorage);\r\n }\r\n return null;\r\n}\r\n/**\r\n * Tests storage object (localStorage or sessionStorage) to verify that it is usable\r\n * More details here: https://mathiasbynens.be/notes/localstorage-pattern\r\n * @param storageType Type of storage\r\n * @return {Storage} Returns storage object verified that it is usable\r\n */\r\nfunction _getVerifiedStorageObject(storageType) {\r\n try {\r\n if (isNullOrUndefined(getGlobal())) {\r\n return null;\r\n }\r\n var uid = (new Date)[_DYN_TO_STRING /* @min:%2etoString */]();\r\n var storage = getGlobalInst(storageType === StorageType.LocalStorage ? \"localStorage\" : \"sessionStorage\");\r\n storage.setItem(uid, uid);\r\n var fail = storage.getItem(uid) !== uid;\r\n storage[_DYN_REMOVE_ITEM /* @min:%2eremoveItem */](uid);\r\n if (!fail) {\r\n return storage;\r\n }\r\n }\r\n catch (exception) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n}\r\n/**\r\n * Gets the sessionStorage object if available\r\n * @return {Storage} - Returns the storage object if available else returns null\r\n */\r\nfunction _getSessionStorageObject() {\r\n if (utlCanUseSessionStorage()) {\r\n return _getVerifiedStorageObject(StorageType.SessionStorage);\r\n }\r\n return null;\r\n}\r\n/**\r\n * Disables the global SDK usage of local or session storage if available\r\n */\r\nexport function utlDisableStorage() {\r\n _canUseLocalStorage = false;\r\n _canUseSessionStorage = false;\r\n}\r\n/**\r\n * Re-enables the global SDK usage of local or session storage if available\r\n */\r\nexport function utlEnableStorage() {\r\n _canUseLocalStorage = utlCanUseLocalStorage(true);\r\n _canUseSessionStorage = utlCanUseSessionStorage(true);\r\n}\r\n/**\r\n * Returns whether LocalStorage can be used, if the reset parameter is passed a true this will override\r\n * any previous disable calls.\r\n * @param reset - Should the usage be reset and determined only based on whether LocalStorage is available\r\n */\r\nexport function utlCanUseLocalStorage(reset) {\r\n if (reset || _canUseLocalStorage === undefined) {\r\n _canUseLocalStorage = !!_getVerifiedStorageObject(StorageType.LocalStorage);\r\n }\r\n return _canUseLocalStorage;\r\n}\r\nexport function utlGetLocalStorage(logger, name) {\r\n var storage = _getLocalStorageObject();\r\n if (storage !== null) {\r\n try {\r\n return storage.getItem(name);\r\n }\r\n catch (e) {\r\n _canUseLocalStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 1 /* _eInternalMessageId.BrowserCannotReadLocalStorage */, \"Browser failed read of local storage. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return null;\r\n}\r\nexport function utlSetLocalStorage(logger, name, data) {\r\n var storage = _getLocalStorageObject();\r\n if (storage !== null) {\r\n try {\r\n storage.setItem(name, data);\r\n return true;\r\n }\r\n catch (e) {\r\n _canUseLocalStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 3 /* _eInternalMessageId.BrowserCannotWriteLocalStorage */, \"Browser failed write to local storage. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return false;\r\n}\r\nexport function utlRemoveStorage(logger, name) {\r\n var storage = _getLocalStorageObject();\r\n if (storage !== null) {\r\n try {\r\n storage[_DYN_REMOVE_ITEM /* @min:%2eremoveItem */](name);\r\n return true;\r\n }\r\n catch (e) {\r\n _canUseLocalStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 5 /* _eInternalMessageId.BrowserFailedRemovalFromLocalStorage */, \"Browser failed removal of local storage item. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return false;\r\n}\r\nexport function utlCanUseSessionStorage(reset) {\r\n if (reset || _canUseSessionStorage === undefined) {\r\n _canUseSessionStorage = !!_getVerifiedStorageObject(StorageType.SessionStorage);\r\n }\r\n return _canUseSessionStorage;\r\n}\r\nexport function utlGetSessionStorageKeys() {\r\n var keys = [];\r\n if (utlCanUseSessionStorage()) {\r\n objForEachKey(getGlobalInst(\"sessionStorage\"), function (key) {\r\n keys.push(key);\r\n });\r\n }\r\n return keys;\r\n}\r\nexport function utlGetSessionStorage(logger, name) {\r\n var storage = _getSessionStorageObject();\r\n if (storage !== null) {\r\n try {\r\n return storage.getItem(name);\r\n }\r\n catch (e) {\r\n _canUseSessionStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 2 /* _eInternalMessageId.BrowserCannotReadSessionStorage */, \"Browser failed read of session storage. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return null;\r\n}\r\nexport function utlSetSessionStorage(logger, name, data) {\r\n var storage = _getSessionStorageObject();\r\n if (storage !== null) {\r\n try {\r\n storage.setItem(name, data);\r\n return true;\r\n }\r\n catch (e) {\r\n _canUseSessionStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 4 /* _eInternalMessageId.BrowserCannotWriteSessionStorage */, \"Browser failed write to session storage. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return false;\r\n}\r\nexport function utlRemoveSessionStorage(logger, name) {\r\n var storage = _getSessionStorageObject();\r\n if (storage !== null) {\r\n try {\r\n storage[_DYN_REMOVE_ITEM /* @min:%2eremoveItem */](name);\r\n return true;\r\n }\r\n catch (e) {\r\n _canUseSessionStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 6 /* _eInternalMessageId.BrowserFailedRemovalFromSessionStorage */, \"Browser failed removal of session storage item. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return false;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nvar Data = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of telemetry data.\r\n */\r\n function Data(baseType, data) {\r\n /**\r\n * The data contract for serializing this object.\r\n */\r\n this.aiDataContract = {\r\n baseType: 1 /* FieldType.Required */,\r\n baseData: 1 /* FieldType.Required */\r\n };\r\n this.baseType = baseType;\r\n this.baseData = data;\r\n }\r\n return Data;\r\n}());\r\nexport { Data };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nvar DataPoint = /** @class */ (function () {\r\n function DataPoint() {\r\n /**\r\n * The data contract for serializing this object.\r\n */\r\n this.aiDataContract = {\r\n name: 1 /* FieldType.Required */,\r\n kind: 0 /* FieldType.Default */,\r\n value: 1 /* FieldType.Required */,\r\n count: 0 /* FieldType.Default */,\r\n min: 0 /* FieldType.Default */,\r\n max: 0 /* FieldType.Default */,\r\n stdDev: 0 /* FieldType.Default */\r\n };\r\n /**\r\n * Metric type. Single measurement or the aggregated value.\r\n */\r\n this.kind = 0 /* DataPointType.Measurement */;\r\n }\r\n return DataPoint;\r\n}());\r\nexport { DataPoint };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nvar _a;\r\nimport { _throwInternal, getJSON, hasJSON, isObject, objForEachKey, strTrim } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_LENGTH, _DYN_SANITIZE_EXCEPTION, _DYN_SANITIZE_KEY_AND_ADD2, _DYN_SANITIZE_MEASUREMENT3, _DYN_SANITIZE_PROPERTIES, _DYN_STRINGIFY, _DYN_SUBSTRING, _DYN_TO_STRING } from \"../../__DynamicConstants\";\r\nexport function dataSanitizeKeyAndAddUniqueness(logger, key, map) {\r\n var origLength = key[_DYN_LENGTH /* @min:%2elength */];\r\n var field = dataSanitizeKey(logger, key);\r\n // validation truncated the length. We need to add uniqueness\r\n if (field[_DYN_LENGTH /* @min:%2elength */] !== origLength) {\r\n var i = 0;\r\n var uniqueField = field;\r\n while (map[uniqueField] !== undefined) {\r\n i++;\r\n uniqueField = field[_DYN_SUBSTRING /* @min:%2esubstring */](0, 150 /* DataSanitizerValues.MAX_NAME_LENGTH */ - 3) + dsPadNumber(i);\r\n }\r\n field = uniqueField;\r\n }\r\n return field;\r\n}\r\nexport function dataSanitizeKey(logger, name) {\r\n var nameTrunc;\r\n if (name) {\r\n // Remove any leading or trailing whitespace\r\n name = strTrim(name[_DYN_TO_STRING /* @min:%2etoString */]());\r\n // truncate the string to 150 chars\r\n if (name[_DYN_LENGTH /* @min:%2elength */] > 150 /* DataSanitizerValues.MAX_NAME_LENGTH */) {\r\n nameTrunc = name[_DYN_SUBSTRING /* @min:%2esubstring */](0, 150 /* DataSanitizerValues.MAX_NAME_LENGTH */);\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 57 /* _eInternalMessageId.NameTooLong */, \"name is too long. It has been truncated to \" + 150 /* DataSanitizerValues.MAX_NAME_LENGTH */ + \" characters.\", { name: name }, true);\r\n }\r\n }\r\n return nameTrunc || name;\r\n}\r\nexport function dataSanitizeString(logger, value, maxLength) {\r\n if (maxLength === void 0) { maxLength = 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */; }\r\n var valueTrunc;\r\n if (value) {\r\n maxLength = maxLength ? maxLength : 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */; // in case default parameters dont work\r\n value = strTrim(value);\r\n if (value.toString()[_DYN_LENGTH /* @min:%2elength */] > maxLength) {\r\n valueTrunc = value[_DYN_TO_STRING /* @min:%2etoString */]()[_DYN_SUBSTRING /* @min:%2esubstring */](0, maxLength);\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 61 /* _eInternalMessageId.StringValueTooLong */, \"string value is too long. It has been truncated to \" + maxLength + \" characters.\", { value: value }, true);\r\n }\r\n }\r\n return valueTrunc || value;\r\n}\r\nexport function dataSanitizeUrl(logger, url) {\r\n return dataSanitizeInput(logger, url, 2048 /* DataSanitizerValues.MAX_URL_LENGTH */, 66 /* _eInternalMessageId.UrlTooLong */);\r\n}\r\nexport function dataSanitizeMessage(logger, message) {\r\n var messageTrunc;\r\n if (message) {\r\n if (message[_DYN_LENGTH /* @min:%2elength */] > 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */) {\r\n messageTrunc = message[_DYN_SUBSTRING /* @min:%2esubstring */](0, 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */);\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 56 /* _eInternalMessageId.MessageTruncated */, \"message is too long, it has been truncated to \" + 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */ + \" characters.\", { message: message }, true);\r\n }\r\n }\r\n return messageTrunc || message;\r\n}\r\nexport function dataSanitizeException(logger, exception) {\r\n var exceptionTrunc;\r\n if (exception) {\r\n // Make surte its a string\r\n var value = \"\" + exception;\r\n if (value[_DYN_LENGTH /* @min:%2elength */] > 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */) {\r\n exceptionTrunc = value[_DYN_SUBSTRING /* @min:%2esubstring */](0, 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */);\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 52 /* _eInternalMessageId.ExceptionTruncated */, \"exception is too long, it has been truncated to \" + 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */ + \" characters.\", { exception: exception }, true);\r\n }\r\n }\r\n return exceptionTrunc || exception;\r\n}\r\nexport function dataSanitizeProperties(logger, properties) {\r\n if (properties) {\r\n var tempProps_1 = {};\r\n objForEachKey(properties, function (prop, value) {\r\n if (isObject(value) && hasJSON()) {\r\n // Stringify any part C properties\r\n try {\r\n value = getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](value);\r\n }\r\n catch (e) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 49 /* _eInternalMessageId.CannotSerializeObjectNonSerializable */, \"custom property is not valid\", { exception: e }, true);\r\n }\r\n }\r\n value = dataSanitizeString(logger, value, 8192 /* DataSanitizerValues.MAX_PROPERTY_LENGTH */);\r\n prop = dataSanitizeKeyAndAddUniqueness(logger, prop, tempProps_1);\r\n tempProps_1[prop] = value;\r\n });\r\n properties = tempProps_1;\r\n }\r\n return properties;\r\n}\r\nexport function dataSanitizeMeasurements(logger, measurements) {\r\n if (measurements) {\r\n var tempMeasurements_1 = {};\r\n objForEachKey(measurements, function (measure, value) {\r\n measure = dataSanitizeKeyAndAddUniqueness(logger, measure, tempMeasurements_1);\r\n tempMeasurements_1[measure] = value;\r\n });\r\n measurements = tempMeasurements_1;\r\n }\r\n return measurements;\r\n}\r\nexport function dataSanitizeId(logger, id) {\r\n return id ? dataSanitizeInput(logger, id, 128 /* DataSanitizerValues.MAX_ID_LENGTH */, 69 /* _eInternalMessageId.IdTooLong */)[_DYN_TO_STRING /* @min:%2etoString */]() : id;\r\n}\r\nexport function dataSanitizeInput(logger, input, maxLength, _msgId) {\r\n var inputTrunc;\r\n if (input) {\r\n input = strTrim(input);\r\n if (input[_DYN_LENGTH /* @min:%2elength */] > maxLength) {\r\n inputTrunc = input[_DYN_SUBSTRING /* @min:%2esubstring */](0, maxLength);\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, _msgId, \"input is too long, it has been truncated to \" + maxLength + \" characters.\", { data: input }, true);\r\n }\r\n }\r\n return inputTrunc || input;\r\n}\r\nexport function dsPadNumber(num) {\r\n var s = \"00\" + num;\r\n return s.substr(s[_DYN_LENGTH /* @min:%2elength */] - 3);\r\n}\r\n/**\r\n * Provides the DataSanitizer functions within the previous namespace.\r\n */\r\nexport var DataSanitizer = (_a = {\r\n MAX_NAME_LENGTH: 150 /* DataSanitizerValues.MAX_NAME_LENGTH */,\r\n MAX_ID_LENGTH: 128 /* DataSanitizerValues.MAX_ID_LENGTH */,\r\n MAX_PROPERTY_LENGTH: 8192 /* DataSanitizerValues.MAX_PROPERTY_LENGTH */,\r\n MAX_STRING_LENGTH: 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */,\r\n MAX_URL_LENGTH: 2048 /* DataSanitizerValues.MAX_URL_LENGTH */,\r\n MAX_MESSAGE_LENGTH: 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */,\r\n MAX_EXCEPTION_LENGTH: 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */\r\n },\r\n _a[_DYN_SANITIZE_KEY_AND_ADD2 /* @min:sanitizeKeyAndAddUniqueness */] = dataSanitizeKeyAndAddUniqueness,\r\n _a.sanitizeKey = dataSanitizeKey,\r\n _a.sanitizeString = dataSanitizeString,\r\n _a.sanitizeUrl = dataSanitizeUrl,\r\n _a.sanitizeMessage = dataSanitizeMessage,\r\n _a[_DYN_SANITIZE_EXCEPTION /* @min:sanitizeException */] = dataSanitizeException,\r\n _a[_DYN_SANITIZE_PROPERTIES /* @min:sanitizeProperties */] = dataSanitizeProperties,\r\n _a[_DYN_SANITIZE_MEASUREMENT3 /* @min:sanitizeMeasurements */] = dataSanitizeMeasurements,\r\n _a.sanitizeId = dataSanitizeId,\r\n _a.sanitizeInput = dataSanitizeInput,\r\n _a.padNumber = dsPadNumber,\r\n _a.trim = strTrim,\r\n _a);\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { toISOString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { strNotSpecified } from \"../../Constants\";\r\nimport { _DYN_NAME } from \"../../__DynamicConstants\";\r\nimport { dataSanitizeString } from \"./DataSanitizer\";\r\nvar Envelope = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of telemetry data.\r\n */\r\n function Envelope(logger, data, name) {\r\n var _this = this;\r\n var _self = this;\r\n _self.ver = 1;\r\n _self.sampleRate = 100.0;\r\n _self.tags = {};\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n _self.data = data;\r\n _self.time = toISOString(new Date());\r\n _self.aiDataContract = {\r\n time: 1 /* FieldType.Required */,\r\n iKey: 1 /* FieldType.Required */,\r\n name: 1 /* FieldType.Required */,\r\n sampleRate: function () {\r\n return (_this.sampleRate === 100) ? 4 /* FieldType.Hidden */ : 1 /* FieldType.Required */;\r\n },\r\n tags: 1 /* FieldType.Required */,\r\n data: 1 /* FieldType.Required */\r\n };\r\n }\r\n return Envelope;\r\n}());\r\nexport { Envelope };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\r\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString } from \"./Common/DataSanitizer\";\r\nvar Event = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the EventTelemetry object\r\n */\r\n function Event(logger, name, properties, measurements) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n name: 1 /* FieldType.Required */,\r\n properties: 0 /* FieldType.Default */,\r\n measurements: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n }\r\n Event.envelopeType = \"Microsoft.ApplicationInsights.{0}.Event\";\r\n Event.dataType = \"EventData\";\r\n return Event;\r\n}());\r\nexport { Event };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { __assignFn as __assign } from \"@microsoft/applicationinsights-shims\";\r\nimport { arrForEach, arrMap, isArray, isError, isFunction, isNullOrUndefined, isObject, isString, strTrim } from \"@microsoft/applicationinsights-core-js\";\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { _DYN_ASSEMBLY, _DYN_EXCEPTIONS, _DYN_FILE_NAME, _DYN_HAS_FULL_STACK, _DYN_INDEX_OF, _DYN_IS_MANUAL, _DYN_LENGTH, _DYN_LEVEL, _DYN_LINE, _DYN_MEASUREMENTS, _DYN_MESSAGE, _DYN_METHOD, _DYN_NAME, _DYN_PARSED_STACK, _DYN_PROBLEM_GROUP, _DYN_PROPERTIES, _DYN_SEVERITY_LEVEL, _DYN_SIZE_IN_BYTES, _DYN_SPLIT, _DYN_STRINGIFY, _DYN_TO_STRING, _DYN_TYPE_NAME, _DYN__CREATE_FROM_INTERFA1 } from \"../__DynamicConstants\";\r\nimport { dataSanitizeException, dataSanitizeMeasurements, dataSanitizeMessage, dataSanitizeProperties, dataSanitizeString } from \"./Common/DataSanitizer\";\r\nvar NoMethod = \"\";\r\nvar strError = \"error\";\r\nvar strStack = \"stack\";\r\nvar strStackDetails = \"stackDetails\";\r\nvar strErrorSrc = \"errorSrc\";\r\nvar strMessage = \"message\";\r\nvar strDescription = \"description\";\r\nfunction _stringify(value, convertToString) {\r\n var result = value;\r\n if (result && !isString(result)) {\r\n if (JSON && JSON[_DYN_STRINGIFY /* @min:%2estringify */]) {\r\n result = JSON[_DYN_STRINGIFY /* @min:%2estringify */](value);\r\n if (convertToString && (!result || result === \"{}\")) {\r\n if (isFunction(value[_DYN_TO_STRING /* @min:%2etoString */])) {\r\n result = value[_DYN_TO_STRING /* @min:%2etoString */]();\r\n }\r\n else {\r\n result = \"\" + value;\r\n }\r\n }\r\n }\r\n else {\r\n result = \"\" + value + \" - (Missing JSON.stringify)\";\r\n }\r\n }\r\n return result || \"\";\r\n}\r\nfunction _formatMessage(theEvent, errorType) {\r\n var evtMessage = theEvent;\r\n if (theEvent) {\r\n if (evtMessage && !isString(evtMessage)) {\r\n evtMessage = theEvent[strMessage] || theEvent[strDescription] || evtMessage;\r\n }\r\n // Make sure the message is a string\r\n if (evtMessage && !isString(evtMessage)) {\r\n // tslint:disable-next-line: prefer-conditional-expression\r\n evtMessage = _stringify(evtMessage, true);\r\n }\r\n if (theEvent[\"filename\"]) {\r\n // Looks like an event object with filename\r\n evtMessage = evtMessage + \" @\" + (theEvent[\"filename\"] || \"\") + \":\" + (theEvent[\"lineno\"] || \"?\") + \":\" + (theEvent[\"colno\"] || \"?\");\r\n }\r\n }\r\n // Automatically add the error type to the message if it does already appear to be present\r\n if (errorType && errorType !== \"String\" && errorType !== \"Object\" && errorType !== \"Error\" && (evtMessage || \"\")[_DYN_INDEX_OF /* @min:%2eindexOf */](errorType) === -1) {\r\n evtMessage = errorType + \": \" + evtMessage;\r\n }\r\n return evtMessage || \"\";\r\n}\r\nfunction _isExceptionDetailsInternal(value) {\r\n try {\r\n if (isObject(value)) {\r\n return \"hasFullStack\" in value && \"typeName\" in value;\r\n }\r\n }\r\n catch (e) {\r\n // This can happen with some native browser objects, but should not happen for the type we are checking for\r\n }\r\n return false;\r\n}\r\nfunction _isExceptionInternal(value) {\r\n try {\r\n if (isObject(value)) {\r\n return (\"ver\" in value && \"exceptions\" in value && \"properties\" in value);\r\n }\r\n }\r\n catch (e) {\r\n // This can happen with some native browser objects, but should not happen for the type we are checking for\r\n }\r\n return false;\r\n}\r\nfunction _isStackDetails(details) {\r\n return details && details.src && isString(details.src) && details.obj && isArray(details.obj);\r\n}\r\nfunction _convertStackObj(errorStack) {\r\n var src = errorStack || \"\";\r\n if (!isString(src)) {\r\n if (isString(src[strStack])) {\r\n src = src[strStack];\r\n }\r\n else {\r\n src = \"\" + src;\r\n }\r\n }\r\n var items = src[_DYN_SPLIT /* @min:%2esplit */](\"\\n\");\r\n return {\r\n src: src,\r\n obj: items\r\n };\r\n}\r\nfunction _getOperaStack(errorMessage) {\r\n var stack = [];\r\n var lines = errorMessage[_DYN_SPLIT /* @min:%2esplit */](\"\\n\");\r\n for (var lp = 0; lp < lines[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n var entry = lines[lp];\r\n if (lines[lp + 1]) {\r\n entry += \"@\" + lines[lp + 1];\r\n lp++;\r\n }\r\n stack.push(entry);\r\n }\r\n return {\r\n src: errorMessage,\r\n obj: stack\r\n };\r\n}\r\nfunction _getStackFromErrorObj(errorObj) {\r\n var details = null;\r\n if (errorObj) {\r\n try {\r\n /* Using bracket notation is support older browsers (IE 7/8 -- dont remember the version) that throw when using dot\r\n notation for undefined objects and we don't want to loose the error from being reported */\r\n if (errorObj[strStack]) {\r\n // Chrome/Firefox\r\n details = _convertStackObj(errorObj[strStack]);\r\n }\r\n else if (errorObj[strError] && errorObj[strError][strStack]) {\r\n // Edge error event provides the stack and error object\r\n details = _convertStackObj(errorObj[strError][strStack]);\r\n }\r\n else if (errorObj[\"exception\"] && errorObj.exception[strStack]) {\r\n details = _convertStackObj(errorObj.exception[strStack]);\r\n }\r\n else if (_isStackDetails(errorObj)) {\r\n details = errorObj;\r\n }\r\n else if (_isStackDetails(errorObj[strStackDetails])) {\r\n details = errorObj[strStackDetails];\r\n }\r\n else if (window && window[\"opera\"] && errorObj[strMessage]) {\r\n // Opera\r\n details = _getOperaStack(errorObj[_DYN_MESSAGE /* @min:%2emessage */]);\r\n }\r\n else if (errorObj[\"reason\"] && errorObj.reason[strStack]) {\r\n // UnhandledPromiseRejection\r\n details = _convertStackObj(errorObj.reason[strStack]);\r\n }\r\n else if (isString(errorObj)) {\r\n details = _convertStackObj(errorObj);\r\n }\r\n else {\r\n var evtMessage = errorObj[strMessage] || errorObj[strDescription] || \"\";\r\n if (isString(errorObj[strErrorSrc])) {\r\n if (evtMessage) {\r\n evtMessage += \"\\n\";\r\n }\r\n evtMessage += \" from \" + errorObj[strErrorSrc];\r\n }\r\n if (evtMessage) {\r\n details = _convertStackObj(evtMessage);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // something unexpected happened so to avoid failing to report any error lets swallow the exception\r\n // and fallback to the callee/caller method\r\n details = _convertStackObj(e);\r\n }\r\n }\r\n return details || {\r\n src: \"\",\r\n obj: null\r\n };\r\n}\r\nfunction _formatStackTrace(stackDetails) {\r\n var stack = \"\";\r\n if (stackDetails) {\r\n if (stackDetails.obj) {\r\n arrForEach(stackDetails.obj, function (entry) {\r\n stack += entry + \"\\n\";\r\n });\r\n }\r\n else {\r\n stack = stackDetails.src || \"\";\r\n }\r\n }\r\n return stack;\r\n}\r\nfunction _parseStack(stack) {\r\n var parsedStack;\r\n var frames = stack.obj;\r\n if (frames && frames[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n parsedStack = [];\r\n var level_1 = 0;\r\n var totalSizeInBytes_1 = 0;\r\n arrForEach(frames, function (frame) {\r\n var theFrame = frame[_DYN_TO_STRING /* @min:%2etoString */]();\r\n if (_StackFrame.regex.test(theFrame)) {\r\n var parsedFrame = new _StackFrame(theFrame, level_1++);\r\n totalSizeInBytes_1 += parsedFrame[_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */];\r\n parsedStack.push(parsedFrame);\r\n }\r\n });\r\n // DP Constraint - exception parsed stack must be < 32KB\r\n // remove frames from the middle to meet the threshold\r\n var exceptionParsedStackThreshold = 32 * 1024;\r\n if (totalSizeInBytes_1 > exceptionParsedStackThreshold) {\r\n var left = 0;\r\n var right = parsedStack[_DYN_LENGTH /* @min:%2elength */] - 1;\r\n var size = 0;\r\n var acceptedLeft = left;\r\n var acceptedRight = right;\r\n while (left < right) {\r\n // check size\r\n var lSize = parsedStack[left][_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */];\r\n var rSize = parsedStack[right][_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */];\r\n size += lSize + rSize;\r\n if (size > exceptionParsedStackThreshold) {\r\n // remove extra frames from the middle\r\n var howMany = acceptedRight - acceptedLeft + 1;\r\n parsedStack.splice(acceptedLeft, howMany);\r\n break;\r\n }\r\n // update pointers\r\n acceptedLeft = left;\r\n acceptedRight = right;\r\n left++;\r\n right--;\r\n }\r\n }\r\n }\r\n return parsedStack;\r\n}\r\nfunction _getErrorType(errorType) {\r\n // Gets the Error Type by passing the constructor (used to get the true type of native error object).\r\n var typeName = \"\";\r\n if (errorType) {\r\n typeName = errorType.typeName || errorType[_DYN_NAME /* @min:%2ename */] || \"\";\r\n if (!typeName) {\r\n try {\r\n var funcNameRegex = /function (.{1,200})\\(/;\r\n var results = (funcNameRegex).exec((errorType).constructor[_DYN_TO_STRING /* @min:%2etoString */]());\r\n typeName = (results && results[_DYN_LENGTH /* @min:%2elength */] > 1) ? results[1] : \"\";\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty -- Ignoring any failures as nothing we can do\r\n }\r\n }\r\n }\r\n return typeName;\r\n}\r\n/**\r\n * Formats the provided errorObj for display and reporting, it may be a String, Object, integer or undefined depending on the browser.\r\n * @param errorObj The supplied errorObj\r\n */\r\nexport function _formatErrorCode(errorObj) {\r\n if (errorObj) {\r\n try {\r\n if (!isString(errorObj)) {\r\n var errorType = _getErrorType(errorObj);\r\n var result = _stringify(errorObj, false);\r\n if (!result || result === \"{}\") {\r\n if (errorObj[strError]) {\r\n // Looks like an MS Error Event\r\n errorObj = errorObj[strError];\r\n errorType = _getErrorType(errorObj);\r\n }\r\n result = _stringify(errorObj, true);\r\n }\r\n if (result[_DYN_INDEX_OF /* @min:%2eindexOf */](errorType) !== 0 && errorType !== \"String\") {\r\n return errorType + \":\" + result;\r\n }\r\n return result;\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty -- Ignoring any failures as nothing we can do\r\n }\r\n }\r\n // Fallback to just letting the object format itself into a string\r\n return \"\" + (errorObj || \"\");\r\n}\r\nvar Exception = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the ExceptionTelemetry object\r\n */\r\n function Exception(logger, exception, properties, measurements, severityLevel, id) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n exceptions: 1 /* FieldType.Required */,\r\n severityLevel: 0 /* FieldType.Default */,\r\n properties: 0 /* FieldType.Default */,\r\n measurements: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2; // TODO: handle the CS\"4.0\" ==> breeze 2 conversion in a better way\r\n if (!_isExceptionInternal(exception)) {\r\n if (!properties) {\r\n properties = {};\r\n }\r\n _self[_DYN_EXCEPTIONS /* @min:%2eexceptions */] = [new _ExceptionDetails(logger, exception, properties)];\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n if (severityLevel) {\r\n _self[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */] = severityLevel;\r\n }\r\n if (id) {\r\n _self.id = id;\r\n }\r\n }\r\n else {\r\n _self[_DYN_EXCEPTIONS /* @min:%2eexceptions */] = exception[_DYN_EXCEPTIONS /* @min:%2eexceptions */] || [];\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = exception[_DYN_PROPERTIES /* @min:%2eproperties */];\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = exception[_DYN_MEASUREMENTS /* @min:%2emeasurements */];\r\n if (exception[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */]) {\r\n _self[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */] = exception[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */];\r\n }\r\n if (exception.id) {\r\n _self.id = exception.id;\r\n }\r\n if (exception[_DYN_PROBLEM_GROUP /* @min:%2eproblemGroup */]) {\r\n _self[_DYN_PROBLEM_GROUP /* @min:%2eproblemGroup */] = exception[_DYN_PROBLEM_GROUP /* @min:%2eproblemGroup */];\r\n }\r\n // bool/int types, use isNullOrUndefined\r\n if (!isNullOrUndefined(exception[_DYN_IS_MANUAL /* @min:%2eisManual */])) {\r\n _self[_DYN_IS_MANUAL /* @min:%2eisManual */] = exception[_DYN_IS_MANUAL /* @min:%2eisManual */];\r\n }\r\n }\r\n }\r\n Exception.CreateAutoException = function (message, url, lineNumber, columnNumber, error, evt, stack, errorSrc) {\r\n var _a;\r\n var errorType = _getErrorType(error || evt || message);\r\n return _a = {},\r\n _a[_DYN_MESSAGE /* @min:message */] = _formatMessage(message, errorType),\r\n _a.url = url,\r\n _a.lineNumber = lineNumber,\r\n _a.columnNumber = columnNumber,\r\n _a.error = _formatErrorCode(error || evt || message),\r\n _a.evt = _formatErrorCode(evt || message),\r\n _a[_DYN_TYPE_NAME /* @min:typeName */] = errorType,\r\n _a.stackDetails = _getStackFromErrorObj(stack || error || evt),\r\n _a.errorSrc = errorSrc,\r\n _a;\r\n };\r\n Exception.CreateFromInterface = function (logger, exception, properties, measurements) {\r\n var exceptions = exception[_DYN_EXCEPTIONS /* @min:%2eexceptions */]\r\n && arrMap(exception[_DYN_EXCEPTIONS /* @min:%2eexceptions */], function (ex) { return _ExceptionDetails[_DYN__CREATE_FROM_INTERFA1 /* @min:%2eCreateFromInterface */](logger, ex); });\r\n var exceptionData = new Exception(logger, __assign(__assign({}, exception), { exceptions: exceptions }), properties, measurements);\r\n return exceptionData;\r\n };\r\n Exception.prototype.toInterface = function () {\r\n var _a;\r\n var _b = this, exceptions = _b.exceptions, properties = _b.properties, measurements = _b.measurements, severityLevel = _b.severityLevel, problemGroup = _b.problemGroup, id = _b.id, isManual = _b.isManual;\r\n var exceptionDetailsInterface = exceptions instanceof Array\r\n && arrMap(exceptions, function (exception) { return exception.toInterface(); })\r\n || undefined;\r\n return _a = {\r\n ver: \"4.0\"\r\n },\r\n _a[_DYN_EXCEPTIONS /* @min:exceptions */] = exceptionDetailsInterface,\r\n _a.severityLevel = severityLevel,\r\n _a.properties = properties,\r\n _a.measurements = measurements,\r\n _a.problemGroup = problemGroup,\r\n _a.id = id,\r\n _a.isManual = isManual,\r\n _a;\r\n };\r\n /**\r\n * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception.\r\n */\r\n Exception.CreateSimpleException = function (message, typeName, assembly, fileName, details, line) {\r\n var _a;\r\n return {\r\n exceptions: [\r\n (_a = {},\r\n _a[_DYN_HAS_FULL_STACK /* @min:hasFullStack */] = true,\r\n _a.message = message,\r\n _a.stack = details,\r\n _a.typeName = typeName,\r\n _a)\r\n ]\r\n };\r\n };\r\n Exception.envelopeType = \"Microsoft.ApplicationInsights.{0}.Exception\";\r\n Exception.dataType = \"ExceptionData\";\r\n Exception.formatError = _formatErrorCode;\r\n return Exception;\r\n}());\r\nexport { Exception };\r\nvar _ExceptionDetails = /** @class */ (function () {\r\n function _ExceptionDetails(logger, exception, properties) {\r\n this.aiDataContract = {\r\n id: 0 /* FieldType.Default */,\r\n outerId: 0 /* FieldType.Default */,\r\n typeName: 1 /* FieldType.Required */,\r\n message: 1 /* FieldType.Required */,\r\n hasFullStack: 0 /* FieldType.Default */,\r\n stack: 0 /* FieldType.Default */,\r\n parsedStack: 2 /* FieldType.Array */\r\n };\r\n var _self = this;\r\n if (!_isExceptionDetailsInternal(exception)) {\r\n var error = exception;\r\n var evt = error && error.evt;\r\n if (!isError(error)) {\r\n error = error[strError] || evt || error;\r\n }\r\n _self[_DYN_TYPE_NAME /* @min:%2etypeName */] = dataSanitizeString(logger, _getErrorType(error)) || strNotSpecified;\r\n _self[_DYN_MESSAGE /* @min:%2emessage */] = dataSanitizeMessage(logger, _formatMessage(exception || error, _self[_DYN_TYPE_NAME /* @min:%2etypeName */])) || strNotSpecified;\r\n var stack = exception[strStackDetails] || _getStackFromErrorObj(exception);\r\n _self[_DYN_PARSED_STACK /* @min:%2eparsedStack */] = _parseStack(stack);\r\n // after parsedStack is inited, iterate over each frame object, sanitize its assembly field\r\n if (isArray(_self[_DYN_PARSED_STACK /* @min:%2eparsedStack */])) {\r\n arrMap(_self[_DYN_PARSED_STACK /* @min:%2eparsedStack */], function (frame) { return frame[_DYN_ASSEMBLY /* @min:%2eassembly */] = dataSanitizeString(logger, frame[_DYN_ASSEMBLY /* @min:%2eassembly */]); });\r\n }\r\n _self[strStack] = dataSanitizeException(logger, _formatStackTrace(stack));\r\n _self.hasFullStack = isArray(_self.parsedStack) && _self.parsedStack[_DYN_LENGTH /* @min:%2elength */] > 0;\r\n if (properties) {\r\n properties[_DYN_TYPE_NAME /* @min:%2etypeName */] = properties[_DYN_TYPE_NAME /* @min:%2etypeName */] || _self[_DYN_TYPE_NAME /* @min:%2etypeName */];\r\n }\r\n }\r\n else {\r\n _self[_DYN_TYPE_NAME /* @min:%2etypeName */] = exception[_DYN_TYPE_NAME /* @min:%2etypeName */];\r\n _self[_DYN_MESSAGE /* @min:%2emessage */] = exception[_DYN_MESSAGE /* @min:%2emessage */];\r\n _self[strStack] = exception[strStack];\r\n _self[_DYN_PARSED_STACK /* @min:%2eparsedStack */] = exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */] || [];\r\n _self[_DYN_HAS_FULL_STACK /* @min:%2ehasFullStack */] = exception[_DYN_HAS_FULL_STACK /* @min:%2ehasFullStack */];\r\n }\r\n }\r\n _ExceptionDetails.prototype.toInterface = function () {\r\n var _a;\r\n var _self = this;\r\n var parsedStack = _self[_DYN_PARSED_STACK /* @min:%2eparsedStack */] instanceof Array\r\n && arrMap(_self[_DYN_PARSED_STACK /* @min:%2eparsedStack */], function (frame) { return frame.toInterface(); });\r\n var exceptionDetailsInterface = (_a = {\r\n id: _self.id,\r\n outerId: _self.outerId,\r\n typeName: _self[_DYN_TYPE_NAME /* @min:%2etypeName */],\r\n message: _self[_DYN_MESSAGE /* @min:%2emessage */],\r\n hasFullStack: _self[_DYN_HAS_FULL_STACK /* @min:%2ehasFullStack */],\r\n stack: _self[strStack]\r\n },\r\n _a[_DYN_PARSED_STACK /* @min:parsedStack */] = parsedStack || undefined,\r\n _a);\r\n return exceptionDetailsInterface;\r\n };\r\n _ExceptionDetails.CreateFromInterface = function (logger, exception) {\r\n var parsedStack = (exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */] instanceof Array\r\n && arrMap(exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */], function (frame) { return _StackFrame[_DYN__CREATE_FROM_INTERFA1 /* @min:%2eCreateFromInterface */](frame); }))\r\n || exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */];\r\n var exceptionDetails = new _ExceptionDetails(logger, __assign(__assign({}, exception), { parsedStack: parsedStack }));\r\n return exceptionDetails;\r\n };\r\n return _ExceptionDetails;\r\n}());\r\nexport { _ExceptionDetails };\r\nvar _StackFrame = /** @class */ (function () {\r\n function _StackFrame(sourceFrame, level) {\r\n this.aiDataContract = {\r\n level: 1 /* FieldType.Required */,\r\n method: 1 /* FieldType.Required */,\r\n assembly: 0 /* FieldType.Default */,\r\n fileName: 0 /* FieldType.Default */,\r\n line: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self[_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */] = 0;\r\n // Not converting this to isString() as typescript uses this logic to \"understand\" the different\r\n // types for the 2 different code paths\r\n if (typeof sourceFrame === \"string\") {\r\n var frame = sourceFrame;\r\n _self[_DYN_LEVEL /* @min:%2elevel */] = level;\r\n _self[_DYN_METHOD /* @min:%2emethod */] = NoMethod;\r\n _self[_DYN_ASSEMBLY /* @min:%2eassembly */] = strTrim(frame);\r\n _self[_DYN_FILE_NAME /* @min:%2efileName */] = \"\";\r\n _self[_DYN_LINE /* @min:%2eline */] = 0;\r\n var matches = frame.match(_StackFrame.regex);\r\n if (matches && matches[_DYN_LENGTH /* @min:%2elength */] >= 5) {\r\n _self[_DYN_METHOD /* @min:%2emethod */] = strTrim(matches[2]) || _self[_DYN_METHOD /* @min:%2emethod */];\r\n _self[_DYN_FILE_NAME /* @min:%2efileName */] = strTrim(matches[4]);\r\n _self[_DYN_LINE /* @min:%2eline */] = parseInt(matches[5]) || 0;\r\n }\r\n }\r\n else {\r\n _self[_DYN_LEVEL /* @min:%2elevel */] = sourceFrame[_DYN_LEVEL /* @min:%2elevel */];\r\n _self[_DYN_METHOD /* @min:%2emethod */] = sourceFrame[_DYN_METHOD /* @min:%2emethod */];\r\n _self[_DYN_ASSEMBLY /* @min:%2eassembly */] = sourceFrame[_DYN_ASSEMBLY /* @min:%2eassembly */];\r\n _self[_DYN_FILE_NAME /* @min:%2efileName */] = sourceFrame[_DYN_FILE_NAME /* @min:%2efileName */];\r\n _self[_DYN_LINE /* @min:%2eline */] = sourceFrame[_DYN_LINE /* @min:%2eline */];\r\n _self[_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */] = 0;\r\n }\r\n _self.sizeInBytes += _self.method[_DYN_LENGTH /* @min:%2elength */];\r\n _self.sizeInBytes += _self.fileName[_DYN_LENGTH /* @min:%2elength */];\r\n _self.sizeInBytes += _self.assembly[_DYN_LENGTH /* @min:%2elength */];\r\n // todo: these might need to be removed depending on how the back-end settles on their size calculation\r\n _self[_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */] += _StackFrame.baseSize;\r\n _self.sizeInBytes += _self.level.toString()[_DYN_LENGTH /* @min:%2elength */];\r\n _self.sizeInBytes += _self.line.toString()[_DYN_LENGTH /* @min:%2elength */];\r\n }\r\n _StackFrame.CreateFromInterface = function (frame) {\r\n return new _StackFrame(frame, null /* level is available in frame interface */);\r\n };\r\n _StackFrame.prototype.toInterface = function () {\r\n var _self = this;\r\n return {\r\n level: _self[_DYN_LEVEL /* @min:%2elevel */],\r\n method: _self[_DYN_METHOD /* @min:%2emethod */],\r\n assembly: _self[_DYN_ASSEMBLY /* @min:%2eassembly */],\r\n fileName: _self[_DYN_FILE_NAME /* @min:%2efileName */],\r\n line: _self[_DYN_LINE /* @min:%2eline */]\r\n };\r\n };\r\n // regex to match stack frames from ie/chrome/ff\r\n // methodName=$2, fileName=$4, lineNo=$5, column=$6\r\n _StackFrame.regex = /^([\\s]+at)?[\\s]{0,50}([^\\@\\()]+?)[\\s]{0,50}(\\@|\\()([^\\(\\n]+):([0-9]+):([0-9]+)(\\)?)$/;\r\n _StackFrame.baseSize = 58; // '{\"method\":\"\",\"level\":,\"assembly\":\"\",\"fileName\":\"\",\"line\":}'.length\r\n return _StackFrame;\r\n}());\r\nexport { _StackFrame };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { _DYN_COUNT, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\r\nimport { DataPoint } from \"./Common/DataPoint\";\r\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString } from \"./Common/DataSanitizer\";\r\nvar Metric = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the MetricTelemetry object\r\n */\r\n function Metric(logger, name, value, count, min, max, stdDev, properties, measurements) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n metrics: 1 /* FieldType.Required */,\r\n properties: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n var dataPoint = new DataPoint();\r\n dataPoint[_DYN_COUNT /* @min:%2ecount */] = count > 0 ? count : undefined;\r\n dataPoint.max = isNaN(max) || max === null ? undefined : max;\r\n dataPoint.min = isNaN(min) || min === null ? undefined : min;\r\n dataPoint[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n dataPoint.value = value;\r\n dataPoint.stdDev = isNaN(stdDev) || stdDev === null ? undefined : stdDev;\r\n _self.metrics = [dataPoint];\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n }\r\n Metric.envelopeType = \"Microsoft.ApplicationInsights.{0}.Metric\";\r\n Metric.dataType = \"MetricData\";\r\n return Metric;\r\n}());\r\nexport { Metric };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { msToTimeSpan } from \"../HelperFuncs\";\r\nimport { _DYN_DURATION, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\r\nimport { dataSanitizeId, dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from \"./Common/DataSanitizer\";\r\nvar PageView = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the PageEventTelemetry object\r\n */\r\n function PageView(logger, name, url, durationMs, properties, measurements, id) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n name: 0 /* FieldType.Default */,\r\n url: 0 /* FieldType.Default */,\r\n duration: 0 /* FieldType.Default */,\r\n properties: 0 /* FieldType.Default */,\r\n measurements: 0 /* FieldType.Default */,\r\n id: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n _self.id = dataSanitizeId(logger, id);\r\n _self.url = dataSanitizeUrl(logger, url);\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n if (!isNaN(durationMs)) {\r\n _self[_DYN_DURATION /* @min:%2eduration */] = msToTimeSpan(durationMs);\r\n }\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n }\r\n PageView.envelopeType = \"Microsoft.ApplicationInsights.{0}.Pageview\";\r\n PageView.dataType = \"PageviewData\";\r\n return PageView;\r\n}());\r\nexport { PageView };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { _DYN_DURATION, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES, _DYN_RECEIVED_RESPONSE } from \"../__DynamicConstants\";\r\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from \"./Common/DataSanitizer\";\r\nvar PageViewPerformance = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the PageEventTelemetry object\r\n */\r\n function PageViewPerformance(logger, name, url, unused, properties, measurements, cs4BaseData) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n name: 0 /* FieldType.Default */,\r\n url: 0 /* FieldType.Default */,\r\n duration: 0 /* FieldType.Default */,\r\n perfTotal: 0 /* FieldType.Default */,\r\n networkConnect: 0 /* FieldType.Default */,\r\n sentRequest: 0 /* FieldType.Default */,\r\n receivedResponse: 0 /* FieldType.Default */,\r\n domProcessing: 0 /* FieldType.Default */,\r\n properties: 0 /* FieldType.Default */,\r\n measurements: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n _self.url = dataSanitizeUrl(logger, url);\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n if (cs4BaseData) {\r\n _self.domProcessing = cs4BaseData.domProcessing;\r\n _self[_DYN_DURATION /* @min:%2eduration */] = cs4BaseData[_DYN_DURATION /* @min:%2eduration */];\r\n _self.networkConnect = cs4BaseData.networkConnect;\r\n _self.perfTotal = cs4BaseData.perfTotal;\r\n _self[_DYN_RECEIVED_RESPONSE /* @min:%2ereceivedResponse */] = cs4BaseData[_DYN_RECEIVED_RESPONSE /* @min:%2ereceivedResponse */];\r\n _self.sentRequest = cs4BaseData.sentRequest;\r\n }\r\n }\r\n PageViewPerformance.envelopeType = \"Microsoft.ApplicationInsights.{0}.PageviewPerformance\";\r\n PageViewPerformance.dataType = \"PageviewPerformanceData\";\r\n return PageViewPerformance;\r\n}());\r\nexport { PageViewPerformance };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { msToTimeSpan } from \"../HelperFuncs\";\r\nimport { AjaxHelperParseDependencyPath } from \"../Util\";\r\nimport { _DYN_DURATION, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\r\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from \"./Common/DataSanitizer\";\r\nvar RemoteDependencyData = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the RemoteDependencyData object\r\n */\r\n function RemoteDependencyData(logger, id, absoluteUrl, commandName, value, success, resultCode, method, requestAPI, correlationContext, properties, measurements) {\r\n if (requestAPI === void 0) { requestAPI = \"Ajax\"; }\r\n this.aiDataContract = {\r\n id: 1 /* FieldType.Required */,\r\n ver: 1 /* FieldType.Required */,\r\n name: 0 /* FieldType.Default */,\r\n resultCode: 0 /* FieldType.Default */,\r\n duration: 0 /* FieldType.Default */,\r\n success: 0 /* FieldType.Default */,\r\n data: 0 /* FieldType.Default */,\r\n target: 0 /* FieldType.Default */,\r\n type: 0 /* FieldType.Default */,\r\n properties: 0 /* FieldType.Default */,\r\n measurements: 0 /* FieldType.Default */,\r\n kind: 0 /* FieldType.Default */,\r\n value: 0 /* FieldType.Default */,\r\n count: 0 /* FieldType.Default */,\r\n min: 0 /* FieldType.Default */,\r\n max: 0 /* FieldType.Default */,\r\n stdDev: 0 /* FieldType.Default */,\r\n dependencyKind: 0 /* FieldType.Default */,\r\n dependencySource: 0 /* FieldType.Default */,\r\n commandName: 0 /* FieldType.Default */,\r\n dependencyTypeName: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n _self.id = id;\r\n _self[_DYN_DURATION /* @min:%2eduration */] = msToTimeSpan(value);\r\n _self.success = success;\r\n _self.resultCode = resultCode + \"\";\r\n _self.type = dataSanitizeString(logger, requestAPI);\r\n var dependencyFields = AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName);\r\n _self.data = dataSanitizeUrl(logger, commandName) || dependencyFields.data; // get a value from hosturl if commandName not available\r\n _self.target = dataSanitizeString(logger, dependencyFields.target);\r\n if (correlationContext) {\r\n _self.target = \"\".concat(_self.target, \" | \").concat(correlationContext);\r\n }\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, dependencyFields[_DYN_NAME /* @min:%2ename */]);\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n }\r\n RemoteDependencyData.envelopeType = \"Microsoft.ApplicationInsights.{0}.RemoteDependency\";\r\n RemoteDependencyData.dataType = \"RemoteDependencyData\";\r\n return RemoteDependencyData;\r\n}());\r\nexport { RemoteDependencyData };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { _DYN_MEASUREMENTS, _DYN_MESSAGE, _DYN_PROPERTIES, _DYN_SEVERITY_LEVEL } from \"../__DynamicConstants\";\r\nimport { dataSanitizeMeasurements, dataSanitizeMessage, dataSanitizeProperties } from \"./Common/DataSanitizer\";\r\nvar Trace = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the TraceTelemetry object\r\n */\r\n function Trace(logger, message, severityLevel, properties, measurements) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n message: 1 /* FieldType.Required */,\r\n severityLevel: 0 /* FieldType.Default */,\r\n properties: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n message = message || strNotSpecified;\r\n _self[_DYN_MESSAGE /* @min:%2emessage */] = dataSanitizeMessage(logger, message);\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n if (severityLevel) {\r\n _self[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */] = severityLevel;\r\n }\r\n }\r\n Trace.envelopeType = \"Microsoft.ApplicationInsights.{0}.Message\";\r\n Trace.dataType = \"MessageData\";\r\n return Trace;\r\n}());\r\nexport { Trace };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { isNullOrUndefined, objForEachKey, throwError, toISOString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { strIkey, strNotSpecified } from \"./Constants\";\r\nimport { dataSanitizeString } from \"./Telemetry/Common/DataSanitizer\";\r\nimport { _DYN_NAME } from \"./__DynamicConstants\";\r\n/**\r\n * Create a telemetry item that the 1DS channel understands\r\n * @param item domain specific properties; part B\r\n * @param baseType telemetry item type. ie PageViewData\r\n * @param envelopeName name of the envelope. ie Microsoft.ApplicationInsights..PageView\r\n * @param customProperties user defined custom properties; part C\r\n * @param systemProperties system properties that are added to the context; part A\r\n * @returns ITelemetryItem that is sent to channel\r\n */\r\nexport function createTelemetryItem(item, baseType, envelopeName, logger, customProperties, systemProperties) {\r\n var _a;\r\n envelopeName = dataSanitizeString(logger, envelopeName) || strNotSpecified;\r\n if (isNullOrUndefined(item) ||\r\n isNullOrUndefined(baseType) ||\r\n isNullOrUndefined(envelopeName)) {\r\n throwError(\"Input doesn't contain all required fields\");\r\n }\r\n var iKey = \"\";\r\n if (item[strIkey]) {\r\n iKey = item[strIkey];\r\n delete item[strIkey];\r\n }\r\n var telemetryItem = (_a = {},\r\n _a[_DYN_NAME /* @min:name */] = envelopeName,\r\n _a.time = toISOString(new Date()),\r\n _a.iKey = iKey,\r\n _a.ext = systemProperties ? systemProperties : {},\r\n _a.tags = [],\r\n _a.data = {},\r\n _a.baseType = baseType,\r\n _a.baseData = item // Part B\r\n ,\r\n _a);\r\n // Part C\r\n if (!isNullOrUndefined(customProperties)) {\r\n objForEachKey(customProperties, function (prop, value) {\r\n telemetryItem.data[prop] = value;\r\n });\r\n }\r\n return telemetryItem;\r\n}\r\nvar TelemetryItemCreator = /** @class */ (function () {\r\n function TelemetryItemCreator() {\r\n }\r\n /**\r\n * Create a telemetry item that the 1DS channel understands\r\n * @param item domain specific properties; part B\r\n * @param baseType telemetry item type. ie PageViewData\r\n * @param envelopeName name of the envelope. ie Microsoft.ApplicationInsights..PageView\r\n * @param customProperties user defined custom properties; part C\r\n * @param systemProperties system properties that are added to the context; part A\r\n * @returns ITelemetryItem that is sent to channel\r\n */\r\n TelemetryItemCreator.create = createTelemetryItem;\r\n return TelemetryItemCreator;\r\n}());\r\nexport { TelemetryItemCreator };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { _throwInternal, arrForEach, arrIndexOf, isNotNullOrUndefined, isNullOrUndefined, randomValue, safeGetLogger, strTrim } from \"@microsoft/applicationinsights-core-js\";\r\nimport { utlCanUseLocalStorage, utlGetLocalStorage, utlSetLocalStorage } from \"./StorageHelperFuncs\";\r\nimport { _DYN_COUNT, _DYN_DATE, _DYN_DAYS_OF_MONTH, _DYN_DISABLED, _DYN_GET_UTCDATE, _DYN_INTERVAL, _DYN_LENGTH, _DYN_MESSAGE, _DYN_PRE_TRIGGER_DATE, _DYN_STRINGIFY } from \"./__DynamicConstants\";\r\nvar THROTTLE_STORAGE_PREFIX = \"appInsightsThrottle\";\r\nvar ThrottleMgr = /** @class */ (function () {\r\n function ThrottleMgr(throttleMgr, core, namePrefix) {\r\n var _self = this;\r\n var _canUseLocalStorage;\r\n var _logger;\r\n var _config;\r\n var _localStorageName;\r\n var _localStorageObj;\r\n var _isTriggered; //_isTriggered is to make sure that we only trigger throttle once a day\r\n var _namePrefix;\r\n var _queue;\r\n var _isReady = false;\r\n var _isSpecificDaysGiven = false;\r\n _initConfig();\r\n _self.getConfig = function () {\r\n return _config;\r\n };\r\n /**\r\n * Check if it is the correct day to send message.\r\n * If _isTriggered is true, even if canThrottle returns true, message will not be sent,\r\n * because we only allow triggering sendMessage() once a day.\r\n * @returns if the current date is the valid date to send message\r\n */\r\n _self.canThrottle = function () {\r\n return _canThrottle(_config, _canUseLocalStorage, _localStorageObj);\r\n };\r\n /**\r\n * Check if throttle is triggered on current day(UTC)\r\n * if canThrottle returns false, isTriggered will return false\r\n * @returns if throttle is triggered on current day(UTC)\r\n */\r\n _self.isTriggered = function () {\r\n return _isTriggered;\r\n };\r\n /**\r\n * Before isReady set to true, all message will be stored in queue.\r\n * Message will only be sent out after isReady set to true.\r\n * Initial and default value: false\r\n * @returns isReady state\r\n */\r\n _self.isReady = function () {\r\n return _isReady;\r\n };\r\n /**\r\n * Flush all message in queue with isReady state set to true.\r\n * @returns if message queue is flushed\r\n */\r\n _self.flush = function () {\r\n try {\r\n if (_isReady && _queue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(_queue, function (item) {\r\n _self.sendMessage(item.msgID, item[_DYN_MESSAGE /* @min:%2emessage */], item.severity);\r\n });\r\n return true;\r\n }\r\n }\r\n catch (err) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n };\r\n /**\r\n * Set isReady State\r\n * if isReady set to true, message queue will be flushed automatically.\r\n * @param isReady isReady State\r\n * @returns if message queue is flushed\r\n */\r\n _self.onReadyState = function (isReady) {\r\n _isReady = isNullOrUndefined(isReady) ? true : isReady;\r\n return _self.flush();\r\n };\r\n _self.sendMessage = function (msgID, message, severity) {\r\n if (_isReady) {\r\n var isSampledIn = _canSampledIn();\r\n if (!isSampledIn) {\r\n return;\r\n }\r\n var canThrottle = _canThrottle(_config, _canUseLocalStorage, _localStorageObj);\r\n var throttled = false;\r\n var number = 0;\r\n try {\r\n if (canThrottle && !_isTriggered) {\r\n number = Math.min(_config.limit.maxSendNumber, _localStorageObj[_DYN_COUNT /* @min:%2ecount */] + 1);\r\n _localStorageObj[_DYN_COUNT /* @min:%2ecount */] = 0;\r\n throttled = true;\r\n _isTriggered = true;\r\n _localStorageObj[_DYN_PRE_TRIGGER_DATE /* @min:%2epreTriggerDate */] = new Date();\r\n }\r\n else {\r\n _isTriggered = canThrottle;\r\n _localStorageObj[_DYN_COUNT /* @min:%2ecount */] += 1;\r\n }\r\n _resetLocalStorage(_logger, _localStorageName, _localStorageObj);\r\n for (var i = 0; i < number; i++) {\r\n _sendMessage(msgID, _logger, message, severity);\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return {\r\n isThrottled: throttled,\r\n throttleNum: number\r\n };\r\n }\r\n else {\r\n _queue.push({\r\n msgID: msgID,\r\n message: message,\r\n severity: severity\r\n });\r\n }\r\n return null;\r\n };\r\n function _initConfig() {\r\n var _a, _b;\r\n _canUseLocalStorage = utlCanUseLocalStorage();\r\n _logger = safeGetLogger(core);\r\n _isTriggered = false;\r\n _namePrefix = isNotNullOrUndefined(namePrefix) ? namePrefix : \"\";\r\n _queue = [];\r\n var configMgr = throttleMgr;\r\n _config = {};\r\n _config[_DYN_DISABLED /* @min:%2edisabled */] = !!configMgr[_DYN_DISABLED /* @min:%2edisabled */];\r\n _config.msgKey = configMgr.msgKey;\r\n var configInterval = configMgr[_DYN_INTERVAL /* @min:%2einterval */] || {};\r\n _isSpecificDaysGiven = (configInterval === null || configInterval === void 0 ? void 0 : configInterval.daysOfMonth) && (configInterval === null || configInterval === void 0 ? void 0 : configInterval.daysOfMonth[_DYN_LENGTH /* @min:%2elength */]) > 0;\r\n _config[_DYN_INTERVAL /* @min:%2einterval */] = _getIntervalConfig(configInterval);\r\n var limit = {\r\n samplingRate: ((_a = configMgr.limit) === null || _a === void 0 ? void 0 : _a.samplingRate) || 100,\r\n // dafault: every time sent only 1 event\r\n maxSendNumber: ((_b = configMgr.limit) === null || _b === void 0 ? void 0 : _b.maxSendNumber) || 1\r\n };\r\n _config.limit = limit;\r\n _localStorageName = _getLocalStorageName(_config.msgKey, _namePrefix);\r\n if (_canUseLocalStorage && _localStorageName) {\r\n _localStorageObj = _getLocalStorageObj(utlGetLocalStorage(_logger, _localStorageName), _logger, _localStorageName);\r\n }\r\n if (_localStorageObj) {\r\n _isTriggered = _isTriggeredOnCurDate(_localStorageObj[_DYN_PRE_TRIGGER_DATE /* @min:%2epreTriggerDate */]);\r\n }\r\n }\r\n function _getIntervalConfig(interval) {\r\n interval = interval || {};\r\n var monthInterval = interval === null || interval === void 0 ? void 0 : interval.monthInterval;\r\n var dayInterval = interval === null || interval === void 0 ? void 0 : interval.dayInterval;\r\n // default: send data every 3 month each year\r\n if (isNullOrUndefined(monthInterval) && isNullOrUndefined(dayInterval)) {\r\n interval.monthInterval = 3;\r\n if (!_isSpecificDaysGiven) {\r\n // default: send data on 28th\r\n interval[_DYN_DAYS_OF_MONTH /* @min:%2edaysOfMonth */] = [28];\r\n _isSpecificDaysGiven = true;\r\n }\r\n }\r\n interval = {\r\n // dafault: sent every three months\r\n monthInterval: interval === null || interval === void 0 ? void 0 : interval.monthInterval,\r\n dayInterval: interval === null || interval === void 0 ? void 0 : interval.dayInterval,\r\n daysOfMonth: interval === null || interval === void 0 ? void 0 : interval.daysOfMonth\r\n };\r\n return interval;\r\n }\r\n function _canThrottle(config, canUseLocalStorage, localStorageObj) {\r\n if (!config[_DYN_DISABLED /* @min:%2edisabled */] && canUseLocalStorage && isNotNullOrUndefined(localStorageObj)) {\r\n var curDate = _getThrottleDate();\r\n var date = localStorageObj[_DYN_DATE /* @min:%2edate */];\r\n var interval = config[_DYN_INTERVAL /* @min:%2einterval */];\r\n var monthCheck = 1;\r\n if (interval === null || interval === void 0 ? void 0 : interval.monthInterval) {\r\n var monthExpand = (curDate.getUTCFullYear() - date.getUTCFullYear()) * 12 + curDate.getUTCMonth() - date.getUTCMonth();\r\n monthCheck = _checkInterval(interval.monthInterval, 0, monthExpand);\r\n }\r\n var dayCheck = 1;\r\n if (_isSpecificDaysGiven) {\r\n dayCheck = arrIndexOf(interval[_DYN_DAYS_OF_MONTH /* @min:%2edaysOfMonth */], curDate[_DYN_GET_UTCDATE /* @min:%2egetUTCDate */]());\r\n }\r\n else if (interval === null || interval === void 0 ? void 0 : interval.dayInterval) {\r\n var daySpan = Math.floor((curDate.getTime() - date.getTime()) / 86400000);\r\n dayCheck = _checkInterval(interval.dayInterval, 0, daySpan);\r\n }\r\n return monthCheck >= 0 && dayCheck >= 0;\r\n }\r\n return false;\r\n }\r\n function _getLocalStorageName(msgKey, prefix) {\r\n var fix = isNotNullOrUndefined(prefix) ? prefix : \"\";\r\n if (msgKey) {\r\n return THROTTLE_STORAGE_PREFIX + fix + \"-\" + msgKey;\r\n }\r\n return null;\r\n }\r\n // returns if throttle is triggered on current Date\r\n function _isTriggeredOnCurDate(preTriggerDate) {\r\n try {\r\n if (preTriggerDate) {\r\n var curDate = new Date();\r\n return preTriggerDate.getUTCFullYear() === curDate.getUTCFullYear() &&\r\n preTriggerDate.getUTCMonth() === curDate.getUTCMonth() &&\r\n preTriggerDate[_DYN_GET_UTCDATE /* @min:%2egetUTCDate */]() === curDate[_DYN_GET_UTCDATE /* @min:%2egetUTCDate */]();\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n }\r\n // transfer local storage string value to object that identifies start date, current count and preTriggerDate\r\n function _getLocalStorageObj(value, logger, storageName) {\r\n try {\r\n var storageObj = {\r\n date: _getThrottleDate(),\r\n count: 0\r\n };\r\n if (value) {\r\n var obj = JSON.parse(value);\r\n return {\r\n date: _getThrottleDate(obj[_DYN_DATE /* @min:%2edate */]) || storageObj[_DYN_DATE /* @min:%2edate */],\r\n count: obj[_DYN_COUNT /* @min:%2ecount */] || storageObj[_DYN_COUNT /* @min:%2ecount */],\r\n preTriggerDate: obj.preTriggerDate ? _getThrottleDate(obj[_DYN_PRE_TRIGGER_DATE /* @min:%2epreTriggerDate */]) : undefined\r\n };\r\n }\r\n else {\r\n _resetLocalStorage(logger, storageName, storageObj);\r\n return storageObj;\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n }\r\n // if datestr is not defined, current date will be returned\r\n function _getThrottleDate(dateStr) {\r\n // if new Date() can't be created through the provided dateStr, null will be returned.\r\n try {\r\n if (dateStr) {\r\n var date = new Date(dateStr);\r\n //make sure it is a valid Date Object\r\n if (!isNaN(date.getDate())) {\r\n return date;\r\n }\r\n }\r\n else {\r\n return new Date();\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n }\r\n function _resetLocalStorage(logger, storageName, obj) {\r\n try {\r\n return utlSetLocalStorage(logger, storageName, strTrim(JSON[_DYN_STRINGIFY /* @min:%2estringify */](obj)));\r\n }\r\n catch (e) {\r\n // // eslint-disable-next-line no-empty\r\n }\r\n return false;\r\n }\r\n function _checkInterval(interval, start, current) {\r\n // count from start year\r\n return (current >= start) && (current - start) % interval == 0 ? Math.floor((current - start) / interval) + 1 : -1;\r\n }\r\n function _sendMessage(msgID, logger, message, severity) {\r\n _throwInternal(logger, severity || 1 /* eLoggingSeverity.CRITICAL */, msgID, message);\r\n }\r\n // NOTE: config.limit.samplingRate is set to 4 decimal places,\r\n // so config.limit.samplingRate = 1 means 0.0001%\r\n function _canSampledIn() {\r\n return randomValue(1000000) <= _config.limit.samplingRate;\r\n }\r\n }\r\n return ThrottleMgr;\r\n}());\r\nexport { ThrottleMgr };\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { getDocument, isString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_LENGTH, _DYN_PATHNAME, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\r\nvar _document = getDocument() || {};\r\nvar _htmlAnchorIdx = 0;\r\n// Use an array of temporary values as it's possible for multiple calls to parseUrl() will be called with different URLs\r\n// Using a cache size of 5 for now as it current depth usage is at least 2, so adding a minor buffer to handle future updates\r\nvar _htmlAnchorElement = [null, null, null, null, null];\r\nexport function urlParseUrl(url) {\r\n var anchorIdx = _htmlAnchorIdx;\r\n var anchorCache = _htmlAnchorElement;\r\n var tempAnchor = anchorCache[anchorIdx];\r\n if (!_document.createElement) {\r\n // Always create the temp instance if createElement is not available\r\n tempAnchor = { host: urlParseHost(url, true) };\r\n }\r\n else if (!anchorCache[anchorIdx]) {\r\n // Create and cache the unattached anchor instance\r\n tempAnchor = anchorCache[anchorIdx] = _document.createElement(\"a\");\r\n }\r\n tempAnchor.href = url;\r\n // Move the cache index forward\r\n anchorIdx++;\r\n if (anchorIdx >= anchorCache[_DYN_LENGTH /* @min:%2elength */]) {\r\n anchorIdx = 0;\r\n }\r\n _htmlAnchorIdx = anchorIdx;\r\n return tempAnchor;\r\n}\r\nexport function urlGetAbsoluteUrl(url) {\r\n var result;\r\n var a = urlParseUrl(url);\r\n if (a) {\r\n result = a.href;\r\n }\r\n return result;\r\n}\r\nexport function urlGetPathName(url) {\r\n var result;\r\n var a = urlParseUrl(url);\r\n if (a) {\r\n result = a[_DYN_PATHNAME /* @min:%2epathname */];\r\n }\r\n return result;\r\n}\r\nexport function urlGetCompleteUrl(method, absoluteUrl) {\r\n if (method) {\r\n return method.toUpperCase() + \" \" + absoluteUrl;\r\n }\r\n return absoluteUrl;\r\n}\r\n// Fallback method to grab host from url if document.createElement method is not available\r\nexport function urlParseHost(url, inclPort) {\r\n var fullHost = urlParseFullHost(url, inclPort) || \"\";\r\n if (fullHost) {\r\n var match = fullHost.match(/(www\\d{0,5}\\.)?([^\\/:]{1,256})(:\\d{1,20})?/i);\r\n if (match != null && match[_DYN_LENGTH /* @min:%2elength */] > 3 && isString(match[2]) && match[2][_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n return match[2] + (match[3] || \"\");\r\n }\r\n }\r\n return fullHost;\r\n}\r\nexport function urlParseFullHost(url, inclPort) {\r\n var result = null;\r\n if (url) {\r\n var match = url.match(/(\\w{1,150}):\\/\\/([^\\/:]{1,256})(:\\d{1,20})?/i);\r\n if (match != null && match[_DYN_LENGTH /* @min:%2elength */] > 2 && isString(match[2]) && match[2][_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n result = match[2] || \"\";\r\n if (inclPort && match[_DYN_LENGTH /* @min:%2elength */] > 2) {\r\n var protocol = (match[1] || \"\")[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n var port = match[3] || \"\";\r\n // IE includes the standard port so pass it off if it's the same as the protocol\r\n if (protocol === \"http\" && port === \":80\") {\r\n port = \"\";\r\n }\r\n else if (protocol === \"https\" && port === \":443\") {\r\n port = \"\";\r\n }\r\n result += port;\r\n }\r\n }\r\n }\r\n return result;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { arrForEach, arrIndexOf, attachEvent, canUseCookies as coreCanUseCookies, dateNow, deleteCookie as coreDeleteCookie, disableCookies as coreDisableCookies, dumpObj, generateW3CId, getCookie as coreGetCookie, getExceptionName as coreGetExceptionName, getIEVersion, getPerformance, isArray, isBeaconsSupported, isDate, isError, isNullOrUndefined, isValidSpanId, isValidTraceId, newId, random32, setCookie as coreSetCookie, strTrim, toISOString, uaDisallowsSameSiteNone } from \"@microsoft/applicationinsights-core-js\";\r\nimport { DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, strNotSpecified } from \"./Constants\";\r\nimport { createDomEvent } from \"./DomHelperFuncs\";\r\nimport { getExtensionByName, isCrossOriginError, msToTimeSpan, stringToBoolOrDefault } from \"./HelperFuncs\";\r\nimport { RequestHeaders } from \"./RequestResponseHeaders\";\r\nimport { utlCanUseLocalStorage, utlCanUseSessionStorage, utlDisableStorage, utlGetLocalStorage, utlGetSessionStorage, utlGetSessionStorageKeys, utlRemoveSessionStorage, utlRemoveStorage, utlSetLocalStorage, utlSetSessionStorage } from \"./StorageHelperFuncs\";\r\nimport { dataSanitizeString } from \"./Telemetry/Common/DataSanitizer\";\r\nimport { urlGetAbsoluteUrl, urlGetCompleteUrl, urlGetPathName, urlParseFullHost, urlParseHost, urlParseUrl } from \"./UrlHelperFuncs\";\r\nimport { _DYN_CORRELATION_HEADER_E0, _DYN_INDEX_OF, _DYN_LENGTH, _DYN_NAME, _DYN_PATHNAME, _DYN_SPLIT, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\r\n// listing only non-geo specific locations\r\nvar _internalEndpoints = [\r\n DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH,\r\n \"https://breeze.aimon.applicationinsights.io\" + DEFAULT_BREEZE_PATH,\r\n \"https://dc-int.services.visualstudio.com\" + DEFAULT_BREEZE_PATH\r\n];\r\nexport function isInternalApplicationInsightsEndpoint(endpointUrl) {\r\n return arrIndexOf(_internalEndpoints, endpointUrl[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]()) !== -1;\r\n}\r\nexport var Util = {\r\n NotSpecified: strNotSpecified,\r\n createDomEvent: createDomEvent,\r\n disableStorage: utlDisableStorage,\r\n isInternalApplicationInsightsEndpoint: isInternalApplicationInsightsEndpoint,\r\n canUseLocalStorage: utlCanUseLocalStorage,\r\n getStorage: utlGetLocalStorage,\r\n setStorage: utlSetLocalStorage,\r\n removeStorage: utlRemoveStorage,\r\n canUseSessionStorage: utlCanUseSessionStorage,\r\n getSessionStorageKeys: utlGetSessionStorageKeys,\r\n getSessionStorage: utlGetSessionStorage,\r\n setSessionStorage: utlSetSessionStorage,\r\n removeSessionStorage: utlRemoveSessionStorage,\r\n disableCookies: coreDisableCookies,\r\n canUseCookies: coreCanUseCookies,\r\n disallowsSameSiteNone: uaDisallowsSameSiteNone,\r\n setCookie: coreSetCookie,\r\n stringToBoolOrDefault: stringToBoolOrDefault,\r\n getCookie: coreGetCookie,\r\n deleteCookie: coreDeleteCookie,\r\n trim: strTrim,\r\n newId: newId,\r\n random32: function () {\r\n return random32(true);\r\n },\r\n generateW3CId: generateW3CId,\r\n isArray: isArray,\r\n isError: isError,\r\n isDate: isDate,\r\n toISOStringForIE8: toISOString,\r\n getIEVersion: getIEVersion,\r\n msToTimeSpan: msToTimeSpan,\r\n isCrossOriginError: isCrossOriginError,\r\n dump: dumpObj,\r\n getExceptionName: coreGetExceptionName,\r\n addEventHandler: attachEvent,\r\n IsBeaconApiSupported: isBeaconsSupported,\r\n getExtension: getExtensionByName\r\n};\r\nexport var UrlHelper = {\r\n parseUrl: urlParseUrl,\r\n getAbsoluteUrl: urlGetAbsoluteUrl,\r\n getPathName: urlGetPathName,\r\n getCompleteUrl: urlGetCompleteUrl,\r\n parseHost: urlParseHost,\r\n parseFullHost: urlParseFullHost\r\n};\r\nexport var CorrelationIdHelper = {\r\n correlationIdPrefix: \"cid-v1:\",\r\n /**\r\n * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers.\r\n * Headers are always included if the current domain matches the request domain. If they do not match (CORS),\r\n * they are regex-ed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included.\r\n * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must\r\n * manually supply domains to include correlation headers on. Else, no headers will be included at all.\r\n */\r\n canIncludeCorrelationHeader: function (config, requestUrl, currentHost) {\r\n if (!requestUrl || (config && config.disableCorrelationHeaders)) {\r\n return false;\r\n }\r\n if (config && config[_DYN_CORRELATION_HEADER_E0 /* @min:%2ecorrelationHeaderExcludePatterns */]) {\r\n for (var i = 0; i < config.correlationHeaderExcludePatterns[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n if (config[_DYN_CORRELATION_HEADER_E0 /* @min:%2ecorrelationHeaderExcludePatterns */][i].test(requestUrl)) {\r\n return false;\r\n }\r\n }\r\n }\r\n var requestHost = urlParseUrl(requestUrl).host[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n if (requestHost && (requestHost[_DYN_INDEX_OF /* @min:%2eindexOf */](\":443\") !== -1 || requestHost[_DYN_INDEX_OF /* @min:%2eindexOf */](\":80\") !== -1)) {\r\n // [Bug #1260] IE can include the port even for http and https URLs so if present\r\n // try and parse it to remove if it matches the default protocol port\r\n requestHost = (urlParseFullHost(requestUrl, true) || \"\")[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n }\r\n if ((!config || !config.enableCorsCorrelation) && (requestHost && requestHost !== currentHost)) {\r\n return false;\r\n }\r\n var includedDomains = config && config.correlationHeaderDomains;\r\n if (includedDomains) {\r\n var matchExists_1;\r\n arrForEach(includedDomains, function (domain) {\r\n var regex = new RegExp(domain.toLowerCase().replace(/\\\\/g, \"\\\\\\\\\").replace(/\\./g, \"\\\\.\").replace(/\\*/g, \".*\"));\r\n matchExists_1 = matchExists_1 || regex.test(requestHost);\r\n });\r\n if (!matchExists_1) {\r\n return false;\r\n }\r\n }\r\n var excludedDomains = config && config.correlationHeaderExcludedDomains;\r\n if (!excludedDomains || excludedDomains[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n return true;\r\n }\r\n for (var i = 0; i < excludedDomains[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n var regex = new RegExp(excludedDomains[i].toLowerCase().replace(/\\\\/g, \"\\\\\\\\\").replace(/\\./g, \"\\\\.\").replace(/\\*/g, \".*\"));\r\n if (regex.test(requestHost)) {\r\n return false;\r\n }\r\n }\r\n // if we don't know anything about the requestHost, require the user to use included/excludedDomains.\r\n // Previously we always returned false for a falsy requestHost\r\n return requestHost && requestHost[_DYN_LENGTH /* @min:%2elength */] > 0;\r\n },\r\n /**\r\n * Combines target appId and target role name from response header.\r\n */\r\n getCorrelationContext: function (responseHeader) {\r\n if (responseHeader) {\r\n var correlationId = CorrelationIdHelper.getCorrelationContextValue(responseHeader, RequestHeaders[1 /* eRequestHeaders.requestContextTargetKey */]);\r\n if (correlationId && correlationId !== CorrelationIdHelper.correlationIdPrefix) {\r\n return correlationId;\r\n }\r\n }\r\n },\r\n /**\r\n * Gets key from correlation response header\r\n */\r\n getCorrelationContextValue: function (responseHeader, key) {\r\n if (responseHeader) {\r\n var keyValues = responseHeader[_DYN_SPLIT /* @min:%2esplit */](\",\");\r\n for (var i = 0; i < keyValues[_DYN_LENGTH /* @min:%2elength */]; ++i) {\r\n var keyValue = keyValues[i][_DYN_SPLIT /* @min:%2esplit */](\"=\");\r\n if (keyValue[_DYN_LENGTH /* @min:%2elength */] === 2 && keyValue[0] === key) {\r\n return keyValue[1];\r\n }\r\n }\r\n }\r\n }\r\n};\r\nexport function AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName) {\r\n var target, name = commandName, data = commandName;\r\n if (absoluteUrl && absoluteUrl[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var parsedUrl = urlParseUrl(absoluteUrl);\r\n target = parsedUrl.host;\r\n if (!name) {\r\n if (parsedUrl[_DYN_PATHNAME /* @min:%2epathname */] != null) {\r\n var pathName = (parsedUrl.pathname[_DYN_LENGTH /* @min:%2elength */] === 0) ? \"/\" : parsedUrl[_DYN_PATHNAME /* @min:%2epathname */];\r\n if (pathName.charAt(0) !== \"/\") {\r\n pathName = \"/\" + pathName;\r\n }\r\n data = parsedUrl[_DYN_PATHNAME /* @min:%2epathname */];\r\n name = dataSanitizeString(logger, method ? method + \" \" + pathName : pathName);\r\n }\r\n else {\r\n name = dataSanitizeString(logger, absoluteUrl);\r\n }\r\n }\r\n }\r\n else {\r\n target = commandName;\r\n name = commandName;\r\n }\r\n return {\r\n target: target,\r\n name: name,\r\n data: data\r\n };\r\n}\r\nexport function dateTimeUtilsNow() {\r\n // returns the window or webworker performance object\r\n var perf = getPerformance();\r\n if (perf && perf.now && perf.timing) {\r\n var now = perf.now() + perf.timing.navigationStart;\r\n // Known issue with IE where this calculation can be negative, so if it is then ignore and fallback\r\n if (now > 0) {\r\n return now;\r\n }\r\n }\r\n return dateNow();\r\n}\r\nexport function dateTimeUtilsDuration(start, end) {\r\n var result = null;\r\n if (start !== 0 && end !== 0 && !isNullOrUndefined(start) && !isNullOrUndefined(end)) {\r\n result = end - start;\r\n }\r\n return result;\r\n}\r\n/**\r\n * A utility class that helps getting time related parameters\r\n */\r\nexport var DateTimeUtils = {\r\n Now: dateTimeUtilsNow,\r\n GetDuration: dateTimeUtilsDuration\r\n};\r\n/**\r\n * Creates a IDistributedTraceContext from an optional telemetryTrace\r\n * @param telemetryTrace - The telemetryTrace instance that is being wrapped\r\n * @param parentCtx - An optional parent distributed trace instance, almost always undefined as this scenario is only used in the case of multiple property handlers.\r\n * @returns A new IDistributedTraceContext instance that is backed by the telemetryTrace or temporary object\r\n */\r\nexport function createDistributedTraceContextFromTrace(telemetryTrace, parentCtx) {\r\n var trace = telemetryTrace || {};\r\n return {\r\n getName: function () {\r\n return trace[_DYN_NAME /* @min:%2ename */];\r\n },\r\n setName: function (newValue) {\r\n parentCtx && parentCtx.setName(newValue);\r\n trace[_DYN_NAME /* @min:%2ename */] = newValue;\r\n },\r\n getTraceId: function () {\r\n return trace.traceID;\r\n },\r\n setTraceId: function (newValue) {\r\n parentCtx && parentCtx.setTraceId(newValue);\r\n if (isValidTraceId(newValue)) {\r\n trace.traceID = newValue;\r\n }\r\n },\r\n getSpanId: function () {\r\n return trace.parentID;\r\n },\r\n setSpanId: function (newValue) {\r\n parentCtx && parentCtx.setSpanId(newValue);\r\n if (isValidSpanId(newValue)) {\r\n trace.parentID = newValue;\r\n }\r\n },\r\n getTraceFlags: function () {\r\n return trace.traceFlags;\r\n },\r\n setTraceFlags: function (newTraceFlags) {\r\n parentCtx && parentCtx.setTraceFlags(newTraceFlags);\r\n trace.traceFlags = newTraceFlags;\r\n }\r\n };\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_SPLIT = \"split\"; // Count: 6\r\nexport var _DYN_LENGTH = \"length\"; // Count: 41\r\nexport var _DYN_TO_LOWER_CASE = \"toLowerCase\"; // Count: 6\r\nexport var _DYN_INGESTIONENDPOINT = \"ingestionendpoint\"; // Count: 4\r\nexport var _DYN_TO_STRING = \"toString\"; // Count: 12\r\nexport var _DYN_REMOVE_ITEM = \"removeItem\"; // Count: 3\r\nexport var _DYN_NAME = \"name\"; // Count: 11\r\nexport var _DYN_MESSAGE = \"message\"; // Count: 10\r\nexport var _DYN_COUNT = \"count\"; // Count: 8\r\nexport var _DYN_PRE_TRIGGER_DATE = \"preTriggerDate\"; // Count: 4\r\nexport var _DYN_DISABLED = \"disabled\"; // Count: 3\r\nexport var _DYN_INTERVAL = \"interval\"; // Count: 3\r\nexport var _DYN_DAYS_OF_MONTH = \"daysOfMonth\"; // Count: 3\r\nexport var _DYN_DATE = \"date\"; // Count: 5\r\nexport var _DYN_GET_UTCDATE = \"getUTCDate\"; // Count: 3\r\nexport var _DYN_STRINGIFY = \"stringify\"; // Count: 4\r\nexport var _DYN_PATHNAME = \"pathname\"; // Count: 4\r\nexport var _DYN_CORRELATION_HEADER_E0 = \"correlationHeaderExcludePatterns\"; // Count: 2\r\nexport var _DYN_INDEX_OF = \"indexOf\"; // Count: 4\r\nexport var _DYN_EXTENSION_CONFIG = \"extensionConfig\"; // Count: 4\r\nexport var _DYN_EXCEPTIONS = \"exceptions\"; // Count: 6\r\nexport var _DYN_PARSED_STACK = \"parsedStack\"; // Count: 13\r\nexport var _DYN_PROPERTIES = \"properties\"; // Count: 9\r\nexport var _DYN_MEASUREMENTS = \"measurements\"; // Count: 9\r\nexport var _DYN_SIZE_IN_BYTES = \"sizeInBytes\"; // Count: 11\r\nexport var _DYN_TYPE_NAME = \"typeName\"; // Count: 11\r\nexport var _DYN_SEVERITY_LEVEL = \"severityLevel\"; // Count: 5\r\nexport var _DYN_PROBLEM_GROUP = \"problemGroup\"; // Count: 3\r\nexport var _DYN_IS_MANUAL = \"isManual\"; // Count: 3\r\nexport var _DYN__CREATE_FROM_INTERFA1 = \"CreateFromInterface\"; // Count: 2\r\nexport var _DYN_ASSEMBLY = \"assembly\"; // Count: 7\r\nexport var _DYN_HAS_FULL_STACK = \"hasFullStack\"; // Count: 6\r\nexport var _DYN_LEVEL = \"level\"; // Count: 5\r\nexport var _DYN_METHOD = \"method\"; // Count: 7\r\nexport var _DYN_FILE_NAME = \"fileName\"; // Count: 6\r\nexport var _DYN_LINE = \"line\"; // Count: 6\r\nexport var _DYN_DURATION = \"duration\"; // Count: 4\r\nexport var _DYN_RECEIVED_RESPONSE = \"receivedResponse\"; // Count: 2\r\nexport var _DYN_SUBSTRING = \"substring\"; // Count: 6\r\nexport var _DYN_SANITIZE_KEY_AND_ADD2 = \"sanitizeKeyAndAddUniqueness\"; // Count: 2\r\nexport var _DYN_SANITIZE_EXCEPTION = \"sanitizeException\"; // Count: 2\r\nexport var _DYN_SANITIZE_PROPERTIES = \"sanitizeProperties\"; // Count: 2\r\nexport var _DYN_SANITIZE_MEASUREMENT3 = \"sanitizeMeasurements\"; // Count: 2\r\n","/*\n * Application Insights JavaScript SDK - Common, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n// Licensed under the\r\nexport { Util, CorrelationIdHelper, DateTimeUtils, dateTimeUtilsNow, dateTimeUtilsDuration, UrlHelper, isInternalApplicationInsightsEndpoint, createDistributedTraceContextFromTrace } from \"./Util\";\r\nexport { ThrottleMgr } from \"./ThrottleMgr\";\r\nexport { parseConnectionString, ConnectionStringParser } from \"./ConnectionStringParser\";\r\nexport { RequestHeaders } from \"./RequestResponseHeaders\";\r\nexport { DisabledPropertyName, ProcessLegacy, SampleRate, HttpMethod, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, strNotSpecified } from \"./Constants\";\r\nexport { Envelope } from \"./Telemetry/Common/Envelope\";\r\nexport { Event } from \"./Telemetry/Event\";\r\nexport { Exception } from \"./Telemetry/Exception\";\r\nexport { Metric } from \"./Telemetry/Metric\";\r\nexport { PageView } from \"./Telemetry/PageView\";\r\nexport { RemoteDependencyData } from \"./Telemetry/RemoteDependencyData\";\r\nexport { Trace } from \"./Telemetry/Trace\";\r\nexport { PageViewPerformance } from \"./Telemetry/PageViewPerformance\";\r\nexport { Data } from \"./Telemetry/Common/Data\";\r\nexport { SeverityLevel } from \"./Interfaces/Contracts/SeverityLevel\";\r\nexport { ConfigurationManager } from \"./Interfaces/IConfig\";\r\nexport { ContextTagKeys } from \"./Interfaces/Contracts/ContextTagKeys\";\r\nexport { DataSanitizer, dataSanitizeKeyAndAddUniqueness, dataSanitizeKey, dataSanitizeString, dataSanitizeUrl, dataSanitizeMessage, dataSanitizeException, dataSanitizeProperties, dataSanitizeMeasurements, dataSanitizeId, dataSanitizeInput, dsPadNumber } from \"./Telemetry/Common/DataSanitizer\";\r\nexport { TelemetryItemCreator, createTelemetryItem } from \"./TelemetryItemCreator\";\r\nexport { CtxTagKeys, Extensions } from \"./Interfaces/PartAExtensions\";\r\nexport { DistributedTracingModes } from \"./Enums\";\r\nexport { stringToBoolOrDefault, msToTimeSpan, getExtensionByName, isCrossOriginError } from \"./HelperFuncs\";\r\nexport { isBeaconsSupported as isBeaconApiSupported, createTraceParent, parseTraceParent, isValidTraceId, isValidSpanId, isValidTraceParent, isSampledFlag, formatTraceParent, findW3cTraceParent } from \"@microsoft/applicationinsights-core-js\";\r\nexport { createDomEvent } from \"./DomHelperFuncs\";\r\nexport { utlDisableStorage, utlEnableStorage, utlCanUseLocalStorage, utlGetLocalStorage, utlSetLocalStorage, utlRemoveStorage, utlCanUseSessionStorage, utlGetSessionStorageKeys, utlGetSessionStorage, utlSetSessionStorage, utlRemoveSessionStorage } from \"./StorageHelperFuncs\";\r\nexport { urlParseUrl, urlGetAbsoluteUrl, urlGetPathName, urlGetCompleteUrl, urlParseHost, urlParseFullHost } from \"./UrlHelperFuncs\";\r\nexport var PropertiesPluginIdentifier = \"AppInsightsPropertiesPlugin\";\r\nexport var BreezeChannelIdentifier = \"AppInsightsChannelPlugin\";\r\nexport var AnalyticsPluginIdentifier = \"ApplicationInsightsAnalytics\";\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { objForEachKey, deepFreeze } from \"../JavaScriptSDK/HelperFuncs\";\r\n/**\r\n * Create an enum style object which has both the key => value and value => key mappings\r\n * @param values - The values to populate on the new object\r\n * @returns\r\n */\r\nexport function createEnumStyle(values) {\r\n var enumClass = {};\r\n objForEachKey(values, function (field, value) {\r\n enumClass[field] = value;\r\n enumClass[value] = field;\r\n });\r\n return deepFreeze(enumClass);\r\n}\r\n/**\r\n * Create a 2 index map that maps an enum's key as both the key and value, X[\"key\"] => \"key\" and X[0] => \"keyof 0\".\r\n * @param values - The values to populate on the new object\r\n * @returns\r\n */\r\nexport function createEnumMap(values) {\r\n var mapClass = {};\r\n objForEachKey(values, function (field, value) {\r\n mapClass[field] = field;\r\n mapClass[value] = field;\r\n });\r\n return deepFreeze(mapClass);\r\n}\r\n/**\r\n * Create a 2 index map that maps an enum's key and value to the defined map value, X[\"key\"] => mapValue and X[0] => mapValue.\r\n * Generic values\r\n * - E = the const enum type (typeof eRequestHeaders);\r\n * - V = Identifies the valid values for the keys, this should include both the enum numeric and string key of the type. The\r\n * resulting \"Value\" of each entry identifies the valid values withing the assignments.\r\n * @param values - The values to populate on the new object\r\n * @returns\r\n */\r\nexport function createValueMap(values) {\r\n var mapClass = {};\r\n objForEachKey(values, function (field, value) {\r\n mapClass[field] = value[1];\r\n mapClass[value[0]] = value[1];\r\n });\r\n return deepFreeze(mapClass);\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\r\n\r\n\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { _DYN_GET_NOTIFY_MGR, _DYN_INITIALIZE, _DYN_NAME } from \"../__DynamicConstants\";\r\nimport { BaseCore } from \"./BaseCore\";\r\nimport { DiagnosticLogger } from \"./DiagnosticLogger\";\r\nimport { isNullOrUndefined, throwError } from \"./HelperFuncs\";\r\nimport { STR_EVENTS_DISCARDED, STR_GET_PERF_MGR } from \"./InternalConstants\";\r\nimport { NotificationManager } from \"./NotificationManager\";\r\nimport { doPerf } from \"./PerfManager\";\r\nvar AppInsightsCore = /** @class */ (function (_super) {\r\n __extends(AppInsightsCore, _super);\r\n function AppInsightsCore() {\r\n var _this = _super.call(this) || this;\r\n dynamicProto(AppInsightsCore, _this, function (_self, _base) {\r\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, extensions, logger, notificationManager) {\r\n _base[_DYN_INITIALIZE /* @min:%2einitialize */](config, extensions, logger || new DiagnosticLogger(config), notificationManager || new NotificationManager(config));\r\n };\r\n _self.track = function (telemetryItem) {\r\n doPerf(_self[STR_GET_PERF_MGR /* @min:%2egetPerfMgr */](), function () { return \"AppInsightsCore:track\"; }, function () {\r\n if (telemetryItem === null) {\r\n _notifyInvalidEvent(telemetryItem);\r\n // throw error\r\n throwError(\"Invalid telemetry item\");\r\n }\r\n // do basic validation before sending it through the pipeline\r\n _validateTelemetryItem(telemetryItem);\r\n _base.track(telemetryItem);\r\n }, function () { return ({ item: telemetryItem }); }, !(telemetryItem.sync));\r\n };\r\n function _validateTelemetryItem(telemetryItem) {\r\n if (isNullOrUndefined(telemetryItem[_DYN_NAME /* @min:%2ename */])) {\r\n _notifyInvalidEvent(telemetryItem);\r\n throwError(\"telemetry name required\");\r\n }\r\n }\r\n function _notifyInvalidEvent(telemetryItem) {\r\n var manager = _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */]();\r\n if (manager) {\r\n manager[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */]([telemetryItem], 2 /* eEventsDiscardedReason.InvalidEvent */);\r\n }\r\n }\r\n });\r\n return _this;\r\n }\r\n// Removed Stub for AppInsightsCore.prototype.initialize.\r\n// Removed Stub for AppInsightsCore.prototype.track.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n AppInsightsCore.__ieDyn=1;\n\n return AppInsightsCore;\r\n}(BaseCore));\r\nexport { AppInsightsCore };\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n\"use strict\";\r\nimport { __spreadArrayFn as __spreadArray } from \"@microsoft/applicationinsights-shims\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { objCreateFn } from \"@microsoft/applicationinsights-shims\";\r\nimport { _DYN_ADD_NOTIFICATION_LIS1, _DYN_CONFIG, _DYN_FLUSH, _DYN_GET_NOTIFY_MGR, _DYN_GET_PLUGIN, _DYN_GET_PROCESS_TEL_CONT0, _DYN_IDENTIFIER, _DYN_INITIALIZE, _DYN_INSTRUMENTATION_KEY, _DYN_IS_ASYNC, _DYN_IS_INITIALIZED, _DYN_LENGTH, _DYN_LOGGER, _DYN_MESSAGE, _DYN_MESSAGE_ID, _DYN_NAME, _DYN_ON_COMPLETE, _DYN_PROCESS_NEXT, _DYN_PUSH, _DYN_REMOVE_NOTIFICATION_2, _DYN_SET_ENABLED, _DYN_SPLICE, _DYN_STOP_POLLING_INTERNA3, _DYN_TEARDOWN, _DYN_TIME, _DYN__EXTENSIONS } from \"../__DynamicConstants\";\r\nimport { ChannelControllerPriority, createChannelControllerPlugin, createChannelQueues } from \"./ChannelController\";\r\nimport { createCookieMgr } from \"./CookieMgr\";\r\nimport { createUniqueNamespace } from \"./DataCacheHelper\";\r\nimport { getDebugListener } from \"./DbgExtensionUtils\";\r\nimport { DiagnosticLogger, _InternalLogMessage, _throwInternal, _warnToConsole } from \"./DiagnosticLogger\";\r\nimport { arrForEach, arrIndexOf, getCfgValue, getSetValue, isFunction, isNullOrUndefined, objExtend, objFreeze, proxyFunctionAs, proxyFunctions, throwError, toISOString } from \"./HelperFuncs\";\r\nimport { STR_CHANNELS, STR_CORE, STR_CREATE_PERF_MGR, STR_DISABLED, STR_EVENTS_DISCARDED, STR_EVENTS_SEND_REQUEST, STR_EVENTS_SENT, STR_EXTENSIONS, STR_EXTENSION_CONFIG, STR_GET_PERF_MGR, STR_PRIORITY } from \"./InternalConstants\";\r\nimport { PerfManager, getGblPerfMgr } from \"./PerfManager\";\r\nimport { createProcessTelemetryContext, createProcessTelemetryUnloadContext, createProcessTelemetryUpdateContext, createTelemetryProxyChain } from \"./ProcessTelemetryContext\";\r\nimport { _getPluginState, createDistributedTraceContext, initializePlugins, sortPlugins } from \"./TelemetryHelpers\";\r\nimport { TelemetryInitializerPlugin } from \"./TelemetryInitializerPlugin\";\r\nimport { createUnloadHandlerContainer } from \"./UnloadHandlerContainer\";\r\nvar strValidationError = \"Plugins must provide initialize method\";\r\nvar strNotificationManager = \"_notificationManager\";\r\nvar strSdkUnloadingError = \"SDK is still unloading...\";\r\nvar strSdkNotInitialized = \"SDK is not initialized\";\r\n// const strPluginUnloadFailed = \"Failed to unload plugin\";\r\nvar defaultInitConfig = {\r\n // Have the Diagnostic Logger default to log critical errors to the console\r\n loggingLevelConsole: 1 /* eLoggingSeverity.CRITICAL */\r\n};\r\n/**\r\n * Helper to create the default performance manager\r\n * @param core\r\n * @param notificationMgr\r\n */\r\nfunction _createPerfManager(core, notificationMgr) {\r\n return new PerfManager(notificationMgr);\r\n}\r\nfunction _validateExtensions(logger, channelPriority, allExtensions) {\r\n var _a;\r\n // Concat all available extensions\r\n var coreExtensions = [];\r\n // Check if any two extensions have the same priority, then warn to console\r\n // And extract the local extensions from the\r\n var extPriorities = {};\r\n // Extension validation\r\n arrForEach(allExtensions, function (ext) {\r\n // Check for ext.initialize\r\n if (isNullOrUndefined(ext) || isNullOrUndefined(ext[_DYN_INITIALIZE /* @min:%2einitialize */])) {\r\n throwError(strValidationError);\r\n }\r\n var extPriority = ext[STR_PRIORITY /* @min:%2epriority */];\r\n var identifier = ext[_DYN_IDENTIFIER /* @min:%2eidentifier */];\r\n if (ext && extPriority) {\r\n if (!isNullOrUndefined(extPriorities[extPriority])) {\r\n _warnToConsole(logger, \"Two extensions have same priority #\" + extPriority + \" - \" + extPriorities[extPriority] + \", \" + identifier);\r\n }\r\n else {\r\n // set a value\r\n extPriorities[extPriority] = identifier;\r\n }\r\n }\r\n // Split extensions to core and channelController\r\n if (!extPriority || extPriority < channelPriority) {\r\n // Add to core extension that will be managed by BaseCore\r\n coreExtensions[_DYN_PUSH /* @min:%2epush */](ext);\r\n }\r\n });\r\n return _a = {\r\n all: allExtensions\r\n },\r\n _a[STR_CORE /* @min:core */] = coreExtensions,\r\n _a;\r\n}\r\nfunction _isPluginPresent(thePlugin, plugins) {\r\n var exists = false;\r\n arrForEach(plugins, function (plugin) {\r\n if (plugin === thePlugin) {\r\n exists = true;\r\n return -1;\r\n }\r\n });\r\n return exists;\r\n}\r\nfunction _createDummyNotificationManager() {\r\n var _a;\r\n return objCreateFn((_a = {},\r\n _a[_DYN_ADD_NOTIFICATION_LIS1 /* @min:addNotificationListener */] = function (listener) { },\r\n _a[_DYN_REMOVE_NOTIFICATION_2 /* @min:removeNotificationListener */] = function (listener) { },\r\n _a[STR_EVENTS_SENT /* @min:eventsSent */] = function (events) { },\r\n _a[STR_EVENTS_DISCARDED /* @min:eventsDiscarded */] = function (events, reason) { },\r\n _a[STR_EVENTS_SEND_REQUEST /* @min:eventsSendRequest */] = function (sendReason, isAsync) { },\r\n _a));\r\n}\r\nvar BaseCore = /** @class */ (function () {\r\n function BaseCore() {\r\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\r\n var _config;\r\n var _isInitialized;\r\n var _eventQueue;\r\n var _notificationManager;\r\n var _perfManager;\r\n var _cfgPerfManager;\r\n var _cookieManager;\r\n var _pluginChain;\r\n var _configExtensions;\r\n var _coreExtensions;\r\n var _channelControl;\r\n var _channelConfig;\r\n var _channelQueue;\r\n var _isUnloading;\r\n var _telemetryInitializerPlugin;\r\n var _internalLogsEventName;\r\n var _evtNamespace;\r\n var _unloadHandlers;\r\n var _debugListener;\r\n var _traceCtx;\r\n /**\r\n * Internal log poller\r\n */\r\n var _internalLogPoller = 0;\r\n dynamicProto(BaseCore, this, function (_self) {\r\n // Set the default values (also called during teardown)\r\n _initDefaults();\r\n _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = function () { return _isInitialized; };\r\n // Creating the self.initialize = ()\r\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, extensions, logger, notificationManager) {\r\n if (_isUnloading) {\r\n throwError(strSdkUnloadingError);\r\n }\r\n // Make sure core is only initialized once\r\n if (_self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]()) {\r\n throwError(\"Core should not be initialized more than once\");\r\n }\r\n _config = config || {};\r\n _self[_DYN_CONFIG /* @min:%2econfig */] = _config;\r\n if (isNullOrUndefined(config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */])) {\r\n throwError(\"Please provide instrumentation key\");\r\n }\r\n _notificationManager = notificationManager;\r\n // For backward compatibility only\r\n _self[strNotificationManager] = notificationManager;\r\n _initDebugListener();\r\n _initPerfManager();\r\n // add notification to the extensions in the config so other plugins can access it\r\n _initExtConfig();\r\n if (logger) {\r\n _self[_DYN_LOGGER /* @min:%2elogger */] = logger;\r\n }\r\n var cfgExtensions = getSetValue(_config, STR_EXTENSIONS, []);\r\n // Extension validation\r\n _configExtensions = [];\r\n _configExtensions[_DYN_PUSH /* @min:%2epush */].apply(_configExtensions, __spreadArray(__spreadArray([], extensions, false), cfgExtensions, false));\r\n _channelConfig = getSetValue(_config, STR_CHANNELS, []);\r\n _initPluginChain(null);\r\n if (!_channelQueue || _channelQueue[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n throwError(\"No \" + STR_CHANNELS + \" available\");\r\n }\r\n _isInitialized = true;\r\n _self.releaseQueue();\r\n };\r\n _self.getTransmissionControls = function () {\r\n var controls = [];\r\n if (_channelQueue) {\r\n arrForEach(_channelQueue, function (channels) {\r\n controls[_DYN_PUSH /* @min:%2epush */](channels.queue);\r\n });\r\n }\r\n return objFreeze(controls);\r\n };\r\n _self.track = function (telemetryItem) {\r\n // setup default iKey if not passed in\r\n telemetryItem.iKey = telemetryItem.iKey || _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];\r\n // add default timestamp if not passed in\r\n telemetryItem[_DYN_TIME /* @min:%2etime */] = telemetryItem[_DYN_TIME /* @min:%2etime */] || toISOString(new Date());\r\n // Common Schema 4.0\r\n telemetryItem.ver = telemetryItem.ver || \"4.0\";\r\n if (!_isUnloading && _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]()) {\r\n // Process the telemetry plugin chain\r\n _createTelCtx()[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](telemetryItem);\r\n }\r\n else {\r\n // Queue events until all extensions are initialized\r\n _eventQueue[_DYN_PUSH /* @min:%2epush */](telemetryItem);\r\n }\r\n };\r\n _self[_DYN_GET_PROCESS_TEL_CONT0 /* @min:%2egetProcessTelContext */] = _createTelCtx;\r\n _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */] = function () {\r\n if (!_notificationManager) {\r\n // Create Dummy notification manager\r\n _notificationManager = _createDummyNotificationManager();\r\n // For backward compatibility only\r\n _self[strNotificationManager] = _notificationManager;\r\n }\r\n return _notificationManager;\r\n };\r\n /**\r\n * Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.\r\n * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be\r\n * called.\r\n * @param {INotificationListener} listener - An INotificationListener object.\r\n */\r\n _self[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */] = function (listener) {\r\n if (_notificationManager) {\r\n _notificationManager[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */](listener);\r\n }\r\n };\r\n /**\r\n * Removes all instances of the listener.\r\n * @param {INotificationListener} listener - INotificationListener to remove.\r\n */\r\n _self[_DYN_REMOVE_NOTIFICATION_2 /* @min:%2eremoveNotificationListener */] = function (listener) {\r\n if (_notificationManager) {\r\n _notificationManager[_DYN_REMOVE_NOTIFICATION_2 /* @min:%2eremoveNotificationListener */](listener);\r\n }\r\n };\r\n _self.getCookieMgr = function () {\r\n if (!_cookieManager) {\r\n _cookieManager = createCookieMgr(_config, _self[_DYN_LOGGER /* @min:%2elogger */]);\r\n }\r\n return _cookieManager;\r\n };\r\n _self.setCookieMgr = function (cookieMgr) {\r\n _cookieManager = cookieMgr;\r\n };\r\n _self[STR_GET_PERF_MGR /* @min:%2egetPerfMgr */] = function () {\r\n if (!_perfManager && !_cfgPerfManager) {\r\n if (getCfgValue(_config.enablePerfMgr)) {\r\n var createPerfMgr = getCfgValue(_config[STR_CREATE_PERF_MGR /* @min:%2ecreatePerfMgr */]);\r\n if (isFunction(createPerfMgr)) {\r\n _cfgPerfManager = createPerfMgr(_self, _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */]());\r\n }\r\n }\r\n }\r\n return _perfManager || _cfgPerfManager || getGblPerfMgr();\r\n };\r\n _self.setPerfMgr = function (perfMgr) {\r\n _perfManager = perfMgr;\r\n };\r\n _self.eventCnt = function () {\r\n return _eventQueue[_DYN_LENGTH /* @min:%2elength */];\r\n };\r\n _self.releaseQueue = function () {\r\n if (_isInitialized && _eventQueue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var eventQueue = _eventQueue;\r\n _eventQueue = [];\r\n arrForEach(eventQueue, function (event) {\r\n _createTelCtx()[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](event);\r\n });\r\n }\r\n };\r\n /**\r\n * Periodically check logger.queue for log messages to be flushed\r\n */\r\n _self.pollInternalLogs = function (eventName) {\r\n _internalLogsEventName = eventName || null;\r\n var interval = getCfgValue(_config.diagnosticLogInterval);\r\n if (!interval || !(interval > 0)) {\r\n interval = 10000;\r\n }\r\n if (_internalLogPoller) {\r\n clearInterval(_internalLogPoller);\r\n }\r\n _internalLogPoller = setInterval(function () {\r\n _flushInternalLogs();\r\n }, interval);\r\n return _internalLogPoller;\r\n };\r\n /**\r\n * Stop polling log messages from logger.queue\r\n */\r\n _self[_DYN_STOP_POLLING_INTERNA3 /* @min:%2estopPollingInternalLogs */] = function () {\r\n if (_internalLogPoller) {\r\n clearInterval(_internalLogPoller);\r\n _internalLogPoller = 0;\r\n _flushInternalLogs();\r\n }\r\n };\r\n // Add addTelemetryInitializer\r\n proxyFunctions(_self, function () { return _telemetryInitializerPlugin; }, [\"addTelemetryInitializer\"]);\r\n _self.unload = function (isAsync, unloadComplete, cbTimeout) {\r\n var _a;\r\n if (isAsync === void 0) { isAsync = true; }\r\n if (!_isInitialized) {\r\n // The SDK is not initialized\r\n throwError(strSdkNotInitialized);\r\n }\r\n // Check if the SDK still unloading so throw\r\n if (_isUnloading) {\r\n // The SDK is already unloading\r\n throwError(strSdkUnloadingError);\r\n }\r\n var unloadState = (_a = {\r\n reason: 50 /* TelemetryUnloadReason.SdkUnload */\r\n },\r\n _a[_DYN_IS_ASYNC /* @min:isAsync */] = isAsync,\r\n _a.flushComplete = false,\r\n _a);\r\n var processUnloadCtx = createProcessTelemetryUnloadContext(_getPluginChain(), _self);\r\n processUnloadCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](function () {\r\n _initDefaults();\r\n unloadComplete && unloadComplete(unloadState);\r\n }, _self);\r\n function _doUnload(flushComplete) {\r\n unloadState.flushComplete = flushComplete;\r\n _isUnloading = true;\r\n // Run all of the unload handlers first (before unloading the plugins)\r\n _unloadHandlers.run(processUnloadCtx, unloadState);\r\n // Stop polling the internal logs\r\n _self[_DYN_STOP_POLLING_INTERNA3 /* @min:%2estopPollingInternalLogs */]();\r\n // Start unloading the components, from this point onwards the SDK should be considered to be in an unstable state\r\n processUnloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\r\n }\r\n if (!_flushChannels(isAsync, _doUnload, 6 /* SendRequestReason.SdkUnload */, cbTimeout)) {\r\n _doUnload(false);\r\n }\r\n };\r\n _self[_DYN_GET_PLUGIN /* @min:%2egetPlugin */] = _getPlugin;\r\n _self.addPlugin = function (plugin, replaceExisting, isAsync, addCb) {\r\n if (!plugin) {\r\n addCb && addCb(false);\r\n _logOrThrowError(strValidationError);\r\n return;\r\n }\r\n var existingPlugin = _getPlugin(plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */]);\r\n if (existingPlugin && !replaceExisting) {\r\n addCb && addCb(false);\r\n _logOrThrowError(\"Plugin [\" + plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] + \"] is already loaded!\");\r\n return;\r\n }\r\n var updateState = {\r\n reason: 16 /* TelemetryUpdateReason.PluginAdded */\r\n };\r\n function _addPlugin(removed) {\r\n _configExtensions[_DYN_PUSH /* @min:%2epush */](plugin);\r\n updateState.added = [plugin];\r\n // Re-Initialize the plugin chain\r\n _initPluginChain(updateState);\r\n addCb && addCb(true);\r\n }\r\n if (existingPlugin) {\r\n var removedPlugins_1 = [existingPlugin.plugin];\r\n var unloadState = {\r\n reason: 2 /* TelemetryUnloadReason.PluginReplace */,\r\n isAsync: !!isAsync\r\n };\r\n _removePlugins(removedPlugins_1, unloadState, function (removed) {\r\n if (!removed) {\r\n // Previous plugin was successfully removed or was not installed\r\n addCb && addCb(false);\r\n }\r\n else {\r\n updateState.removed = removedPlugins_1;\r\n updateState.reason |= 32 /* TelemetryUpdateReason.PluginRemoved */;\r\n _addPlugin(true);\r\n }\r\n });\r\n }\r\n else {\r\n _addPlugin(false);\r\n }\r\n };\r\n _self.evtNamespace = function () {\r\n return _evtNamespace;\r\n };\r\n _self[_DYN_FLUSH /* @min:%2eflush */] = _flushChannels;\r\n _self.getTraceCtx = function (createNew) {\r\n if (!_traceCtx) {\r\n _traceCtx = createDistributedTraceContext();\r\n }\r\n return _traceCtx;\r\n };\r\n _self.setTraceCtx = function (traceCtx) {\r\n _traceCtx = traceCtx || null;\r\n };\r\n // Create the addUnloadCb\r\n proxyFunctionAs(_self, \"addUnloadCb\", function () { return _unloadHandlers; }, \"add\");\r\n function _initDefaults() {\r\n _isInitialized = false;\r\n // Use a default logger so initialization errors are not dropped on the floor with full logging\r\n _config = objExtend(true, {}, defaultInitConfig);\r\n _self[_DYN_CONFIG /* @min:%2econfig */] = _config;\r\n _self[_DYN_LOGGER /* @min:%2elogger */] = new DiagnosticLogger(_config);\r\n _self[_DYN__EXTENSIONS /* @min:%2e_extensions */] = [];\r\n _telemetryInitializerPlugin = new TelemetryInitializerPlugin();\r\n _eventQueue = [];\r\n _notificationManager = null;\r\n _perfManager = null;\r\n _cfgPerfManager = null;\r\n _cookieManager = null;\r\n _pluginChain = null;\r\n _coreExtensions = null;\r\n _configExtensions = [];\r\n _channelControl = null;\r\n _channelConfig = null;\r\n _channelQueue = null;\r\n _isUnloading = false;\r\n _internalLogsEventName = null;\r\n _evtNamespace = createUniqueNamespace(\"AIBaseCore\", true);\r\n _unloadHandlers = createUnloadHandlerContainer();\r\n _traceCtx = null;\r\n }\r\n function _createTelCtx() {\r\n return createProcessTelemetryContext(_getPluginChain(), _config, _self);\r\n }\r\n // Initialize or Re-initialize the plugins\r\n function _initPluginChain(updateState) {\r\n // Extension validation\r\n var theExtensions = _validateExtensions(_self[_DYN_LOGGER /* @min:%2elogger */], ChannelControllerPriority, _configExtensions);\r\n _coreExtensions = theExtensions[STR_CORE /* @min:%2ecore */];\r\n _pluginChain = null;\r\n // Sort the complete set of extensions by priority\r\n var allExtensions = theExtensions.all;\r\n // Initialize the Channel Queues and the channel plugins first\r\n _channelQueue = objFreeze(createChannelQueues(_channelConfig, allExtensions, _self));\r\n if (_channelControl) {\r\n // During add / remove of a plugin this may get called again, so don't re-add if already present\r\n // But we also want the controller as the last, so remove if already present\r\n // And reusing the existing instance, just in case an installed plugin has a reference and\r\n // is using it.\r\n var idx = arrIndexOf(allExtensions, _channelControl);\r\n if (idx !== -1) {\r\n allExtensions[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\r\n }\r\n idx = arrIndexOf(_coreExtensions, _channelControl);\r\n if (idx !== -1) {\r\n _coreExtensions[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\r\n }\r\n _channelControl._setQueue(_channelQueue);\r\n }\r\n else {\r\n _channelControl = createChannelControllerPlugin(_channelQueue, _self);\r\n }\r\n // Add on \"channelController\" as the last \"plugin\"\r\n allExtensions[_DYN_PUSH /* @min:%2epush */](_channelControl);\r\n _coreExtensions[_DYN_PUSH /* @min:%2epush */](_channelControl);\r\n // Required to allow plugins to call core.getPlugin() during their own initialization\r\n _self[_DYN__EXTENSIONS /* @min:%2e_extensions */] = sortPlugins(allExtensions);\r\n // Initialize the controls\r\n _channelControl[_DYN_INITIALIZE /* @min:%2einitialize */](_config, _self, allExtensions);\r\n initializePlugins(_createTelCtx(), allExtensions);\r\n // Now reset the extensions to just those being managed by Basecore\r\n _self[_DYN__EXTENSIONS /* @min:%2e_extensions */] = objFreeze(sortPlugins(_coreExtensions || [])).slice();\r\n if (updateState) {\r\n _doUpdate(updateState);\r\n }\r\n }\r\n function _getPlugin(pluginIdentifier) {\r\n var _a;\r\n var theExt = null;\r\n var thePlugin = null;\r\n arrForEach(_self[_DYN__EXTENSIONS /* @min:%2e_extensions */], function (ext) {\r\n if (ext[_DYN_IDENTIFIER /* @min:%2eidentifier */] === pluginIdentifier && ext !== _channelControl && ext !== _telemetryInitializerPlugin) {\r\n thePlugin = ext;\r\n return -1;\r\n }\r\n });\r\n if (!thePlugin && _channelControl) {\r\n // Check the channel Controller\r\n thePlugin = _channelControl.getChannel(pluginIdentifier);\r\n }\r\n if (thePlugin) {\r\n theExt = (_a = {\r\n plugin: thePlugin\r\n },\r\n _a[_DYN_SET_ENABLED /* @min:setEnabled */] = function (enabled) {\r\n _getPluginState(thePlugin)[STR_DISABLED] = !enabled;\r\n },\r\n _a.isEnabled = function () {\r\n var pluginState = _getPluginState(thePlugin);\r\n return !pluginState[_DYN_TEARDOWN /* @min:%2eteardown */] && !pluginState[STR_DISABLED];\r\n },\r\n _a.remove = function (isAsync, removeCb) {\r\n var _a;\r\n if (isAsync === void 0) { isAsync = true; }\r\n var pluginsToRemove = [thePlugin];\r\n var unloadState = (_a = {\r\n reason: 1 /* TelemetryUnloadReason.PluginUnload */\r\n },\r\n _a[_DYN_IS_ASYNC /* @min:isAsync */] = isAsync,\r\n _a);\r\n _removePlugins(pluginsToRemove, unloadState, function (removed) {\r\n if (removed) {\r\n // Re-Initialize the plugin chain\r\n _initPluginChain({\r\n reason: 32 /* TelemetryUpdateReason.PluginRemoved */,\r\n removed: pluginsToRemove\r\n });\r\n }\r\n removeCb && removeCb(removed);\r\n });\r\n },\r\n _a);\r\n }\r\n return theExt;\r\n }\r\n function _getPluginChain() {\r\n if (!_pluginChain) {\r\n // copy the collection of extensions\r\n var extensions = (_coreExtensions || []).slice();\r\n // During add / remove this may get called again, so don't readd if already present\r\n if (arrIndexOf(extensions, _telemetryInitializerPlugin) === -1) {\r\n extensions[_DYN_PUSH /* @min:%2epush */](_telemetryInitializerPlugin);\r\n }\r\n _pluginChain = createTelemetryProxyChain(sortPlugins(extensions), _config, _self);\r\n }\r\n return _pluginChain;\r\n }\r\n function _removePlugins(thePlugins, unloadState, removeComplete) {\r\n if (thePlugins && thePlugins[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var unloadChain = createTelemetryProxyChain(thePlugins, _config, _self);\r\n var unloadCtx = createProcessTelemetryUnloadContext(unloadChain, _self);\r\n unloadCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](function () {\r\n var removed = false;\r\n // Remove the listed config extensions\r\n var newConfigExtensions = [];\r\n arrForEach(_configExtensions, function (plugin, idx) {\r\n if (!_isPluginPresent(plugin, thePlugins)) {\r\n newConfigExtensions[_DYN_PUSH /* @min:%2epush */](plugin);\r\n }\r\n else {\r\n removed = true;\r\n }\r\n });\r\n _configExtensions = newConfigExtensions;\r\n // Re-Create the channel config\r\n var newChannelConfig = [];\r\n if (_channelConfig) {\r\n arrForEach(_channelConfig, function (queue, idx) {\r\n var newQueue = [];\r\n arrForEach(queue, function (channel) {\r\n if (!_isPluginPresent(channel, thePlugins)) {\r\n newQueue[_DYN_PUSH /* @min:%2epush */](channel);\r\n }\r\n else {\r\n removed = true;\r\n }\r\n });\r\n newChannelConfig[_DYN_PUSH /* @min:%2epush */](newQueue);\r\n });\r\n _channelConfig = newChannelConfig;\r\n }\r\n removeComplete && removeComplete(removed);\r\n });\r\n unloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\r\n }\r\n else {\r\n removeComplete(false);\r\n }\r\n }\r\n function _flushInternalLogs() {\r\n var queue = _self[_DYN_LOGGER /* @min:%2elogger */] ? _self[_DYN_LOGGER /* @min:%2elogger */].queue : [];\r\n if (queue) {\r\n arrForEach(queue, function (logMessage) {\r\n var _a;\r\n var item = (_a = {},\r\n _a[_DYN_NAME /* @min:name */] = _internalLogsEventName ? _internalLogsEventName : \"InternalMessageId: \" + logMessage[_DYN_MESSAGE_ID /* @min:%2emessageId */],\r\n _a.iKey = getCfgValue(_config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */]),\r\n _a.time = toISOString(new Date()),\r\n _a.baseType = _InternalLogMessage.dataType,\r\n _a.baseData = { message: logMessage[_DYN_MESSAGE /* @min:%2emessage */] },\r\n _a);\r\n _self.track(item);\r\n });\r\n queue[_DYN_LENGTH /* @min:%2elength */] = 0;\r\n }\r\n }\r\n function _flushChannels(isAsync, callBack, sendReason, cbTimeout) {\r\n if (_channelControl) {\r\n return _channelControl[_DYN_FLUSH /* @min:%2eflush */](isAsync, callBack, sendReason || 6 /* SendRequestReason.SdkUnload */, cbTimeout);\r\n }\r\n callBack && callBack(false);\r\n return true;\r\n }\r\n function _initDebugListener() {\r\n var disableDbgExt = getCfgValue(_config.disableDbgExt);\r\n if (disableDbgExt === true && _debugListener) {\r\n // Remove any previously loaded debug listener\r\n _notificationManager[_DYN_REMOVE_NOTIFICATION_2 /* @min:%2eremoveNotificationListener */](_debugListener);\r\n _debugListener = null;\r\n }\r\n if (_notificationManager && !_debugListener && disableDbgExt !== true) {\r\n _debugListener = getDebugListener(_config);\r\n _notificationManager[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */](_debugListener);\r\n }\r\n }\r\n function _initPerfManager() {\r\n var enablePerfMgr = getCfgValue(_config.enablePerfMgr);\r\n if (!enablePerfMgr && _cfgPerfManager) {\r\n // Remove any existing config based performance manager\r\n _cfgPerfManager = null;\r\n }\r\n if (enablePerfMgr) {\r\n // Set the performance manager creation function if not defined\r\n getSetValue(_config, STR_CREATE_PERF_MGR, _createPerfManager);\r\n }\r\n }\r\n function _initExtConfig() {\r\n var extConfig = getSetValue(_config, STR_EXTENSION_CONFIG, {});\r\n extConfig.NotificationManager = _notificationManager;\r\n }\r\n function _doUpdate(updateState) {\r\n var updateCtx = createProcessTelemetryUpdateContext(_getPluginChain(), _self);\r\n if (!_self._updateHook || _self._updateHook(updateCtx, updateState) !== true) {\r\n updateCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](updateState);\r\n }\r\n }\r\n function _logOrThrowError(message) {\r\n var logger = _self[_DYN_LOGGER /* @min:%2elogger */];\r\n if (logger) {\r\n // there should always be a logger\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, message);\r\n }\r\n else {\r\n throwError(message);\r\n }\r\n }\r\n });\r\n }\r\n// Removed Stub for BaseCore.prototype.initialize.\r\n// Removed Stub for BaseCore.prototype.getTransmissionControls.\r\n// Removed Stub for BaseCore.prototype.track.\r\n// Removed Stub for BaseCore.prototype.getProcessTelContext.\r\n// Removed Stub for BaseCore.prototype.getNotifyMgr.\r\n// Removed Stub for BaseCore.prototype.addNotificationListener.\r\n// Removed Stub for BaseCore.prototype.removeNotificationListener.\r\n// Removed Stub for BaseCore.prototype.getCookieMgr.\r\n// Removed Stub for BaseCore.prototype.setCookieMgr.\r\n// Removed Stub for BaseCore.prototype.getPerfMgr.\r\n// Removed Stub for BaseCore.prototype.setPerfMgr.\r\n// Removed Stub for BaseCore.prototype.eventCnt.\r\n// Removed Stub for BaseCore.prototype.pollInternalLogs.\r\n// Removed Stub for BaseCore.prototype.stopPollingInternalLogs.\r\n// Removed Stub for BaseCore.prototype.addTelemetryInitializer.\r\n// Removed Stub for BaseCore.prototype.unload.\r\n// Removed Stub for BaseCore.prototype.getPlugin.\r\n// Removed Stub for BaseCore.prototype.addPlugin.\r\n// Removed Stub for BaseCore.prototype.evtNamespace.\r\n// Removed Stub for BaseCore.prototype.addUnloadCb.\r\n// Removed Stub for BaseCore.prototype.flush.\r\n// Removed Stub for BaseCore.prototype.getTraceCtx.\r\n// Removed Stub for BaseCore.prototype.setTraceCtx.\r\n// Removed Stub for BaseCore.prototype.releaseQueue.\r\n// Removed Stub for BaseCore.prototype._updateHook.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n BaseCore.__ieDyn=1;\n\n return BaseCore;\r\n}());\r\nexport { BaseCore };\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n\"use strict\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { _DYN_CREATE_NEW, _DYN_DIAG_LOG, _DYN_GET_NEXT, _DYN_GET_PROCESS_TEL_CONT0, _DYN_INITIALIZE, _DYN_IS_ASYNC, _DYN_IS_INITIALIZED, _DYN_PROCESS_NEXT, _DYN_PUSH, _DYN_SET_NEXT_PLUGIN, _DYN_TEARDOWN, _DYN_UPDATE, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\r\nimport { arrForEach, isArray, isFunction, isNullOrUndefined, proxyFunctionAs, setValue } from \"./HelperFuncs\";\r\nimport { STR_CORE, STR_EXTENSION_CONFIG, STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\r\nimport { createProcessTelemetryContext, createProcessTelemetryUnloadContext, createProcessTelemetryUpdateContext } from \"./ProcessTelemetryContext\";\r\nimport { createUnloadHandlerContainer } from \"./UnloadHandlerContainer\";\r\nvar strGetPlugin = \"getPlugin\";\r\n/**\r\n * BaseTelemetryPlugin provides a basic implementation of the ITelemetryPlugin interface so that plugins\r\n * can avoid implementation the same set of boiler plate code as well as provide a base\r\n * implementation so that new default implementations can be added without breaking all plugins.\r\n */\r\nvar BaseTelemetryPlugin = /** @class */ (function () {\r\n function BaseTelemetryPlugin() {\r\n var _self = this; // Setting _self here as it's used outside of the dynamicProto as well\r\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\r\n var _isinitialized;\r\n var _rootCtx; // Used as the root context, holding the current config and initialized core\r\n var _nextPlugin; // Used for backward compatibility where plugins don't call the main pipeline\r\n var _unloadHandlerContainer;\r\n var _hooks;\r\n _initDefaults();\r\n dynamicProto(BaseTelemetryPlugin, _self, function (_self) {\r\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, core, extensions, pluginChain) {\r\n _setDefaults(config, core, pluginChain);\r\n _isinitialized = true;\r\n };\r\n _self[_DYN_TEARDOWN /* @min:%2eteardown */] = function (unloadCtx, unloadState) {\r\n var _a;\r\n // If this plugin has already been torn down (not operational) or is not initialized (core is not set)\r\n // or the core being used for unload was not the same core used for initialization.\r\n var core = _self[STR_CORE /* @min:%2ecore */];\r\n if (!core || (unloadCtx && core !== unloadCtx[STR_CORE /* @min:%2ecore */]())) {\r\n // Do Nothing as either the plugin is not initialized or was not initialized by the current core\r\n return;\r\n }\r\n var result;\r\n var unloadDone = false;\r\n var theUnloadCtx = unloadCtx || createProcessTelemetryUnloadContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin);\r\n var theUnloadState = unloadState || (_a = {\r\n reason: 0 /* TelemetryUnloadReason.ManualTeardown */\r\n },\r\n _a[_DYN_IS_ASYNC /* @min:isAsync */] = false,\r\n _a);\r\n function _unloadCallback() {\r\n if (!unloadDone) {\r\n unloadDone = true;\r\n _unloadHandlerContainer.run(theUnloadCtx, unloadState);\r\n var oldHooks = _hooks;\r\n _hooks = [];\r\n // Remove all instrumentation hooks\r\n arrForEach(oldHooks, function (fn) {\r\n fn.rm();\r\n });\r\n if (result === true) {\r\n theUnloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](theUnloadState);\r\n }\r\n _initDefaults();\r\n }\r\n }\r\n if (!_self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */] || _self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */](theUnloadCtx, theUnloadState, _unloadCallback) !== true) {\r\n _unloadCallback();\r\n }\r\n else {\r\n // Tell the caller that we will be calling processNext()\r\n result = true;\r\n }\r\n return result;\r\n };\r\n _self[_DYN_UPDATE /* @min:%2eupdate */] = function (updateCtx, updateState) {\r\n // If this plugin has already been torn down (not operational) or is not initialized (core is not set)\r\n // or the core being used for unload was not the same core used for initialization.\r\n var core = _self[STR_CORE /* @min:%2ecore */];\r\n if (!core || (updateCtx && core !== updateCtx[STR_CORE /* @min:%2ecore */]())) {\r\n // Do Nothing\r\n return;\r\n }\r\n var result;\r\n var updateDone = false;\r\n var theUpdateCtx = updateCtx || createProcessTelemetryUpdateContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin);\r\n var theUpdateState = updateState || {\r\n reason: 0 /* TelemetryUpdateReason.Unknown */\r\n };\r\n function _updateCallback() {\r\n if (!updateDone) {\r\n updateDone = true;\r\n _setDefaults(theUpdateCtx.getCfg(), theUpdateCtx.core(), theUpdateCtx[_DYN_GET_NEXT /* @min:%2egetNext */]());\r\n }\r\n }\r\n if (!_self._doUpdate || _self._doUpdate(theUpdateCtx, theUpdateState, _updateCallback) !== true) {\r\n _updateCallback();\r\n }\r\n else {\r\n result = true;\r\n }\r\n return result;\r\n };\r\n _self._addHook = function (hooks) {\r\n if (hooks) {\r\n if (isArray(hooks)) {\r\n _hooks = _hooks.concat(hooks);\r\n }\r\n else {\r\n _hooks[_DYN_PUSH /* @min:%2epush */](hooks);\r\n }\r\n }\r\n };\r\n proxyFunctionAs(_self, \"_addUnloadCb\", function () { return _unloadHandlerContainer; }, \"add\");\r\n });\r\n // These are added after the dynamicProto so that are not moved to the prototype\r\n _self[_DYN_DIAG_LOG /* @min:%2ediagLog */] = function (itemCtx) {\r\n return _getTelCtx(itemCtx)[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\r\n };\r\n _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = function () {\r\n return _isinitialized;\r\n };\r\n _self.setInitialized = function (isInitialized) {\r\n _isinitialized = isInitialized;\r\n };\r\n // _self.getNextPlugin = () => DO NOT IMPLEMENT\r\n // Sub-classes of this base class *should* not be relying on this value and instead\r\n // should use processNext() function. If you require access to the plugin use the\r\n // IProcessTelemetryContext.getNext().getPlugin() while in the pipeline, Note getNext() may return null.\r\n _self[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */] = function (next) {\r\n _nextPlugin = next;\r\n };\r\n _self[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = function (env, itemCtx) {\r\n if (itemCtx) {\r\n // Normal core execution sequence\r\n itemCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](env);\r\n }\r\n else if (_nextPlugin && isFunction(_nextPlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */])) {\r\n // Looks like backward compatibility or out of band processing. And as it looks\r\n // like a ITelemetryPlugin or ITelemetryPluginChain, just call processTelemetry\r\n _nextPlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */](env, null);\r\n }\r\n };\r\n _self._getTelCtx = _getTelCtx;\r\n function _getTelCtx(currentCtx) {\r\n if (currentCtx === void 0) { currentCtx = null; }\r\n var itemCtx = currentCtx;\r\n if (!itemCtx) {\r\n var rootCtx = _rootCtx || createProcessTelemetryContext(null, {}, _self[STR_CORE /* @min:%2ecore */]);\r\n // tslint:disable-next-line: prefer-conditional-expression\r\n if (_nextPlugin && _nextPlugin[strGetPlugin]) {\r\n // Looks like a chain object\r\n itemCtx = rootCtx[_DYN_CREATE_NEW /* @min:%2ecreateNew */](null, _nextPlugin[strGetPlugin]);\r\n }\r\n else {\r\n itemCtx = rootCtx[_DYN_CREATE_NEW /* @min:%2ecreateNew */](null, _nextPlugin);\r\n }\r\n }\r\n return itemCtx;\r\n }\r\n function _setDefaults(config, core, pluginChain) {\r\n if (config) {\r\n // Make sure the extensionConfig exists\r\n setValue(config, STR_EXTENSION_CONFIG, [], null, isNullOrUndefined);\r\n }\r\n if (!pluginChain && core) {\r\n // Get the first plugin from the core\r\n pluginChain = core[_DYN_GET_PROCESS_TEL_CONT0 /* @min:%2egetProcessTelContext */]()[_DYN_GET_NEXT /* @min:%2egetNext */]();\r\n }\r\n var nextPlugin = _nextPlugin;\r\n if (_nextPlugin && _nextPlugin[strGetPlugin]) {\r\n // If it looks like a proxy/chain then get the plugin\r\n nextPlugin = _nextPlugin[strGetPlugin]();\r\n }\r\n // Support legacy plugins where core was defined as a property\r\n _self[STR_CORE /* @min:%2ecore */] = core;\r\n _rootCtx = createProcessTelemetryContext(pluginChain, config, core, nextPlugin);\r\n }\r\n function _initDefaults() {\r\n _isinitialized = false;\r\n _self[STR_CORE /* @min:%2ecore */] = null;\r\n _rootCtx = null;\r\n _nextPlugin = null;\r\n _hooks = [];\r\n _unloadHandlerContainer = createUnloadHandlerContainer();\r\n }\r\n }\r\n// Removed Stub for BaseTelemetryPlugin.prototype.initialize.\r\n// Removed Stub for BaseTelemetryPlugin.prototype.teardown.\r\n// Removed Stub for BaseTelemetryPlugin.prototype.update.\r\n// Removed Stub for BaseTelemetryPlugin.prototype._addUnloadCb.\r\n// Removed Stub for BaseTelemetryPlugin.prototype._addHook.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n BaseTelemetryPlugin.__ieDyn=1;\n\n return BaseTelemetryPlugin;\r\n}());\r\nexport { BaseTelemetryPlugin };\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n// \r\nimport { _DYN_CONFIG, _DYN_CREATE_NEW, _DYN_FLUSH, _DYN_IDENTIFIER, _DYN_LENGTH, _DYN_ON_COMPLETE, _DYN_PROCESS_NEXT, _DYN_PUSH } from \"../__DynamicConstants\";\r\nimport { arrForEach, isArray, objFreeze, throwError } from \"./HelperFuncs\";\r\nimport { STR_PRIORITY } from \"./InternalConstants\";\r\nimport { createProcessTelemetryContext, createTelemetryProxyChain } from \"./ProcessTelemetryContext\";\r\nimport { initializePlugins } from \"./TelemetryHelpers\";\r\nexport var ChannelControllerPriority = 500;\r\nvar ChannelValidationMessage = \"Channel has invalid priority - \";\r\nfunction _addChannelQueue(channelQueue, queue, core) {\r\n if (queue && isArray(queue) && queue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n queue = queue.sort(function (a, b) {\r\n return a[STR_PRIORITY /* @min:%2epriority */] - b[STR_PRIORITY /* @min:%2epriority */];\r\n });\r\n arrForEach(queue, function (queueItem) {\r\n if (queueItem[STR_PRIORITY /* @min:%2epriority */] < ChannelControllerPriority) {\r\n throwError(ChannelValidationMessage + queueItem[_DYN_IDENTIFIER /* @min:%2eidentifier */]);\r\n }\r\n });\r\n channelQueue[_DYN_PUSH /* @min:%2epush */]({\r\n queue: objFreeze(queue),\r\n chain: createTelemetryProxyChain(queue, core[_DYN_CONFIG /* @min:%2econfig */], core)\r\n });\r\n }\r\n}\r\nexport function createChannelControllerPlugin(channelQueue, core) {\r\n function _getTelCtx() {\r\n return createProcessTelemetryContext(null, core[_DYN_CONFIG /* @min:%2econfig */], core, null);\r\n }\r\n function _processChannelQueue(theChannels, itemCtx, processFn, onComplete) {\r\n var waiting = theChannels ? (theChannels[_DYN_LENGTH /* @min:%2elength */] + 1) : 1;\r\n function _runChainOnComplete() {\r\n waiting--;\r\n if (waiting === 0) {\r\n onComplete && onComplete();\r\n onComplete = null;\r\n }\r\n }\r\n if (waiting > 0) {\r\n arrForEach(theChannels, function (channels) {\r\n // pass on to first item in queue\r\n if (channels && channels.queue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var channelChain = channels.chain;\r\n var chainCtx = itemCtx[_DYN_CREATE_NEW /* @min:%2ecreateNew */](channelChain);\r\n chainCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](_runChainOnComplete);\r\n // Cause this chain to start processing\r\n processFn(chainCtx);\r\n }\r\n else {\r\n waiting--;\r\n }\r\n });\r\n }\r\n _runChainOnComplete();\r\n }\r\n function _doUpdate(updateCtx, updateState) {\r\n var theUpdateState = updateState || {\r\n reason: 0 /* TelemetryUpdateReason.Unknown */\r\n };\r\n _processChannelQueue(channelQueue, updateCtx, function (chainCtx) {\r\n chainCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](theUpdateState);\r\n }, function () {\r\n updateCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](theUpdateState);\r\n });\r\n return true;\r\n }\r\n function _doTeardown(unloadCtx, unloadState) {\r\n var theUnloadState = unloadState || {\r\n reason: 0 /* TelemetryUnloadReason.ManualTeardown */,\r\n isAsync: false\r\n };\r\n _processChannelQueue(channelQueue, unloadCtx, function (chainCtx) {\r\n chainCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](theUnloadState);\r\n }, function () {\r\n unloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](theUnloadState);\r\n isInitialized = false;\r\n });\r\n return true;\r\n }\r\n function _getChannel(pluginIdentifier) {\r\n var thePlugin = null;\r\n if (channelQueue && channelQueue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(channelQueue, function (channels) {\r\n // pass on to first item in queue\r\n if (channels && channels.queue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(channels.queue, function (ext) {\r\n if (ext[_DYN_IDENTIFIER /* @min:%2eidentifier */] === pluginIdentifier) {\r\n thePlugin = ext;\r\n // Cause arrForEach to stop iterating\r\n return -1;\r\n }\r\n });\r\n if (thePlugin) {\r\n // Cause arrForEach to stop iterating\r\n return -1;\r\n }\r\n }\r\n });\r\n }\r\n return thePlugin;\r\n }\r\n var isInitialized = false;\r\n var channelController = {\r\n identifier: \"ChannelControllerPlugin\",\r\n priority: ChannelControllerPriority,\r\n initialize: function (config, core, extensions, pluginChain) {\r\n isInitialized = true;\r\n arrForEach(channelQueue, function (channels) {\r\n if (channels && channels.queue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n initializePlugins(createProcessTelemetryContext(channels.chain, config, core), extensions);\r\n }\r\n });\r\n },\r\n isInitialized: function () {\r\n return isInitialized;\r\n },\r\n processTelemetry: function (item, itemCtx) {\r\n _processChannelQueue(channelQueue, itemCtx || _getTelCtx(), function (chainCtx) {\r\n chainCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](item);\r\n }, function () {\r\n itemCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](item);\r\n });\r\n },\r\n update: _doUpdate,\r\n pause: function () {\r\n _processChannelQueue(channelQueue, _getTelCtx(), function (chainCtx) {\r\n chainCtx.iterate(function (plugin) {\r\n plugin.pause && plugin.pause();\r\n });\r\n }, null);\r\n },\r\n resume: function () {\r\n _processChannelQueue(channelQueue, _getTelCtx(), function (chainCtx) {\r\n chainCtx.iterate(function (plugin) {\r\n plugin.resume && plugin.resume();\r\n });\r\n }, null);\r\n },\r\n teardown: _doTeardown,\r\n getChannel: _getChannel,\r\n flush: function (isAsync, callBack, sendReason, cbTimeout) {\r\n // Setting waiting to one so that we don't call the callBack until we finish iterating\r\n var waiting = 1;\r\n var doneIterating = false;\r\n var cbTimer = null;\r\n cbTimeout = cbTimeout || 5000;\r\n function doCallback() {\r\n waiting--;\r\n if (doneIterating && waiting === 0) {\r\n if (cbTimer) {\r\n clearTimeout(cbTimer);\r\n cbTimer = null;\r\n }\r\n callBack && callBack(doneIterating);\r\n callBack = null;\r\n }\r\n }\r\n _processChannelQueue(channelQueue, _getTelCtx(), function (chainCtx) {\r\n chainCtx.iterate(function (plugin) {\r\n if (plugin[_DYN_FLUSH /* @min:%2eflush */]) {\r\n waiting++;\r\n var handled_1 = false;\r\n // Not all channels will call this callback for every scenario\r\n if (!plugin[_DYN_FLUSH /* @min:%2eflush */](isAsync, function () {\r\n handled_1 = true;\r\n doCallback();\r\n }, sendReason)) {\r\n if (!handled_1) {\r\n // If any channel doesn't return true and it didn't call the callback, then we should assume that the callback\r\n // will never be called, so use a timeout to allow the channel(s) some time to \"finish\" before triggering any\r\n // followup function (such as unloading)\r\n if (isAsync && cbTimer == null) {\r\n cbTimer = setTimeout(function () {\r\n cbTimer = null;\r\n doCallback();\r\n }, cbTimeout);\r\n }\r\n else {\r\n doCallback();\r\n }\r\n }\r\n }\r\n }\r\n });\r\n }, function () {\r\n doneIterating = true;\r\n doCallback();\r\n });\r\n return true;\r\n },\r\n _setQueue: function (queue) {\r\n channelQueue = queue;\r\n }\r\n };\r\n return channelController;\r\n}\r\nexport function createChannelQueues(channels, extensions, core) {\r\n var channelQueue = [];\r\n if (channels) {\r\n // Add and sort the configuration channel queues\r\n arrForEach(channels, function (queue) { return _addChannelQueue(channelQueue, queue, core); });\r\n }\r\n if (extensions) {\r\n // Create a new channel queue for any extensions with a priority > the ChannelControllerPriority\r\n var extensionQueue_1 = [];\r\n arrForEach(extensions, function (plugin) {\r\n if (plugin[STR_PRIORITY /* @min:%2epriority */] > ChannelControllerPriority) {\r\n extensionQueue_1[_DYN_PUSH /* @min:%2epush */](plugin);\r\n }\r\n });\r\n _addChannelQueue(channelQueue, extensionQueue_1, core);\r\n }\r\n return channelQueue;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { _DYN_COOKIE_CFG, _DYN_INDEX_OF, _DYN_LENGTH, _DYN_LOGGER, _DYN_SET_ENABLED, _DYN_SPLIT, _DYN_SUBSTRING, _DYN_USER_AGENT } from \"../__DynamicConstants\";\r\nimport { _throwInternal } from \"./DiagnosticLogger\";\r\nimport { dumpObj, getDocument, getLocation, getNavigator, isIE } from \"./EnvUtils\";\r\nimport { arrForEach, dateNow, getExceptionName, isArray, isFunction, isNotNullOrUndefined, isNullOrUndefined, isString, isTruthy, isUndefined, objForEachKey, setValue, strContains, strEndsWith, strTrim } from \"./HelperFuncs\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\nvar strToGMTString = \"toGMTString\";\r\nvar strToUTCString = \"toUTCString\";\r\nvar strCookie = \"cookie\";\r\nvar strExpires = \"expires\";\r\nvar strEnabled = \"enabled\";\r\nvar strIsCookieUseDisabled = \"isCookieUseDisabled\";\r\nvar strDisableCookiesUsage = \"disableCookiesUsage\";\r\nvar strConfigCookieMgr = \"_ckMgr\";\r\nvar _supportsCookies = null;\r\nvar _allowUaSameSite = null;\r\nvar _parsedCookieValue = null;\r\nvar _doc = getDocument();\r\nvar _cookieCache = {};\r\nvar _globalCookieConfig = {};\r\n/**\r\n * @ignore\r\n * DO NOT USE or export from the module, this is exposed as public to support backward compatibility of previous static utility methods only.\r\n * If you want to manager cookies either use the ICookieMgr available from the core instance via getCookieMgr() or create\r\n * your own instance of the CookieMgr and use that.\r\n * Using this directly for enabling / disabling cookie handling will not only affect your usage but EVERY user of cookies.\r\n * Example, if you are using a shared component that is also using Application Insights you will affect their cookie handling.\r\n * @param logger - The DiagnosticLogger to use for reporting errors.\r\n */\r\nexport function _gblCookieMgr(config, logger) {\r\n // Stash the global instance against the BaseCookieMgr class\r\n var inst = createCookieMgr[strConfigCookieMgr] || _globalCookieConfig[strConfigCookieMgr];\r\n if (!inst) {\r\n // Note: not using the getSetValue() helper as that would require always creating a temporary cookieMgr\r\n // that ultimately is never used\r\n inst = createCookieMgr[strConfigCookieMgr] = createCookieMgr(config, logger);\r\n _globalCookieConfig[strConfigCookieMgr] = inst;\r\n }\r\n return inst;\r\n}\r\nfunction _isMgrEnabled(cookieMgr) {\r\n if (cookieMgr) {\r\n return cookieMgr.isEnabled();\r\n }\r\n return true;\r\n}\r\nfunction _createCookieMgrConfig(rootConfig) {\r\n var cookieMgrCfg = rootConfig[_DYN_COOKIE_CFG /* @min:%2ecookieCfg */] = rootConfig[_DYN_COOKIE_CFG /* @min:%2ecookieCfg */] || {};\r\n // Sets the values from the root config if not already present on the cookieMgrCfg\r\n setValue(cookieMgrCfg, \"domain\", rootConfig.cookieDomain, isNotNullOrUndefined, isNullOrUndefined);\r\n setValue(cookieMgrCfg, \"path\", rootConfig.cookiePath || \"/\", null, isNullOrUndefined);\r\n if (isNullOrUndefined(cookieMgrCfg[strEnabled])) {\r\n // Set the enabled from the provided setting or the legacy root values\r\n var cookieEnabled = void 0;\r\n if (!isUndefined(rootConfig[strIsCookieUseDisabled])) {\r\n cookieEnabled = !rootConfig[strIsCookieUseDisabled];\r\n }\r\n if (!isUndefined(rootConfig[strDisableCookiesUsage])) {\r\n cookieEnabled = !rootConfig[strDisableCookiesUsage];\r\n }\r\n cookieMgrCfg[strEnabled] = cookieEnabled;\r\n }\r\n return cookieMgrCfg;\r\n}\r\nfunction _isIgnoredCookie(cookieMgrCfg, name) {\r\n if (name && cookieMgrCfg && isArray(cookieMgrCfg.ignoreCookies)) {\r\n return cookieMgrCfg.ignoreCookies[_DYN_INDEX_OF /* @min:%2eindexOf */](name) !== -1;\r\n }\r\n return false;\r\n}\r\nfunction _isBlockedCookie(cookieMgrCfg, name) {\r\n if (name && cookieMgrCfg && isArray(cookieMgrCfg.blockedCookies)) {\r\n if (cookieMgrCfg.blockedCookies[_DYN_INDEX_OF /* @min:%2eindexOf */](name) !== -1) {\r\n return true;\r\n }\r\n }\r\n return _isIgnoredCookie(cookieMgrCfg, name);\r\n}\r\n/**\r\n * Helper to return the ICookieMgr from the core (if not null/undefined) or a default implementation\r\n * associated with the configuration or a legacy default.\r\n * @param core\r\n * @param config\r\n * @returns\r\n */\r\nexport function safeGetCookieMgr(core, config) {\r\n var cookieMgr;\r\n if (core) {\r\n // Always returns an instance\r\n cookieMgr = core.getCookieMgr();\r\n }\r\n else if (config) {\r\n var cookieCfg = config[_DYN_COOKIE_CFG /* @min:%2ecookieCfg */];\r\n if (cookieCfg[strConfigCookieMgr]) {\r\n cookieMgr = cookieCfg[strConfigCookieMgr];\r\n }\r\n else {\r\n cookieMgr = createCookieMgr(config);\r\n }\r\n }\r\n if (!cookieMgr) {\r\n // Get or initialize the default global (legacy) cookie manager if we couldn't find one\r\n cookieMgr = _gblCookieMgr(config, (core || {})[_DYN_LOGGER /* @min:%2elogger */]);\r\n }\r\n return cookieMgr;\r\n}\r\nexport function createCookieMgr(rootConfig, logger) {\r\n var _a;\r\n var cookieMgrConfig = _createCookieMgrConfig(rootConfig || _globalCookieConfig);\r\n var _path = cookieMgrConfig.path || \"/\";\r\n var _domain = cookieMgrConfig.domain;\r\n // Explicitly checking against false, so that setting to undefined will === true\r\n var _enabled = cookieMgrConfig[strEnabled] !== false;\r\n var cookieMgr = (_a = {\r\n isEnabled: function () {\r\n var enabled = _enabled && areCookiesSupported(logger);\r\n // Using an indirect lookup for any global cookie manager to support tree shaking for SDK's\r\n // that don't use the \"applicationinsights-core\" version of the default cookie function\r\n var gblManager = _globalCookieConfig[strConfigCookieMgr];\r\n if (enabled && gblManager && cookieMgr !== gblManager) {\r\n // Make sure the GlobalCookie Manager instance (if not this instance) is also enabled.\r\n // As the global (deprecated) functions may have been called (for backward compatibility)\r\n enabled = _isMgrEnabled(gblManager);\r\n }\r\n return enabled;\r\n }\r\n },\r\n _a[_DYN_SET_ENABLED /* @min:setEnabled */] = function (value) {\r\n // Explicitly checking against false, so that setting to undefined will === true\r\n _enabled = value !== false;\r\n },\r\n _a.set = function (name, value, maxAgeSec, domain, path) {\r\n var result = false;\r\n if (_isMgrEnabled(cookieMgr) && !_isBlockedCookie(cookieMgrConfig, name)) {\r\n var values = {};\r\n var theValue = strTrim(value || STR_EMPTY);\r\n var idx = theValue[_DYN_INDEX_OF /* @min:%2eindexOf */](\";\");\r\n if (idx !== -1) {\r\n theValue = strTrim(value[_DYN_SUBSTRING /* @min:%2esubstring */](0, idx));\r\n values = _extractParts(value[_DYN_SUBSTRING /* @min:%2esubstring */](idx + 1));\r\n }\r\n // Only update domain if not already present (isUndefined) and the value is truthy (not null, undefined or empty string)\r\n setValue(values, \"domain\", domain || _domain, isTruthy, isUndefined);\r\n if (!isNullOrUndefined(maxAgeSec)) {\r\n var _isIE = isIE();\r\n if (isUndefined(values[strExpires])) {\r\n var nowMs = dateNow();\r\n // Only add expires if not already present\r\n var expireMs = nowMs + (maxAgeSec * 1000);\r\n // Sanity check, if zero or -ve then ignore\r\n if (expireMs > 0) {\r\n var expiry = new Date();\r\n expiry.setTime(expireMs);\r\n setValue(values, strExpires, _formatDate(expiry, !_isIE ? strToUTCString : strToGMTString) || _formatDate(expiry, _isIE ? strToGMTString : strToUTCString) || STR_EMPTY, isTruthy);\r\n }\r\n }\r\n if (!_isIE) {\r\n // Only replace if not already present\r\n setValue(values, \"max-age\", STR_EMPTY + maxAgeSec, null, isUndefined);\r\n }\r\n }\r\n var location_1 = getLocation();\r\n if (location_1 && location_1.protocol === \"https:\") {\r\n setValue(values, \"secure\", null, null, isUndefined);\r\n // Only set same site if not also secure\r\n if (_allowUaSameSite === null) {\r\n _allowUaSameSite = !uaDisallowsSameSiteNone((getNavigator() || {})[_DYN_USER_AGENT /* @min:%2euserAgent */]);\r\n }\r\n if (_allowUaSameSite) {\r\n setValue(values, \"SameSite\", \"None\", null, isUndefined);\r\n }\r\n }\r\n setValue(values, \"path\", path || _path, null, isUndefined);\r\n var setCookieFn = cookieMgrConfig.setCookie || _setCookieValue;\r\n setCookieFn(name, _formatCookieValue(theValue, values));\r\n result = true;\r\n }\r\n return result;\r\n },\r\n _a.get = function (name) {\r\n var value = STR_EMPTY;\r\n if (_isMgrEnabled(cookieMgr) && !_isIgnoredCookie(cookieMgrConfig, name)) {\r\n value = (cookieMgrConfig.getCookie || _getCookieValue)(name);\r\n }\r\n return value;\r\n },\r\n _a.del = function (name, path) {\r\n var result = false;\r\n if (_isMgrEnabled(cookieMgr)) {\r\n // Only remove the cookie if the manager and cookie support has not been disabled\r\n result = cookieMgr.purge(name, path);\r\n }\r\n return result;\r\n },\r\n _a.purge = function (name, path) {\r\n var _a;\r\n var result = false;\r\n if (areCookiesSupported(logger)) {\r\n // Setting the expiration date in the past immediately removes the cookie\r\n var values = (_a = {},\r\n _a[\"path\"] = path ? path : \"/\",\r\n _a[strExpires] = \"Thu, 01 Jan 1970 00:00:01 GMT\",\r\n _a);\r\n if (!isIE()) {\r\n // Set max age to expire now\r\n values[\"max-age\"] = \"0\";\r\n }\r\n var delCookie = cookieMgrConfig.delCookie || _setCookieValue;\r\n delCookie(name, _formatCookieValue(STR_EMPTY, values));\r\n result = true;\r\n }\r\n return result;\r\n },\r\n _a);\r\n // Associated this cookie manager with the config\r\n cookieMgr[strConfigCookieMgr] = cookieMgr;\r\n return cookieMgr;\r\n}\r\n/*\r\n* Helper method to tell if document.cookie object is supported by the runtime\r\n*/\r\nexport function areCookiesSupported(logger) {\r\n if (_supportsCookies === null) {\r\n _supportsCookies = false;\r\n try {\r\n var doc = _doc || {};\r\n _supportsCookies = doc[strCookie] !== undefined;\r\n }\r\n catch (e) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 68 /* _eInternalMessageId.CannotAccessCookie */, \"Cannot access document.cookie - \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return _supportsCookies;\r\n}\r\nfunction _extractParts(theValue) {\r\n var values = {};\r\n if (theValue && theValue[_DYN_LENGTH /* @min:%2elength */]) {\r\n var parts = strTrim(theValue)[_DYN_SPLIT /* @min:%2esplit */](\";\");\r\n arrForEach(parts, function (thePart) {\r\n thePart = strTrim(thePart || STR_EMPTY);\r\n if (thePart) {\r\n var idx = thePart[_DYN_INDEX_OF /* @min:%2eindexOf */](\"=\");\r\n if (idx === -1) {\r\n values[thePart] = null;\r\n }\r\n else {\r\n values[strTrim(thePart[_DYN_SUBSTRING /* @min:%2esubstring */](0, idx))] = strTrim(thePart[_DYN_SUBSTRING /* @min:%2esubstring */](idx + 1));\r\n }\r\n }\r\n });\r\n }\r\n return values;\r\n}\r\nfunction _formatDate(theDate, func) {\r\n if (isFunction(theDate[func])) {\r\n return theDate[func]();\r\n }\r\n return null;\r\n}\r\nfunction _formatCookieValue(value, values) {\r\n var cookieValue = value || STR_EMPTY;\r\n objForEachKey(values, function (name, theValue) {\r\n cookieValue += \"; \" + name + (!isNullOrUndefined(theValue) ? \"=\" + theValue : STR_EMPTY);\r\n });\r\n return cookieValue;\r\n}\r\nfunction _getCookieValue(name) {\r\n var cookieValue = STR_EMPTY;\r\n if (_doc) {\r\n var theCookie = _doc[strCookie] || STR_EMPTY;\r\n if (_parsedCookieValue !== theCookie) {\r\n _cookieCache = _extractParts(theCookie);\r\n _parsedCookieValue = theCookie;\r\n }\r\n cookieValue = strTrim(_cookieCache[name] || STR_EMPTY);\r\n }\r\n return cookieValue;\r\n}\r\nfunction _setCookieValue(name, cookieValue) {\r\n if (_doc) {\r\n _doc[strCookie] = name + \"=\" + cookieValue;\r\n }\r\n}\r\nexport function uaDisallowsSameSiteNone(userAgent) {\r\n if (!isString(userAgent)) {\r\n return false;\r\n }\r\n // Cover all iOS based browsers here. This includes:\r\n // - Safari on iOS 12 for iPhone, iPod Touch, iPad\r\n // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad\r\n // - Chrome on iOS 12 for iPhone, iPod Touch, iPad\r\n // All of which are broken by SameSite=None, because they use the iOS networking stack\r\n if (strContains(userAgent, \"CPU iPhone OS 12\") || strContains(userAgent, \"iPad; CPU OS 12\")) {\r\n return true;\r\n }\r\n // Cover Mac OS X based browsers that use the Mac OS networking stack. This includes:\r\n // - Safari on Mac OS X\r\n // This does not include:\r\n // - Internal browser on Mac OS X\r\n // - Chrome on Mac OS X\r\n // - Chromium on Mac OS X\r\n // Because they do not use the Mac OS networking stack.\r\n if (strContains(userAgent, \"Macintosh; Intel Mac OS X 10_14\") && strContains(userAgent, \"Version/\") && strContains(userAgent, \"Safari\")) {\r\n return true;\r\n }\r\n // Cover Mac OS X internal browsers that use the Mac OS networking stack. This includes:\r\n // - Internal browser on Mac OS X\r\n // This does not include:\r\n // - Safari on Mac OS X\r\n // - Chrome on Mac OS X\r\n // - Chromium on Mac OS X\r\n // Because they do not use the Mac OS networking stack.\r\n if (strContains(userAgent, \"Macintosh; Intel Mac OS X 10_14\") && strEndsWith(userAgent, \"AppleWebKit/605.1.15 (KHTML, like Gecko)\")) {\r\n return true;\r\n }\r\n // Cover Chrome 50-69, because some versions are broken by SameSite=None, and none in this range require it.\r\n // Note: this covers some pre-Chromium Edge versions, but pre-Chromim Edge does not require SameSite=None, so this is fine.\r\n // Note: this regex applies to Windows, Mac OS X, and Linux, deliberately.\r\n if (strContains(userAgent, \"Chrome/5\") || strContains(userAgent, \"Chrome/6\")) {\r\n return true;\r\n }\r\n // Unreal Engine runs Chromium 59, but does not advertise as Chrome until 4.23. Treat versions of Unreal\r\n // that don't specify their Chrome version as lacking support for SameSite=None.\r\n if (strContains(userAgent, \"UnrealEngine\") && !strContains(userAgent, \"Chrome\")) {\r\n return true;\r\n }\r\n // UCBrowser < 12.13.2 ignores Set-Cookie headers with SameSite=None\r\n // NB: this rule isn't complete - you need regex to make a complete rule.\r\n // See: https://www.chromium.org/updates/same-site/incompatible-clients\r\n if (strContains(userAgent, \"UCBrowser/12\") || strContains(userAgent, \"UCBrowser/11\")) {\r\n return true;\r\n }\r\n return false;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n\"use strict\";\r\nimport { objCreateFn, strShimUndefined } from \"@microsoft/applicationinsights-shims\";\r\nimport { _DYN_LENGTH, _DYN_PUSH, _DYN_SET_ENABLED, _DYN_SUBSTR, _DYN_SUBSTRING } from \"../__DynamicConstants\";\r\nimport { _gblCookieMgr } from \"./CookieMgr\";\r\nimport { getPerformance, isIE } from \"./EnvUtils\";\r\nimport { addEventHandler, attachEvent, detachEvent } from \"./EventHelpers\";\r\nimport { arrForEach, arrIndexOf, arrMap, arrReduce, dateNow, hasOwnProperty, isArray, isBoolean, isDate, isError, isFunction, isNullOrUndefined, isNumber, isObject, isString, isTypeof, isUndefined, objDefineAccessors, objKeys, strTrim, toISOString } from \"./HelperFuncs\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\nimport { mwcRandom32, mwcRandomSeed, newId, random32, randomValue } from \"./RandomHelper\";\r\nvar _cookieMgrs = null;\r\nvar _canUseCookies; // legacy supported config\r\n// Added to help with minfication\r\nexport var Undefined = strShimUndefined;\r\nexport function newGuid() {\r\n var uuid = generateW3CId();\r\n return uuid[_DYN_SUBSTRING /* @min:%2esubstring */](0, 8) + \"-\" + uuid[_DYN_SUBSTRING /* @min:%2esubstring */](8, 12) + \"-\" + uuid[_DYN_SUBSTRING /* @min:%2esubstring */](12, 16) + \"-\" + uuid[_DYN_SUBSTRING /* @min:%2esubstring */](16, 20) + \"-\" + uuid[_DYN_SUBSTRING /* @min:%2esubstring */](20);\r\n}\r\n/**\r\n * Return the current value of the Performance Api now() function (if available) and fallback to dateNow() if it is unavailable (IE9 or less)\r\n * https://caniuse.com/#search=performance.now\r\n */\r\nexport function perfNow() {\r\n var perf = getPerformance();\r\n if (perf && perf.now) {\r\n return perf.now();\r\n }\r\n return dateNow();\r\n}\r\n/**\r\n * The strEndsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.\r\n * @param value - The value to check whether it ends with the search value.\r\n * @param search - The characters to be searched for at the end of the value.\r\n * @returns true if the given search value is found at the end of the string, otherwise false.\r\n */\r\nexport function strEndsWith(value, search) {\r\n if (value && search) {\r\n var len = value[_DYN_LENGTH /* @min:%2elength */];\r\n var start = len - search[_DYN_LENGTH /* @min:%2elength */];\r\n return value[_DYN_SUBSTRING /* @min:%2esubstring */](start >= 0 ? start : 0, len) === search;\r\n }\r\n return false;\r\n}\r\n/**\r\n * generate W3C trace id\r\n */\r\nexport function generateW3CId() {\r\n var hexValues = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\"];\r\n // rfc4122 version 4 UUID without dashes and with lowercase letters\r\n var oct = STR_EMPTY, tmp;\r\n for (var a = 0; a < 4; a++) {\r\n tmp = random32();\r\n oct +=\r\n hexValues[tmp & 0xF] +\r\n hexValues[tmp >> 4 & 0xF] +\r\n hexValues[tmp >> 8 & 0xF] +\r\n hexValues[tmp >> 12 & 0xF] +\r\n hexValues[tmp >> 16 & 0xF] +\r\n hexValues[tmp >> 20 & 0xF] +\r\n hexValues[tmp >> 24 & 0xF] +\r\n hexValues[tmp >> 28 & 0xF];\r\n }\r\n // \"Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively\"\r\n var clockSequenceHi = hexValues[8 + (random32() & 0x03) | 0];\r\n return oct[_DYN_SUBSTR /* @min:%2esubstr */](0, 8) + oct[_DYN_SUBSTR /* @min:%2esubstr */](9, 4) + \"4\" + oct[_DYN_SUBSTR /* @min:%2esubstr */](13, 3) + clockSequenceHi + oct[_DYN_SUBSTR /* @min:%2esubstr */](16, 3) + oct[_DYN_SUBSTR /* @min:%2esubstr */](19, 12);\r\n}\r\n/**\r\n * Provides a collection of utility functions, included for backward compatibility with previous releases.\r\n * @deprecated Marking this instance as deprecated in favor of direct usage of the helper functions\r\n * as direct usage provides better tree-shaking and minification by avoiding the inclusion of the unused items\r\n * in your resulting code.\r\n */\r\nexport var CoreUtils = {\r\n _canUseCookies: undefined,\r\n isTypeof: isTypeof,\r\n isUndefined: isUndefined,\r\n isNullOrUndefined: isNullOrUndefined,\r\n hasOwnProperty: hasOwnProperty,\r\n isFunction: isFunction,\r\n isObject: isObject,\r\n isDate: isDate,\r\n isArray: isArray,\r\n isError: isError,\r\n isString: isString,\r\n isNumber: isNumber,\r\n isBoolean: isBoolean,\r\n toISOString: toISOString,\r\n arrForEach: arrForEach,\r\n arrIndexOf: arrIndexOf,\r\n arrMap: arrMap,\r\n arrReduce: arrReduce,\r\n strTrim: strTrim,\r\n objCreate: objCreateFn,\r\n objKeys: objKeys,\r\n objDefineAccessors: objDefineAccessors,\r\n addEventHandler: addEventHandler,\r\n dateNow: dateNow,\r\n isIE: isIE,\r\n disableCookies: disableCookies,\r\n newGuid: newGuid,\r\n perfNow: perfNow,\r\n newId: newId,\r\n randomValue: randomValue,\r\n random32: random32,\r\n mwcRandomSeed: mwcRandomSeed,\r\n mwcRandom32: mwcRandom32,\r\n generateW3CId: generateW3CId\r\n};\r\nvar GuidRegex = /[xy]/g;\r\nexport var EventHelper = {\r\n Attach: attachEvent,\r\n AttachEvent: attachEvent,\r\n Detach: detachEvent,\r\n DetachEvent: detachEvent\r\n};\r\n/**\r\n * Helper to support backward compatibility for users that use the legacy cookie handling functions and the use the internal\r\n * CoreUtils._canUseCookies global flag to enable/disable cookies usage.\r\n * Note: This has the following deliberate side-effects\r\n * - Creates the global (legacy) cookie manager if it does not already exist\r\n * - Attempts to add \"listeners\" to the CoreUtils._canUseCookies property to support the legacy usage\r\n * @param config\r\n * @param logger\r\n * @returns\r\n */\r\nexport function _legacyCookieMgr(config, logger) {\r\n var cookieMgr = _gblCookieMgr(config, logger);\r\n var legacyCanUseCookies = CoreUtils._canUseCookies;\r\n if (_cookieMgrs === null) {\r\n _cookieMgrs = [];\r\n _canUseCookies = legacyCanUseCookies;\r\n // Dynamically create get/set property accessors for backward compatibility for enabling / disabling cookies\r\n // this WILL NOT work for ES3 browsers (< IE8)\r\n objDefineAccessors(CoreUtils, \"_canUseCookies\", function () {\r\n return _canUseCookies;\r\n }, function (value) {\r\n _canUseCookies = value;\r\n arrForEach(_cookieMgrs, function (mgr) {\r\n mgr[_DYN_SET_ENABLED /* @min:%2esetEnabled */](value);\r\n });\r\n });\r\n }\r\n if (arrIndexOf(_cookieMgrs, cookieMgr) === -1) {\r\n _cookieMgrs[_DYN_PUSH /* @min:%2epush */](cookieMgr);\r\n }\r\n if (isBoolean(legacyCanUseCookies)) {\r\n cookieMgr[_DYN_SET_ENABLED /* @min:%2esetEnabled */](legacyCanUseCookies);\r\n }\r\n if (isBoolean(_canUseCookies)) {\r\n cookieMgr[_DYN_SET_ENABLED /* @min:%2esetEnabled */](_canUseCookies);\r\n }\r\n return cookieMgr;\r\n}\r\n/**\r\n * @deprecated - Use the core.getCookieMgr().disable()\r\n * Force the SDK not to store and read any data from cookies.\r\n */\r\nexport function disableCookies() {\r\n _legacyCookieMgr()[_DYN_SET_ENABLED /* @min:%2esetEnabled */](false);\r\n}\r\n/**\r\n * @deprecated - Use the core.getCookieMgr().isEnabled()\r\n * Helper method to tell if document.cookie object is available and whether it can be used.\r\n */\r\nexport function canUseCookies(logger) {\r\n return _legacyCookieMgr(null, logger).isEnabled();\r\n}\r\n/**\r\n * @deprecated - Use the core.getCookieMgr().get()\r\n * helper method to access userId and sessionId cookie\r\n */\r\nexport function getCookie(logger, name) {\r\n return _legacyCookieMgr(null, logger).get(name);\r\n}\r\n/**\r\n * @deprecated - Use the core.getCookieMgr().set()\r\n * helper method to set userId and sessionId cookie\r\n */\r\nexport function setCookie(logger, name, value, domain) {\r\n _legacyCookieMgr(null, logger).set(name, value, null, domain);\r\n}\r\n/**\r\n * @deprecated - Use the core.getCookieMgr().del()\r\n * Deletes a cookie by setting it's expiration time in the past.\r\n * @param name - The name of the cookie to delete.\r\n */\r\nexport function deleteCookie(logger, name) {\r\n return _legacyCookieMgr(null, logger).del(name);\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { ObjDefineProperty } from \"@microsoft/applicationinsights-shims\";\r\nimport { _DYN_NODE_TYPE } from \"../__DynamicConstants\";\r\nimport { normalizeJsName } from \"./HelperFuncs\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\nimport { newId } from \"./RandomHelper\";\r\nvar _objDefineProperty = ObjDefineProperty;\r\nvar version = '2.8.11';\r\nvar instanceName = \".\" + newId(6);\r\nvar _dataUid = 0;\r\nfunction _createAccessor(target, prop, value) {\r\n if (_objDefineProperty) {\r\n try {\r\n _objDefineProperty(target, prop, {\r\n value: value,\r\n enumerable: false,\r\n configurable: true\r\n });\r\n return true;\r\n }\r\n catch (e) {\r\n // IE8 Defines a defineProperty on Object but it's only supported for DOM elements so it will throw\r\n // We will just ignore this here.\r\n }\r\n }\r\n return false;\r\n}\r\n// Accepts only:\r\n// - Node\r\n// - Node.ELEMENT_NODE\r\n// - Node.DOCUMENT_NODE\r\n// - Object\r\n// - Any\r\nfunction _canAcceptData(target) {\r\n return target[_DYN_NODE_TYPE /* @min:%2enodeType */] === 1 || target[_DYN_NODE_TYPE /* @min:%2enodeType */] === 9 || !(+target[_DYN_NODE_TYPE /* @min:%2enodeType */]);\r\n}\r\nfunction _getCache(data, target) {\r\n var theCache = target[data.id];\r\n if (!theCache) {\r\n theCache = {};\r\n try {\r\n if (_canAcceptData(target)) {\r\n if (!_createAccessor(target, data.id, theCache)) {\r\n // Environment doesn't support accessor, so just use direct assignment\r\n target[data.id] = theCache;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // Not all environments allow extending all objects, so just ignore the cache in those cases\r\n }\r\n }\r\n return theCache;\r\n}\r\nexport function createUniqueNamespace(name, includeVersion) {\r\n if (includeVersion === void 0) { includeVersion = false; }\r\n return normalizeJsName(name + (_dataUid++) + (includeVersion ? \".\" + version : STR_EMPTY) + instanceName);\r\n}\r\nexport function createElmNodeData(name) {\r\n var data = {\r\n id: createUniqueNamespace(\"_aiData-\" + (name || STR_EMPTY) + \".\" + version),\r\n accept: function (target) {\r\n return _canAcceptData(target);\r\n },\r\n get: function (target, name, defValue, addDefault) {\r\n var theCache = target[data.id];\r\n if (!theCache) {\r\n if (addDefault) {\r\n // Side effect is adds the cache\r\n theCache = _getCache(data, target);\r\n theCache[normalizeJsName(name)] = defValue;\r\n }\r\n return defValue;\r\n }\r\n return theCache[normalizeJsName(name)];\r\n },\r\n kill: function (target, name) {\r\n if (target && target[name]) {\r\n try {\r\n delete target[name];\r\n }\r\n catch (e) {\r\n // Just cleaning up, so if this fails -- ignore\r\n }\r\n }\r\n }\r\n };\r\n return data;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { _DYN_APPLY, _DYN_LENGTH } from \"../__DynamicConstants\";\r\nimport { getGlobalInst } from \"./EnvUtils\";\r\nvar listenerFuncs = [\"eventsSent\", \"eventsDiscarded\", \"eventsSendRequest\", \"perfEvent\"];\r\nvar _aiNamespace = null;\r\nvar _debugListener;\r\nfunction _listenerProxyFunc(name, config) {\r\n return function () {\r\n var args = arguments;\r\n var dbgExt = getDebugExt(config);\r\n if (dbgExt) {\r\n var listener = dbgExt.listener;\r\n if (listener && listener[name]) {\r\n listener[name][_DYN_APPLY /* @min:%2eapply */](listener, args);\r\n }\r\n }\r\n };\r\n}\r\nfunction _getExtensionNamespace() {\r\n // Cache the lookup of the global namespace object\r\n var target = getGlobalInst(\"Microsoft\");\r\n if (target) {\r\n _aiNamespace = target[\"ApplicationInsights\"];\r\n }\r\n return _aiNamespace;\r\n}\r\nexport function getDebugExt(config) {\r\n var ns = _aiNamespace;\r\n if (!ns && config.disableDbgExt !== true) {\r\n ns = _aiNamespace || _getExtensionNamespace();\r\n }\r\n return ns ? ns[\"ChromeDbgExt\"] : null;\r\n}\r\nexport function getDebugListener(config) {\r\n if (!_debugListener) {\r\n _debugListener = {};\r\n for (var lp = 0; lp < listenerFuncs[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n _debugListener[listenerFuncs[lp]] = _listenerProxyFunc(listenerFuncs[lp], config);\r\n }\r\n }\r\n return _debugListener;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n\"use strict\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { _DYN_DIAG_LOG, _DYN_ENABLE_DEBUG_EXCEPTI4, _DYN_LOGGER, _DYN_LOG_INTERNAL_MESSAGE, _DYN_MESSAGE, _DYN_MESSAGE_ID, _DYN_PUSH, _DYN_REPLACE } from \"../__DynamicConstants\";\r\nimport { getDebugExt } from \"./DbgExtensionUtils\";\r\nimport { dumpObj, getConsole, getJSON, hasJSON } from \"./EnvUtils\";\r\nimport { getCfgValue, isFunction, isUndefined } from \"./HelperFuncs\";\r\nimport { STR_EMPTY, STR_ERROR_TO_CONSOLE, STR_WARN_TO_CONSOLE } from \"./InternalConstants\";\r\n/**\r\n * For user non actionable traces use AI Internal prefix.\r\n */\r\nvar AiNonUserActionablePrefix = \"AI (Internal): \";\r\n/**\r\n * Prefix of the traces in portal.\r\n */\r\nvar AiUserActionablePrefix = \"AI: \";\r\n/**\r\n * Session storage key for the prefix for the key indicating message type already logged\r\n */\r\nvar AIInternalMessagePrefix = \"AITR_\";\r\nfunction _sanitizeDiagnosticText(text) {\r\n if (text) {\r\n return \"\\\"\" + text[_DYN_REPLACE /* @min:%2ereplace */](/\\\"/g, STR_EMPTY) + \"\\\"\";\r\n }\r\n return STR_EMPTY;\r\n}\r\nfunction _logToConsole(func, message) {\r\n var theConsole = getConsole();\r\n if (!!theConsole) {\r\n var logFunc = \"log\";\r\n if (theConsole[func]) {\r\n logFunc = func;\r\n }\r\n if (isFunction(theConsole[logFunc])) {\r\n theConsole[logFunc](message);\r\n }\r\n }\r\n}\r\nvar _InternalLogMessage = /** @class */ (function () {\r\n function _InternalLogMessage(msgId, msg, isUserAct, properties) {\r\n if (isUserAct === void 0) { isUserAct = false; }\r\n var _self = this;\r\n _self[_DYN_MESSAGE_ID /* @min:%2emessageId */] = msgId;\r\n _self[_DYN_MESSAGE /* @min:%2emessage */] =\r\n (isUserAct ? AiUserActionablePrefix : AiNonUserActionablePrefix) +\r\n msgId;\r\n var strProps = STR_EMPTY;\r\n if (hasJSON()) {\r\n strProps = getJSON().stringify(properties);\r\n }\r\n var diagnosticText = (msg ? \" message:\" + _sanitizeDiagnosticText(msg) : STR_EMPTY) +\r\n (properties ? \" props:\" + _sanitizeDiagnosticText(strProps) : STR_EMPTY);\r\n _self[_DYN_MESSAGE /* @min:%2emessage */] += diagnosticText;\r\n }\r\n _InternalLogMessage.dataType = \"MessageData\";\r\n return _InternalLogMessage;\r\n}());\r\nexport { _InternalLogMessage };\r\nexport function safeGetLogger(core, config) {\r\n return (core || {})[_DYN_LOGGER /* @min:%2elogger */] || new DiagnosticLogger(config);\r\n}\r\nvar DiagnosticLogger = /** @class */ (function () {\r\n function DiagnosticLogger(config) {\r\n this.identifier = \"DiagnosticLogger\";\r\n /**\r\n * The internal logging queue\r\n */\r\n this.queue = [];\r\n /**\r\n * Count of internal messages sent\r\n */\r\n var _messageCount = 0;\r\n /**\r\n * Holds information about what message types were already logged to console or sent to server.\r\n */\r\n var _messageLogged = {};\r\n var _loggingLevelConsole;\r\n var _loggingLevelTelemetry;\r\n var _maxInternalMessageLimit;\r\n var _enableDebugExceptions;\r\n dynamicProto(DiagnosticLogger, this, function (_self) {\r\n _setDefaultsFromConfig(config || {});\r\n _self.consoleLoggingLevel = function () { return _loggingLevelConsole; };\r\n _self.telemetryLoggingLevel = function () { return _loggingLevelTelemetry; };\r\n _self.maxInternalMessageLimit = function () { return _maxInternalMessageLimit; };\r\n _self[_DYN_ENABLE_DEBUG_EXCEPTI4 /* @min:%2eenableDebugExceptions */] = function () { return _enableDebugExceptions; };\r\n /**\r\n * This method will throw exceptions in debug mode or attempt to log the error as a console warning.\r\n * @param severity {LoggingSeverity} - The severity of the log message\r\n * @param message {_InternalLogMessage} - The log message.\r\n */\r\n _self.throwInternal = function (severity, msgId, msg, properties, isUserAct) {\r\n if (isUserAct === void 0) { isUserAct = false; }\r\n var message = new _InternalLogMessage(msgId, msg, isUserAct, properties);\r\n if (_enableDebugExceptions) {\r\n throw dumpObj(message);\r\n }\r\n else {\r\n // Get the logging function and fallback to warnToConsole of for some reason errorToConsole doesn't exist\r\n var logFunc = severity === 1 /* eLoggingSeverity.CRITICAL */ ? STR_ERROR_TO_CONSOLE : STR_WARN_TO_CONSOLE;\r\n if (!isUndefined(message[_DYN_MESSAGE /* @min:%2emessage */])) {\r\n if (isUserAct) {\r\n // check if this message type was already logged to console for this page view and if so, don't log it again\r\n var messageKey = +message[_DYN_MESSAGE_ID /* @min:%2emessageId */];\r\n if (!_messageLogged[messageKey] && _loggingLevelConsole >= severity) {\r\n _self[logFunc](message[_DYN_MESSAGE /* @min:%2emessage */]);\r\n _messageLogged[messageKey] = true;\r\n }\r\n }\r\n else {\r\n // Only log traces if the console Logging Level is >= the throwInternal severity level\r\n if (_loggingLevelConsole >= severity) {\r\n _self[logFunc](message[_DYN_MESSAGE /* @min:%2emessage */]);\r\n }\r\n }\r\n _logInternalMessage(severity, message);\r\n }\r\n else {\r\n _debugExtMsg(\"throw\" + (severity === 1 /* eLoggingSeverity.CRITICAL */ ? \"Critical\" : \"Warning\"), message);\r\n }\r\n }\r\n };\r\n /**\r\n * This will write a warning to the console if possible\r\n * @param message {string} - The warning message\r\n */\r\n _self[STR_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */] = function (message) {\r\n _logToConsole(\"warn\", message);\r\n _debugExtMsg(\"warning\", message);\r\n };\r\n /**\r\n * This will write an error to the console if possible\r\n * @param message {string} - The error message\r\n */\r\n _self[STR_ERROR_TO_CONSOLE /* @min:%2eerrorToConsole */] = function (message) {\r\n _logToConsole(\"error\", message);\r\n _debugExtMsg(\"error\", message);\r\n };\r\n /**\r\n * Resets the internal message count\r\n */\r\n _self.resetInternalMessageCount = function () {\r\n _messageCount = 0;\r\n _messageLogged = {};\r\n };\r\n /**\r\n * Logs a message to the internal queue.\r\n * @param severity {LoggingSeverity} - The severity of the log message\r\n * @param message {_InternalLogMessage} - The message to log.\r\n */\r\n _self[_DYN_LOG_INTERNAL_MESSAGE /* @min:%2elogInternalMessage */] = _logInternalMessage;\r\n function _logInternalMessage(severity, message) {\r\n if (_areInternalMessagesThrottled()) {\r\n return;\r\n }\r\n // check if this message type was already logged for this session and if so, don't log it again\r\n var logMessage = true;\r\n var messageKey = AIInternalMessagePrefix + message[_DYN_MESSAGE_ID /* @min:%2emessageId */];\r\n // if the session storage is not available, limit to only one message type per page view\r\n if (_messageLogged[messageKey]) {\r\n logMessage = false;\r\n }\r\n else {\r\n _messageLogged[messageKey] = true;\r\n }\r\n if (logMessage) {\r\n // Push the event in the internal queue\r\n if (severity <= _loggingLevelTelemetry) {\r\n _self.queue[_DYN_PUSH /* @min:%2epush */](message);\r\n _messageCount++;\r\n _debugExtMsg((severity === 1 /* eLoggingSeverity.CRITICAL */ ? \"error\" : \"warn\"), message);\r\n }\r\n // When throttle limit reached, send a special event\r\n if (_messageCount === _maxInternalMessageLimit) {\r\n var throttleLimitMessage = \"Internal events throttle limit per PageView reached for this app.\";\r\n var throttleMessage = new _InternalLogMessage(23 /* _eInternalMessageId.MessageLimitPerPVExceeded */, throttleLimitMessage, false);\r\n _self.queue[_DYN_PUSH /* @min:%2epush */](throttleMessage);\r\n if (severity === 1 /* eLoggingSeverity.CRITICAL */) {\r\n _self[STR_ERROR_TO_CONSOLE /* @min:%2eerrorToConsole */](throttleLimitMessage);\r\n }\r\n else {\r\n _self[STR_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */](throttleLimitMessage);\r\n }\r\n }\r\n }\r\n }\r\n function _setDefaultsFromConfig(config) {\r\n _loggingLevelConsole = getCfgValue(config.loggingLevelConsole, 0);\r\n _loggingLevelTelemetry = getCfgValue(config.loggingLevelTelemetry, 1);\r\n _maxInternalMessageLimit = getCfgValue(config.maxMessageLimit, 25);\r\n _enableDebugExceptions = getCfgValue(config[_DYN_ENABLE_DEBUG_EXCEPTI4 /* @min:%2eenableDebugExceptions */], false);\r\n }\r\n function _areInternalMessagesThrottled() {\r\n return _messageCount >= _maxInternalMessageLimit;\r\n }\r\n function _debugExtMsg(name, data) {\r\n var dbgExt = getDebugExt(config || {});\r\n if (dbgExt && dbgExt[_DYN_DIAG_LOG /* @min:%2ediagLog */]) {\r\n dbgExt[_DYN_DIAG_LOG /* @min:%2ediagLog */](name, data);\r\n }\r\n }\r\n });\r\n }\r\n// Removed Stub for DiagnosticLogger.prototype.enableDebugExceptions.\r\n// Removed Stub for DiagnosticLogger.prototype.consoleLoggingLevel.\r\n// Removed Stub for DiagnosticLogger.prototype.telemetryLoggingLevel.\r\n// Removed Stub for DiagnosticLogger.prototype.maxInternalMessageLimit.\r\n// Removed Stub for DiagnosticLogger.prototype.throwInternal.\r\n// Removed Stub for DiagnosticLogger.prototype.warnToConsole.\r\n// Removed Stub for DiagnosticLogger.prototype.errorToConsole.\r\n// Removed Stub for DiagnosticLogger.prototype.resetInternalMessageCount.\r\n// Removed Stub for DiagnosticLogger.prototype.logInternalMessage.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n DiagnosticLogger.__ieDyn=1;\n\n return DiagnosticLogger;\r\n}());\r\nexport { DiagnosticLogger };\r\nfunction _getLogger(logger) {\r\n return (logger || new DiagnosticLogger());\r\n}\r\n/**\r\n * This is a helper method which will call throwInternal on the passed logger, will throw exceptions in\r\n * debug mode or attempt to log the error as a console warning. This helper is provided mostly to better\r\n * support minification as logger.throwInternal() will not compress the publish \"throwInternal\" used throughout\r\n * the code.\r\n * @param logger - The Diagnostic Logger instance to use.\r\n * @param severity {LoggingSeverity} - The severity of the log message\r\n * @param message {_InternalLogMessage} - The log message.\r\n */\r\nexport function _throwInternal(logger, severity, msgId, msg, properties, isUserAct) {\r\n if (isUserAct === void 0) { isUserAct = false; }\r\n _getLogger(logger).throwInternal(severity, msgId, msg, properties, isUserAct);\r\n}\r\n/**\r\n * This is a helper method which will call warnToConsole on the passed logger with the provided message.\r\n * @param logger - The Diagnostic Logger instance to use.\r\n * @param message {_InternalLogMessage} - The log message.\r\n */\r\nexport function _warnToConsole(logger, message) {\r\n _getLogger(logger)[STR_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */](message);\r\n}\r\n/**\r\n * Logs a message to the internal queue.\r\n * @param logger - The Diagnostic Logger instance to use.\r\n * @param severity {LoggingSeverity} - The severity of the log message\r\n * @param message {_InternalLogMessage} - The message to log.\r\n */\r\nexport function _logInternalMessage(logger, severity, message) {\r\n _getLogger(logger)[_DYN_LOG_INTERNAL_MESSAGE /* @min:%2elogInternalMessage */](severity, message);\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n\"use strict\";\r\nimport { getGlobal, strShimObject, strShimPrototype, strShimUndefined } from \"@microsoft/applicationinsights-shims\";\r\nimport { _DYN_CALL, _DYN_INDEX_OF, _DYN_LENGTH, _DYN_NAME, _DYN_SPLIT, _DYN_TO_LOWER_CASE, _DYN_USER_AGENT } from \"../__DynamicConstants\";\r\nimport { isString, isUndefined, strContains } from \"./HelperFuncs\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\n/**\r\n * This file exists to hold environment utilities that are required to check and\r\n * validate the current operating environment. Unless otherwise required, please\r\n * only use defined methods (functions) in this class so that users of these\r\n * functions/properties only need to include those that are used within their own modules.\r\n */\r\nvar strWindow = \"window\";\r\nvar strDocument = \"document\";\r\nvar strDocumentMode = \"documentMode\";\r\nvar strNavigator = \"navigator\";\r\nvar strHistory = \"history\";\r\nvar strLocation = \"location\";\r\nvar strConsole = \"console\";\r\nvar strPerformance = \"performance\";\r\nvar strJSON = \"JSON\";\r\nvar strCrypto = \"crypto\";\r\nvar strMsCrypto = \"msCrypto\";\r\nvar strReactNative = \"ReactNative\";\r\nvar strMsie = \"msie\";\r\nvar strTrident = \"trident/\";\r\nvar strXMLHttpRequest = \"XMLHttpRequest\";\r\nvar _isTrident = null;\r\nvar _navUserAgentCheck = null;\r\nvar _enableMocks = false;\r\nvar _useXDomainRequest = null;\r\nvar _beaconsSupported = null;\r\nfunction _hasProperty(theClass, property) {\r\n var supported = false;\r\n if (theClass) {\r\n try {\r\n supported = property in theClass;\r\n if (!supported) {\r\n var proto = theClass[strShimPrototype];\r\n if (proto) {\r\n supported = property in proto;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // Do Nothing\r\n }\r\n if (!supported) {\r\n try {\r\n var tmp = new theClass();\r\n supported = !isUndefined(tmp[property]);\r\n }\r\n catch (e) {\r\n // Do Nothing\r\n }\r\n }\r\n }\r\n return supported;\r\n}\r\n/**\r\n * Enable the lookup of test mock objects if requested\r\n * @param enabled\r\n */\r\nexport function setEnableEnvMocks(enabled) {\r\n _enableMocks = enabled;\r\n}\r\n/**\r\n * Return the named global object if available, will return null if the object is not available.\r\n * @param name The globally named object\r\n */\r\nexport function getGlobalInst(name) {\r\n var gbl = getGlobal();\r\n if (gbl && gbl[name]) {\r\n return gbl[name];\r\n }\r\n // Test workaround, for environments where .window (when global == window) doesn't return the base window\r\n if (name === strWindow && hasWindow()) {\r\n // tslint:disable-next-line: no-angle-bracket-type-assertion\r\n return window;\r\n }\r\n return null;\r\n}\r\n/**\r\n * Checks if window object is available, this is required as we support the API running without a\r\n * window /document (eg. Node server, electron webworkers) and if we attempt to assign a window\r\n * object to a local variable or pass as an argument an \"Uncaught ReferenceError: window is not defined\"\r\n * exception will be thrown.\r\n * Defined as a function to support lazy / late binding environments.\r\n */\r\nexport function hasWindow() {\r\n return Boolean(typeof window === strShimObject && window);\r\n}\r\n/**\r\n * Returns the global window object if it is present otherwise null.\r\n * This helper is used to access the window object without causing an exception\r\n * \"Uncaught ReferenceError: window is not defined\"\r\n */\r\nexport function getWindow() {\r\n if (hasWindow()) {\r\n return window;\r\n }\r\n // Return the global instance or null\r\n return getGlobalInst(strWindow);\r\n}\r\n/**\r\n * Checks if document object is available, this is required as we support the API running without a\r\n * window /document (eg. Node server, electron webworkers) and if we attempt to assign a document\r\n * object to a local variable or pass as an argument an \"Uncaught ReferenceError: document is not defined\"\r\n * exception will be thrown.\r\n * Defined as a function to support lazy / late binding environments.\r\n */\r\nexport function hasDocument() {\r\n return Boolean(typeof document === strShimObject && document);\r\n}\r\n/**\r\n * Returns the global document object if it is present otherwise null.\r\n * This helper is used to access the document object without causing an exception\r\n * \"Uncaught ReferenceError: document is not defined\"\r\n */\r\nexport function getDocument() {\r\n if (hasDocument()) {\r\n return document;\r\n }\r\n return getGlobalInst(strDocument);\r\n}\r\n/**\r\n * Checks if navigator object is available, this is required as we support the API running without a\r\n * window /document (eg. Node server, electron webworkers) and if we attempt to assign a navigator\r\n * object to a local variable or pass as an argument an \"Uncaught ReferenceError: navigator is not defined\"\r\n * exception will be thrown.\r\n * Defined as a function to support lazy / late binding environments.\r\n */\r\nexport function hasNavigator() {\r\n return Boolean(typeof navigator === strShimObject && navigator);\r\n}\r\n/**\r\n * Returns the global navigator object if it is present otherwise null.\r\n * This helper is used to access the navigator object without causing an exception\r\n * \"Uncaught ReferenceError: navigator is not defined\"\r\n */\r\nexport function getNavigator() {\r\n if (hasNavigator()) {\r\n return navigator;\r\n }\r\n return getGlobalInst(strNavigator);\r\n}\r\n/**\r\n * Checks if history object is available, this is required as we support the API running without a\r\n * window /document (eg. Node server, electron webworkers) and if we attempt to assign a history\r\n * object to a local variable or pass as an argument an \"Uncaught ReferenceError: history is not defined\"\r\n * exception will be thrown.\r\n * Defined as a function to support lazy / late binding environments.\r\n */\r\nexport function hasHistory() {\r\n return Boolean(typeof history === strShimObject && history);\r\n}\r\n/**\r\n * Returns the global history object if it is present otherwise null.\r\n * This helper is used to access the history object without causing an exception\r\n * \"Uncaught ReferenceError: history is not defined\"\r\n */\r\nexport function getHistory() {\r\n if (hasHistory()) {\r\n return history;\r\n }\r\n return getGlobalInst(strHistory);\r\n}\r\n/**\r\n * Returns the global location object if it is present otherwise null.\r\n * This helper is used to access the location object without causing an exception\r\n * \"Uncaught ReferenceError: location is not defined\"\r\n */\r\nexport function getLocation(checkForMock) {\r\n if (checkForMock && _enableMocks) {\r\n var mockLocation = getGlobalInst(\"__mockLocation\");\r\n if (mockLocation) {\r\n return mockLocation;\r\n }\r\n }\r\n if (typeof location === strShimObject && location) {\r\n return location;\r\n }\r\n return getGlobalInst(strLocation);\r\n}\r\n/**\r\n * Returns the global console object\r\n */\r\nexport function getConsole() {\r\n if (typeof console !== strShimUndefined) {\r\n return console;\r\n }\r\n return getGlobalInst(strConsole);\r\n}\r\n/**\r\n * Returns the performance object if it is present otherwise null.\r\n * This helper is used to access the performance object from the current\r\n * global instance which could be window or globalThis for a web worker\r\n */\r\nexport function getPerformance() {\r\n return getGlobalInst(strPerformance);\r\n}\r\n/**\r\n * Checks if JSON object is available, this is required as we support the API running without a\r\n * window /document (eg. Node server, electron webworkers) and if we attempt to assign a history\r\n * object to a local variable or pass as an argument an \"Uncaught ReferenceError: JSON is not defined\"\r\n * exception will be thrown.\r\n * Defined as a function to support lazy / late binding environments.\r\n */\r\nexport function hasJSON() {\r\n return Boolean((typeof JSON === strShimObject && JSON) || getGlobalInst(strJSON) !== null);\r\n}\r\n/**\r\n * Returns the global JSON object if it is present otherwise null.\r\n * This helper is used to access the JSON object without causing an exception\r\n * \"Uncaught ReferenceError: JSON is not defined\"\r\n */\r\nexport function getJSON() {\r\n if (hasJSON()) {\r\n return JSON || getGlobalInst(strJSON);\r\n }\r\n return null;\r\n}\r\n/**\r\n * Returns the crypto object if it is present otherwise null.\r\n * This helper is used to access the crypto object from the current\r\n * global instance which could be window or globalThis for a web worker\r\n */\r\nexport function getCrypto() {\r\n return getGlobalInst(strCrypto);\r\n}\r\n/**\r\n * Returns the crypto object if it is present otherwise null.\r\n * This helper is used to access the crypto object from the current\r\n * global instance which could be window or globalThis for a web worker\r\n */\r\nexport function getMsCrypto() {\r\n return getGlobalInst(strMsCrypto);\r\n}\r\n/**\r\n * Returns whether the environment is reporting that we are running in a React Native Environment\r\n */\r\nexport function isReactNative() {\r\n // If running in React Native, navigator.product will be populated\r\n var nav = getNavigator();\r\n if (nav && nav.product) {\r\n return nav.product === strReactNative;\r\n }\r\n return false;\r\n}\r\n/**\r\n * Identifies whether the current environment appears to be IE\r\n */\r\nexport function isIE() {\r\n var nav = getNavigator();\r\n if (nav && (nav[_DYN_USER_AGENT /* @min:%2euserAgent */] !== _navUserAgentCheck || _isTrident === null)) {\r\n // Added to support test mocking of the user agent\r\n _navUserAgentCheck = nav[_DYN_USER_AGENT /* @min:%2euserAgent */];\r\n var userAgent = (_navUserAgentCheck || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n _isTrident = (strContains(userAgent, strMsie) || strContains(userAgent, strTrident));\r\n }\r\n return _isTrident;\r\n}\r\n/**\r\n * Gets IE version returning the document emulation mode if we are running on IE, or null otherwise\r\n */\r\nexport function getIEVersion(userAgentStr) {\r\n if (userAgentStr === void 0) { userAgentStr = null; }\r\n if (!userAgentStr) {\r\n var navigator_1 = getNavigator() || {};\r\n userAgentStr = navigator_1 ? (navigator_1[_DYN_USER_AGENT /* @min:%2euserAgent */] || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() : STR_EMPTY;\r\n }\r\n var ua = (userAgentStr || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n // Also check for documentMode in case X-UA-Compatible meta tag was included in HTML.\r\n if (strContains(ua, strMsie)) {\r\n var doc = getDocument() || {};\r\n return Math.max(parseInt(ua[_DYN_SPLIT /* @min:%2esplit */](strMsie)[1]), (doc[strDocumentMode] || 0));\r\n }\r\n else if (strContains(ua, strTrident)) {\r\n var tridentVer = parseInt(ua[_DYN_SPLIT /* @min:%2esplit */](strTrident)[1]);\r\n if (tridentVer) {\r\n return tridentVer + 4;\r\n }\r\n }\r\n return null;\r\n}\r\n/**\r\n * Returns string representation of an object suitable for diagnostics logging.\r\n */\r\nexport function dumpObj(object) {\r\n var objectTypeDump = Object[strShimPrototype].toString[_DYN_CALL /* @min:%2ecall */](object);\r\n var propertyValueDump = STR_EMPTY;\r\n if (objectTypeDump === \"[object Error]\") {\r\n propertyValueDump = \"{ stack: '\" + object.stack + \"', message: '\" + object.message + \"', name: '\" + object[_DYN_NAME /* @min:%2ename */] + \"'\";\r\n }\r\n else if (hasJSON()) {\r\n propertyValueDump = getJSON().stringify(object);\r\n }\r\n return objectTypeDump + propertyValueDump;\r\n}\r\nexport function isSafari(userAgentStr) {\r\n if (!userAgentStr || !isString(userAgentStr)) {\r\n var navigator_2 = getNavigator() || {};\r\n userAgentStr = navigator_2 ? (navigator_2[_DYN_USER_AGENT /* @min:%2euserAgent */] || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() : STR_EMPTY;\r\n }\r\n var ua = (userAgentStr || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n return (ua[_DYN_INDEX_OF /* @min:%2eindexOf */](\"safari\") >= 0);\r\n}\r\n/**\r\n * Checks if HTML5 Beacons are supported in the current environment.\r\n * @returns True if supported, false otherwise.\r\n */\r\nexport function isBeaconsSupported() {\r\n if (_beaconsSupported === null) {\r\n _beaconsSupported = hasNavigator() && Boolean(getNavigator().sendBeacon);\r\n }\r\n return _beaconsSupported;\r\n}\r\n/**\r\n * Checks if the Fetch API is supported in the current environment.\r\n * @param withKeepAlive - [Optional] If True, check if fetch is available and it supports the keepalive feature, otherwise only check if fetch is supported\r\n * @returns True if supported, otherwise false\r\n */\r\nexport function isFetchSupported(withKeepAlive) {\r\n var isSupported = false;\r\n try {\r\n isSupported = !!getGlobalInst(\"fetch\");\r\n var request = getGlobalInst(\"Request\");\r\n if (isSupported && withKeepAlive && request) {\r\n isSupported = _hasProperty(request, \"keepalive\");\r\n }\r\n }\r\n catch (e) {\r\n // Just Swallow any failure during availability checks\r\n }\r\n return isSupported;\r\n}\r\nexport function useXDomainRequest() {\r\n if (_useXDomainRequest === null) {\r\n _useXDomainRequest = (typeof XDomainRequest !== strShimUndefined);\r\n if (_useXDomainRequest && isXhrSupported()) {\r\n _useXDomainRequest = _useXDomainRequest && !_hasProperty(getGlobalInst(strXMLHttpRequest), \"withCredentials\");\r\n }\r\n }\r\n return _useXDomainRequest;\r\n}\r\n/**\r\n * Checks if XMLHttpRequest is supported\r\n * @returns True if supported, otherwise false\r\n */\r\nexport function isXhrSupported() {\r\n var isSupported = false;\r\n try {\r\n var xmlHttpRequest = getGlobalInst(strXMLHttpRequest);\r\n isSupported = !!xmlHttpRequest;\r\n }\r\n catch (e) {\r\n // Just Swallow any failure during availability checks\r\n }\r\n return isSupported;\r\n}\r\nfunction _getNamedValue(values, name) {\r\n if (values) {\r\n for (var i = 0; i < values[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n var value = values[i];\r\n if (value[_DYN_NAME /* @min:%2ename */]) {\r\n if (value[_DYN_NAME /* @min:%2ename */] === name) {\r\n return value;\r\n }\r\n }\r\n }\r\n }\r\n return {};\r\n}\r\n/**\r\n * Helper function to fetch the named meta-tag from the page.\r\n * @param name\r\n */\r\nexport function findMetaTag(name) {\r\n var doc = getDocument();\r\n if (doc && name) {\r\n // Look for a meta-tag\r\n return _getNamedValue(doc.querySelectorAll(\"meta\"), name).content;\r\n }\r\n return null;\r\n}\r\n/**\r\n * Helper function to fetch the named server timing value from the page response (first navigation event).\r\n * @param name\r\n */\r\nexport function findNamedServerTiming(name) {\r\n var value;\r\n var perf = getPerformance();\r\n if (perf) {\r\n // Try looking for a server-timing header\r\n var navPerf = perf.getEntriesByType(\"navigation\") || [];\r\n value = _getNamedValue((navPerf[_DYN_LENGTH /* @min:%2elength */] > 0 ? navPerf[0] : {}).serverTiming, name).description;\r\n }\r\n return value;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { _DYN_HANDLER, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_REPLACE, _DYN_SPLICE, _DYN_SPLIT, _DYN_TYPE } from \"../__DynamicConstants\";\r\nimport { createElmNodeData, createUniqueNamespace } from \"./DataCacheHelper\";\r\nimport { getDocument, getWindow } from \"./EnvUtils\";\r\nimport { arrForEach, arrIndexOf, isArray, objForEachKey, objKeys } from \"./HelperFuncs\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\n// Added to help with minfication\r\nvar strOnPrefix = \"on\";\r\nvar strAttachEvent = \"attachEvent\";\r\nvar strAddEventHelper = \"addEventListener\";\r\nvar strDetachEvent = \"detachEvent\";\r\nvar strRemoveEventListener = \"removeEventListener\";\r\nvar strEvents = \"events\";\r\nvar strVisibilityChangeEvt = \"visibilitychange\";\r\nvar strPageHide = \"pagehide\";\r\nvar strPageShow = \"pageshow\";\r\nvar strUnload = \"unload\";\r\nvar strBeforeUnload = \"beforeunload\";\r\nvar strPageHideNamespace = createUniqueNamespace(\"aiEvtPageHide\");\r\nvar strPageShowNamespace = createUniqueNamespace(\"aiEvtPageShow\");\r\nvar rRemoveEmptyNs = /\\.[\\.]+/g;\r\nvar rRemoveTrailingEmptyNs = /[\\.]+$/;\r\nvar _guid = 1;\r\nvar elmNodeData = createElmNodeData(\"events\");\r\nvar eventNamespace = /^([^.]*)(?:\\.(.+)|)/;\r\nfunction _normalizeNamespace(name) {\r\n if (name && name[_DYN_REPLACE /* @min:%2ereplace */]) {\r\n return name[_DYN_REPLACE /* @min:%2ereplace */](/^[\\s\\.]+|(?=[\\s\\.])[\\.\\s]+$/g, STR_EMPTY);\r\n }\r\n return name;\r\n}\r\nfunction _getEvtNamespace(eventName, evtNamespace) {\r\n var _a;\r\n if (evtNamespace) {\r\n var theNamespace_1 = STR_EMPTY;\r\n if (isArray(evtNamespace)) {\r\n theNamespace_1 = STR_EMPTY;\r\n arrForEach(evtNamespace, function (name) {\r\n name = _normalizeNamespace(name);\r\n if (name) {\r\n if (name[0] !== \".\") {\r\n name = \".\" + name;\r\n }\r\n theNamespace_1 += name;\r\n }\r\n });\r\n }\r\n else {\r\n theNamespace_1 = _normalizeNamespace(evtNamespace);\r\n }\r\n if (theNamespace_1) {\r\n if (theNamespace_1[0] !== \".\") {\r\n theNamespace_1 = \".\" + theNamespace_1;\r\n }\r\n // We may only have the namespace and not an eventName\r\n eventName = (eventName || STR_EMPTY) + theNamespace_1;\r\n }\r\n }\r\n var parsedEvent = (eventNamespace.exec(eventName || STR_EMPTY) || []);\r\n return _a = {},\r\n _a[_DYN_TYPE /* @min:type */] = parsedEvent[1],\r\n _a.ns = ((parsedEvent[2] || STR_EMPTY).replace(rRemoveEmptyNs, \".\").replace(rRemoveTrailingEmptyNs, STR_EMPTY)[_DYN_SPLIT /* @min:%2esplit */](\".\").sort()).join(\".\"),\r\n _a;\r\n}\r\n/**\r\n * Get all of the registered events on the target object, this is primarily used for testing cleanup but may also be used by\r\n * applications to remove their own events\r\n * @param target - The EventTarget that has registered events\r\n * @param eventName - [Optional] The name of the event to return the registered handlers and full name (with namespaces)\r\n * @param evtNamespace - [Optional] Additional namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace,\r\n * if the eventName also includes a namespace the namespace(s) are merged into a single namespace\r\n */\r\nexport function __getRegisteredEvents(target, eventName, evtNamespace) {\r\n var theEvents = [];\r\n var eventCache = elmNodeData.get(target, strEvents, {}, false);\r\n var evtName = _getEvtNamespace(eventName, evtNamespace);\r\n objForEachKey(eventCache, function (evtType, registeredEvents) {\r\n arrForEach(registeredEvents, function (value) {\r\n var _a;\r\n if (!evtName[_DYN_TYPE /* @min:%2etype */] || evtName[_DYN_TYPE /* @min:%2etype */] === value.evtName[_DYN_TYPE /* @min:%2etype */]) {\r\n if (!evtName.ns || evtName.ns === evtName.ns) {\r\n theEvents[_DYN_PUSH /* @min:%2epush */]((_a = {},\r\n _a[_DYN_NAME /* @min:name */] = value.evtName[_DYN_TYPE /* @min:%2etype */] + (value.evtName.ns ? \".\" + value.evtName.ns : STR_EMPTY),\r\n _a.handler = value[_DYN_HANDLER /* @min:%2ehandler */],\r\n _a));\r\n }\r\n }\r\n });\r\n });\r\n return theEvents;\r\n}\r\n// Exported for internal unit testing only\r\nfunction _getRegisteredEvents(target, evtName, addDefault) {\r\n if (addDefault === void 0) { addDefault = true; }\r\n var aiEvts = elmNodeData.get(target, strEvents, {}, addDefault);\r\n var registeredEvents = aiEvts[evtName];\r\n if (!registeredEvents) {\r\n registeredEvents = aiEvts[evtName] = [];\r\n }\r\n return registeredEvents;\r\n}\r\nfunction _doDetach(obj, evtName, handlerRef, useCapture) {\r\n if (obj && evtName && evtName[_DYN_TYPE /* @min:%2etype */]) {\r\n if (obj[strRemoveEventListener]) {\r\n obj[strRemoveEventListener](evtName[_DYN_TYPE /* @min:%2etype */], handlerRef, useCapture);\r\n }\r\n else if (obj[strDetachEvent]) {\r\n obj[strDetachEvent](strOnPrefix + evtName[_DYN_TYPE /* @min:%2etype */], handlerRef);\r\n }\r\n }\r\n}\r\nfunction _doAttach(obj, evtName, handlerRef, useCapture) {\r\n var result = false;\r\n if (obj && evtName && evtName[_DYN_TYPE /* @min:%2etype */] && handlerRef) {\r\n if (obj[strAddEventHelper]) {\r\n // all browsers except IE before version 9\r\n obj[strAddEventHelper](evtName[_DYN_TYPE /* @min:%2etype */], handlerRef, useCapture);\r\n result = true;\r\n }\r\n else if (obj[strAttachEvent]) {\r\n // IE before version 9\r\n obj[strAttachEvent](strOnPrefix + evtName[_DYN_TYPE /* @min:%2etype */], handlerRef);\r\n result = true;\r\n }\r\n }\r\n return result;\r\n}\r\nfunction _doUnregister(target, events, evtName, unRegFn) {\r\n var idx = events[_DYN_LENGTH /* @min:%2elength */];\r\n while (idx--) {\r\n var theEvent = events[idx];\r\n if (theEvent) {\r\n if (!evtName.ns || evtName.ns === theEvent.evtName.ns) {\r\n if (!unRegFn || unRegFn(theEvent)) {\r\n _doDetach(target, theEvent.evtName, theEvent[_DYN_HANDLER /* @min:%2ehandler */], theEvent.capture);\r\n // Remove the registered event\r\n events[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\r\n }\r\n }\r\n }\r\n }\r\n}\r\nfunction _unregisterEvents(target, evtName, unRegFn) {\r\n if (evtName[_DYN_TYPE /* @min:%2etype */]) {\r\n _doUnregister(target, _getRegisteredEvents(target, evtName[_DYN_TYPE /* @min:%2etype */]), evtName, unRegFn);\r\n }\r\n else {\r\n var eventCache = elmNodeData.get(target, strEvents, {});\r\n objForEachKey(eventCache, function (evtType, events) {\r\n _doUnregister(target, events, evtName, unRegFn);\r\n });\r\n // Cleanup\r\n if (objKeys(eventCache)[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n elmNodeData.kill(target, strEvents);\r\n }\r\n }\r\n}\r\nexport function mergeEvtNamespace(theNamespace, namespaces) {\r\n var newNamespaces;\r\n if (namespaces) {\r\n if (isArray(namespaces)) {\r\n newNamespaces = [theNamespace].concat(namespaces);\r\n }\r\n else {\r\n newNamespaces = [theNamespace, namespaces];\r\n }\r\n // resort the namespaces so they are always in order\r\n newNamespaces = (_getEvtNamespace(\"xx\", newNamespaces).ns)[_DYN_SPLIT /* @min:%2esplit */](\".\");\r\n }\r\n else {\r\n newNamespaces = theNamespace;\r\n }\r\n return newNamespaces;\r\n}\r\n/**\r\n * Binds the specified function to an event, so that the function gets called whenever the event fires on the object\r\n * @param obj Object to add the event too.\r\n * @param eventName String that specifies any of the standard DHTML Events without \"on\" prefix, if may also include an optional (dot \".\" prefixed)\r\n * namespaces \"click\" \"click.mynamespace\" in addition to specific namespaces.\r\n * @param handlerRef Pointer that specifies the function to call when event fires\r\n * @param evtNamespace - [Optional] Additional namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace,\r\n * if the eventName also includes a namespace the namespace(s) are merged into a single namespace\r\n * @param useCapture [Optional] Defaults to false\r\n * @returns True if the function was bound successfully to the event, otherwise false\r\n */\r\nexport function eventOn(target, eventName, handlerRef, evtNamespace, useCapture) {\r\n var _a;\r\n if (useCapture === void 0) { useCapture = false; }\r\n var result = false;\r\n if (target) {\r\n try {\r\n var evtName = _getEvtNamespace(eventName, evtNamespace);\r\n result = _doAttach(target, evtName, handlerRef, useCapture);\r\n if (result && elmNodeData.accept(target)) {\r\n var registeredEvent = (_a = {\r\n guid: _guid++,\r\n evtName: evtName\r\n },\r\n _a[_DYN_HANDLER /* @min:handler */] = handlerRef,\r\n _a.capture = useCapture,\r\n _a);\r\n _getRegisteredEvents(target, evtName.type)[_DYN_PUSH /* @min:%2epush */](registeredEvent);\r\n }\r\n }\r\n catch (e) {\r\n // Just Ignore any error so that we don't break any execution path\r\n }\r\n }\r\n return result;\r\n}\r\n/**\r\n * Removes an event handler for the specified event\r\n * @param Object to remove the event from\r\n * @param eventName {string} - The name of the event, with optional namespaces or just the namespaces,\r\n * such as \"click\", \"click.mynamespace\" or \".mynamespace\"\r\n * @param handlerRef {any} - The callback function that needs to be removed from the given event, when using a\r\n * namespace (with or without a qualifying event) this may be null to remove all previously attached event handlers\r\n * otherwise this will only remove events with this specific handler.\r\n * @param evtNamespace - [Optional] Additional namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace,\r\n * if the eventName also includes a namespace the namespace(s) are merged into a single namespace\r\n * @param useCapture [Optional] Defaults to false\r\n */\r\nexport function eventOff(target, eventName, handlerRef, evtNamespace, useCapture) {\r\n if (useCapture === void 0) { useCapture = false; }\r\n if (target) {\r\n try {\r\n var evtName_1 = _getEvtNamespace(eventName, evtNamespace);\r\n var found_1 = false;\r\n _unregisterEvents(target, evtName_1, function (regEvent) {\r\n if ((evtName_1.ns && !handlerRef) || regEvent[_DYN_HANDLER /* @min:%2ehandler */] === handlerRef) {\r\n found_1 = true;\r\n return true;\r\n }\r\n return false;\r\n });\r\n if (!found_1) {\r\n // fallback to try and remove as requested\r\n _doDetach(target, evtName_1, handlerRef, useCapture);\r\n }\r\n }\r\n catch (e) {\r\n // Just Ignore any error so that we don't break any execution path\r\n }\r\n }\r\n}\r\n/**\r\n * Binds the specified function to an event, so that the function gets called whenever the event fires on the object\r\n * @param obj Object to add the event too.\r\n * @param eventNameWithoutOn String that specifies any of the standard DHTML Events without \"on\" prefix and optional (dot \".\" prefixed) namespaces \"click\" \"click.mynamespace\".\r\n * @param handlerRef Pointer that specifies the function to call when event fires\r\n * @param useCapture [Optional] Defaults to false\r\n * @returns True if the function was bound successfully to the event, otherwise false\r\n */\r\nexport function attachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {\r\n if (useCapture === void 0) { useCapture = false; }\r\n return eventOn(obj, eventNameWithoutOn, handlerRef, null, useCapture);\r\n}\r\n/**\r\n * Removes an event handler for the specified event\r\n * @param Object to remove the event from\r\n * @param eventNameWithoutOn {string} - The name of the event, with optional namespaces or just the namespaces,\r\n * such as \"click\", \"click.mynamespace\" or \".mynamespace\"\r\n * @param handlerRef {any} - The callback function that needs to be removed from the given event, when using a\r\n * namespace (with or without a qualifying event) this may be null to remove all previously attached event handlers\r\n * otherwise this will only remove events with this specific handler.\r\n * @param useCapture [Optional] Defaults to false\r\n */\r\nexport function detachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {\r\n if (useCapture === void 0) { useCapture = false; }\r\n eventOff(obj, eventNameWithoutOn, handlerRef, null, useCapture);\r\n}\r\n/**\r\n * Trys to add an event handler for the specified event to the window, body and document\r\n * @param eventName {string} - The name of the event\r\n * @param callback {any} - The callback function that needs to be executed for the given event\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n * @return {boolean} - true if the handler was successfully added\r\n */\r\nexport function addEventHandler(eventName, callback, evtNamespace) {\r\n var result = false;\r\n var w = getWindow();\r\n if (w) {\r\n result = eventOn(w, eventName, callback, evtNamespace);\r\n result = eventOn(w[\"body\"], eventName, callback, evtNamespace) || result;\r\n }\r\n var doc = getDocument();\r\n if (doc) {\r\n result = eventOn(doc, eventName, callback, evtNamespace) || result;\r\n }\r\n return result;\r\n}\r\n/**\r\n * Trys to remove event handler(s) for the specified event/namespace to the window, body and document\r\n * @param eventName {string} - The name of the event, with optional namespaces or just the namespaces,\r\n * such as \"click\", \"click.mynamespace\" or \".mynamespace\"\r\n * @param callback {any} - - The callback function that needs to be removed from the given event, when using a\r\n * namespace (with or without a qualifying event) this may be null to remove all previously attached event handlers\r\n * otherwise this will only remove events with this specific handler.\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n */\r\nexport function removeEventHandler(eventName, callback, evtNamespace) {\r\n var w = getWindow();\r\n if (w) {\r\n eventOff(w, eventName, callback, evtNamespace);\r\n eventOff(w[\"body\"], eventName, callback, evtNamespace);\r\n }\r\n var doc = getDocument();\r\n if (doc) {\r\n eventOff(doc, eventName, callback, evtNamespace);\r\n }\r\n}\r\n/**\r\n * Bind the listener to the array of events\r\n * @param events An string array of event names to bind the listener to\r\n * @param listener The event callback to call when the event is triggered\r\n * @param excludeEvents - [Optional] An array of events that should not be hooked (if possible), unless no other events can be.\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\r\nfunction _addEventListeners(events, listener, excludeEvents, evtNamespace) {\r\n var added = false;\r\n if (listener && events && events[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(events, function (name) {\r\n if (name) {\r\n if (!excludeEvents || arrIndexOf(excludeEvents, name) === -1) {\r\n added = addEventHandler(name, listener, evtNamespace) || added;\r\n }\r\n }\r\n });\r\n }\r\n return added;\r\n}\r\n/**\r\n * Bind the listener to the array of events\r\n * @param events An string array of event names to bind the listener to\r\n * @param listener The event callback to call when the event is triggered\r\n * @param excludeEvents - [Optional] An array of events that should not be hooked (if possible), unless no other events can be.\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\r\nexport function addEventListeners(events, listener, excludeEvents, evtNamespace) {\r\n var added = false;\r\n if (listener && events && isArray(events)) {\r\n added = _addEventListeners(events, listener, excludeEvents, evtNamespace);\r\n if (!added && excludeEvents && excludeEvents[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n // Failed to add any listeners and we excluded some, so just attempt to add the excluded events\r\n added = _addEventListeners(events, listener, null, evtNamespace);\r\n }\r\n }\r\n return added;\r\n}\r\n/**\r\n * Remove the listener from the array of events\r\n * @param events An string array of event names to bind the listener to\r\n * @param listener The event callback to call when the event is triggered\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n */\r\nexport function removeEventListeners(events, listener, evtNamespace) {\r\n if (events && isArray(events)) {\r\n arrForEach(events, function (name) {\r\n if (name) {\r\n removeEventHandler(name, listener, evtNamespace);\r\n }\r\n });\r\n }\r\n}\r\n/**\r\n * Listen to the 'beforeunload', 'unload' and 'pagehide' events which indicates a page unload is occurring,\r\n * this does NOT listen to the 'visibilitychange' event as while it does indicate that the page is being hidden\r\n * it does not *necessarily* mean that the page is being completely unloaded, it can mean that the user is\r\n * just navigating to a different Tab and may come back (without unloading the page). As such you may also\r\n * need to listen to the 'addPageHideEventListener' and 'addPageShowEventListener' events.\r\n * @param listener - The event callback to call when a page unload event is triggered\r\n * @param excludeEvents - [Optional] An array of events that should not be hooked, unless no other events can be.\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\r\nexport function addPageUnloadEventListener(listener, excludeEvents, evtNamespace) {\r\n // Hook the unload event for the document, window and body to ensure that the client events are flushed to the server\r\n // As just hooking the window does not always fire (on chrome) for page navigation's.\r\n return addEventListeners([strBeforeUnload, strUnload, strPageHide], listener, excludeEvents, evtNamespace);\r\n}\r\n/**\r\n * Remove any matching 'beforeunload', 'unload' and 'pagehide' events that may have been added via addEventListener,\r\n * addEventListeners, addPageUnloadEventListener or addPageHideEventListener.\r\n * @param listener - The specific event callback to to be removed\r\n * @param evtNamespace - [Optional] Namespace(s) uniquely identified and removed based on this namespace.\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\r\nexport function removePageUnloadEventListener(listener, evtNamespace) {\r\n removeEventListeners([strBeforeUnload, strUnload, strPageHide], listener, evtNamespace);\r\n}\r\n/**\r\n * Listen to the pagehide and visibility changing to 'hidden' events, because the 'visibilitychange' uses\r\n * an internal proxy to detect the visibility state you SHOULD use a unique namespace when if you plan to call\r\n * removePageShowEventListener as the remove ignores the listener argument for the 'visibilitychange' event.\r\n * @param listener - The event callback to call when a page hide event is triggered\r\n * @param excludeEvents - [Optional] An array of events that should not be hooked (if possible), unless no other events can be.\r\n * @param evtNamespace - [Optional] A Namespace to append to the event listeners so they can be uniquely identified and removed\r\n * based on this namespace. This call also adds an additional unique \"pageshow\" namespace to the events\r\n * so that only the matching \"removePageHideEventListener\" can remove these events.\r\n * Suggestion: pass as true if you are also calling addPageUnloadEventListener as that also hooks pagehide\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\r\nexport function addPageHideEventListener(listener, excludeEvents, evtNamespace) {\r\n function _handlePageVisibility(evt) {\r\n var doc = getDocument();\r\n if (listener && doc && doc.visibilityState === \"hidden\") {\r\n listener(evt);\r\n }\r\n }\r\n // add the unique page show namespace to any provided namespace so we can only remove the ones added by \"pagehide\"\r\n var newNamespaces = mergeEvtNamespace(strPageHideNamespace, evtNamespace);\r\n var pageUnloadAdded = _addEventListeners([strPageHide], listener, excludeEvents, newNamespaces);\r\n if (!excludeEvents || arrIndexOf(excludeEvents, strVisibilityChangeEvt) === -1) {\r\n pageUnloadAdded = _addEventListeners([strVisibilityChangeEvt], _handlePageVisibility, excludeEvents, newNamespaces) || pageUnloadAdded;\r\n }\r\n if (!pageUnloadAdded && excludeEvents) {\r\n // Failed to add any listeners and we where requested to exclude some, so just call again without excluding anything\r\n pageUnloadAdded = addPageHideEventListener(listener, null, evtNamespace);\r\n }\r\n return pageUnloadAdded;\r\n}\r\n/**\r\n * Removes the pageHide event listeners added by addPageHideEventListener, because the 'visibilitychange' uses\r\n * an internal proxy to detect the visibility state you SHOULD use a unique namespace when calling addPageHideEventListener\r\n * as the remove ignores the listener argument for the 'visibilitychange' event.\r\n * @param listener - The specific listener to remove for the 'pageshow' event only (ignored for 'visibilitychange')\r\n * @param evtNamespace - The unique namespace used when calling addPageShowEventListener\r\n */\r\nexport function removePageHideEventListener(listener, evtNamespace) {\r\n // add the unique page show namespace to any provided namespace so we only remove the ones added by \"pagehide\"\r\n var newNamespaces = mergeEvtNamespace(strPageHideNamespace, evtNamespace);\r\n removeEventListeners([strPageHide], listener, newNamespaces);\r\n removeEventListeners([strVisibilityChangeEvt], null, newNamespaces);\r\n}\r\n/**\r\n * Listen to the pageshow and visibility changing to 'visible' events, because the 'visibilitychange' uses\r\n * an internal proxy to detect the visibility state you SHOULD use a unique namespace when if you plan to call\r\n * removePageShowEventListener as the remove ignores the listener argument for the 'visibilitychange' event.\r\n * @param listener - The event callback to call when a page is show event is triggered\r\n * @param excludeEvents - [Optional] An array of events that should not be hooked (if possible), unless no other events can be.\r\n * @param evtNamespace - [Optional/Recommended] A Namespace to append to the event listeners so they can be uniquely\r\n * identified and removed based on this namespace. This call also adds an additional unique \"pageshow\" namespace to the events\r\n * so that only the matching \"removePageShowEventListener\" can remove these events.\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\r\nexport function addPageShowEventListener(listener, excludeEvents, evtNamespace) {\r\n function _handlePageVisibility(evt) {\r\n var doc = getDocument();\r\n if (listener && doc && doc.visibilityState === \"visible\") {\r\n listener(evt);\r\n }\r\n }\r\n // add the unique page show namespace to any provided namespace so we can only remove the ones added by \"pageshow\"\r\n var newNamespaces = mergeEvtNamespace(strPageShowNamespace, evtNamespace);\r\n var pageShowAdded = _addEventListeners([strPageShow], listener, excludeEvents, newNamespaces);\r\n pageShowAdded = _addEventListeners([strVisibilityChangeEvt], _handlePageVisibility, excludeEvents, newNamespaces) || pageShowAdded;\r\n if (!pageShowAdded && excludeEvents) {\r\n // Failed to add any listeners and we where requested to exclude some, so just call again without excluding anything\r\n pageShowAdded = addPageShowEventListener(listener, null, evtNamespace);\r\n }\r\n return pageShowAdded;\r\n}\r\n/**\r\n * Removes the pageShow event listeners added by addPageShowEventListener, because the 'visibilitychange' uses\r\n * an internal proxy to detect the visibility state you SHOULD use a unique namespace when calling addPageShowEventListener\r\n * as the remove ignores the listener argument for the 'visibilitychange' event.\r\n * @param listener - The specific listener to remove for the 'pageshow' event only (ignored for 'visibilitychange')\r\n * @param evtNamespace - The unique namespace used when calling addPageShowEventListener\r\n */\r\nexport function removePageShowEventListener(listener, evtNamespace) {\r\n // add the unique page show namespace to any provided namespace so we only remove the ones added by \"pageshow\"\r\n var newNamespaces = mergeEvtNamespace(strPageShowNamespace, evtNamespace);\r\n removeEventListeners([strPageShow], listener, newNamespaces);\r\n removeEventListeners([strVisibilityChangeEvt], null, newNamespaces);\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { ObjAssign, ObjClass, ObjDefineProperty, ObjHasOwnProperty, ObjProto, strShimFunction, strShimObject, strShimPrototype, strShimUndefined, throwTypeError } from \"@microsoft/applicationinsights-shims\";\r\nimport { _DYN_APPLY, _DYN_CALL, _DYN_INDEX_OF, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_REPLACE } from \"../__DynamicConstants\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\n// RESTRICT and AVOID circular dependencies you should not import other contained modules or export the contents of this file directly\r\n// Added to help with minfication\r\nvar strToISOString = \"toISOString\";\r\nvar cStrEndsWith = \"endsWith\";\r\nvar cStrStartsWith = \"startsWith\";\r\nvar strIndexOf = \"indexOf\";\r\nvar strMap = \"map\";\r\nvar strReduce = \"reduce\";\r\nvar cStrTrim = \"trim\";\r\nvar strToString = \"toString\";\r\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\r\nvar str__Proto = \"__proto__\";\r\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\r\nvar strConstructor = \"constructor\";\r\nvar _objDefineProperty = ObjDefineProperty;\r\nvar _objFreeze = ObjClass.freeze;\r\nvar _objSeal = ObjClass.seal;\r\nvar _objKeys = ObjClass.keys;\r\nvar StringProto = String[strShimPrototype];\r\nvar _strTrim = StringProto[cStrTrim];\r\nvar _strEndsWith = StringProto[cStrEndsWith];\r\nvar _strStartsWith = StringProto[cStrStartsWith];\r\nvar DateProto = Date[strShimPrototype];\r\nvar _dataToISOString = DateProto[strToISOString];\r\nvar _isArray = Array.isArray;\r\nvar _objToString = ObjProto[strToString];\r\nvar _fnToString = ObjHasOwnProperty[strToString];\r\n// Cache what this browser reports as the object function constructor (as a string)\r\nvar _objFunctionString = _fnToString[_DYN_CALL /* @min:%2ecall */](ObjClass);\r\nvar rCamelCase = /-([a-z])/g;\r\nvar rNormalizeInvalid = /([^\\w\\d_$])/g;\r\nvar rLeadingNumeric = /^(\\d+[\\w\\d_$])/;\r\n/**\r\n * Pre-lookup to check if we are running on a modern browser (i.e. not IE8)\r\n * @ignore\r\n */\r\nvar _objGetPrototypeOf = Object[\"getPrototypeOf\"];\r\n/**\r\n * Helper used to get the prototype of the target object as getPrototypeOf is not available in an ES3 environment.\r\n * @ignore\r\n */\r\nexport function _getObjProto(target) {\r\n if (target) {\r\n // This method doesn't existing in older browsers (e.g. IE8)\r\n if (_objGetPrototypeOf) {\r\n return _objGetPrototypeOf(target);\r\n }\r\n // target[Constructor] May break if the constructor has been changed or removed\r\n var newProto = target[str__Proto] || target[strShimPrototype] || target[strConstructor];\r\n if (newProto) {\r\n return newProto;\r\n }\r\n }\r\n return null;\r\n}\r\nexport function objToString(obj) {\r\n return _objToString[_DYN_CALL /* @min:%2ecall */](obj);\r\n}\r\nexport function isTypeof(value, theType) {\r\n return typeof value === theType;\r\n}\r\nexport function isUndefined(value) {\r\n return value === undefined || typeof value === strShimUndefined;\r\n}\r\nexport function isNotUndefined(value) {\r\n return !isUndefined(value);\r\n}\r\nexport function isNullOrUndefined(value) {\r\n return (value === null || isUndefined(value));\r\n}\r\nexport function isNotNullOrUndefined(value) {\r\n return !isNullOrUndefined(value);\r\n}\r\nexport function hasOwnProperty(obj, prop) {\r\n return !!(obj && ObjHasOwnProperty[_DYN_CALL /* @min:%2ecall */](obj, prop));\r\n}\r\nexport function isObject(value) {\r\n // Changing to inline for performance\r\n return !!(value && typeof value === strShimObject);\r\n}\r\nexport function isFunction(value) {\r\n // Changing to inline for performance\r\n return !!(value && typeof value === strShimFunction);\r\n}\r\nexport function isPromiseLike(value) {\r\n return value && isFunction(value.then);\r\n}\r\n/**\r\n * Validates that the string name conforms to the JS IdentifierName specification and if not\r\n * normalizes the name so that it would. This method does not identify or change any keywords\r\n * meaning that if you pass in a known keyword the same value will be returned.\r\n * This is a simplified version\r\n * @param name The name to validate\r\n */\r\nexport function normalizeJsName(name) {\r\n var value = name;\r\n if (value && isString(value)) {\r\n // CamelCase everything after the \"-\" and remove the dash\r\n value = value[_DYN_REPLACE /* @min:%2ereplace */](rCamelCase, function (_all, letter) {\r\n return letter.toUpperCase();\r\n });\r\n value = value[_DYN_REPLACE /* @min:%2ereplace */](rNormalizeInvalid, \"_\");\r\n value = value[_DYN_REPLACE /* @min:%2ereplace */](rLeadingNumeric, function (_all, match) {\r\n return \"_\" + match;\r\n });\r\n }\r\n return value;\r\n}\r\n/**\r\n * This is a helper function for the equivalent of arForEach(objKeys(target), callbackFn), this is a\r\n * performance optimization to avoid the creation of a new array for large objects\r\n * @param target The target object to find and process the keys\r\n * @param callbackfn The function to call with the details\r\n */\r\nexport function objForEachKey(target, callbackfn) {\r\n if (target) {\r\n for (var prop in target) {\r\n if (ObjHasOwnProperty[_DYN_CALL /* @min:%2ecall */](target, prop)) {\r\n callbackfn[_DYN_CALL /* @min:%2ecall */](target, prop, target[prop]);\r\n }\r\n }\r\n }\r\n}\r\n/**\r\n * The strEndsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.\r\n * @param value - The value to check whether it ends with the search value.\r\n * @param search - The characters to be searched for at the end of the value.\r\n * @returns true if the given search value is found at the end of the string, otherwise false.\r\n */\r\nexport function strEndsWith(value, search) {\r\n var result = false;\r\n if (value && search && !(result = value === search)) {\r\n // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification\r\n result = _strEndsWith ? value[cStrEndsWith](search) : _strEndsWithPoly(value, search);\r\n }\r\n return result;\r\n}\r\n/**\r\n * The _strEndsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.\r\n * @param value - The value to check whether it ends with the search value.\r\n * @param search - The characters to be searched for at the end of the value.\r\n * @returns true if the given search value is found at the end of the string, otherwise false.\r\n */\r\nexport function _strEndsWithPoly(value, search) {\r\n var result = false;\r\n var searchLen = search ? search[_DYN_LENGTH /* @min:%2elength */] : 0;\r\n var valLen = value ? value[_DYN_LENGTH /* @min:%2elength */] : 0;\r\n if (searchLen && valLen && valLen >= searchLen && !(result = value === search)) {\r\n var pos = valLen - 1;\r\n for (var lp = searchLen - 1; lp >= 0; lp--) {\r\n if (value[pos] != search[lp]) {\r\n return false;\r\n }\r\n pos--;\r\n }\r\n result = true;\r\n }\r\n return result;\r\n}\r\n/**\r\n * The strStartsWith() method determines whether a string starts with the characters of the specified string, returning true or false as appropriate.\r\n * @param value - The value to check whether it ends with the search value.\r\n * @param checkValue - The characters to be searched for at the start of the value.\r\n * @returns true if the given search value is found at the start of the string, otherwise false.\r\n */\r\nexport function strStartsWith(value, checkValue) {\r\n var result = false;\r\n if (value && checkValue && !(result = value === checkValue)) {\r\n // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification\r\n result = _strStartsWith ? value[cStrStartsWith](checkValue) : _strStartsWithPoly(value, checkValue);\r\n }\r\n return result;\r\n}\r\n/**\r\n * The strStartsWith() method determines whether a string starts with the characters of the specified string, returning true or false as appropriate.\r\n * @param value - The value to check whether it ends with the search value.\r\n * @param checkValue - The characters to be searched for at the start of the value.\r\n * @returns true if the given search value is found at the start of the string, otherwise false.\r\n */\r\nexport function _strStartsWithPoly(value, checkValue) {\r\n // Using helper for performance and because string startsWith() is not available on IE\r\n var result = false;\r\n var chkLen = checkValue ? checkValue[_DYN_LENGTH /* @min:%2elength */] : 0;\r\n if (value && chkLen && value[_DYN_LENGTH /* @min:%2elength */] >= chkLen && !(result = value === checkValue)) {\r\n for (var lp = 0; lp < chkLen; lp++) {\r\n if (value[lp] !== checkValue[lp]) {\r\n return false;\r\n }\r\n }\r\n result = true;\r\n }\r\n return result;\r\n}\r\n/**\r\n * A simple wrapper (for minification support) to check if the value contains the search string.\r\n * @param value - The string value to check for the existence of the search value\r\n * @param search - The value search within the value\r\n */\r\nexport function strContains(value, search) {\r\n if (value && search) {\r\n return value[_DYN_INDEX_OF /* @min:%2eindexOf */](search) !== -1;\r\n }\r\n return false;\r\n}\r\n/**\r\n * Check if an object is of type Date\r\n */\r\nexport function isDate(obj) {\r\n return !!(obj && _objToString[_DYN_CALL /* @min:%2ecall */](obj) === \"[object Date]\");\r\n}\r\n/**\r\n * Check if an object is of type Array with optional generic T, the generic type is not validated\r\n * and exists to help with TypeScript validation only.\r\n */\r\nexport var isArray = _isArray || _isArrayPoly;\r\nfunction _isArrayPoly(obj) {\r\n return !!(obj && _objToString[_DYN_CALL /* @min:%2ecall */](obj) === \"[object Array]\");\r\n}\r\n/**\r\n * Check if an object is of type Error\r\n */\r\nexport function isError(obj) {\r\n return !!(obj && _objToString[_DYN_CALL /* @min:%2ecall */](obj) === \"[object Error]\");\r\n}\r\n/**\r\n * Checks if the type of value is a string.\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a string, false otherwise.\r\n */\r\nexport function isString(value) {\r\n // Changing to inline for performance\r\n return typeof value === \"string\";\r\n}\r\n/**\r\n * Checks if the type of value is a number.\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a number, false otherwise.\r\n */\r\nexport function isNumber(value) {\r\n // Changing to inline for performance\r\n return typeof value === \"number\";\r\n}\r\n/**\r\n * Checks if the type of value is a boolean.\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a boolean, false otherwise.\r\n */\r\nexport function isBoolean(value) {\r\n // Changing to inline for performance\r\n return typeof value === \"boolean\";\r\n}\r\n/**\r\n * Checks if the type of value is a Symbol.\r\n * This only returns a boolean as returning value is Symbol will cause issues for older TypeScript consumers\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a Symbol, false otherwise.\r\n */\r\nexport function isSymbol(value) {\r\n return typeof value === \"symbol\";\r\n}\r\n/**\r\n * Checks if the type of the value is a normal plain object (not a null or data)\r\n * @param value\r\n */\r\nexport function isPlainObject(value) {\r\n var result = false;\r\n if (value && typeof value === \"object\") {\r\n // Inlining _objGetPrototypeOf for performance to avoid an additional function call\r\n var proto = _objGetPrototypeOf ? _objGetPrototypeOf(value) : _getObjProto(value);\r\n if (!proto) {\r\n // No prototype found so this is a plain Object eg. 'Object.create(null)'\r\n result = true;\r\n }\r\n else {\r\n // Objects that have a prototype are plain only if they were created using the Object global (native) function\r\n if (proto[strConstructor] && ObjHasOwnProperty[_DYN_CALL /* @min:%2ecall */](proto, strConstructor)) {\r\n proto = proto[strConstructor];\r\n }\r\n result = typeof proto === strShimFunction && _fnToString[_DYN_CALL /* @min:%2ecall */](proto) === _objFunctionString;\r\n }\r\n }\r\n return result;\r\n}\r\n/**\r\n * Convert a date to I.S.O. format in IE8\r\n */\r\nexport function toISOString(date) {\r\n if (date) {\r\n // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification\r\n return _dataToISOString ? date[strToISOString]() : _toISOStringPoly(date);\r\n }\r\n}\r\n/**\r\n * Convert a date to I.S.O. format in IE8\r\n */\r\nexport function _toISOStringPoly(date) {\r\n if (date && date.getUTCFullYear) {\r\n var pad = function (num) {\r\n var r = String(num);\r\n if (r[_DYN_LENGTH /* @min:%2elength */] === 1) {\r\n r = \"0\" + r;\r\n }\r\n return r;\r\n };\r\n return date.getUTCFullYear()\r\n + \"-\" + pad(date.getUTCMonth() + 1)\r\n + \"-\" + pad(date.getUTCDate())\r\n + \"T\" + pad(date.getUTCHours())\r\n + \":\" + pad(date.getUTCMinutes())\r\n + \":\" + pad(date.getUTCSeconds())\r\n + \".\" + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5)\r\n + \"Z\";\r\n }\r\n}\r\n/**\r\n * Performs the specified action for each element in an array. This helper exists to avoid adding a polyfil for older browsers\r\n * that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype\r\n * implementation. Note: For consistency this will not use the Array.prototype.xxxx implementation if it exists as this would\r\n * cause a testing requirement to test with and without the implementations\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. It can return -1 to break out of the loop\r\n * @param thisArg [Optional] An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\nexport function arrForEach(arr, callbackfn, thisArg) {\r\n var len = arr[_DYN_LENGTH /* @min:%2elength */];\r\n try {\r\n for (var idx = 0; idx < len; idx++) {\r\n if (idx in arr) {\r\n if (callbackfn[_DYN_CALL /* @min:%2ecall */](thisArg || arr, arr[idx], idx, arr) === -1) {\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // This can happen with some native browser objects, but should not happen for the type we are checking for\r\n }\r\n}\r\n/**\r\n * Returns the index of the first occurrence of a value in an array. This helper exists to avoid adding a polyfil for older browsers\r\n * that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype\r\n * implementation. Note: For consistency this will not use the Array.prototype.xxxx implementation if it exists as this would\r\n * cause a testing requirement to test with and without the implementations\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\r\n */\r\nexport function arrIndexOf(arr, searchElement, fromIndex) {\r\n if (arr) {\r\n // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification\r\n if (arr[strIndexOf]) {\r\n return arr[strIndexOf](searchElement, fromIndex);\r\n }\r\n var len = arr[_DYN_LENGTH /* @min:%2elength */];\r\n var from = fromIndex || 0;\r\n try {\r\n for (var lp = Math.max(from >= 0 ? from : len - Math.abs(from), 0); lp < len; lp++) {\r\n if (lp in arr && arr[lp] === searchElement) {\r\n return lp;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // This can happen with some native browser objects, but should not happen for the type we are checking for\r\n }\r\n }\r\n return -1;\r\n}\r\n/**\r\n * Calls a defined callback function on each element of an array, and returns an array that contains the results. This helper exists\r\n * to avoid adding a polyfil for older browsers that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page\r\n * checks for presence/absence of the prototype implementation. Note: For consistency this will not use the Array.prototype.xxxx\r\n * implementation if it exists as this would cause a testing requirement to test with and without the implementations\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\nexport function arrMap(arr, callbackfn, thisArg) {\r\n var results;\r\n if (arr) {\r\n // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification\r\n if (arr[strMap]) {\r\n return arr[strMap](callbackfn, thisArg);\r\n }\r\n var len = arr[_DYN_LENGTH /* @min:%2elength */];\r\n var _this = thisArg || arr;\r\n results = new Array(len);\r\n try {\r\n for (var lp = 0; lp < len; lp++) {\r\n if (lp in arr) {\r\n results[lp] = callbackfn[_DYN_CALL /* @min:%2ecall */](_this, arr[lp], arr);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // This can happen with some native browser objects, but should not happen for the type we are checking for\r\n }\r\n }\r\n return results;\r\n}\r\n/**\r\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is\r\n * provided as an argument in the next call to the callback function. This helper exists to avoid adding a polyfil for older browsers that do not define\r\n * Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype implementation. Note: For consistency\r\n * this will not use the Array.prototype.xxxx implementation if it exists as this would cause a testing requirement to test with and without the implementations\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\nexport function arrReduce(arr, callbackfn, initialValue) {\r\n var value;\r\n if (arr) {\r\n // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification\r\n if (arr[strReduce]) {\r\n return arr[strReduce](callbackfn, initialValue);\r\n }\r\n var len = arr[_DYN_LENGTH /* @min:%2elength */];\r\n var lp = 0;\r\n // Specifically checking the number of passed arguments as the value could be anything\r\n if (arguments[_DYN_LENGTH /* @min:%2elength */] >= 3) {\r\n value = arguments[2];\r\n }\r\n else {\r\n while (lp < len && !(lp in arr)) {\r\n lp++;\r\n }\r\n value = arr[lp++];\r\n }\r\n while (lp < len) {\r\n if (lp in arr) {\r\n value = callbackfn(value, arr[lp], lp, arr);\r\n }\r\n lp++;\r\n }\r\n }\r\n return value;\r\n}\r\n/**\r\n * helper method to trim strings (IE8 does not implement String.prototype.trim)\r\n */\r\nexport function strTrim(str) {\r\n if (str) {\r\n // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification\r\n str = (_strTrim && str[cStrTrim]) ? str[cStrTrim]() : (str[_DYN_REPLACE /* @min:%2ereplace */] ? str[_DYN_REPLACE /* @min:%2ereplace */](/^\\s+|(?=\\s)\\s+$/g, STR_EMPTY) : str);\r\n }\r\n return str;\r\n}\r\nvar _objKeysHasDontEnumBug = !({ toString: null }).propertyIsEnumerable(\"toString\");\r\nvar _objKeysDontEnums = [\r\n \"toString\",\r\n \"toLocaleString\",\r\n \"valueOf\",\r\n \"hasOwnProperty\",\r\n \"isPrototypeOf\",\r\n \"propertyIsEnumerable\",\r\n \"constructor\"\r\n];\r\n/**\r\n * Returns the names of the enumerable string properties and methods of an object. This helper exists to avoid adding a polyfil for older browsers\r\n * that do not define Object.keys eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation.\r\n * Note: For consistency this will not use the Object.keys implementation if it exists as this would cause a testing requirement to test with and without the implementations\r\n * @param obj Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.\r\n */\r\nexport function objKeys(obj) {\r\n var objType = typeof obj;\r\n if (objType !== strShimFunction && (objType !== strShimObject || obj === null)) {\r\n throwTypeError(\"objKeys called on non-object\");\r\n }\r\n // For Performance try and use the native instance, using string lookup of the function to easily pass the ES3 build checks and minification\r\n if (!_objKeysHasDontEnumBug && _objKeys) {\r\n return _objKeys(obj);\r\n }\r\n var result = [];\r\n for (var prop in obj) {\r\n if (obj && ObjHasOwnProperty[_DYN_CALL /* @min:%2ecall */](obj, prop)) {\r\n result[_DYN_PUSH /* @min:%2epush */](prop);\r\n }\r\n }\r\n if (_objKeysHasDontEnumBug) {\r\n var dontEnumsLength = _objKeysDontEnums[_DYN_LENGTH /* @min:%2elength */];\r\n for (var lp = 0; lp < dontEnumsLength; lp++) {\r\n if (obj && ObjHasOwnProperty[_DYN_CALL /* @min:%2ecall */](obj, _objKeysDontEnums[lp])) {\r\n result[_DYN_PUSH /* @min:%2epush */](_objKeysDontEnums[lp]);\r\n }\r\n }\r\n }\r\n return result;\r\n}\r\n/**\r\n * Try to define get/set object property accessors for the target object/prototype, this will provide compatibility with\r\n * existing API definition when run within an ES5+ container that supports accessors but still enable the code to be loaded\r\n * and executed in an ES3 container, providing basic IE8 compatibility.\r\n * @param target The object on which to define the property.\r\n * @param prop The name of the property to be defined or modified.\r\n * @param getProp The getter function to wire against the getter.\r\n * @param setProp The setter function to wire against the setter.\r\n * @returns True if it was able to create the accessors otherwise false\r\n */\r\nexport function objDefineAccessors(target, prop, getProp, setProp) {\r\n if (_objDefineProperty) {\r\n try {\r\n var descriptor = {\r\n enumerable: true,\r\n configurable: true\r\n };\r\n if (getProp) {\r\n descriptor.get = getProp;\r\n }\r\n if (setProp) {\r\n descriptor.set = setProp;\r\n }\r\n _objDefineProperty(target, prop, descriptor);\r\n return true;\r\n }\r\n catch (e) {\r\n // IE8 Defines a defineProperty on Object but it's only supported for DOM elements so it will throw\r\n // We will just ignore this here.\r\n }\r\n }\r\n return false;\r\n}\r\nfunction _doNothing(value) {\r\n return value;\r\n}\r\nexport function deepFreeze(obj) {\r\n if (_objFreeze) {\r\n objForEachKey(obj, function (name, value) {\r\n if (isArray(value) || isObject(value)) {\r\n _objFreeze(value);\r\n }\r\n });\r\n }\r\n return objFreeze(obj);\r\n}\r\nexport var objFreeze = _objFreeze || _doNothing;\r\nexport var objSeal = _objSeal || _doNothing;\r\n/**\r\n * Return the current time via the Date now() function (if available) and falls back to (new Date()).getTime() if now() is unavailable (IE8 or less)\r\n * https://caniuse.com/#search=Date.now\r\n */\r\nexport function dateNow() {\r\n var dt = Date;\r\n return dt.now ? dt.now() : new dt().getTime();\r\n}\r\n/**\r\n * Returns the name of object if it's an Error. Otherwise, returns empty string.\r\n */\r\nexport function getExceptionName(object) {\r\n if (isError(object)) {\r\n return object[_DYN_NAME /* @min:%2ename */];\r\n }\r\n return STR_EMPTY;\r\n}\r\n/**\r\n * Sets the provided value on the target instance using the field name when the provided chk function returns true, the chk\r\n * function will only be called if the new value is no equal to the original value.\r\n * @param target - The target object\r\n * @param field - The key of the target\r\n * @param value - The value to set\r\n * @param valChk - [Optional] Callback to check the value that if supplied will be called check if the new value can be set\r\n * @param srcChk - [Optional] Callback to check to original value that if supplied will be called if the new value should be set (if allowed)\r\n * @returns The existing or new value, depending what was set\r\n */\r\nexport function setValue(target, field, value, valChk, srcChk) {\r\n var theValue = value;\r\n if (target) {\r\n theValue = target[field];\r\n if (theValue !== value && (!srcChk || srcChk(theValue)) && (!valChk || valChk(value))) {\r\n theValue = value;\r\n target[field] = theValue;\r\n }\r\n }\r\n return theValue;\r\n}\r\n/**\r\n * Returns the current value from the target object if not null or undefined otherwise sets the new value and returns it\r\n * @param target - The target object to return or set the default value\r\n * @param field - The key for the field to set on the target\r\n * @param defValue - [Optional] The value to set if not already present, when not provided a empty object will be added\r\n */\r\nexport function getSetValue(target, field, defValue) {\r\n var theValue;\r\n if (target) {\r\n theValue = target[field];\r\n if (!theValue && isNullOrUndefined(theValue)) {\r\n // Supports having the default as null\r\n theValue = !isUndefined(defValue) ? defValue : {};\r\n target[field] = theValue;\r\n }\r\n }\r\n else {\r\n // Expanded for performance so we only check defValue if required\r\n theValue = !isUndefined(defValue) ? defValue : {};\r\n }\r\n return theValue;\r\n}\r\n/**\r\n * Get the mapped config value, if null or undefined any supplied defaultValue will be returned.\r\n * @param field - The name of the field as the named enum value (number) or the string name.\r\n * @param defaultValue - The default value to return if the config field is not present, null or undefined.\r\n */\r\nexport function getCfgValue(theValue, defaultValue) {\r\n return !isNullOrUndefined(theValue) ? theValue : defaultValue;\r\n}\r\nexport function isNotTruthy(value) {\r\n return !value;\r\n}\r\nexport function isTruthy(value) {\r\n return !!value;\r\n}\r\nexport function throwError(message) {\r\n throw new Error(message);\r\n}\r\nfunction _createProxyFunction(source, funcName) {\r\n var srcFunc = null;\r\n var src = null;\r\n if (isFunction(source)) {\r\n srcFunc = source;\r\n }\r\n else {\r\n src = source;\r\n }\r\n return function () {\r\n // Capture the original arguments passed to the method\r\n var originalArguments = arguments;\r\n if (srcFunc) {\r\n src = srcFunc();\r\n }\r\n if (src) {\r\n return src[funcName][_DYN_APPLY /* @min:%2eapply */](src, originalArguments);\r\n }\r\n };\r\n}\r\n/**\r\n * Effectively assigns all enumerable properties (not just own properties) and functions (including inherited prototype) from\r\n * the source object to the target, it attempts to use proxy getters / setters (if possible) and proxy functions to avoid potential\r\n * implementation issues by assigning prototype functions as instance ones\r\n *\r\n * This method is the primary method used to \"update\" the snippet proxy with the ultimate implementations.\r\n *\r\n * Special ES3 Notes:\r\n * Updates (setting) of direct property values on the target or indirectly on the source object WILL NOT WORK PROPERLY, updates to the\r\n * properties of \"referenced\" object will work (target.context.newValue = 10 => will be reflected in the source.context as it's the\r\n * same object). ES3 Failures: assigning target.myProp = 3 -> Won't change source.myProp = 3, likewise the reverse would also fail.\r\n * @param target - The target object to be assigned with the source properties and functions\r\n * @param source - The source object which will be assigned / called by setting / calling the targets proxies\r\n * @param chkSet - An optional callback to determine whether a specific property/function should be proxied\r\n */\r\nexport function proxyAssign(target, source, chkSet) {\r\n if (target && source && isObject(target) && isObject(source)) {\r\n var _loop_1 = function (field) {\r\n if (isString(field)) {\r\n var value = source[field];\r\n if (isFunction(value)) {\r\n if (!chkSet || chkSet(field, true, source, target)) {\r\n // Create a proxy function rather than just copying the (possible) prototype to the new object as an instance function\r\n target[field] = _createProxyFunction(source, field);\r\n }\r\n }\r\n else if (!chkSet || chkSet(field, false, source, target)) {\r\n if (hasOwnProperty(target, field)) {\r\n // Remove any previous instance property\r\n delete target[field];\r\n }\r\n if (!objDefineAccessors(target, field, function () {\r\n return source[field];\r\n }, function (theValue) {\r\n source[field] = theValue;\r\n })) {\r\n // Unable to create an accessor, so just assign the values as a fallback\r\n // -- this will (mostly) work for objects\r\n // -- but will fail for accessing primitives (if the source changes it) and all types of \"setters\" as the source won't be modified\r\n target[field] = value;\r\n }\r\n }\r\n }\r\n };\r\n // effectively apply/proxy full source to the target instance\r\n for (var field in source) {\r\n _loop_1(field);\r\n }\r\n }\r\n return target;\r\n}\r\n/**\r\n * Creates a proxy function on the target which internally will call the source version with all arguments passed to the target method.\r\n *\r\n * @param target - The target object to be assigned with the source properties and functions\r\n * @param name - The function name that will be added on the target\r\n * @param source - The source object which will be assigned / called by setting / calling the targets proxies\r\n * @param theFunc - The function name on the source that will be proxied on the target\r\n * @param overwriteTarget - If `false` this will not replace any pre-existing name otherwise (the default) it will overwrite any existing name\r\n */\r\nexport function proxyFunctionAs(target, name, source, theFunc, overwriteTarget) {\r\n if (target && name && source) {\r\n if (overwriteTarget !== false || isUndefined(target[name])) {\r\n target[name] = _createProxyFunction(source, theFunc);\r\n }\r\n }\r\n}\r\n/**\r\n * Creates proxy functions on the target which internally will call the source version with all arguments passed to the target method.\r\n *\r\n * @param target - The target object to be assigned with the source properties and functions\r\n * @param source - The source object which will be assigned / called by setting / calling the targets proxies\r\n * @param functionsToProxy - An array of function names that will be proxied on the target\r\n * @param overwriteTarget - If false this will not replace any pre-existing name otherwise (the default) it will overwrite any existing name\r\n */\r\nexport function proxyFunctions(target, source, functionsToProxy, overwriteTarget) {\r\n if (target && source && isObject(target) && isArray(functionsToProxy)) {\r\n arrForEach(functionsToProxy, function (theFuncName) {\r\n if (isString(theFuncName)) {\r\n proxyFunctionAs(target, theFuncName, source, theFuncName, overwriteTarget);\r\n }\r\n });\r\n }\r\n return target;\r\n}\r\n/**\r\n * Simpler helper to create a dynamic class that implements the interface and populates the values with the defaults.\r\n * Only instance properties (hasOwnProperty) values are copied from the defaults to the new instance\r\n * @param defaults Simple helper\r\n */\r\nexport function createClassFromInterface(defaults) {\r\n return /** @class */ (function () {\r\n function class_1() {\r\n var _this_1 = this;\r\n if (defaults) {\r\n objForEachKey(defaults, function (field, value) {\r\n _this_1[field] = value;\r\n });\r\n }\r\n }\r\n return class_1;\r\n }());\r\n}\r\n/**\r\n * A helper function to assist with JIT performance for objects that have properties added / removed dynamically\r\n * this is primarily for chromium based browsers and has limited effects on Firefox and none of IE. Only call this\r\n * function after you have finished \"updating\" the object, calling this within loops reduces or defeats the benefits.\r\n * This helps when iterating using for..in, objKeys() and objForEach()\r\n * @param theObject - The object to be optimized if possible\r\n */\r\nexport function optimizeObject(theObject) {\r\n // V8 Optimization to cause the JIT compiler to create a new optimized object for looking up the own properties\r\n // primarily for object with <= 19 properties for >= 20 the effect is reduced or non-existent\r\n if (theObject && ObjAssign) {\r\n theObject = ObjClass(ObjAssign({}, theObject));\r\n }\r\n return theObject;\r\n}\r\nexport function objExtend(obj1, obj2, obj3, obj4, obj5, obj6) {\r\n // Variables\r\n var theArgs = arguments;\r\n var extended = theArgs[0] || {};\r\n var argLen = theArgs[_DYN_LENGTH /* @min:%2elength */];\r\n var deep = false;\r\n var idx = 1;\r\n // Check for \"Deep\" flag\r\n if (argLen > 0 && isBoolean(extended)) {\r\n deep = extended;\r\n extended = theArgs[idx] || {};\r\n idx++;\r\n }\r\n // Handle case when target is a string or something (possible in deep copy)\r\n if (!isObject(extended)) {\r\n extended = {};\r\n }\r\n // Loop through each remaining object and conduct a merge\r\n for (; idx < argLen; idx++) {\r\n var arg = theArgs[idx];\r\n var isArgArray = isArray(arg);\r\n var isArgObj = isObject(arg);\r\n for (var prop in arg) {\r\n var propOk = (isArgArray && (prop in arg)) || (isArgObj && (ObjHasOwnProperty[_DYN_CALL /* @min:%2ecall */](arg, prop)));\r\n if (!propOk) {\r\n continue;\r\n }\r\n var newValue = arg[prop];\r\n var isNewArray = void 0;\r\n // If deep merge and property is an object, merge properties\r\n if (deep && newValue && ((isNewArray = isArray(newValue)) || isPlainObject(newValue))) {\r\n // Grab the current value of the extended object\r\n var clone = extended[prop];\r\n if (isNewArray) {\r\n if (!isArray(clone)) {\r\n // We can't \"merge\" an array with a non-array so overwrite the original\r\n clone = [];\r\n }\r\n }\r\n else if (!isPlainObject(clone)) {\r\n // We can't \"merge\" an object with a non-object\r\n clone = {};\r\n }\r\n // Never move the original objects always clone them\r\n newValue = objExtend(deep, clone, newValue);\r\n }\r\n // Assign the new (or previous) value (unless undefined)\r\n if (newValue !== undefined) {\r\n extended[prop] = newValue;\r\n }\r\n }\r\n }\r\n return extended;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { strShimFunction, strShimPrototype } from \"@microsoft/applicationinsights-shims\";\r\nimport { _DYN_APPLY, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_SPLICE } from \"../__DynamicConstants\";\r\nimport { getGlobalInst } from \"./EnvUtils\";\r\nimport { _getObjProto, hasOwnProperty } from \"./HelperFuncs\";\r\nvar aiInstrumentHooks = \"_aiHooks\";\r\nvar cbNames = [\r\n \"req\", \"rsp\", \"hkErr\", \"fnErr\"\r\n];\r\n/** @ignore */\r\nfunction _arrLoop(arr, fn) {\r\n if (arr) {\r\n for (var lp = 0; lp < arr[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n if (fn(arr[lp], lp)) {\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n/** @ignore */\r\nfunction _doCallbacks(hooks, callDetails, cbArgs, hookCtx, type) {\r\n if (type >= 0 /* CallbackType.Request */ && type <= 2 /* CallbackType.HookError */) {\r\n _arrLoop(hooks, function (hook, idx) {\r\n var cbks = hook.cbks;\r\n var cb = cbks[cbNames[type]];\r\n if (cb) {\r\n // Set the specific hook context implementation using a lazy creation pattern\r\n callDetails.ctx = function () {\r\n var ctx = hookCtx[idx] = (hookCtx[idx] || {});\r\n return ctx;\r\n };\r\n try {\r\n cb[_DYN_APPLY /* @min:%2eapply */](callDetails.inst, cbArgs);\r\n }\r\n catch (err) {\r\n var orgEx = callDetails.err;\r\n try {\r\n // Report Hook error via the callback\r\n var hookErrorCb = cbks[cbNames[2 /* CallbackType.HookError */]];\r\n if (hookErrorCb) {\r\n callDetails.err = err;\r\n hookErrorCb[_DYN_APPLY /* @min:%2eapply */](callDetails.inst, cbArgs);\r\n }\r\n }\r\n catch (e) {\r\n // Not much we can do here -- swallowing the exception to avoid crashing the hosting app\r\n }\r\n finally {\r\n // restore the original exception (if any)\r\n callDetails.err = orgEx;\r\n }\r\n }\r\n }\r\n });\r\n }\r\n}\r\n/** @ignore */\r\nfunction _createFunctionHook(aiHook) {\r\n // Define a temporary method that queues-up a the real method call\r\n return function () {\r\n var _a;\r\n var funcThis = this;\r\n // Capture the original arguments passed to the method\r\n var orgArgs = arguments;\r\n var hooks = aiHook.h;\r\n var funcArgs = (_a = {},\r\n _a[_DYN_NAME /* @min:name */] = aiHook.n,\r\n _a.inst = funcThis,\r\n _a.ctx = null,\r\n _a.set = _replaceArg,\r\n _a);\r\n var hookCtx = [];\r\n var cbArgs = _createArgs([funcArgs], orgArgs);\r\n funcArgs.evt = getGlobalInst(\"event\");\r\n function _createArgs(target, theArgs) {\r\n _arrLoop(theArgs, function (arg) {\r\n target[_DYN_PUSH /* @min:%2epush */](arg);\r\n });\r\n return target;\r\n }\r\n function _replaceArg(idx, value) {\r\n orgArgs = _createArgs([], orgArgs);\r\n orgArgs[idx] = value;\r\n cbArgs = _createArgs([funcArgs], orgArgs);\r\n }\r\n // Call the pre-request hooks\r\n _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 0 /* CallbackType.Request */);\r\n // Call the original function was called\r\n var theFunc = aiHook.f;\r\n if (theFunc) {\r\n try {\r\n funcArgs.rslt = theFunc[_DYN_APPLY /* @min:%2eapply */](funcThis, orgArgs);\r\n }\r\n catch (err) {\r\n // Report the request callback\r\n funcArgs.err = err;\r\n _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 3 /* CallbackType.FunctionError */);\r\n // rethrow the original exception so anyone listening for it can catch the exception\r\n throw err;\r\n }\r\n }\r\n // Call the post-request hooks\r\n _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 1 /* CallbackType.Response */);\r\n return funcArgs.rslt;\r\n };\r\n}\r\n/** @ignore */\r\nfunction _getOwner(target, name, checkPrototype, checkParentProto) {\r\n var owner = null;\r\n if (target) {\r\n if (hasOwnProperty(target, name)) {\r\n owner = target;\r\n }\r\n else if (checkPrototype) {\r\n owner = _getOwner(_getObjProto(target), name, checkParentProto, false);\r\n }\r\n }\r\n return owner;\r\n}\r\n/**\r\n * Intercept the named prototype functions for the target class / object\r\n * @param target - The target object\r\n * @param funcName - The function name\r\n * @param callbacks - The callbacks to configure and call whenever the function is called\r\n */\r\nexport function InstrumentProto(target, funcName, callbacks) {\r\n if (target) {\r\n return InstrumentFunc(target[strShimPrototype], funcName, callbacks, false);\r\n }\r\n return null;\r\n}\r\n/**\r\n * Intercept the named prototype functions for the target class / object\r\n * @param target - The target object\r\n * @param funcNames - The function names to intercept and call\r\n * @param callbacks - The callbacks to configure and call whenever the function is called\r\n */\r\nexport function InstrumentProtos(target, funcNames, callbacks) {\r\n if (target) {\r\n return InstrumentFuncs(target[strShimPrototype], funcNames, callbacks, false);\r\n }\r\n return null;\r\n}\r\nfunction _createInstrumentHook(owner, funcName, fn, callbacks) {\r\n var aiHook = fn && fn[aiInstrumentHooks];\r\n if (!aiHook) {\r\n // Only hook the function once\r\n aiHook = {\r\n i: 0,\r\n n: funcName,\r\n f: fn,\r\n h: []\r\n };\r\n // Override (hook) the original function\r\n var newFunc = _createFunctionHook(aiHook);\r\n newFunc[aiInstrumentHooks] = aiHook; // Tag and store the function hooks\r\n owner[funcName] = newFunc;\r\n }\r\n var theHook = {\r\n // tslint:disable:object-literal-shorthand\r\n id: aiHook.i,\r\n cbks: callbacks,\r\n rm: function () {\r\n // DO NOT Use () => { shorthand for the function as the this gets replaced\r\n // with the outer this and not the this for theHook instance.\r\n var id = this.id;\r\n _arrLoop(aiHook.h, function (hook, idx) {\r\n if (hook.id === id) {\r\n aiHook.h[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\r\n return 1;\r\n }\r\n });\r\n }\r\n // tslint:enable:object-literal-shorthand\r\n };\r\n aiHook.i++;\r\n aiHook.h[_DYN_PUSH /* @min:%2epush */](theHook);\r\n return theHook;\r\n}\r\n/**\r\n * Intercept the named prototype functions for the target class / object\r\n * @param target - The target object\r\n * @param funcName - The function name\r\n * @param callbacks - The callbacks to configure and call whenever the function is called\r\n * @param checkPrototype - If the function doesn't exist on the target should it attempt to hook the prototype function\r\n * @param checkParentProto - If the function doesn't exist on the target or it's prototype should it attempt to hook the parent's prototype\r\n */\r\nexport function InstrumentFunc(target, funcName, callbacks, checkPrototype, checkParentProto) {\r\n if (checkPrototype === void 0) { checkPrototype = true; }\r\n if (target && funcName && callbacks) {\r\n var owner = _getOwner(target, funcName, checkPrototype, checkParentProto);\r\n if (owner) {\r\n var fn = owner[funcName];\r\n if (typeof fn === strShimFunction) {\r\n return _createInstrumentHook(owner, funcName, fn, callbacks);\r\n }\r\n }\r\n }\r\n return null;\r\n}\r\n/**\r\n * Intercept the named functions for the target class / object\r\n * @param target - The target object\r\n * @param funcNames - The function names to intercept and call\r\n * @param callbacks - The callbacks to configure and call whenever the function is called\r\n * @param checkPrototype - If the function doesn't exist on the target should it attempt to hook the prototype function\r\n * @param checkParentProto - If the function doesn't exist on the target or it's prototype should it attempt to hook the parent's prototype\r\n */\r\nexport function InstrumentFuncs(target, funcNames, callbacks, checkPrototype, checkParentProto) {\r\n if (checkPrototype === void 0) { checkPrototype = true; }\r\n var hooks = null;\r\n _arrLoop(funcNames, function (funcName) {\r\n var hook = InstrumentFunc(target, funcName, callbacks, checkPrototype, checkParentProto);\r\n if (hook) {\r\n if (!hooks) {\r\n hooks = [];\r\n }\r\n hooks[_DYN_PUSH /* @min:%2epush */](hook);\r\n }\r\n });\r\n return hooks;\r\n}\r\n/**\r\n * Add an instrumentation hook to the provided named \"event\" for the target class / object, this doesn't check whether the\r\n * named \"event\" is in fact a function and just assigns the instrumentation hook to the target[evtName]\r\n * @param target - The target object\r\n * @param evtName - The name of the event\r\n * @param callbacks - The callbacks to configure and call whenever the function is called\r\n * @param checkPrototype - If the function doesn't exist on the target should it attempt to hook the prototype function\r\n * @param checkParentProto - If the function doesn't exist on the target or it's prototype should it attempt to hook the parent's prototype\r\n */\r\nexport function InstrumentEvent(target, evtName, callbacks, checkPrototype, checkParentProto) {\r\n if (target && evtName && callbacks) {\r\n var owner = _getOwner(target, evtName, checkPrototype, checkParentProto) || target;\r\n if (owner) {\r\n return _createInstrumentHook(owner, evtName, owner[evtName], callbacks);\r\n }\r\n }\r\n return null;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var STR_EMPTY = \"\";\r\nexport var STR_CHANNELS = \"channels\";\r\nexport var STR_CORE = \"core\";\r\nexport var STR_CREATE_PERF_MGR = \"createPerfMgr\";\r\nexport var STR_DISABLED = \"disabled\";\r\nexport var STR_EXTENSION_CONFIG = \"extensionConfig\";\r\nexport var STR_EXTENSIONS = \"extensions\";\r\nexport var STR_PROCESS_TELEMETRY = \"processTelemetry\";\r\nexport var STR_PRIORITY = \"priority\";\r\nexport var STR_EVENTS_SENT = \"eventsSent\";\r\nexport var STR_EVENTS_DISCARDED = \"eventsDiscarded\";\r\nexport var STR_EVENTS_SEND_REQUEST = \"eventsSendRequest\";\r\nexport var STR_PERF_EVENT = \"perfEvent\";\r\nexport var STR_ERROR_TO_CONSOLE = \"errorToConsole\";\r\nexport var STR_WARN_TO_CONSOLE = \"warnToConsole\";\r\nexport var STR_GET_PERF_MGR = \"getPerfMgr\";\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { _DYN_ADD_NOTIFICATION_LIS1, _DYN_IS_ASYNC, _DYN_IS_CHILD_EVT, _DYN_LISTENERS, _DYN_PUSH, _DYN_REMOVE_NOTIFICATION_2, _DYN_SPLICE } from \"../__DynamicConstants\";\r\nimport { arrForEach, arrIndexOf } from \"./HelperFuncs\";\r\nimport { STR_EVENTS_DISCARDED, STR_EVENTS_SEND_REQUEST, STR_EVENTS_SENT, STR_PERF_EVENT } from \"./InternalConstants\";\r\nfunction _runListeners(listeners, name, isAsync, callback) {\r\n arrForEach(listeners, function (listener) {\r\n if (listener && listener[name]) {\r\n if (isAsync) {\r\n setTimeout(function () { return callback(listener); }, 0);\r\n }\r\n else {\r\n try {\r\n callback(listener);\r\n }\r\n catch (e) {\r\n // Catch errors to ensure we don't block sending the requests\r\n }\r\n }\r\n }\r\n });\r\n}\r\n/**\r\n * Class to manage sending notifications to all the listeners.\r\n */\r\nvar NotificationManager = /** @class */ (function () {\r\n function NotificationManager(config) {\r\n this.listeners = [];\r\n var perfEvtsSendAll = !!(config || {}).perfEvtsSendAll;\r\n dynamicProto(NotificationManager, this, function (_self) {\r\n _self[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */] = function (listener) {\r\n _self.listeners[_DYN_PUSH /* @min:%2epush */](listener);\r\n };\r\n /**\r\n * Removes all instances of the listener.\r\n * @param {INotificationListener} listener - AWTNotificationListener to remove.\r\n */\r\n _self[_DYN_REMOVE_NOTIFICATION_2 /* @min:%2eremoveNotificationListener */] = function (listener) {\r\n var index = arrIndexOf(_self[_DYN_LISTENERS /* @min:%2elisteners */], listener);\r\n while (index > -1) {\r\n _self.listeners[_DYN_SPLICE /* @min:%2esplice */](index, 1);\r\n index = arrIndexOf(_self[_DYN_LISTENERS /* @min:%2elisteners */], listener);\r\n }\r\n };\r\n /**\r\n * Notification for events sent.\r\n * @param {ITelemetryItem[]} events - The array of events that have been sent.\r\n */\r\n _self[STR_EVENTS_SENT /* @min:%2eeventsSent */] = function (events) {\r\n _runListeners(_self[_DYN_LISTENERS /* @min:%2elisteners */], STR_EVENTS_SENT, true, function (listener) {\r\n listener[STR_EVENTS_SENT /* @min:%2eeventsSent */](events);\r\n });\r\n };\r\n /**\r\n * Notification for events being discarded.\r\n * @param {ITelemetryItem[]} events - The array of events that have been discarded by the SDK.\r\n * @param {number} reason - The reason for which the SDK discarded the events. The EventsDiscardedReason\r\n * constant should be used to check the different values.\r\n */\r\n _self[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */] = function (events, reason) {\r\n _runListeners(_self[_DYN_LISTENERS /* @min:%2elisteners */], STR_EVENTS_DISCARDED, true, function (listener) {\r\n listener[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */](events, reason);\r\n });\r\n };\r\n /**\r\n * [Optional] A function called when the events have been requested to be sent to the sever.\r\n * @param {number} sendReason - The reason why the event batch is being sent.\r\n * @param {boolean} isAsync - A flag which identifies whether the requests are being sent in an async or sync manner.\r\n */\r\n _self[STR_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */] = function (sendReason, isAsync) {\r\n _runListeners(_self[_DYN_LISTENERS /* @min:%2elisteners */], STR_EVENTS_SEND_REQUEST, isAsync, function (listener) {\r\n listener[STR_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */](sendReason, isAsync);\r\n });\r\n };\r\n _self[STR_PERF_EVENT /* @min:%2eperfEvent */] = function (perfEvent) {\r\n if (perfEvent) {\r\n // Send all events or only parent events\r\n if (perfEvtsSendAll || !perfEvent[_DYN_IS_CHILD_EVT /* @min:%2eisChildEvt */]()) {\r\n _runListeners(_self[_DYN_LISTENERS /* @min:%2elisteners */], STR_PERF_EVENT, false, function (listener) {\r\n if (perfEvent[_DYN_IS_ASYNC /* @min:%2eisAsync */]) {\r\n setTimeout(function () { return listener[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent); }, 0);\r\n }\r\n else {\r\n listener[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent);\r\n }\r\n });\r\n }\r\n }\r\n };\r\n });\r\n }\r\n// Removed Stub for NotificationManager.prototype.addNotificationListener.\r\n// Removed Stub for NotificationManager.prototype.removeNotificationListener.\r\n// Removed Stub for NotificationManager.prototype.eventsSent.\r\n// Removed Stub for NotificationManager.prototype.eventsDiscarded.\r\n// Removed Stub for NotificationManager.prototype.eventsSendRequest.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n NotificationManager.__ieDyn=1;\n\n return NotificationManager;\r\n}());\r\nexport { NotificationManager };\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { _DYN_COMPLETE, _DYN_GET_CTX, _DYN_IS_ASYNC, _DYN_IS_CHILD_EVT, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_SET_CTX, _DYN_TIME } from \"../__DynamicConstants\";\r\nimport { dateNow, isArray, isFunction, objDefineAccessors } from \"./HelperFuncs\";\r\nimport { STR_GET_PERF_MGR, STR_PERF_EVENT } from \"./InternalConstants\";\r\nvar strExecutionContextKey = \"ctx\";\r\nvar strParentContextKey = \"ParentContextKey\";\r\nvar strChildrenContextKey = \"ChildrenContextKey\";\r\nvar _defaultPerfManager = null;\r\nvar PerfEvent = /** @class */ (function () {\r\n function PerfEvent(name, payloadDetails, isAsync) {\r\n var _self = this;\r\n var accessorDefined = false;\r\n _self.start = dateNow();\r\n _self[_DYN_NAME /* @min:%2ename */] = name;\r\n _self[_DYN_IS_ASYNC /* @min:%2eisAsync */] = isAsync;\r\n _self[_DYN_IS_CHILD_EVT /* @min:%2eisChildEvt */] = function () { return false; };\r\n if (isFunction(payloadDetails)) {\r\n // Create an accessor to minimize the potential performance impact of executing the payloadDetails callback\r\n var theDetails_1;\r\n accessorDefined = objDefineAccessors(_self, \"payload\", function () {\r\n // Delay the execution of the payloadDetails until needed\r\n if (!theDetails_1 && isFunction(payloadDetails)) {\r\n theDetails_1 = payloadDetails();\r\n // clear it out now so the referenced objects can be garbage collected\r\n payloadDetails = null;\r\n }\r\n return theDetails_1;\r\n });\r\n }\r\n _self[_DYN_GET_CTX /* @min:%2egetCtx */] = function (key) {\r\n if (key) {\r\n // The parent and child links are located directly on the object (for better viewing in the DebugPlugin)\r\n if (key === PerfEvent[strParentContextKey] || key === PerfEvent[strChildrenContextKey]) {\r\n return _self[key];\r\n }\r\n return (_self[strExecutionContextKey] || {})[key];\r\n }\r\n return null;\r\n };\r\n _self[_DYN_SET_CTX /* @min:%2esetCtx */] = function (key, value) {\r\n if (key) {\r\n // Put the parent and child links directly on the object (for better viewing in the DebugPlugin)\r\n if (key === PerfEvent[strParentContextKey]) {\r\n // Simple assumption, if we are setting a parent then we must be a child\r\n if (!_self[key]) {\r\n _self[_DYN_IS_CHILD_EVT /* @min:%2eisChildEvt */] = function () { return true; };\r\n }\r\n _self[key] = value;\r\n }\r\n else if (key === PerfEvent[strChildrenContextKey]) {\r\n _self[key] = value;\r\n }\r\n else {\r\n var ctx = _self[strExecutionContextKey] = _self[strExecutionContextKey] || {};\r\n ctx[key] = value;\r\n }\r\n }\r\n };\r\n _self[_DYN_COMPLETE /* @min:%2ecomplete */] = function () {\r\n var childTime = 0;\r\n var childEvts = _self[_DYN_GET_CTX /* @min:%2egetCtx */](PerfEvent[strChildrenContextKey]);\r\n if (isArray(childEvts)) {\r\n for (var lp = 0; lp < childEvts[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n var childEvt = childEvts[lp];\r\n if (childEvt) {\r\n childTime += childEvt[_DYN_TIME /* @min:%2etime */];\r\n }\r\n }\r\n }\r\n _self[_DYN_TIME /* @min:%2etime */] = dateNow() - _self.start;\r\n _self.exTime = _self[_DYN_TIME /* @min:%2etime */] - childTime;\r\n _self[_DYN_COMPLETE /* @min:%2ecomplete */] = function () { };\r\n if (!accessorDefined && isFunction(payloadDetails)) {\r\n // If we couldn't define the property set during complete -- to minimize the perf impact until after the time\r\n _self.payload = payloadDetails();\r\n }\r\n };\r\n }\r\n PerfEvent.ParentContextKey = \"parent\";\r\n PerfEvent.ChildrenContextKey = \"childEvts\";\r\n return PerfEvent;\r\n}());\r\nexport { PerfEvent };\r\nvar PerfManager = /** @class */ (function () {\r\n function PerfManager(manager) {\r\n /**\r\n * General bucket used for execution context set and retrieved via setCtx() and getCtx.\r\n * Defined as private so it can be visualized via the DebugPlugin\r\n */\r\n this.ctx = {};\r\n dynamicProto(PerfManager, this, function (_self) {\r\n _self.create = function (src, payloadDetails, isAsync) {\r\n // TODO (@MSNev): at some point we will want to add additional configuration to \"select\" which events to instrument\r\n // for now this is just a simple do everything.\r\n return new PerfEvent(src, payloadDetails, isAsync);\r\n };\r\n _self.fire = function (perfEvent) {\r\n if (perfEvent) {\r\n perfEvent[_DYN_COMPLETE /* @min:%2ecomplete */]();\r\n if (manager && isFunction(manager[STR_PERF_EVENT /* @min:%2eperfEvent */])) {\r\n manager[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent);\r\n }\r\n }\r\n };\r\n _self[_DYN_SET_CTX /* @min:%2esetCtx */] = function (key, value) {\r\n if (key) {\r\n var ctx = _self[strExecutionContextKey] = _self[strExecutionContextKey] || {};\r\n ctx[key] = value;\r\n }\r\n };\r\n _self[_DYN_GET_CTX /* @min:%2egetCtx */] = function (key) {\r\n return (_self[strExecutionContextKey] || {})[key];\r\n };\r\n });\r\n }\r\n// Removed Stub for PerfManager.prototype.create.\r\n// Removed Stub for PerfManager.prototype.fire.\r\n// Removed Stub for PerfManager.prototype.setCtx.\r\n// Removed Stub for PerfManager.prototype.getCtx.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n PerfManager.__ieDyn=1;\n\n return PerfManager;\r\n}());\r\nexport { PerfManager };\r\nvar doPerfActiveKey = \"CoreUtils.doPerf\";\r\n/**\r\n * Helper function to wrap a function with a perf event\r\n * @param mgrSource - The Performance Manager or a Performance provider source (may be null)\r\n * @param getSource - The callback to create the source name for the event (if perf monitoring is enabled)\r\n * @param func - The function to call and measure\r\n * @param details - A function to return the payload details\r\n * @param isAsync - Is the event / function being call asynchronously or synchronously\r\n */\r\nexport function doPerf(mgrSource, getSource, func, details, isAsync) {\r\n if (mgrSource) {\r\n var perfMgr = mgrSource;\r\n if (perfMgr[STR_GET_PERF_MGR]) {\r\n // Looks like a perf manager provider object\r\n perfMgr = perfMgr[STR_GET_PERF_MGR]();\r\n }\r\n if (perfMgr) {\r\n var perfEvt = void 0;\r\n var currentActive = perfMgr[_DYN_GET_CTX /* @min:%2egetCtx */](doPerfActiveKey);\r\n try {\r\n perfEvt = perfMgr.create(getSource(), details, isAsync);\r\n if (perfEvt) {\r\n if (currentActive && perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */]) {\r\n perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */](PerfEvent[strParentContextKey], currentActive);\r\n if (currentActive[_DYN_GET_CTX /* @min:%2egetCtx */] && currentActive[_DYN_SET_CTX /* @min:%2esetCtx */]) {\r\n var children = currentActive[_DYN_GET_CTX /* @min:%2egetCtx */](PerfEvent[strChildrenContextKey]);\r\n if (!children) {\r\n children = [];\r\n currentActive[_DYN_SET_CTX /* @min:%2esetCtx */](PerfEvent[strChildrenContextKey], children);\r\n }\r\n children[_DYN_PUSH /* @min:%2epush */](perfEvt);\r\n }\r\n }\r\n // Set this event as the active event now\r\n perfMgr[_DYN_SET_CTX /* @min:%2esetCtx */](doPerfActiveKey, perfEvt);\r\n return func(perfEvt);\r\n }\r\n }\r\n catch (ex) {\r\n if (perfEvt && perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */]) {\r\n perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */](\"exception\", ex);\r\n }\r\n }\r\n finally {\r\n // fire the perf event\r\n if (perfEvt) {\r\n perfMgr.fire(perfEvt);\r\n }\r\n // Reset the active event to the previous value\r\n perfMgr[_DYN_SET_CTX /* @min:%2esetCtx */](doPerfActiveKey, currentActive);\r\n }\r\n }\r\n }\r\n return func();\r\n}\r\n/**\r\n * Set the global performance manager to use when there is no core instance or it has not been initialized yet.\r\n * @param perfManager - The IPerfManager instance to use when no performance manager is supplied.\r\n */\r\nexport function setGblPerfMgr(perfManager) {\r\n _defaultPerfManager = perfManager;\r\n}\r\n/**\r\n * Get the current global performance manager that will be used with no performance manager is supplied.\r\n * @returns - The current default manager\r\n */\r\nexport function getGblPerfMgr() {\r\n return _defaultPerfManager;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n\"use strict\";\r\nimport { _DYN_CALL, _DYN_CONFIG, _DYN_CREATE_NEW, _DYN_DIAG_LOG, _DYN_GET_NEXT, _DYN_GET_PLUGIN, _DYN_IDENTIFIER, _DYN_IS_ASYNC, _DYN_IS_INITIALIZED, _DYN_LENGTH, _DYN_LOGGER, _DYN_PROCESS_NEXT, _DYN_PUSH, _DYN_SET_NEXT_PLUGIN, _DYN_TEARDOWN, _DYN_UPDATE } from \"../__DynamicConstants\";\r\nimport { _throwInternal, safeGetLogger } from \"./DiagnosticLogger\";\r\nimport { dumpObj } from \"./EnvUtils\";\r\nimport { arrForEach, isArray, isFunction, isNullOrUndefined, isObject, isUndefined, objExtend, objForEachKey, objFreeze, objKeys, proxyFunctions } from \"./HelperFuncs\";\r\nimport { STR_CORE, STR_DISABLED, STR_EMPTY, STR_EXTENSION_CONFIG, STR_PRIORITY, STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\r\nimport { doPerf } from \"./PerfManager\";\r\nimport { _getPluginState } from \"./TelemetryHelpers\";\r\nvar strTelemetryPluginChain = \"TelemetryPluginChain\";\r\nvar strHasRunFlags = \"_hasRun\";\r\nvar strGetTelCtx = \"_getTelCtx\";\r\nvar _chainId = 0;\r\nfunction _getNextProxyStart(proxy, core, startAt) {\r\n while (proxy) {\r\n if (proxy[_DYN_GET_PLUGIN /* @min:%2egetPlugin */]() === startAt) {\r\n return proxy;\r\n }\r\n proxy = proxy[_DYN_GET_NEXT /* @min:%2egetNext */]();\r\n }\r\n // This wasn't found in the existing chain so create an isolated one with just this plugin\r\n return createTelemetryProxyChain([startAt], core[_DYN_CONFIG /* @min:%2econfig */] || {}, core);\r\n}\r\n/**\r\n * @ignore\r\n * @param telemetryChain\r\n * @param config\r\n * @param core\r\n * @param startAt - Identifies the next plugin to execute, if null there is no \"next\" plugin and if undefined it should assume the start of the chain\r\n * @returns\r\n */\r\nfunction _createInternalContext(telemetryChain, config, core, startAt) {\r\n // We have a special case where we want to start execution from this specific plugin\r\n // or we simply reuse the existing telemetry plugin chain (normal execution case)\r\n var _nextProxy = null; // By Default set as no next plugin\r\n var _onComplete = [];\r\n if (startAt !== null) {\r\n // There is no next element (null) vs not defined (undefined) so use the full chain\r\n _nextProxy = startAt ? _getNextProxyStart(telemetryChain, core, startAt) : telemetryChain;\r\n }\r\n var context = {\r\n _next: _moveNext,\r\n ctx: {\r\n core: function () {\r\n return core;\r\n },\r\n diagLog: function () {\r\n return safeGetLogger(core, config);\r\n },\r\n getCfg: function () {\r\n return config;\r\n },\r\n getExtCfg: _getExtCfg,\r\n getConfig: _getConfig,\r\n hasNext: function () {\r\n return !!_nextProxy;\r\n },\r\n getNext: function () {\r\n return _nextProxy;\r\n },\r\n setNext: function (nextPlugin) {\r\n _nextProxy = nextPlugin;\r\n },\r\n iterate: _iterateChain,\r\n onComplete: _addOnComplete\r\n }\r\n };\r\n function _addOnComplete(onComplete, that) {\r\n var args = [];\r\n for (var _i = 2; _i < arguments.length; _i++) {\r\n args[_i - 2] = arguments[_i];\r\n }\r\n if (onComplete) {\r\n _onComplete[_DYN_PUSH /* @min:%2epush */]({\r\n func: onComplete,\r\n self: !isUndefined(that) ? that : context.ctx,\r\n args: args\r\n });\r\n }\r\n }\r\n function _moveNext() {\r\n var nextProxy = _nextProxy;\r\n // Automatically move to the next plugin\r\n _nextProxy = nextProxy ? nextProxy[_DYN_GET_NEXT /* @min:%2egetNext */]() : null;\r\n if (!nextProxy) {\r\n var onComplete = _onComplete;\r\n if (onComplete && onComplete[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(onComplete, function (completeDetails) {\r\n try {\r\n completeDetails.func[_DYN_CALL /* @min:%2ecall */](completeDetails.self, completeDetails.args);\r\n }\r\n catch (e) {\r\n _throwInternal(core[_DYN_LOGGER /* @min:%2elogger */], 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, \"Unexpected Exception during onComplete - \" + dumpObj(e));\r\n }\r\n });\r\n _onComplete = [];\r\n }\r\n }\r\n return nextProxy;\r\n }\r\n function _getExtCfg(identifier, defaultValue, mergeDefault) {\r\n if (defaultValue === void 0) { defaultValue = {}; }\r\n if (mergeDefault === void 0) { mergeDefault = 0 /* GetExtCfgMergeType.None */; }\r\n var theConfig;\r\n if (config) {\r\n var extConfig = config[STR_EXTENSION_CONFIG /* @min:%2eextensionConfig */];\r\n if (extConfig && identifier) {\r\n theConfig = extConfig[identifier];\r\n }\r\n }\r\n if (!theConfig) {\r\n // Just use the defaults\r\n theConfig = defaultValue;\r\n }\r\n else if (isObject(defaultValue)) {\r\n if (mergeDefault !== 0 /* GetExtCfgMergeType.None */) {\r\n // Merge the defaults and configured values\r\n var newConfig_1 = objExtend(true, defaultValue, theConfig);\r\n if (config && mergeDefault === 2 /* GetExtCfgMergeType.MergeDefaultFromRootOrDefault */) {\r\n // Enumerate over the defaultValues and if not already populated attempt to\r\n // find a value from the root config\r\n objForEachKey(defaultValue, function (field) {\r\n // for each unspecified field, set the default value\r\n if (isNullOrUndefined(newConfig_1[field])) {\r\n var cfgValue = config[field];\r\n if (!isNullOrUndefined(cfgValue)) {\r\n newConfig_1[field] = cfgValue;\r\n }\r\n }\r\n });\r\n }\r\n theConfig = newConfig_1;\r\n }\r\n }\r\n return theConfig;\r\n }\r\n function _getConfig(identifier, field, defaultValue) {\r\n if (defaultValue === void 0) { defaultValue = false; }\r\n var theValue;\r\n var extConfig = _getExtCfg(identifier, null);\r\n if (extConfig && !isNullOrUndefined(extConfig[field])) {\r\n theValue = extConfig[field];\r\n }\r\n else if (config && !isNullOrUndefined(config[field])) {\r\n theValue = config[field];\r\n }\r\n return !isNullOrUndefined(theValue) ? theValue : defaultValue;\r\n }\r\n function _iterateChain(cb) {\r\n // Keep processing until we reach the end of the chain\r\n var nextPlugin;\r\n while (!!(nextPlugin = context._next())) {\r\n var plugin = nextPlugin[_DYN_GET_PLUGIN /* @min:%2egetPlugin */]();\r\n if (plugin) {\r\n // callback with the current on\r\n cb(plugin);\r\n }\r\n }\r\n }\r\n return context;\r\n}\r\n/**\r\n * Creates a new Telemetry Item context with the current config, core and plugin execution chain\r\n * @param plugins - The plugin instances that will be executed\r\n * @param config - The current config\r\n * @param core - The current core instance\r\n * @param startAt - Identifies the next plugin to execute, if null there is no \"next\" plugin and if undefined it should assume the start of the chain\r\n */\r\nexport function createProcessTelemetryContext(telemetryChain, config, core, startAt) {\r\n var internalContext = _createInternalContext(telemetryChain, config, core, startAt);\r\n var context = internalContext.ctx;\r\n function _processNext(env) {\r\n var nextPlugin = internalContext._next();\r\n // Run the next plugin which will call \"processNext()\"\r\n nextPlugin && nextPlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */](env, context);\r\n return !nextPlugin;\r\n }\r\n function _createNew(plugins, startAt) {\r\n if (plugins === void 0) { plugins = null; }\r\n if (isArray(plugins)) {\r\n plugins = createTelemetryProxyChain(plugins, config, core, startAt);\r\n }\r\n return createProcessTelemetryContext(plugins || context[_DYN_GET_NEXT /* @min:%2egetNext */](), config, core, startAt);\r\n }\r\n context[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = _processNext;\r\n context[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = _createNew;\r\n return context;\r\n}\r\n/**\r\n * Creates a new Telemetry Item context with the current config, core and plugin execution chain for handling the unloading of the chain\r\n * @param plugins - The plugin instances that will be executed\r\n * @param config - The current config\r\n * @param core - The current core instance\r\n * @param startAt - Identifies the next plugin to execute, if null there is no \"next\" plugin and if undefined it should assume the start of the chain\r\n */\r\nexport function createProcessTelemetryUnloadContext(telemetryChain, core, startAt) {\r\n var config = core[_DYN_CONFIG /* @min:%2econfig */] || {};\r\n var internalContext = _createInternalContext(telemetryChain, config, core, startAt);\r\n var context = internalContext.ctx;\r\n function _processNext(unloadState) {\r\n var nextPlugin = internalContext._next();\r\n nextPlugin && nextPlugin.unload(context, unloadState);\r\n return !nextPlugin;\r\n }\r\n function _createNew(plugins, startAt) {\r\n if (plugins === void 0) { plugins = null; }\r\n if (isArray(plugins)) {\r\n plugins = createTelemetryProxyChain(plugins, config, core, startAt);\r\n }\r\n return createProcessTelemetryUnloadContext(plugins || context[_DYN_GET_NEXT /* @min:%2egetNext */](), core, startAt);\r\n }\r\n context[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = _processNext;\r\n context[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = _createNew;\r\n return context;\r\n}\r\n/**\r\n * Creates a new Telemetry Item context with the current config, core and plugin execution chain for updating the configuration\r\n * @param plugins - The plugin instances that will be executed\r\n * @param config - The current config\r\n * @param core - The current core instance\r\n * @param startAt - Identifies the next plugin to execute, if null there is no \"next\" plugin and if undefined it should assume the start of the chain\r\n */\r\nexport function createProcessTelemetryUpdateContext(telemetryChain, core, startAt) {\r\n var config = core[_DYN_CONFIG /* @min:%2econfig */] || {};\r\n var internalContext = _createInternalContext(telemetryChain, config, core, startAt);\r\n var context = internalContext.ctx;\r\n function _processNext(updateState) {\r\n return context.iterate(function (plugin) {\r\n if (isFunction(plugin[_DYN_UPDATE /* @min:%2eupdate */])) {\r\n plugin[_DYN_UPDATE /* @min:%2eupdate */](context, updateState);\r\n }\r\n });\r\n }\r\n function _createNew(plugins, startAt) {\r\n if (plugins === void 0) { plugins = null; }\r\n if (isArray(plugins)) {\r\n plugins = createTelemetryProxyChain(plugins, config, core, startAt);\r\n }\r\n return createProcessTelemetryUpdateContext(plugins || context[_DYN_GET_NEXT /* @min:%2egetNext */](), core, startAt);\r\n }\r\n context[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = _processNext;\r\n context[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = _createNew;\r\n return context;\r\n}\r\n/**\r\n * Creates an execution chain from the array of plugins\r\n * @param plugins - The array of plugins that will be executed in this order\r\n * @param defItemCtx - The default execution context to use when no telemetry context is passed to processTelemetry(), this\r\n * should be for legacy plugins only. Currently, only used for passing the current core instance and to provide better error\r\n * reporting (hasRun) when errors occur.\r\n */\r\nexport function createTelemetryProxyChain(plugins, config, core, startAt) {\r\n var firstProxy = null;\r\n var add = startAt ? false : true;\r\n if (isArray(plugins) && plugins[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n // Create the proxies and wire up the next plugin chain\r\n var lastProxy_1 = null;\r\n arrForEach(plugins, function (thePlugin) {\r\n if (!add && startAt === thePlugin) {\r\n add = true;\r\n }\r\n if (add && thePlugin && isFunction(thePlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */])) {\r\n // Only add plugins that are processors\r\n var newProxy = createTelemetryPluginProxy(thePlugin, config, core);\r\n if (!firstProxy) {\r\n firstProxy = newProxy;\r\n }\r\n if (lastProxy_1) {\r\n // Set this new proxy as the next for the previous one\r\n lastProxy_1._setNext(newProxy);\r\n }\r\n lastProxy_1 = newProxy;\r\n }\r\n });\r\n }\r\n if (startAt && !firstProxy) {\r\n // Special case where the \"startAt\" was not in the original list of plugins\r\n return createTelemetryProxyChain([startAt], config, core);\r\n }\r\n return firstProxy;\r\n}\r\n/**\r\n * Create the processing telemetry proxy instance, the proxy is used to abstract the current plugin to allow monitoring and\r\n * execution plugins while passing around the dynamic execution state (IProcessTelemetryContext), the proxy instance no longer\r\n * contains any execution state and can be reused between requests (this was not the case for 2.7.2 and earlier with the\r\n * TelemetryPluginChain class).\r\n * @param plugin - The plugin instance to proxy\r\n * @param config - The default execution context to use when no telemetry context is passed to processTelemetry(), this\r\n * should be for legacy plugins only. Currently, only used for passing the current core instance and to provide better error\r\n * reporting (hasRun) when errors occur.\r\n * @returns\r\n */\r\nexport function createTelemetryPluginProxy(plugin, config, core) {\r\n var nextProxy = null;\r\n var hasProcessTelemetry = isFunction(plugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */]);\r\n var hasSetNext = isFunction(plugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */]);\r\n var chainId;\r\n if (plugin) {\r\n chainId = plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] + \"-\" + plugin[STR_PRIORITY /* @min:%2epriority */] + \"-\" + _chainId++;\r\n }\r\n else {\r\n chainId = \"Unknown-0-\" + _chainId++;\r\n }\r\n var proxyChain = {\r\n getPlugin: function () {\r\n return plugin;\r\n },\r\n getNext: function () {\r\n return nextProxy;\r\n },\r\n processTelemetry: _processTelemetry,\r\n unload: _unloadPlugin,\r\n update: _updatePlugin,\r\n _id: chainId,\r\n _setNext: function (nextPlugin) {\r\n nextProxy = nextPlugin;\r\n }\r\n };\r\n function _getTelCtx() {\r\n var itemCtx;\r\n // Looks like a plugin didn't pass the (optional) context, so create a new one\r\n if (plugin && isFunction(plugin[strGetTelCtx])) {\r\n // This plugin extends from the BaseTelemetryPlugin so lets use it\r\n itemCtx = plugin[strGetTelCtx]();\r\n }\r\n if (!itemCtx) {\r\n // Create a temporary one\r\n itemCtx = createProcessTelemetryContext(proxyChain, config, core);\r\n }\r\n return itemCtx;\r\n }\r\n function _processChain(itemCtx, processPluginFn, name, details, isAsync) {\r\n var hasRun = false;\r\n var identifier = plugin ? plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] : strTelemetryPluginChain;\r\n var hasRunContext = itemCtx[strHasRunFlags];\r\n if (!hasRunContext) {\r\n // Assign and populate\r\n hasRunContext = itemCtx[strHasRunFlags] = {};\r\n }\r\n // Ensure that we keep the context in sync\r\n itemCtx.setNext(nextProxy);\r\n if (plugin) {\r\n doPerf(itemCtx[STR_CORE /* @min:%2ecore */](), function () { return identifier + \":\" + name; }, function () {\r\n // Mark this component as having run\r\n hasRunContext[chainId] = true;\r\n try {\r\n // Set a flag on the next plugin so we know if it was attempted to be executed\r\n var nextId = nextProxy ? nextProxy._id : STR_EMPTY;\r\n if (nextId) {\r\n hasRunContext[nextId] = false;\r\n }\r\n hasRun = processPluginFn(itemCtx);\r\n }\r\n catch (error) {\r\n var hasNextRun = nextProxy ? hasRunContext[nextProxy._id] : true;\r\n if (hasNextRun) {\r\n // The next plugin after us has already run so set this one as complete\r\n hasRun = true;\r\n }\r\n if (!nextProxy || !hasNextRun) {\r\n // Either we have no next plugin or the current one did not attempt to call the next plugin\r\n // Which means the current one is the root of the failure so log/report this failure\r\n _throwInternal(itemCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 73 /* _eInternalMessageId.PluginException */, \"Plugin [\" + identifier + \"] failed during \" + name + \" - \" + dumpObj(error) + \", run flags: \" + dumpObj(hasRunContext));\r\n }\r\n }\r\n }, details, isAsync);\r\n }\r\n return hasRun;\r\n }\r\n function _processTelemetry(env, itemCtx) {\r\n itemCtx = itemCtx || _getTelCtx();\r\n function _callProcessTelemetry(itemCtx) {\r\n if (!plugin || !hasProcessTelemetry) {\r\n return false;\r\n }\r\n var pluginState = _getPluginState(plugin);\r\n if (pluginState[_DYN_TEARDOWN /* @min:%2eteardown */] || pluginState[STR_DISABLED]) {\r\n return false;\r\n }\r\n // Ensure that we keep the context in sync (for processNext()), just in case a plugin\r\n // doesn't calls processTelemetry() instead of itemContext.processNext() or some\r\n // other form of error occurred\r\n if (hasSetNext) {\r\n // Backward compatibility setting the next plugin on the instance\r\n plugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */](nextProxy);\r\n }\r\n plugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */](env, itemCtx);\r\n // Process Telemetry is expected to call itemCtx.processNext() or nextPlugin.processTelemetry()\r\n return true;\r\n }\r\n if (!_processChain(itemCtx, _callProcessTelemetry, \"processTelemetry\", function () { return ({ item: env }); }, !(env.sync))) {\r\n // The underlying plugin is either not defined, not enabled or does not have a processTelemetry implementation\r\n // so we still want the next plugin to be executed.\r\n itemCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](env);\r\n }\r\n }\r\n function _unloadPlugin(unloadCtx, unloadState) {\r\n function _callTeardown() {\r\n // Setting default of hasRun as false so the proxyProcessFn() is called as teardown() doesn't have to exist or call unloadNext().\r\n var hasRun = false;\r\n if (plugin) {\r\n var pluginState = _getPluginState(plugin);\r\n var pluginCore = plugin[STR_CORE] || pluginState[STR_CORE /* @min:%2ecore */];\r\n // Only teardown the plugin if it was initialized by the current core (i.e. It's not a shared plugin)\r\n if (plugin && (!pluginCore || pluginCore === unloadCtx.core()) && !pluginState[_DYN_TEARDOWN /* @min:%2eteardown */]) {\r\n // Handle plugins that don't extend from the BaseTelemetryPlugin\r\n pluginState[STR_CORE /* @min:%2ecore */] = null;\r\n pluginState[_DYN_TEARDOWN /* @min:%2eteardown */] = true;\r\n pluginState[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = false;\r\n if (plugin[_DYN_TEARDOWN /* @min:%2eteardown */] && plugin[_DYN_TEARDOWN /* @min:%2eteardown */](unloadCtx, unloadState) === true) {\r\n // plugin told us that it was going to (or has) call unloadCtx.processNext()\r\n hasRun = true;\r\n }\r\n }\r\n }\r\n return hasRun;\r\n }\r\n if (!_processChain(unloadCtx, _callTeardown, \"unload\", function () { }, unloadState[_DYN_IS_ASYNC /* @min:%2eisAsync */])) {\r\n // Only called if we hasRun was not true\r\n unloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\r\n }\r\n }\r\n function _updatePlugin(updateCtx, updateState) {\r\n function _callUpdate() {\r\n // Setting default of hasRun as false so the proxyProcessFn() is called as teardown() doesn't have to exist or call unloadNext().\r\n var hasRun = false;\r\n if (plugin) {\r\n var pluginState = _getPluginState(plugin);\r\n var pluginCore = plugin[STR_CORE] || pluginState[STR_CORE /* @min:%2ecore */];\r\n // Only update the plugin if it was initialized by the current core (i.e. It's not a shared plugin)\r\n if (plugin && (!pluginCore || pluginCore === updateCtx.core()) && !pluginState[_DYN_TEARDOWN /* @min:%2eteardown */]) {\r\n if (plugin[_DYN_UPDATE /* @min:%2eupdate */] && plugin[_DYN_UPDATE /* @min:%2eupdate */](updateCtx, updateState) === true) {\r\n // plugin told us that it was going to (or has) call unloadCtx.processNext()\r\n hasRun = true;\r\n }\r\n }\r\n }\r\n return hasRun;\r\n }\r\n if (!_processChain(updateCtx, _callUpdate, \"update\", function () { }, false)) {\r\n // Only called if we hasRun was not true\r\n updateCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](updateState);\r\n }\r\n }\r\n return objFreeze(proxyChain);\r\n}\r\n/**\r\n * This class will be removed!\r\n * @deprecated use createProcessTelemetryContext() instead\r\n */\r\nvar ProcessTelemetryContext = /** @class */ (function () {\r\n /**\r\n * Creates a new Telemetry Item context with the current config, core and plugin execution chain\r\n * @param plugins - The plugin instances that will be executed\r\n * @param config - The current config\r\n * @param core - The current core instance\r\n */\r\n function ProcessTelemetryContext(pluginChain, config, core, startAt) {\r\n var _self = this;\r\n var context = createProcessTelemetryContext(pluginChain, config, core, startAt);\r\n // Proxy all functions of the context to this object\r\n proxyFunctions(_self, context, objKeys(context));\r\n }\r\n return ProcessTelemetryContext;\r\n}());\r\nexport { ProcessTelemetryContext };\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\r\nimport { getCrypto, getMsCrypto, isIE } from \"./EnvUtils\";\r\nimport { dateNow } from \"./HelperFuncs\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\nvar UInt32Mask = 0x100000000;\r\nvar MaxUInt32 = 0xffffffff;\r\n// MWC based Random generator (for IE)\r\nvar _mwcSeeded = false;\r\nvar _mwcW = 123456789;\r\nvar _mwcZ = 987654321;\r\n// Takes any integer\r\nfunction _mwcSeed(seedValue) {\r\n if (seedValue < 0) {\r\n // Make sure we end up with a positive number and not -ve one.\r\n seedValue >>>= 0;\r\n }\r\n _mwcW = (123456789 + seedValue) & MaxUInt32;\r\n _mwcZ = (987654321 - seedValue) & MaxUInt32;\r\n _mwcSeeded = true;\r\n}\r\nfunction _autoSeedMwc() {\r\n // Simple initialization using default Math.random() - So we inherit any entropy from the browser\r\n // and bitwise XOR with the current milliseconds\r\n try {\r\n var now = dateNow() & 0x7fffffff;\r\n _mwcSeed(((Math.random() * UInt32Mask) ^ now) + now);\r\n }\r\n catch (e) {\r\n // Don't crash if something goes wrong\r\n }\r\n}\r\n/**\r\n * Generate a random value between 0 and maxValue, max value should be limited to a 32-bit maximum.\r\n * So maxValue(16) will produce a number from 0..16 (range of 17)\r\n * @param maxValue\r\n */\r\nexport function randomValue(maxValue) {\r\n if (maxValue > 0) {\r\n return Math.floor((random32() / MaxUInt32) * (maxValue + 1)) >>> 0;\r\n }\r\n return 0;\r\n}\r\n/**\r\n * generate a random 32-bit number (0x000000..0xFFFFFFFF) or (-0x80000000..0x7FFFFFFF), defaults un-unsigned.\r\n * @param signed - True to return a signed 32-bit number (-0x80000000..0x7FFFFFFF) otherwise an unsigned one (0x000000..0xFFFFFFFF)\r\n */\r\nexport function random32(signed) {\r\n var value = 0;\r\n var c = getCrypto() || getMsCrypto();\r\n if (c && c.getRandomValues) {\r\n // Make sure the number is converted into the specified range (-0x80000000..0x7FFFFFFF)\r\n value = c.getRandomValues(new Uint32Array(1))[0] & MaxUInt32;\r\n }\r\n if (value === 0 && isIE()) {\r\n // For IE 6, 7, 8 (especially on XP) Math.random is not very random\r\n if (!_mwcSeeded) {\r\n // Set the seed for the Mwc algorithm\r\n _autoSeedMwc();\r\n }\r\n // Don't use Math.random for IE\r\n // Make sure the number is converted into the specified range (-0x80000000..0x7FFFFFFF)\r\n value = mwcRandom32() & MaxUInt32;\r\n }\r\n if (value === 0) {\r\n // Make sure the number is converted into the specified range (-0x80000000..0x7FFFFFFF)\r\n value = Math.floor((UInt32Mask * Math.random()) | 0);\r\n }\r\n if (!signed) {\r\n // Make sure we end up with a positive number and not -ve one.\r\n value >>>= 0;\r\n }\r\n return value;\r\n}\r\n/**\r\n * Seed the MWC random number generator with the specified seed or a random value\r\n * @param value - optional the number to used as the seed, if undefined, null or zero a random value will be chosen\r\n */\r\nexport function mwcRandomSeed(value) {\r\n if (!value) {\r\n _autoSeedMwc();\r\n }\r\n else {\r\n _mwcSeed(value);\r\n }\r\n}\r\n/**\r\n * Generate a random 32-bit number between (0x000000..0xFFFFFFFF) or (-0x80000000..0x7FFFFFFF), using MWC (Multiply with carry)\r\n * instead of Math.random() defaults to un-signed.\r\n * Used as a replacement random generator for IE to avoid issues with older IE instances.\r\n * @param signed - True to return a signed 32-bit number (-0x80000000..0x7FFFFFFF) otherwise an unsigned one (0x000000..0xFFFFFFFF)\r\n */\r\nexport function mwcRandom32(signed) {\r\n _mwcZ = (36969 * (_mwcZ & 0xFFFF) + (_mwcZ >> 16)) & MaxUInt32;\r\n _mwcW = (18000 * (_mwcW & 0xFFFF) + (_mwcW >> 16)) & MaxUInt32;\r\n var value = (((_mwcZ << 16) + (_mwcW & 0xFFFF)) >>> 0) & MaxUInt32 | 0;\r\n if (!signed) {\r\n // Make sure we end up with a positive number and not -ve one.\r\n value >>>= 0;\r\n }\r\n return value;\r\n}\r\n/**\r\n * Generate random base64 id string.\r\n * The default length is 22 which is 132-bits so almost the same as a GUID but as base64 (the previous default was 5)\r\n * @param maxLength - Optional value to specify the length of the id to be generated, defaults to 22\r\n */\r\nexport function newId(maxLength) {\r\n if (maxLength === void 0) { maxLength = 22; }\r\n var base64chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\r\n // Start with an initial random number, consuming the value in reverse byte order\r\n var number = random32() >>> 0; // Make sure it's a +ve number\r\n var chars = 0;\r\n var result = STR_EMPTY;\r\n while (result[_DYN_LENGTH /* @min:%2elength */] < maxLength) {\r\n chars++;\r\n result += base64chars.charAt(number & 0x3F);\r\n number >>>= 6; // Zero fill with right shift\r\n if (chars === 5) {\r\n // 5 base64 characters === 30 bits so we don't have enough bits for another base64 char\r\n // So add on another 30 bits and make sure it's +ve\r\n number = (((random32() << 2) & 0xFFFFFFFF) | (number & 0x03)) >>> 0;\r\n chars = 0; // We need to reset the number every 5 chars (30 bits)\r\n }\r\n }\r\n return result;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n\"use strict\";\r\nimport { _DYN_CALL, _DYN_GET_NEXT, _DYN_GET_PLUGIN, _DYN_INITIALIZE, _DYN_IS_INITIALIZED, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_SET_NEXT_PLUGIN, _DYN_SPAN_ID, _DYN_TEARDOWN, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\r\nimport { createElmNodeData } from \"./DataCacheHelper\";\r\nimport { arrForEach, isFunction } from \"./HelperFuncs\";\r\nimport { STR_CORE, STR_PRIORITY, STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\r\nimport { isValidSpanId, isValidTraceId } from \"./W3cTraceParent\";\r\nvar pluginStateData = createElmNodeData(\"plugin\");\r\nexport function _getPluginState(plugin) {\r\n return pluginStateData.get(plugin, \"state\", {}, true);\r\n}\r\n/**\r\n * Initialize the queue of plugins\r\n * @param plugins - The array of plugins to initialize and setting of the next plugin\r\n * @param config The current config for the instance\r\n * @param core THe current core instance\r\n * @param extensions The extensions\r\n */\r\nexport function initializePlugins(processContext, extensions) {\r\n // Set the next plugin and identified the uninitialized plugins\r\n var initPlugins = [];\r\n var lastPlugin = null;\r\n var proxy = processContext[_DYN_GET_NEXT /* @min:%2egetNext */]();\r\n var pluginState;\r\n while (proxy) {\r\n var thePlugin = proxy[_DYN_GET_PLUGIN /* @min:%2egetPlugin */]();\r\n if (thePlugin) {\r\n if (lastPlugin &&\r\n isFunction(lastPlugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */]) &&\r\n isFunction(thePlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */])) {\r\n // Set this plugin as the next for the previous one\r\n lastPlugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */](thePlugin);\r\n }\r\n var isInitialized = false;\r\n if (isFunction(thePlugin[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */])) {\r\n isInitialized = thePlugin[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]();\r\n }\r\n else {\r\n pluginState = _getPluginState(thePlugin);\r\n isInitialized = pluginState[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */];\r\n }\r\n if (!isInitialized) {\r\n initPlugins[_DYN_PUSH /* @min:%2epush */](thePlugin);\r\n }\r\n lastPlugin = thePlugin;\r\n proxy = proxy[_DYN_GET_NEXT /* @min:%2egetNext */]();\r\n }\r\n }\r\n // Now initialize the plugins\r\n arrForEach(initPlugins, function (thePlugin) {\r\n var core = processContext[STR_CORE]();\r\n thePlugin[_DYN_INITIALIZE /* @min:%2einitialize */](processContext.getCfg(), core, extensions, processContext[_DYN_GET_NEXT /* @min:%2egetNext */]());\r\n pluginState = _getPluginState(thePlugin);\r\n // Only add the core to the state if the plugin didn't set it (doesn't extent from BaseTelemetryPlugin)\r\n if (!thePlugin[STR_CORE] && !pluginState[STR_CORE]) {\r\n pluginState[STR_CORE] = core;\r\n }\r\n pluginState[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = true;\r\n delete pluginState[_DYN_TEARDOWN /* @min:%2eteardown */];\r\n });\r\n}\r\nexport function sortPlugins(plugins) {\r\n // Sort by priority\r\n return plugins.sort(function (extA, extB) {\r\n var result = 0;\r\n if (extB) {\r\n var bHasProcess = isFunction(extB[STR_PROCESS_TELEMETRY]);\r\n if (isFunction(extA[STR_PROCESS_TELEMETRY])) {\r\n result = bHasProcess ? extA[STR_PRIORITY] - extB[STR_PRIORITY] : 1;\r\n }\r\n else if (bHasProcess) {\r\n result = -1;\r\n }\r\n }\r\n else {\r\n result = extA ? 1 : -1;\r\n }\r\n return result;\r\n });\r\n // sort complete\r\n}\r\n/**\r\n * Teardown / Unload helper to perform teardown/unloading operations for the provided components synchronously or asynchronously, this will call any\r\n * _doTeardown() or _doUnload() functions on the provided components to allow them to finish removal.\r\n * @param components - The components you want to unload\r\n * @param unloadCtx - This is the context that should be used during unloading.\r\n * @param unloadState - The details / state of the unload process, it holds details like whether it should be unloaded synchronously or asynchronously and the reason for the unload.\r\n * @param asyncCallback - An optional callback that the plugin must call if it returns true to inform the caller that it has completed any async unload/teardown operations.\r\n * @returns boolean - true if the plugin has or will call asyncCallback, this allows the plugin to perform any asynchronous operations.\r\n */\r\nexport function unloadComponents(components, unloadCtx, unloadState, asyncCallback) {\r\n var idx = 0;\r\n function _doUnload() {\r\n while (idx < components[_DYN_LENGTH /* @min:%2elength */]) {\r\n var component = components[idx++];\r\n if (component) {\r\n var func = component._doUnload || component[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */];\r\n if (isFunction(func)) {\r\n if (func[_DYN_CALL /* @min:%2ecall */](component, unloadCtx, unloadState, _doUnload) === true) {\r\n return true;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return _doUnload();\r\n}\r\n/**\r\n * Creates a IDistributedTraceContext which optionally also \"sets\" the value on a parent\r\n * @param parentCtx - An optional parent distributed trace instance\r\n * @returns A new IDistributedTraceContext instance that uses an internal temporary object\r\n */\r\nexport function createDistributedTraceContext(parentCtx) {\r\n var trace = {};\r\n return {\r\n getName: function () {\r\n return trace[_DYN_NAME /* @min:%2ename */];\r\n },\r\n setName: function (newValue) {\r\n parentCtx && parentCtx.setName(newValue);\r\n trace[_DYN_NAME /* @min:%2ename */] = newValue;\r\n },\r\n getTraceId: function () {\r\n return trace[_DYN_TRACE_ID /* @min:%2etraceId */];\r\n },\r\n setTraceId: function (newValue) {\r\n parentCtx && parentCtx.setTraceId(newValue);\r\n if (isValidTraceId(newValue)) {\r\n trace[_DYN_TRACE_ID /* @min:%2etraceId */] = newValue;\r\n }\r\n },\r\n getSpanId: function () {\r\n return trace[_DYN_SPAN_ID /* @min:%2espanId */];\r\n },\r\n setSpanId: function (newValue) {\r\n parentCtx && parentCtx.setSpanId(newValue);\r\n if (isValidSpanId(newValue)) {\r\n trace[_DYN_SPAN_ID /* @min:%2espanId */] = newValue;\r\n }\r\n },\r\n getTraceFlags: function () {\r\n return trace[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\r\n },\r\n setTraceFlags: function (newTraceFlags) {\r\n parentCtx && parentCtx.setTraceFlags(newTraceFlags);\r\n trace[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = newTraceFlags;\r\n }\r\n };\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n// \r\n// \r\nimport { __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { _DYN_APPLY, _DYN_DIAG_LOG, _DYN_LENGTH, _DYN_PROCESS_NEXT, _DYN_PUSH, _DYN_SPLICE, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\r\nimport { BaseTelemetryPlugin } from \"./BaseTelemetryPlugin\";\r\nimport { _throwInternal } from \"./DiagnosticLogger\";\r\nimport { dumpObj } from \"./EnvUtils\";\r\nimport { arrForEach, getExceptionName } from \"./HelperFuncs\";\r\nimport { STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\r\nvar TelemetryInitializerPlugin = /** @class */ (function (_super) {\r\n __extends(TelemetryInitializerPlugin, _super);\r\n function TelemetryInitializerPlugin() {\r\n var _this = _super.call(this) || this;\r\n _this.identifier = \"TelemetryInitializerPlugin\";\r\n _this.priority = 199;\r\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\r\n var _id;\r\n var _initializers;\r\n _initDefaults();\r\n dynamicProto(TelemetryInitializerPlugin, _this, function (_self, _base) {\r\n _self.addTelemetryInitializer = function (telemetryInitializer) {\r\n var theInitializer = {\r\n id: _id++,\r\n fn: telemetryInitializer\r\n };\r\n _initializers[_DYN_PUSH /* @min:%2epush */](theInitializer);\r\n var handler = {\r\n remove: function () {\r\n arrForEach(_initializers, function (initializer, idx) {\r\n if (initializer.id === theInitializer.id) {\r\n _initializers[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\r\n return -1;\r\n }\r\n });\r\n }\r\n };\r\n return handler;\r\n };\r\n _self[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */] = function (item, itemCtx) {\r\n var doNotSendItem = false;\r\n var telemetryInitializersCount = _initializers[_DYN_LENGTH /* @min:%2elength */];\r\n for (var i = 0; i < telemetryInitializersCount; ++i) {\r\n var telemetryInitializer = _initializers[i];\r\n if (telemetryInitializer) {\r\n try {\r\n if (telemetryInitializer.fn[_DYN_APPLY /* @min:%2eapply */](null, [item]) === false) {\r\n doNotSendItem = true;\r\n break;\r\n }\r\n }\r\n catch (e) {\r\n // log error but dont stop executing rest of the telemetry initializers\r\n // doNotSendItem = true;\r\n _throwInternal(itemCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"One of telemetry initializers failed, telemetry item will not be sent: \" + getExceptionName(e), { exception: dumpObj(e) }, true);\r\n }\r\n }\r\n }\r\n if (!doNotSendItem) {\r\n _self[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](item, itemCtx);\r\n }\r\n };\r\n _self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */] = function () {\r\n _initDefaults();\r\n };\r\n });\r\n function _initDefaults() {\r\n _id = 0;\r\n _initializers = [];\r\n }\r\n return _this;\r\n }\r\n// Removed Stub for TelemetryInitializerPlugin.prototype.addTelemetryInitializer.\r\n// Removed Stub for TelemetryInitializerPlugin.prototype.processTelemetry.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n TelemetryInitializerPlugin.__ieDyn=1;\n\n return TelemetryInitializerPlugin;\r\n}(BaseTelemetryPlugin));\r\nexport { TelemetryInitializerPlugin };\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { _DYN_DIAG_LOG, _DYN_PUSH } from \"../__DynamicConstants\";\r\nimport { _throwInternal } from \"./DiagnosticLogger\";\r\nimport { dumpObj } from \"./EnvUtils\";\r\nimport { arrForEach } from \"./HelperFuncs\";\r\nexport function createUnloadHandlerContainer() {\r\n var handlers = [];\r\n function _addHandler(handler) {\r\n if (handler) {\r\n handlers[_DYN_PUSH /* @min:%2epush */](handler);\r\n }\r\n }\r\n function _runHandlers(unloadCtx, unloadState) {\r\n arrForEach(handlers, function (handler) {\r\n try {\r\n handler(unloadCtx, unloadState);\r\n }\r\n catch (e) {\r\n _throwInternal(unloadCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, \"Unexpected error calling unload handler - \" + dumpObj(e));\r\n }\r\n });\r\n handlers = [];\r\n }\r\n return {\r\n add: _addHandler,\r\n run: _runHandlers\r\n };\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { _DYN_LENGTH, _DYN_SPAN_ID, _DYN_SUBSTR, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN_VERSION } from \"../__DynamicConstants\";\r\nimport { generateW3CId } from \"./CoreUtils\";\r\nimport { findMetaTag, findNamedServerTiming } from \"./EnvUtils\";\r\nimport { isArray, isString, strTrim } from \"./HelperFuncs\";\r\n// using {0,16} for leading and trailing whitespace just to constrain the possible runtime of a random string\r\nvar TRACE_PARENT_REGEX = /^([\\da-f]{2})-([\\da-f]{32})-([\\da-f]{16})-([\\da-f]{2})(-[^\\s]*)?$/;\r\nvar DEFAULT_VERSION = \"00\";\r\nvar INVALID_VERSION = \"ff\";\r\nvar INVALID_TRACE_ID = \"00000000000000000000000000000000\";\r\nvar INVALID_SPAN_ID = \"0000000000000000\";\r\nvar SAMPLED_FLAG = 0x01;\r\nfunction _isValid(value, len, invalidValue) {\r\n if (value && value[_DYN_LENGTH /* @min:%2elength */] === len && value !== invalidValue) {\r\n return !!value.match(/^[\\da-f]*$/);\r\n }\r\n return false;\r\n}\r\nfunction _formatValue(value, len, defValue) {\r\n if (_isValid(value, len)) {\r\n return value;\r\n }\r\n return defValue;\r\n}\r\nfunction _formatFlags(value) {\r\n if (isNaN(value) || value < 0 || value > 255) {\r\n value = 0x01;\r\n }\r\n var result = value.toString(16);\r\n while (result[_DYN_LENGTH /* @min:%2elength */] < 2) {\r\n result = \"0\" + result;\r\n }\r\n return result;\r\n}\r\n/**\r\n * Create a new ITraceParent instance using the provided values.\r\n * @param traceId - The traceId to use, when invalid a new random W3C id will be generated.\r\n * @param spanId - The parent/span id to use, a new random value will be generated if it is invalid.\r\n * @param flags - The traceFlags to use, defaults to zero (0) if not supplied or invalid\r\n * @param version - The version to used, defaults to version \"01\" if not supplied or invalid.\r\n * @returns\r\n */\r\nexport function createTraceParent(traceId, spanId, flags, version) {\r\n var _a;\r\n return _a = {},\r\n _a[_DYN_VERSION /* @min:version */] = _isValid(version, 2, INVALID_VERSION) ? version : DEFAULT_VERSION,\r\n _a[_DYN_TRACE_ID /* @min:traceId */] = isValidTraceId(traceId) ? traceId : generateW3CId(),\r\n _a.spanId = isValidSpanId(spanId) ? spanId : generateW3CId()[_DYN_SUBSTR /* @min:%2esubstr */](0, 16),\r\n _a.traceFlags = flags >= 0 && flags <= 0xFF ? flags : 1,\r\n _a;\r\n}\r\n/**\r\n * Attempt to parse the provided string as a W3C TraceParent header value (https://www.w3.org/TR/trace-context/#traceparent-header)\r\n *\r\n * @param value\r\n * @returns\r\n */\r\nexport function parseTraceParent(value) {\r\n var _a;\r\n if (!value) {\r\n // Don't pass a null/undefined or empty string\r\n return null;\r\n }\r\n if (isArray(value)) {\r\n // The value may have been encoded on the page into an array so handle this automatically\r\n value = value[0] || \"\";\r\n }\r\n if (!value || !isString(value) || value[_DYN_LENGTH /* @min:%2elength */] > 8192) {\r\n // limit potential processing based on total length\r\n return null;\r\n }\r\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\r\n var match = TRACE_PARENT_REGEX.exec(strTrim(value));\r\n if (!match || // No match\r\n match[1] === INVALID_VERSION || // version ff is forbidden\r\n match[2] === INVALID_TRACE_ID || // All zeros is considered to be invalid\r\n match[3] === INVALID_SPAN_ID) { // All zeros is considered to be invalid\r\n return null;\r\n }\r\n return _a = {},\r\n _a[_DYN_VERSION /* @min:version */] = match[1],\r\n _a[_DYN_TRACE_ID /* @min:traceId */] = match[2],\r\n _a[_DYN_SPAN_ID /* @min:spanId */] = match[3],\r\n _a[_DYN_TRACE_FLAGS /* @min:traceFlags */] = parseInt(match[4], 16),\r\n _a;\r\n}\r\n/**\r\n * Is the provided W3c Trace Id a valid string representation, it must be a 32-character string\r\n * of lowercase hexadecimal characters for example, 4bf92f3577b34da6a3ce929d0e0e4736.\r\n * If all characters as zero (00000000000000000000000000000000) it will be considered an invalid value.\r\n * @param value - The W3c trace Id to be validated\r\n * @returns true if valid otherwise false\r\n */\r\nexport function isValidTraceId(value) {\r\n return _isValid(value, 32, INVALID_TRACE_ID);\r\n}\r\n/**\r\n * Is the provided W3c span id (aka. parent id) a valid string representation, it must be a 16-character\r\n * string of lowercase hexadecimal characters, for example, 00f067aa0ba902b7.\r\n * If all characters are zero (0000000000000000) this is considered an invalid value.\r\n * @param value - The W3c span id to be validated\r\n * @returns true if valid otherwise false\r\n */\r\nexport function isValidSpanId(value) {\r\n return _isValid(value, 16, INVALID_SPAN_ID);\r\n}\r\n/**\r\n * Validates that the provided ITraceParent instance conforms to the currently supported specifications\r\n * @param value\r\n * @returns\r\n */\r\nexport function isValidTraceParent(value) {\r\n if (!value ||\r\n !_isValid(value[_DYN_VERSION /* @min:%2eversion */], 2, INVALID_VERSION) ||\r\n !_isValid(value[_DYN_TRACE_ID /* @min:%2etraceId */], 32, INVALID_TRACE_ID) ||\r\n !_isValid(value[_DYN_SPAN_ID /* @min:%2espanId */], 16, INVALID_SPAN_ID) ||\r\n !_isValid(_formatFlags(value[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */]), 2)) {\r\n // Each known field must contain a valid value\r\n return false;\r\n }\r\n return true;\r\n}\r\n/**\r\n * Is the parsed traceParent indicating that the trace is currently sampled.\r\n * @param value - The parsed traceParent value\r\n * @returns\r\n */\r\nexport function isSampledFlag(value) {\r\n if (isValidTraceParent(value)) {\r\n return (value[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] & SAMPLED_FLAG) === SAMPLED_FLAG;\r\n }\r\n return false;\r\n}\r\n/**\r\n * Format the ITraceParent value as a string using the supported and know version formats.\r\n * So even if the passed traceParent is a later version the string value returned from this\r\n * function will convert it to only the known version formats.\r\n * This currently only supports version \"00\" and invalid \"ff\"\r\n * @param value - The parsed traceParent value\r\n * @returns\r\n */\r\nexport function formatTraceParent(value) {\r\n if (value) {\r\n // Special Note: This only supports formatting as version 00, future versions should encode any known supported version\r\n // So parsing a future version will populate the correct version value but reformatting will reduce it to version 00.\r\n var flags = _formatFlags(value[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */]);\r\n if (!_isValid(flags, 2)) {\r\n flags = \"01\";\r\n }\r\n var version = value[_DYN_VERSION /* @min:%2eversion */] || DEFAULT_VERSION;\r\n if (version !== \"00\" && version !== \"ff\") {\r\n // Reduce version to \"00\"\r\n version = DEFAULT_VERSION;\r\n }\r\n // Format as version 00\r\n return \"\".concat(version, \"-\").concat(_formatValue(value.traceId, 32, INVALID_TRACE_ID), \"-\").concat(_formatValue(value.spanId, 16, INVALID_SPAN_ID), \"-\").concat(flags);\r\n }\r\n return \"\";\r\n}\r\n/**\r\n * Helper function to fetch the passed traceparent from the page, looking for it as a meta-tag or a Server-Timing header.\r\n * @returns\r\n */\r\nexport function findW3cTraceParent() {\r\n var name = \"traceparent\";\r\n var traceParent = parseTraceParent(findMetaTag(name));\r\n if (!traceParent) {\r\n traceParent = parseTraceParent(findNamedServerTiming(name));\r\n }\r\n return traceParent;\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Core, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_INITIALIZE = \"initialize\"; // Count: 8\r\nexport var _DYN_NAME = \"name\"; // Count: 11\r\nexport var _DYN_GET_NOTIFY_MGR = \"getNotifyMgr\"; // Count: 3\r\nexport var _DYN_IDENTIFIER = \"identifier\"; // Count: 8\r\nexport var _DYN_PUSH = \"push\"; // Count: 30\r\nexport var _DYN_IS_INITIALIZED = \"isInitialized\"; // Count: 10\r\nexport var _DYN_CONFIG = \"config\"; // Count: 7\r\nexport var _DYN_INSTRUMENTATION_KEY = \"instrumentationKey\"; // Count: 3\r\nexport var _DYN_LOGGER = \"logger\"; // Count: 9\r\nexport var _DYN_LENGTH = \"length\"; // Count: 43\r\nexport var _DYN_TIME = \"time\"; // Count: 5\r\nexport var _DYN_PROCESS_NEXT = \"processNext\"; // Count: 21\r\nexport var _DYN_GET_PROCESS_TEL_CONT0 = \"getProcessTelContext\"; // Count: 2\r\nexport var _DYN_ADD_NOTIFICATION_LIS1 = \"addNotificationListener\"; // Count: 5\r\nexport var _DYN_REMOVE_NOTIFICATION_2 = \"removeNotificationListener\"; // Count: 5\r\nexport var _DYN_STOP_POLLING_INTERNA3 = \"stopPollingInternalLogs\"; // Count: 2\r\nexport var _DYN_ON_COMPLETE = \"onComplete\"; // Count: 4\r\nexport var _DYN_GET_PLUGIN = \"getPlugin\"; // Count: 5\r\nexport var _DYN_FLUSH = \"flush\"; // Count: 5\r\nexport var _DYN__EXTENSIONS = \"_extensions\"; // Count: 4\r\nexport var _DYN_SPLICE = \"splice\"; // Count: 6\r\nexport var _DYN_TEARDOWN = \"teardown\"; // Count: 10\r\nexport var _DYN_MESSAGE_ID = \"messageId\"; // Count: 4\r\nexport var _DYN_MESSAGE = \"message\"; // Count: 7\r\nexport var _DYN_IS_ASYNC = \"isAsync\"; // Count: 7\r\nexport var _DYN__DO_TEARDOWN = \"_doTeardown\"; // Count: 4\r\nexport var _DYN_UPDATE = \"update\"; // Count: 7\r\nexport var _DYN_GET_NEXT = \"getNext\"; // Count: 12\r\nexport var _DYN_DIAG_LOG = \"diagLog\"; // Count: 8\r\nexport var _DYN_SET_NEXT_PLUGIN = \"setNextPlugin\"; // Count: 5\r\nexport var _DYN_CREATE_NEW = \"createNew\"; // Count: 6\r\nexport var _DYN_COOKIE_CFG = \"cookieCfg\"; // Count: 3\r\nexport var _DYN_INDEX_OF = \"indexOf\"; // Count: 6\r\nexport var _DYN_SUBSTRING = \"substring\"; // Count: 10\r\nexport var _DYN_USER_AGENT = \"userAgent\"; // Count: 5\r\nexport var _DYN_SPLIT = \"split\"; // Count: 5\r\nexport var _DYN_SET_ENABLED = \"setEnabled\"; // Count: 5\r\nexport var _DYN_SUBSTR = \"substr\"; // Count: 6\r\nexport var _DYN_NODE_TYPE = \"nodeType\"; // Count: 3\r\nexport var _DYN_APPLY = \"apply\"; // Count: 6\r\nexport var _DYN_REPLACE = \"replace\"; // Count: 10\r\nexport var _DYN_ENABLE_DEBUG_EXCEPTI4 = \"enableDebugExceptions\"; // Count: 2\r\nexport var _DYN_LOG_INTERNAL_MESSAGE = \"logInternalMessage\"; // Count: 2\r\nexport var _DYN_TO_LOWER_CASE = \"toLowerCase\"; // Count: 5\r\nexport var _DYN_CALL = \"call\"; // Count: 18\r\nexport var _DYN_TYPE = \"type\"; // Count: 14\r\nexport var _DYN_HANDLER = \"handler\"; // Count: 5\r\nexport var _DYN_LISTENERS = \"listeners\"; // Count: 6\r\nexport var _DYN_IS_CHILD_EVT = \"isChildEvt\"; // Count: 3\r\nexport var _DYN_GET_CTX = \"getCtx\"; // Count: 6\r\nexport var _DYN_SET_CTX = \"setCtx\"; // Count: 10\r\nexport var _DYN_COMPLETE = \"complete\"; // Count: 3\r\nexport var _DYN_TRACE_ID = \"traceId\"; // Count: 5\r\nexport var _DYN_SPAN_ID = \"spanId\"; // Count: 5\r\nexport var _DYN_TRACE_FLAGS = \"traceFlags\"; // Count: 6\r\nexport var _DYN_VERSION = \"version\"; // Count: 4\r\n","/*\n * Application Insights JavaScript SDK - Dependencies Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)\r\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\r\nexport var STR_DURATION = \"duration\";\r\nexport var STR_PROPERTIES = \"properties\";\r\n","/*\n * Application Insights JavaScript SDK - Dependencies Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_REQUEST_URL = \"requestUrl\"; // Count: 12\r\nexport var _DYN_INST = \"inst\"; // Count: 5\r\nexport var _DYN_LENGTH = \"length\"; // Count: 10\r\nexport var _DYN_TRACE_ID = \"traceID\"; // Count: 9\r\nexport var _DYN_SPAN_ID = \"spanID\"; // Count: 8\r\nexport var _DYN_TRACE_FLAGS = \"traceFlags\"; // Count: 13\r\nexport var _DYN_CONTEXT = \"context\"; // Count: 7\r\nexport var _DYN_ABORTED = \"aborted\"; // Count: 7\r\nexport var _DYN_TRACE_ID0 = \"traceId\"; // Count: 5\r\nexport var _DYN_SPAN_ID1 = \"spanId\"; // Count: 5\r\nexport var _DYN_CORE = \"core\"; // Count: 8\r\nexport var _DYN_INCLUDE_CORRELATION_2 = \"includeCorrelationHeaders\"; // Count: 4\r\nexport var _DYN_CAN_INCLUDE_CORRELAT3 = \"canIncludeCorrelationHeader\"; // Count: 2\r\nexport var _DYN_GET_ABSOLUTE_URL = \"getAbsoluteUrl\"; // Count: 3\r\nexport var _DYN_HEADERS = \"headers\"; // Count: 6\r\nexport var _DYN_REQUEST_HEADERS = \"requestHeaders\"; // Count: 13\r\nexport var _DYN_APP_ID = \"appId\"; // Count: 5\r\nexport var _DYN_SET_REQUEST_HEADER = \"setRequestHeader\"; // Count: 3\r\nexport var _DYN_TRACK_DEPENDENCY_DAT4 = \"trackDependencyDataInternal\"; // Count: 2\r\nexport var _DYN_DISTRIBUTED_TRACING_5 = \"distributedTracingMode\"; // Count: 3\r\nexport var _DYN_START_TIME = \"startTime\"; // Count: 6\r\nexport var _DYN_TO_LOWER_CASE = \"toLowerCase\"; // Count: 6\r\nexport var _DYN_ENABLE_REQUEST_HEADE6 = \"enableRequestHeaderTracking\"; // Count: 2\r\nexport var _DYN_ENABLE_AJAX_ERROR_ST7 = \"enableAjaxErrorStatusText\"; // Count: 2\r\nexport var _DYN_ENABLE_AJAX_PERF_TRA8 = \"enableAjaxPerfTracking\"; // Count: 2\r\nexport var _DYN_MAX_AJAX_CALLS_PER_V9 = \"maxAjaxCallsPerView\"; // Count: 2\r\nexport var _DYN_ENABLE_RESPONSE_HEAD10 = \"enableResponseHeaderTracking\"; // Count: 2\r\nexport var _DYN_EXCLUDE_REQUEST_FROM11 = \"excludeRequestFromAutoTrackingPatterns\"; // Count: 2\r\nexport var _DYN_ADD_REQUEST_CONTEXT = \"addRequestContext\"; // Count: 2\r\nexport var _DYN_DISABLE_AJAX_TRACKIN12 = \"disableAjaxTracking\"; // Count: 2\r\nexport var _DYN_DISABLE_FETCH_TRACKI13 = \"disableFetchTracking\"; // Count: 2\r\nexport var _DYN_STATUS = \"status\"; // Count: 11\r\nexport var _DYN_STATUS_TEXT = \"statusText\"; // Count: 9\r\nexport var _DYN_HEADER_MAP = \"headerMap\"; // Count: 8\r\nexport var _DYN_OPEN_DONE = \"openDone\"; // Count: 3\r\nexport var _DYN_SEND_DONE = \"sendDone\"; // Count: 3\r\nexport var _DYN_REQUEST_SENT_TIME = \"requestSentTime\"; // Count: 9\r\nexport var _DYN_ABORT_DONE = \"abortDone\"; // Count: 3\r\nexport var _DYN_GET_TRACE_ID = \"getTraceId\"; // Count: 3\r\nexport var _DYN_GET_TRACE_FLAGS = \"getTraceFlags\"; // Count: 3\r\nexport var _DYN_METHOD = \"method\"; // Count: 8\r\nexport var _DYN_ERROR_STATUS_TEXT = \"errorStatusText\"; // Count: 3\r\nexport var _DYN_STATE_CHANGE_ATTACHE14 = \"stateChangeAttached\"; // Count: 2\r\nexport var _DYN_RESPONSE_TEXT = \"responseText\"; // Count: 6\r\nexport var _DYN_RESPONSE_FINISHED_TI15 = \"responseFinishedTime\"; // Count: 7\r\nexport var _DYN__CREATE_TRACK_ITEM = \"CreateTrackItem\"; // Count: 3\r\nexport var _DYN_RESPONSE = \"response\"; // Count: 4\r\nexport var _DYN_GET_ALL_RESPONSE_HEA16 = \"getAllResponseHeaders\"; // Count: 2\r\nexport var _DYN_GET_PART_APROPS = \"getPartAProps\"; // Count: 3\r\nexport var _DYN_GET_CORRELATION_CONT17 = \"getCorrelationContext\"; // Count: 2\r\nexport var _DYN_PERF_MARK = \"perfMark\"; // Count: 4\r\nexport var _DYN_AJAX_PERF_LOOKUP_DEL18 = \"ajaxPerfLookupDelay\"; // Count: 2\r\nexport var _DYN_NAME = \"name\"; // Count: 6\r\nexport var _DYN_PERF_TIMING = \"perfTiming\"; // Count: 3\r\nexport var _DYN_AJAX_DIAGNOSTICS_MES19 = \"ajaxDiagnosticsMessage\"; // Count: 3\r\nexport var _DYN_CORRELATION_CONTEXT = \"correlationContext\"; // Count: 3\r\nexport var _DYN_AJAX_TOTAL_DURATION = \"ajaxTotalDuration\"; // Count: 3\r\nexport var _DYN_EVENT_TRACE_CTX = \"eventTraceCtx\"; // Count: 3\r\n","/*\n * Application Insights JavaScript SDK - Dependencies Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { __assignFn as __assign, __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { CorrelationIdHelper, DisabledPropertyName, PropertiesPluginIdentifier, RemoteDependencyData, RequestHeaders, createDistributedTraceContextFromTrace, createTelemetryItem, createTraceParent, dateTimeUtilsNow, formatTraceParent, isInternalApplicationInsightsEndpoint } from \"@microsoft/applicationinsights-common\";\r\nimport { BaseTelemetryPlugin, InstrumentFunc, InstrumentProto, _throwInternal, arrForEach, createProcessTelemetryContext, createUniqueNamespace, deepFreeze, dumpObj, eventOn, generateW3CId, getExceptionName, getGlobal, getIEVersion, getLocation, getPerformance, isFunction, isNullOrUndefined, isString, isXhrSupported, mergeEvtNamespace, objForEachKey, strPrototype, strTrim } from \"@microsoft/applicationinsights-core-js\";\r\nimport { STR_PROPERTIES } from \"./InternalConstants\";\r\nimport { _DYN_ABORTED, _DYN_ABORT_DONE, _DYN_ADD_REQUEST_CONTEXT, _DYN_AJAX_PERF_LOOKUP_DEL18, _DYN_APP_ID, _DYN_CAN_INCLUDE_CORRELAT3, _DYN_CONTEXT, _DYN_CORE, _DYN_DISABLE_AJAX_TRACKIN12, _DYN_DISABLE_FETCH_TRACKI13, _DYN_DISTRIBUTED_TRACING_5, _DYN_ENABLE_AJAX_ERROR_ST7, _DYN_ENABLE_AJAX_PERF_TRA8, _DYN_ENABLE_REQUEST_HEADE6, _DYN_ENABLE_RESPONSE_HEAD10, _DYN_ERROR_STATUS_TEXT, _DYN_EXCLUDE_REQUEST_FROM11, _DYN_GET_ABSOLUTE_URL, _DYN_GET_ALL_RESPONSE_HEA16, _DYN_GET_CORRELATION_CONT17, _DYN_GET_PART_APROPS, _DYN_GET_TRACE_FLAGS, _DYN_GET_TRACE_ID, _DYN_HEADERS, _DYN_HEADER_MAP, _DYN_INCLUDE_CORRELATION_2, _DYN_INST, _DYN_LENGTH, _DYN_MAX_AJAX_CALLS_PER_V9, _DYN_METHOD, _DYN_NAME, _DYN_OPEN_DONE, _DYN_PERF_MARK, _DYN_PERF_TIMING, _DYN_REQUEST_HEADERS, _DYN_REQUEST_SENT_TIME, _DYN_REQUEST_URL, _DYN_RESPONSE, _DYN_RESPONSE_FINISHED_TI15, _DYN_RESPONSE_TEXT, _DYN_SEND_DONE, _DYN_SET_REQUEST_HEADER, _DYN_SPAN_ID, _DYN_SPAN_ID1, _DYN_START_TIME, _DYN_STATE_CHANGE_ATTACHE14, _DYN_STATUS, _DYN_STATUS_TEXT, _DYN_TO_LOWER_CASE, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN_TRACE_ID0, _DYN_TRACK_DEPENDENCY_DAT4, _DYN__CREATE_TRACK_ITEM } from \"./__DynamicConstants\";\r\nimport { ajaxRecord } from \"./ajaxRecord\";\r\nvar AJAX_MONITOR_PREFIX = \"ai.ajxmn.\";\r\nvar strDiagLog = \"diagLog\";\r\nvar strAjaxData = \"ajaxData\";\r\nvar STR_FETCH = \"fetch\";\r\nvar ERROR_HEADER = \"Failed to monitor XMLHttpRequest\";\r\nvar ERROR_PREFIX = \", monitoring data for this ajax call \";\r\nvar ERROR_POSTFIX = ERROR_PREFIX + \"may be incorrect.\";\r\nvar ERROR_NOT_SENT = ERROR_PREFIX + \"won't be sent.\";\r\nvar CORRELATION_HEADER_ERROR = \"Failed to get Request-Context correlation header as it may be not included in the response or not accessible.\";\r\nvar CUSTOM_REQUEST_CONTEXT_ERROR = \"Failed to add custom defined request context as configured call back may missing a null check.\";\r\nvar FAILED_TO_CALCULATE_DURATION_ERROR = \"Failed to calculate the duration of the \";\r\n// Using a global value so that to handle same iKey with multiple app insights instances (mostly for testing)\r\nvar _markCount = 0;\r\n/** @Ignore */\r\nfunction _supportsFetch() {\r\n var _global = getGlobal();\r\n if (!_global ||\r\n isNullOrUndefined(_global.Request) ||\r\n isNullOrUndefined(_global.Request[strPrototype]) ||\r\n isNullOrUndefined(_global[STR_FETCH])) {\r\n return null;\r\n }\r\n return _global[STR_FETCH];\r\n}\r\nvar _isWebWorker = null;\r\nfunction isWebWorker() {\r\n if (_isWebWorker == null) {\r\n try {\r\n _isWebWorker = !!(self && self instanceof WorkerGlobalScope);\r\n }\r\n catch (e) {\r\n _isWebWorker = false;\r\n }\r\n }\r\n return _isWebWorker;\r\n}\r\n/**\r\n * Determines whether ajax monitoring can be enabled on this document\r\n * @returns True if Ajax monitoring is supported on this page, otherwise false\r\n * @ignore\r\n */\r\nfunction _supportsAjaxMonitoring(ajaxMonitorInstance) {\r\n var result = false;\r\n if (isXhrSupported()) {\r\n var proto = XMLHttpRequest[strPrototype];\r\n result = !isNullOrUndefined(proto) &&\r\n !isNullOrUndefined(proto.open) && // eslint-disable-line security/detect-non-literal-fs-filename -- false positive\r\n !isNullOrUndefined(proto.send) &&\r\n !isNullOrUndefined(proto.abort);\r\n }\r\n var ieVer = getIEVersion();\r\n if (ieVer && ieVer < 9) {\r\n result = false;\r\n }\r\n if (result) {\r\n // Disable if the XmlHttpRequest can't be extended or hooked\r\n try {\r\n var xhr = new XMLHttpRequest();\r\n xhr[strAjaxData] = {};\r\n // Check that we can update the prototype\r\n var theOpen = XMLHttpRequest[strPrototype].open;\r\n XMLHttpRequest[strPrototype].open = theOpen;\r\n }\r\n catch (e) {\r\n // We can't decorate the xhr object so disable monitoring\r\n result = false;\r\n _throwInternalCritical(ajaxMonitorInstance, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, \"Failed to enable XMLHttpRequest monitoring, extension is not supported\", {\r\n exception: dumpObj(e)\r\n });\r\n }\r\n }\r\n return result;\r\n}\r\n/** @Ignore */\r\nfunction _getFailedAjaxDiagnosticsMessage(xhr) {\r\n var result = \"\";\r\n try {\r\n if (xhr && xhr[strAjaxData] && xhr[strAjaxData][_DYN_REQUEST_URL /* @min:%2erequestUrl */]) {\r\n result += \"(url: '\" + xhr[strAjaxData][_DYN_REQUEST_URL /* @min:%2erequestUrl */] + \"')\";\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _throwInternalCritical(ajaxMonitorInstance, msgId, message, properties, isUserAct) {\r\n _throwInternal(ajaxMonitorInstance[strDiagLog](), 1 /* eLoggingSeverity.CRITICAL */, msgId, message, properties, isUserAct);\r\n}\r\n/** @ignore */\r\nfunction _throwInternalWarning(ajaxMonitorInstance, msgId, message, properties, isUserAct) {\r\n _throwInternal(ajaxMonitorInstance[strDiagLog](), 2 /* eLoggingSeverity.WARNING */, msgId, message, properties, isUserAct);\r\n}\r\n/** @Ignore */\r\nfunction _createErrorCallbackFunc(ajaxMonitorInstance, internalMessage, message) {\r\n // tslint:disable-next-line\r\n return function (args) {\r\n _throwInternalCritical(ajaxMonitorInstance, internalMessage, message, {\r\n ajaxDiagnosticsMessage: _getFailedAjaxDiagnosticsMessage(args[_DYN_INST /* @min:%2einst */]),\r\n exception: dumpObj(args.err)\r\n });\r\n };\r\n}\r\nfunction _indexOf(value, match) {\r\n if (value && match) {\r\n return value.indexOf(match);\r\n }\r\n return -1;\r\n}\r\nfunction _addHandler(container, id, theFunc) {\r\n var theHandler = {\r\n id: id,\r\n fn: theFunc\r\n };\r\n container.push(theHandler);\r\n return {\r\n remove: function () {\r\n arrForEach(container, function (initializer, idx) {\r\n if (initializer.id === theHandler.id) {\r\n container.splice(idx, 1);\r\n return -1;\r\n }\r\n });\r\n }\r\n };\r\n}\r\nfunction _processDependencyContainer(core, container, details, message) {\r\n var result = true;\r\n arrForEach(container, function (theFunc, idx) {\r\n try {\r\n if (theFunc.fn.call(null, details) === false) {\r\n result = false;\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(core && core.logger, 1 /* eLoggingSeverity.CRITICAL */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"Dependency \" + message + \" [#\" + idx + \"] failed: \" + getExceptionName(e), { exception: dumpObj(e) }, true);\r\n }\r\n });\r\n return result;\r\n}\r\nfunction _processDependencyListeners(listeners, core, ajaxData, xhr, input, init) {\r\n var initializersCount = listeners[_DYN_LENGTH /* @min:%2elength */];\r\n if (initializersCount > 0) {\r\n var details = {\r\n core: core,\r\n xhr: xhr,\r\n input: input,\r\n init: init,\r\n traceId: ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */],\r\n spanId: ajaxData[_DYN_SPAN_ID /* @min:%2espanID */],\r\n traceFlags: ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */],\r\n context: ajaxData[_DYN_CONTEXT /* @min:%2econtext */] || {},\r\n aborted: !!ajaxData[_DYN_ABORTED /* @min:%2eaborted */]\r\n };\r\n _processDependencyContainer(core, listeners, details, \"listener\");\r\n ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] = details[_DYN_TRACE_ID0 /* @min:%2etraceId */];\r\n ajaxData[_DYN_SPAN_ID /* @min:%2espanID */] = details[_DYN_SPAN_ID1 /* @min:%2espanId */];\r\n ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = details[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\r\n ajaxData[_DYN_CONTEXT /* @min:%2econtext */] = details[_DYN_CONTEXT /* @min:%2econtext */];\r\n }\r\n}\r\nvar BLOB_CORE = \"*.blob.core.\";\r\nexport var DfltAjaxCorrelationHeaderExDomains = deepFreeze([\r\n BLOB_CORE + \"windows.net\",\r\n BLOB_CORE + \"chinacloudapi.cn\",\r\n BLOB_CORE + \"cloudapi.de\",\r\n BLOB_CORE + \"usgovcloudapi.net\"\r\n]);\r\nvar _internalExcludeEndpoints = [\r\n /https:\\/\\/[^\\/]*(\\.pipe\\.aria|aria\\.pipe|events\\.data|collector\\.azure)\\.[^\\/]+\\/(OneCollector\\/1|Collector\\/3)\\.0/i\r\n];\r\nfunction _getDefaultConfig() {\r\n var config = {\r\n maxAjaxCallsPerView: 500,\r\n disableAjaxTracking: false,\r\n disableFetchTracking: false,\r\n excludeRequestFromAutoTrackingPatterns: undefined,\r\n disableCorrelationHeaders: false,\r\n distributedTracingMode: 1 /* eDistributedTracingModes.AI_AND_W3C */,\r\n correlationHeaderExcludedDomains: DfltAjaxCorrelationHeaderExDomains,\r\n correlationHeaderDomains: undefined,\r\n correlationHeaderExcludePatterns: undefined,\r\n appId: undefined,\r\n enableCorsCorrelation: false,\r\n enableRequestHeaderTracking: false,\r\n enableResponseHeaderTracking: false,\r\n enableAjaxErrorStatusText: false,\r\n enableAjaxPerfTracking: false,\r\n maxAjaxPerfLookupAttempts: 3,\r\n ajaxPerfLookupDelay: 25,\r\n ignoreHeaders: [\r\n \"Authorization\",\r\n \"X-API-Key\",\r\n \"WWW-Authenticate\"\r\n ],\r\n addRequestContext: undefined,\r\n addIntEndpoints: true\r\n };\r\n return config;\r\n}\r\nfunction _getEmptyConfig() {\r\n var emptyConfig = _getDefaultConfig();\r\n objForEachKey(emptyConfig, function (value) {\r\n emptyConfig[value] = undefined;\r\n });\r\n return emptyConfig;\r\n}\r\nvar AjaxMonitor = /** @class */ (function (_super) {\r\n __extends(AjaxMonitor, _super);\r\n function AjaxMonitor() {\r\n var _this = _super.call(this) || this;\r\n _this.identifier = AjaxMonitor.identifier;\r\n _this.priority = 120;\r\n var _fetchInitialized; // fetch monitoring initialized\r\n var _xhrInitialized; // XHR monitoring initialized\r\n var _currentWindowHost;\r\n var _config;\r\n var _enableRequestHeaderTracking;\r\n var _enableAjaxErrorStatusText;\r\n var _trackAjaxAttempts;\r\n var _context;\r\n var _isUsingW3CHeaders;\r\n var _isUsingAIHeaders;\r\n var _markPrefix;\r\n var _enableAjaxPerfTracking;\r\n var _maxAjaxCallsPerView;\r\n var _enableResponseHeaderTracking;\r\n var _disabledUrls;\r\n var _disableAjaxTracking;\r\n var _disableFetchTracking;\r\n var _excludeRequestFromAutoTrackingPatterns;\r\n var _addRequestContext;\r\n var _evtNamespace;\r\n var _dependencyHandlerId;\r\n var _dependencyListeners;\r\n var _dependencyInitializers;\r\n dynamicProto(AjaxMonitor, _this, function (_self, _base) {\r\n var _addHook = _base._addHook;\r\n _initDefaults();\r\n _self.initialize = function (config, core, extensions, pluginChain) {\r\n if (!_self.isInitialized()) {\r\n _base.initialize(config, core, extensions, pluginChain);\r\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"ajax\"), core && core.evtNamespace && core.evtNamespace());\r\n _populateDefaults(config);\r\n _instrumentXhr();\r\n _instrumentFetch();\r\n _populateContext();\r\n }\r\n };\r\n _self._doTeardown = function () {\r\n _initDefaults();\r\n };\r\n _self.trackDependencyData = function (dependency, properties) {\r\n _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], null, dependency, properties);\r\n };\r\n _self[_DYN_INCLUDE_CORRELATION_2 /* @min:%2eincludeCorrelationHeaders */] = function (ajaxData, input, init, xhr) {\r\n // Test Hook to allow the overriding of the location host\r\n var currentWindowHost = _self[\"_currentWindowHost\"] || _currentWindowHost;\r\n _processDependencyListeners(_dependencyListeners, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, xhr, input, init);\r\n if (input) { // Fetch\r\n if (CorrelationIdHelper[_DYN_CAN_INCLUDE_CORRELAT3 /* @min:%2ecanIncludeCorrelationHeader */](_config, ajaxData[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */](), currentWindowHost)) {\r\n if (!init) {\r\n init = {};\r\n }\r\n // init headers override original request headers\r\n // so, if they exist use only them, otherwise use request's because they should have been applied in the first place\r\n // not using original request headers will result in them being lost\r\n var headers = new Headers(init[_DYN_HEADERS /* @min:%2eheaders */] || (input instanceof Request ? (input[_DYN_HEADERS /* @min:%2eheaders */] || {}) : {}));\r\n if (_isUsingAIHeaders) {\r\n var id = \"|\" + ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] + \".\" + ajaxData[_DYN_SPAN_ID /* @min:%2espanID */];\r\n headers.set(RequestHeaders[3 /* eRequestHeaders.requestIdHeader */], id);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[3 /* eRequestHeaders.requestIdHeader */]] = id;\r\n }\r\n }\r\n var appId = _config[_DYN_APP_ID /* @min:%2eappId */] || (_context && _context[_DYN_APP_ID /* @min:%2eappId */]());\r\n if (appId) {\r\n headers.set(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */], RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]] = RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId;\r\n }\r\n }\r\n if (_isUsingW3CHeaders) {\r\n var traceFlags = ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\r\n if (isNullOrUndefined(traceFlags)) {\r\n traceFlags = 0x01;\r\n }\r\n var traceParent = formatTraceParent(createTraceParent(ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */], ajaxData[_DYN_SPAN_ID /* @min:%2espanID */], traceFlags));\r\n headers.set(RequestHeaders[4 /* eRequestHeaders.traceParentHeader */], traceParent);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[4 /* eRequestHeaders.traceParentHeader */]] = traceParent;\r\n }\r\n }\r\n init[_DYN_HEADERS /* @min:%2eheaders */] = headers;\r\n }\r\n return init;\r\n }\r\n else if (xhr) { // XHR\r\n if (CorrelationIdHelper[_DYN_CAN_INCLUDE_CORRELAT3 /* @min:%2ecanIncludeCorrelationHeader */](_config, ajaxData[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */](), currentWindowHost)) {\r\n if (_isUsingAIHeaders) {\r\n var id = \"|\" + ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] + \".\" + ajaxData[_DYN_SPAN_ID /* @min:%2espanID */];\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[3 /* eRequestHeaders.requestIdHeader */], id);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[3 /* eRequestHeaders.requestIdHeader */]] = id;\r\n }\r\n }\r\n var appId = _config[_DYN_APP_ID /* @min:%2eappId */] || (_context && _context[_DYN_APP_ID /* @min:%2eappId */]());\r\n if (appId) {\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[0 /* eRequestHeaders.requestContextHeader */], RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]] = RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId;\r\n }\r\n }\r\n if (_isUsingW3CHeaders) {\r\n var traceFlags = ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\r\n if (isNullOrUndefined(traceFlags)) {\r\n traceFlags = 0x01;\r\n }\r\n var traceParent = formatTraceParent(createTraceParent(ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */], ajaxData[_DYN_SPAN_ID /* @min:%2espanID */], traceFlags));\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[4 /* eRequestHeaders.traceParentHeader */], traceParent);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[4 /* eRequestHeaders.traceParentHeader */]] = traceParent;\r\n }\r\n }\r\n }\r\n return xhr;\r\n }\r\n return undefined;\r\n };\r\n _self[_DYN_TRACK_DEPENDENCY_DAT4 /* @min:%2etrackDependencyDataInternal */] = function (dependency, properties, systemProperties) {\r\n if (_maxAjaxCallsPerView === -1 || _trackAjaxAttempts < _maxAjaxCallsPerView) {\r\n // Hack since expected format in w3c mode is |abc.def.\r\n // Non-w3c format is |abc.def\r\n // @todo Remove if better solution is available, e.g. handle in portal\r\n if ((_config[_DYN_DISTRIBUTED_TRACING_5 /* @min:%2edistributedTracingMode */] === 2 /* eDistributedTracingModes.W3C */\r\n || _config[_DYN_DISTRIBUTED_TRACING_5 /* @min:%2edistributedTracingMode */] === 1 /* eDistributedTracingModes.AI_AND_W3C */)\r\n && typeof dependency.id === \"string\" && dependency.id[dependency.id[_DYN_LENGTH /* @min:%2elength */] - 1] !== \".\") {\r\n dependency.id += \".\";\r\n }\r\n if (isNullOrUndefined(dependency[_DYN_START_TIME /* @min:%2estartTime */])) {\r\n dependency[_DYN_START_TIME /* @min:%2estartTime */] = new Date();\r\n }\r\n var item = createTelemetryItem(dependency, RemoteDependencyData.dataType, RemoteDependencyData.envelopeType, _self[strDiagLog](), properties, systemProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */].track(item);\r\n }\r\n else if (_trackAjaxAttempts === _maxAjaxCallsPerView) {\r\n _throwInternalCritical(_self, 55 /* _eInternalMessageId.MaxAjaxPerPVExceeded */, \"Maximum ajax per page view limit reached, ajax monitoring is paused until the next trackPageView(). In order to increase the limit set the maxAjaxCallsPerView configuration parameter.\", true);\r\n }\r\n ++_trackAjaxAttempts;\r\n };\r\n _self.addDependencyListener = function (dependencyListener) {\r\n return _addHandler(_dependencyListeners, _dependencyHandlerId++, dependencyListener);\r\n };\r\n _self.addDependencyInitializer = function (dependencyInitializer) {\r\n return _addHandler(_dependencyInitializers, _dependencyHandlerId++, dependencyInitializer);\r\n };\r\n function _initDefaults() {\r\n var location = getLocation();\r\n _fetchInitialized = false; // fetch monitoring initialized\r\n _xhrInitialized = false; // XHR monitoring initialized\r\n _currentWindowHost = location && location.host && location.host[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n _config = AjaxMonitor.getEmptyConfig();\r\n _enableRequestHeaderTracking = false;\r\n _enableAjaxErrorStatusText = false;\r\n _trackAjaxAttempts = 0;\r\n _context = null;\r\n _isUsingW3CHeaders = false;\r\n _isUsingAIHeaders = false;\r\n _markPrefix = null;\r\n _enableAjaxPerfTracking = false;\r\n _maxAjaxCallsPerView = 0;\r\n _enableResponseHeaderTracking = false;\r\n _disabledUrls = {};\r\n _disableAjaxTracking = false;\r\n _disableFetchTracking = false;\r\n _excludeRequestFromAutoTrackingPatterns = null;\r\n _addRequestContext = null;\r\n _evtNamespace = null;\r\n _dependencyHandlerId = 0;\r\n _dependencyListeners = [];\r\n _dependencyInitializers = [];\r\n }\r\n function _populateDefaults(config) {\r\n var ctx = createProcessTelemetryContext(null, config, _self[_DYN_CORE /* @min:%2ecore */]);\r\n // Reset to the empty config\r\n _config = _getEmptyConfig();\r\n var defaultConfig = _getDefaultConfig();\r\n objForEachKey(defaultConfig, function (field, value) {\r\n _config[field] = ctx.getConfig(AjaxMonitor.identifier, field, value);\r\n });\r\n var distributedTracingMode = _config[_DYN_DISTRIBUTED_TRACING_5 /* @min:%2edistributedTracingMode */];\r\n _enableRequestHeaderTracking = _config[_DYN_ENABLE_REQUEST_HEADE6 /* @min:%2eenableRequestHeaderTracking */];\r\n _enableAjaxErrorStatusText = _config[_DYN_ENABLE_AJAX_ERROR_ST7 /* @min:%2eenableAjaxErrorStatusText */];\r\n _enableAjaxPerfTracking = _config[_DYN_ENABLE_AJAX_PERF_TRA8 /* @min:%2eenableAjaxPerfTracking */];\r\n _maxAjaxCallsPerView = _config[_DYN_MAX_AJAX_CALLS_PER_V9 /* @min:%2emaxAjaxCallsPerView */];\r\n _enableResponseHeaderTracking = _config[_DYN_ENABLE_RESPONSE_HEAD10 /* @min:%2eenableResponseHeaderTracking */];\r\n _excludeRequestFromAutoTrackingPatterns = [].concat(_config[_DYN_EXCLUDE_REQUEST_FROM11 /* @min:%2eexcludeRequestFromAutoTrackingPatterns */] || [], _config.addIntEndpoints !== false ? _internalExcludeEndpoints : []);\r\n _addRequestContext = _config[_DYN_ADD_REQUEST_CONTEXT /* @min:%2eaddRequestContext */];\r\n _isUsingAIHeaders = distributedTracingMode === 0 /* eDistributedTracingModes.AI */ || distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */;\r\n _isUsingW3CHeaders = distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */ || distributedTracingMode === 2 /* eDistributedTracingModes.W3C */;\r\n if (_enableAjaxPerfTracking) {\r\n var iKey = config.instrumentationKey || \"unkwn\";\r\n if (iKey[_DYN_LENGTH /* @min:%2elength */] > 5) {\r\n _markPrefix = AJAX_MONITOR_PREFIX + iKey.substring(iKey[_DYN_LENGTH /* @min:%2elength */] - 5) + \".\";\r\n }\r\n else {\r\n _markPrefix = AJAX_MONITOR_PREFIX + iKey + \".\";\r\n }\r\n }\r\n _disableAjaxTracking = !!_config[_DYN_DISABLE_AJAX_TRACKIN12 /* @min:%2edisableAjaxTracking */];\r\n _disableFetchTracking = !!_config[_DYN_DISABLE_FETCH_TRACKI13 /* @min:%2edisableFetchTracking */];\r\n }\r\n function _populateContext() {\r\n var propExt = _self[_DYN_CORE /* @min:%2ecore */].getPlugin(PropertiesPluginIdentifier);\r\n if (propExt) {\r\n _context = propExt.plugin[_DYN_CONTEXT /* @min:%2econtext */]; // we could move IPropertiesPlugin to common as well\r\n }\r\n }\r\n // discard the header if it's defined as ignoreHeaders in ICorrelationConfig\r\n function _canIncludeHeaders(header) {\r\n var rlt = true;\r\n if (header || _config.ignoreHeaders) {\r\n arrForEach(_config.ignoreHeaders, (function (key) {\r\n if (key[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === header[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]()) {\r\n rlt = false;\r\n return -1;\r\n }\r\n }));\r\n }\r\n return rlt;\r\n }\r\n // Fetch Stuff\r\n function _instrumentFetch() {\r\n var fetch = _supportsFetch();\r\n if (!fetch) {\r\n return;\r\n }\r\n var global = getGlobal();\r\n var isPolyfill = fetch.polyfill;\r\n if (!_disableFetchTracking && !_fetchInitialized) {\r\n _addHook(InstrumentFunc(global, STR_FETCH, {\r\n ns: _evtNamespace,\r\n // Add request hook\r\n req: function (callDetails, input, init) {\r\n var fetchData;\r\n if (!_disableFetchTracking && _fetchInitialized &&\r\n !_isDisabledRequest(null, input, init) &&\r\n // If we have a polyfil and XHR instrumented then let XHR report otherwise we get duplicates\r\n !(isPolyfill && _xhrInitialized)) {\r\n var ctx = callDetails.ctx();\r\n fetchData = _createFetchRecord(input, init);\r\n var newInit = _self[_DYN_INCLUDE_CORRELATION_2 /* @min:%2eincludeCorrelationHeaders */](fetchData, input, init);\r\n if (newInit !== init) {\r\n callDetails.set(1, newInit);\r\n }\r\n ctx.data = fetchData;\r\n }\r\n },\r\n rsp: function (callDetails, input) {\r\n if (!_disableFetchTracking) {\r\n var fetchData_1 = callDetails.ctx().data;\r\n if (fetchData_1) {\r\n // Replace the result with the new promise from this code\r\n callDetails.rslt = callDetails.rslt.then(function (response) {\r\n _reportFetchMetrics(callDetails, (response || {})[_DYN_STATUS /* @min:%2estatus */], input, response, fetchData_1, function () {\r\n var ajaxResponse = {\r\n statusText: (response || {})[_DYN_STATUS_TEXT /* @min:%2estatusText */],\r\n headerMap: null,\r\n correlationContext: _getFetchCorrelationContext(response)\r\n };\r\n if (_enableResponseHeaderTracking && response) {\r\n var responseHeaderMap_1 = {};\r\n response.headers.forEach(function (value, name) {\r\n if (_canIncludeHeaders(name)) {\r\n responseHeaderMap_1[name] = value;\r\n }\r\n });\r\n ajaxResponse[_DYN_HEADER_MAP /* @min:%2eheaderMap */] = responseHeaderMap_1;\r\n }\r\n return ajaxResponse;\r\n });\r\n return response;\r\n })[\"catch\"](function (reason) {\r\n _reportFetchMetrics(callDetails, 0, input, null, fetchData_1, null, { error: reason.message || dumpObj(reason) });\r\n throw reason;\r\n });\r\n }\r\n }\r\n },\r\n // Create an error callback to report any hook errors\r\n hkErr: _createErrorCallbackFunc(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, \"Failed to monitor Window.fetch\" + ERROR_POSTFIX)\r\n }, true, isWebWorker()));\r\n _fetchInitialized = true;\r\n }\r\n else if (isPolyfill) {\r\n // If fetch is a polyfill we need to capture the request to ensure that we correctly track\r\n // disabled request URLS (i.e. internal urls) to ensure we don't end up in a constant loop\r\n // of reporting ourselves, for example React Native uses a polyfill for fetch\r\n // Note: Polyfill implementations that don't support the \"poyyfill\" tag are not supported\r\n // the workaround is to add a polyfill property to your fetch implementation before initializing\r\n // App Insights\r\n _addHook(InstrumentFunc(global, STR_FETCH, {\r\n ns: _evtNamespace,\r\n req: function (callDetails, input, init) {\r\n // Just call so that we record any disabled URL\r\n _isDisabledRequest(null, input, init);\r\n }\r\n }));\r\n }\r\n if (isPolyfill) {\r\n // retag the instrumented fetch with the same polyfill settings this is mostly for testing\r\n // But also supports multiple App Insights usages\r\n global[STR_FETCH].polyfill = isPolyfill;\r\n }\r\n }\r\n function _hookProto(target, funcName, callbacks) {\r\n _addHook(InstrumentProto(target, funcName, callbacks));\r\n }\r\n function _instrumentXhr() {\r\n if (_supportsAjaxMonitoring(_self) && !_disableAjaxTracking && !_xhrInitialized) {\r\n // Instrument open\r\n _hookProto(XMLHttpRequest, \"open\", {\r\n ns: _evtNamespace,\r\n req: function (args, method, url, async) {\r\n if (!_disableAjaxTracking) {\r\n var xhr = args[_DYN_INST /* @min:%2einst */];\r\n var ajaxData = xhr[strAjaxData];\r\n if (!_isDisabledRequest(xhr, url) && _isMonitoredXhrInstance(xhr, true)) {\r\n if (!ajaxData || !ajaxData.xhrMonitoringState[_DYN_OPEN_DONE /* @min:%2eopenDone */]) {\r\n // Only create a single ajaxData (even when multiple AI instances are running)\r\n _openHandler(xhr, method, url, async);\r\n }\r\n // always attach to the on ready state change (required for handling multiple instances)\r\n _attachToOnReadyStateChange(xhr);\r\n }\r\n }\r\n },\r\n hkErr: _createErrorCallbackFunc(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, ERROR_HEADER + \".open\" + ERROR_POSTFIX)\r\n });\r\n // Instrument send\r\n _hookProto(XMLHttpRequest, \"send\", {\r\n ns: _evtNamespace,\r\n req: function (args, context) {\r\n if (!_disableAjaxTracking) {\r\n var xhr = args[_DYN_INST /* @min:%2einst */];\r\n var ajaxData = xhr[strAjaxData];\r\n if (_isMonitoredXhrInstance(xhr) && !ajaxData.xhrMonitoringState[_DYN_SEND_DONE /* @min:%2esendDone */]) {\r\n _createMarkId(\"xhr\", ajaxData);\r\n ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = dateTimeUtilsNow();\r\n _self[_DYN_INCLUDE_CORRELATION_2 /* @min:%2eincludeCorrelationHeaders */](ajaxData, undefined, undefined, xhr);\r\n ajaxData.xhrMonitoringState[_DYN_SEND_DONE /* @min:%2esendDone */] = true;\r\n }\r\n }\r\n },\r\n hkErr: _createErrorCallbackFunc(_self, 17 /* _eInternalMessageId.FailedMonitorAjaxSend */, ERROR_HEADER + ERROR_POSTFIX)\r\n });\r\n // Instrument abort\r\n _hookProto(XMLHttpRequest, \"abort\", {\r\n ns: _evtNamespace,\r\n req: function (args) {\r\n if (!_disableAjaxTracking) {\r\n var xhr = args[_DYN_INST /* @min:%2einst */];\r\n var ajaxData = xhr[strAjaxData];\r\n if (_isMonitoredXhrInstance(xhr) && !ajaxData.xhrMonitoringState[_DYN_ABORT_DONE /* @min:%2eabortDone */]) {\r\n ajaxData[_DYN_ABORTED /* @min:%2eaborted */] = 1;\r\n ajaxData.xhrMonitoringState[_DYN_ABORT_DONE /* @min:%2eabortDone */] = true;\r\n }\r\n }\r\n },\r\n hkErr: _createErrorCallbackFunc(_self, 13 /* _eInternalMessageId.FailedMonitorAjaxAbort */, ERROR_HEADER + \".abort\" + ERROR_POSTFIX)\r\n });\r\n // Instrument setRequestHeader\r\n _hookProto(XMLHttpRequest, \"setRequestHeader\", {\r\n ns: _evtNamespace,\r\n req: function (args, header, value) {\r\n if (!_disableAjaxTracking && _enableRequestHeaderTracking) {\r\n var xhr = args[_DYN_INST /* @min:%2einst */];\r\n if (_isMonitoredXhrInstance(xhr) && _canIncludeHeaders(header)) {\r\n xhr[strAjaxData][_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][header] = value;\r\n }\r\n }\r\n },\r\n hkErr: _createErrorCallbackFunc(_self, 71 /* _eInternalMessageId.FailedMonitorAjaxSetRequestHeader */, ERROR_HEADER + \".setRequestHeader\" + ERROR_POSTFIX)\r\n });\r\n _xhrInitialized = true;\r\n }\r\n }\r\n function _isDisabledRequest(xhr, request, init) {\r\n var isDisabled = false;\r\n var theUrl = ((!isString(request) ? (request || {}).url || \"\" : request) || \"\")[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n // check excludeRequestFromAutoTrackingPatterns before stripping off any query string\r\n arrForEach(_excludeRequestFromAutoTrackingPatterns, function (regex) {\r\n var theRegex = regex;\r\n if (isString(regex)) {\r\n theRegex = new RegExp(regex);\r\n }\r\n if (!isDisabled) {\r\n isDisabled = theRegex.test(theUrl);\r\n }\r\n });\r\n // if request url matches with exclude regex pattern, return true and no need to check for headers\r\n if (isDisabled) {\r\n return isDisabled;\r\n }\r\n var idx = _indexOf(theUrl, \"?\");\r\n var idx2 = _indexOf(theUrl, \"#\");\r\n if (idx === -1 || (idx2 !== -1 && idx2 < idx)) {\r\n idx = idx2;\r\n }\r\n if (idx !== -1) {\r\n // Strip off any Query string\r\n theUrl = theUrl.substring(0, idx);\r\n }\r\n // check that this instance is not not used by ajax call performed inside client side monitoring to send data to collector\r\n if (!isNullOrUndefined(xhr)) {\r\n // Look on the XMLHttpRequest of the URL string value\r\n isDisabled = xhr[DisabledPropertyName] === true || theUrl[DisabledPropertyName] === true;\r\n }\r\n else if (!isNullOrUndefined(request)) { // fetch\r\n // Look for DisabledPropertyName in either Request or RequestInit\r\n isDisabled = (typeof request === \"object\" ? request[DisabledPropertyName] === true : false) ||\r\n (init ? init[DisabledPropertyName] === true : false);\r\n }\r\n // Also add extra check just in case the XHR or fetch objects where not decorated with the DisableProperty due to sealing or freezing\r\n if (!isDisabled && theUrl && isInternalApplicationInsightsEndpoint(theUrl)) {\r\n isDisabled = true;\r\n }\r\n if (isDisabled) {\r\n // Add the disabled url if not present\r\n if (!_disabledUrls[theUrl]) {\r\n _disabledUrls[theUrl] = 1;\r\n }\r\n }\r\n else {\r\n // Check to see if the url is listed as disabled\r\n if (_disabledUrls[theUrl]) {\r\n isDisabled = true;\r\n }\r\n }\r\n return isDisabled;\r\n }\r\n /// Verifies that particalar instance of XMLHttpRequest needs to be monitored\r\n /// Optional parameter. True if ajaxData must be excluded from verification\r\n /// True if instance needs to be monitored, otherwise false\r\n function _isMonitoredXhrInstance(xhr, excludeAjaxDataValidation) {\r\n var ajaxValidation = true;\r\n var initialized = _xhrInitialized;\r\n if (!isNullOrUndefined(xhr)) {\r\n ajaxValidation = excludeAjaxDataValidation === true || !isNullOrUndefined(xhr[strAjaxData]);\r\n }\r\n // checking to see that all interested functions on xhr were instrumented\r\n return initialized\r\n // checking on ajaxData to see that it was not removed in user code\r\n && ajaxValidation;\r\n }\r\n function _getDistributedTraceCtx() {\r\n var distributedTraceCtx = null;\r\n if (_self[_DYN_CORE /* @min:%2ecore */] && _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx) {\r\n distributedTraceCtx = _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx(false);\r\n }\r\n // Fall back\r\n if (!distributedTraceCtx && _context && _context.telemetryTrace) {\r\n distributedTraceCtx = createDistributedTraceContextFromTrace(_context.telemetryTrace);\r\n }\r\n return distributedTraceCtx;\r\n }\r\n function _openHandler(xhr, method, url, async) {\r\n var _a;\r\n var distributedTraceCtx = _getDistributedTraceCtx();\r\n var traceID = (distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */]()) || generateW3CId();\r\n var spanID = generateW3CId().substr(0, 16);\r\n var ajaxData = new ajaxRecord(traceID, spanID, _self[strDiagLog](), (_a = _self.core) === null || _a === void 0 ? void 0 : _a.getTraceCtx());\r\n ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */]();\r\n ajaxData[_DYN_METHOD /* @min:%2emethod */] = method;\r\n ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = url;\r\n ajaxData.xhrMonitoringState[_DYN_OPEN_DONE /* @min:%2eopenDone */] = true;\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = {};\r\n ajaxData.async = async;\r\n ajaxData[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */] = _enableAjaxErrorStatusText;\r\n xhr[strAjaxData] = ajaxData;\r\n }\r\n function _attachToOnReadyStateChange(xhr) {\r\n xhr[strAjaxData].xhrMonitoringState[_DYN_STATE_CHANGE_ATTACHE14 /* @min:%2estateChangeAttached */] = eventOn(xhr, \"readystatechange\", function () {\r\n try {\r\n if (xhr && xhr.readyState === 4 && _isMonitoredXhrInstance(xhr)) {\r\n _onAjaxComplete(xhr);\r\n }\r\n }\r\n catch (e) {\r\n var exceptionText = dumpObj(e);\r\n // ignore messages with c00c023f, as this a known IE9 XHR abort issue\r\n if (!exceptionText || _indexOf(exceptionText[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](), \"c00c023f\") === -1) {\r\n _throwInternalCritical(_self, 16 /* _eInternalMessageId.FailedMonitorAjaxRSC */, ERROR_HEADER + \" 'readystatechange' event handler\" + ERROR_POSTFIX, {\r\n ajaxDiagnosticsMessage: _getFailedAjaxDiagnosticsMessage(xhr),\r\n exception: exceptionText\r\n });\r\n }\r\n }\r\n }, _evtNamespace);\r\n }\r\n function _getResponseText(xhr) {\r\n try {\r\n var responseType = xhr.responseType;\r\n if (responseType === \"\" || responseType === \"text\") {\r\n // As per the specification responseText is only valid if the type is an empty string or \"text\"\r\n return xhr[_DYN_RESPONSE_TEXT /* @min:%2eresponseText */];\r\n }\r\n }\r\n catch (e) {\r\n // This shouldn't happen because of the above check -- but just in case, so just ignore\r\n }\r\n return null;\r\n }\r\n function _onAjaxComplete(xhr) {\r\n var ajaxData = xhr[strAjaxData];\r\n ajaxData[_DYN_RESPONSE_FINISHED_TI15 /* @min:%2eresponseFinishedTime */] = dateTimeUtilsNow();\r\n ajaxData[_DYN_STATUS /* @min:%2estatus */] = xhr[_DYN_STATUS /* @min:%2estatus */];\r\n function _reportXhrError(e, failedProps) {\r\n var errorProps = failedProps || {};\r\n errorProps[\"ajaxDiagnosticsMessage\"] = _getFailedAjaxDiagnosticsMessage(xhr);\r\n if (e) {\r\n errorProps[\"exception\"] = dumpObj(e);\r\n }\r\n _throwInternalWarning(_self, 14 /* _eInternalMessageId.FailedMonitorAjaxDur */, FAILED_TO_CALCULATE_DURATION_ERROR + \"ajax call\" + ERROR_NOT_SENT, errorProps);\r\n }\r\n _findPerfResourceEntry(\"xmlhttprequest\", ajaxData, function () {\r\n try {\r\n var dependency = ajaxData[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */](\"Ajax\", _enableRequestHeaderTracking, function () {\r\n var ajaxResponse = {\r\n statusText: xhr[_DYN_STATUS_TEXT /* @min:%2estatusText */],\r\n headerMap: null,\r\n correlationContext: _getAjaxCorrelationContext(xhr),\r\n type: xhr.responseType,\r\n responseText: _getResponseText(xhr),\r\n response: xhr[_DYN_RESPONSE /* @min:%2eresponse */]\r\n };\r\n if (_enableResponseHeaderTracking) {\r\n var headers = xhr[_DYN_GET_ALL_RESPONSE_HEA16 /* @min:%2egetAllResponseHeaders */]();\r\n if (headers) {\r\n // xhr.getAllResponseHeaders() method returns all the response headers, separated by CRLF, as a string or null\r\n // the regex converts the header string into an array of individual headers\r\n var arr = strTrim(headers).split(/[\\r\\n]+/);\r\n var responseHeaderMap_2 = {};\r\n arrForEach(arr, function (line) {\r\n var parts = line.split(\": \");\r\n var header = parts.shift();\r\n var value = parts.join(\": \");\r\n if (_canIncludeHeaders(header)) {\r\n responseHeaderMap_2[header] = value;\r\n }\r\n });\r\n ajaxResponse[_DYN_HEADER_MAP /* @min:%2eheaderMap */] = responseHeaderMap_2;\r\n }\r\n }\r\n return ajaxResponse;\r\n });\r\n var properties = void 0;\r\n try {\r\n if (!!_addRequestContext) {\r\n properties = _addRequestContext({ status: xhr[_DYN_STATUS /* @min:%2estatus */], xhr: xhr });\r\n }\r\n }\r\n catch (e) {\r\n _throwInternalWarning(_self, 104 /* _eInternalMessageId.FailedAddingCustomDefinedRequestContext */, CUSTOM_REQUEST_CONTEXT_ERROR);\r\n }\r\n if (dependency) {\r\n if (properties !== undefined) {\r\n dependency[STR_PROPERTIES /* @min:%2eproperties */] = __assign(__assign({}, dependency.properties), properties);\r\n }\r\n var sysProperties = ajaxData[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */]();\r\n _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, dependency, null, sysProperties);\r\n }\r\n else {\r\n _reportXhrError(null, {\r\n requestSentTime: ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */],\r\n responseFinishedTime: ajaxData[_DYN_RESPONSE_FINISHED_TI15 /* @min:%2eresponseFinishedTime */]\r\n });\r\n }\r\n }\r\n finally {\r\n // cleanup telemetry data\r\n try {\r\n xhr[strAjaxData] = null;\r\n }\r\n catch (e) {\r\n // May throw in environments that prevent extension or freeze xhr\r\n }\r\n }\r\n }, function (e) {\r\n _reportXhrError(e, null);\r\n });\r\n }\r\n function _getAjaxCorrelationContext(xhr) {\r\n try {\r\n var responseHeadersString = xhr[_DYN_GET_ALL_RESPONSE_HEA16 /* @min:%2egetAllResponseHeaders */]();\r\n if (responseHeadersString !== null) {\r\n var index = _indexOf(responseHeadersString[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](), RequestHeaders[8 /* eRequestHeaders.requestContextHeaderLowerCase */]);\r\n if (index !== -1) {\r\n var responseHeader = xhr.getResponseHeader(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]);\r\n return CorrelationIdHelper[_DYN_GET_CORRELATION_CONT17 /* @min:%2egetCorrelationContext */](responseHeader);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternalWarning(_self, 18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, CORRELATION_HEADER_ERROR, {\r\n ajaxDiagnosticsMessage: _getFailedAjaxDiagnosticsMessage(xhr),\r\n exception: dumpObj(e)\r\n });\r\n }\r\n }\r\n function _createMarkId(type, ajaxData) {\r\n if (ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] && _markPrefix && _enableAjaxPerfTracking) {\r\n var performance_1 = getPerformance();\r\n if (performance_1 && isFunction(performance_1.mark)) {\r\n _markCount++;\r\n var markId = _markPrefix + type + \"#\" + _markCount;\r\n performance_1.mark(markId);\r\n var entries = performance_1.getEntriesByName(markId);\r\n if (entries && entries[_DYN_LENGTH /* @min:%2elength */] === 1) {\r\n ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */] = entries[0];\r\n }\r\n }\r\n }\r\n }\r\n function _findPerfResourceEntry(initiatorType, ajaxData, trackCallback, reportError) {\r\n var perfMark = ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */];\r\n var performance = getPerformance();\r\n var maxAttempts = _config.maxAjaxPerfLookupAttempts;\r\n var retryDelay = _config[_DYN_AJAX_PERF_LOOKUP_DEL18 /* @min:%2eajaxPerfLookupDelay */];\r\n var requestUrl = ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */];\r\n var attempt = 0;\r\n (function locateResourceTiming() {\r\n try {\r\n if (performance && perfMark) {\r\n attempt++;\r\n var perfTiming = null;\r\n var entries = performance.getEntries();\r\n for (var lp = entries[_DYN_LENGTH /* @min:%2elength */] - 1; lp >= 0; lp--) {\r\n var entry = entries[lp];\r\n if (entry) {\r\n if (entry.entryType === \"resource\") {\r\n if (entry.initiatorType === initiatorType &&\r\n (_indexOf(entry[_DYN_NAME /* @min:%2ename */], requestUrl) !== -1 || _indexOf(requestUrl, entry[_DYN_NAME /* @min:%2ename */]) !== -1)) {\r\n perfTiming = entry;\r\n }\r\n }\r\n else if (entry.entryType === \"mark\" && entry[_DYN_NAME /* @min:%2ename */] === perfMark[_DYN_NAME /* @min:%2ename */]) {\r\n // We hit the start event\r\n ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */] = perfTiming;\r\n break;\r\n }\r\n if (entry[_DYN_START_TIME /* @min:%2estartTime */] < perfMark[_DYN_START_TIME /* @min:%2estartTime */] - 1000) {\r\n // Fallback to try and reduce the time spent looking for the perf entry\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n if (!perfMark || // - we don't have a perfMark or\r\n ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */] || // - we have not found the perf entry or\r\n attempt >= maxAttempts || // - we have tried too many attempts or\r\n ajaxData.async === false) { // - this is a sync request\r\n if (perfMark && isFunction(performance.clearMarks)) {\r\n // Remove the mark so we don't fill up the performance resources too much\r\n performance.clearMarks(perfMark[_DYN_NAME /* @min:%2ename */]);\r\n }\r\n ajaxData.perfAttempts = attempt;\r\n // just continue and report the track event\r\n trackCallback();\r\n }\r\n else {\r\n // We need to wait for the browser to populate the window.performance entry\r\n // This needs to be at least 1ms as waiting <= 1 (on firefox) is not enough time for fetch or xhr,\r\n // this is a scheduling issue for the browser implementation\r\n setTimeout(locateResourceTiming, retryDelay);\r\n }\r\n }\r\n catch (e) {\r\n reportError(e);\r\n }\r\n })();\r\n }\r\n function _createFetchRecord(input, init) {\r\n var _a;\r\n var distributedTraceCtx = _getDistributedTraceCtx();\r\n var traceID = (distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */]()) || generateW3CId();\r\n var spanID = generateW3CId().substr(0, 16);\r\n var ajaxData = new ajaxRecord(traceID, spanID, _self[strDiagLog](), (_a = _self.core) === null || _a === void 0 ? void 0 : _a.getTraceCtx());\r\n ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */]();\r\n ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = dateTimeUtilsNow();\r\n ajaxData[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */] = _enableAjaxErrorStatusText;\r\n if (input instanceof Request) {\r\n ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = input ? input.url : \"\";\r\n }\r\n else {\r\n ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = input;\r\n }\r\n var method = \"GET\";\r\n if (init && init[_DYN_METHOD /* @min:%2emethod */]) {\r\n method = init[_DYN_METHOD /* @min:%2emethod */];\r\n }\r\n else if (input && input instanceof Request) {\r\n method = input[_DYN_METHOD /* @min:%2emethod */];\r\n }\r\n ajaxData[_DYN_METHOD /* @min:%2emethod */] = method;\r\n var requestHeaders = {};\r\n if (_enableRequestHeaderTracking) {\r\n var headers = new Headers((init ? init[_DYN_HEADERS /* @min:%2eheaders */] : 0) || (input instanceof Request ? (input[_DYN_HEADERS /* @min:%2eheaders */] || {}) : {}));\r\n headers.forEach(function (value, key) {\r\n if (_canIncludeHeaders(key)) {\r\n requestHeaders[key] = value;\r\n }\r\n });\r\n }\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = requestHeaders;\r\n _createMarkId(STR_FETCH, ajaxData);\r\n return ajaxData;\r\n }\r\n function _getFailedFetchDiagnosticsMessage(input) {\r\n var result = \"\";\r\n try {\r\n if (!isNullOrUndefined(input)) {\r\n if (typeof (input) === \"string\") {\r\n result += \"(url: '\".concat(input, \"')\");\r\n }\r\n else {\r\n result += \"(url: '\".concat(input.url, \"')\");\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternalCritical(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, \"Failed to grab failed fetch diagnostics message\", { exception: dumpObj(e) });\r\n }\r\n return result;\r\n }\r\n function _reportFetchMetrics(callDetails, status, input, response, ajaxData, getResponse, properties) {\r\n if (!ajaxData) {\r\n return;\r\n }\r\n function _reportFetchError(msgId, e, failedProps) {\r\n var errorProps = failedProps || {};\r\n errorProps[\"fetchDiagnosticsMessage\"] = _getFailedFetchDiagnosticsMessage(input);\r\n if (e) {\r\n errorProps[\"exception\"] = dumpObj(e);\r\n }\r\n _throwInternalWarning(_self, msgId, FAILED_TO_CALCULATE_DURATION_ERROR + \"fetch call\" + ERROR_NOT_SENT, errorProps);\r\n }\r\n ajaxData[_DYN_RESPONSE_FINISHED_TI15 /* @min:%2eresponseFinishedTime */] = dateTimeUtilsNow();\r\n ajaxData[_DYN_STATUS /* @min:%2estatus */] = status;\r\n _findPerfResourceEntry(STR_FETCH, ajaxData, function () {\r\n var dependency = ajaxData[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */](\"Fetch\", _enableRequestHeaderTracking, getResponse);\r\n var properties;\r\n try {\r\n if (!!_addRequestContext) {\r\n properties = _addRequestContext({ status: status, request: input, response: response });\r\n }\r\n }\r\n catch (e) {\r\n _throwInternalWarning(_self, 104 /* _eInternalMessageId.FailedAddingCustomDefinedRequestContext */, CUSTOM_REQUEST_CONTEXT_ERROR);\r\n }\r\n if (dependency) {\r\n if (properties !== undefined) {\r\n dependency[STR_PROPERTIES /* @min:%2eproperties */] = __assign(__assign({}, dependency.properties), properties);\r\n }\r\n var sysProperties = ajaxData[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */]();\r\n _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, dependency, null, sysProperties);\r\n }\r\n else {\r\n _reportFetchError(14 /* _eInternalMessageId.FailedMonitorAjaxDur */, null, {\r\n requestSentTime: ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */],\r\n responseFinishedTime: ajaxData[_DYN_RESPONSE_FINISHED_TI15 /* @min:%2eresponseFinishedTime */]\r\n });\r\n }\r\n }, function (e) {\r\n _reportFetchError(18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, e, null);\r\n });\r\n }\r\n function _getFetchCorrelationContext(response) {\r\n if (response && response[_DYN_HEADERS /* @min:%2eheaders */]) {\r\n try {\r\n var responseHeader = response[_DYN_HEADERS /* @min:%2eheaders */].get(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]);\r\n return CorrelationIdHelper[_DYN_GET_CORRELATION_CONT17 /* @min:%2egetCorrelationContext */](responseHeader);\r\n }\r\n catch (e) {\r\n _throwInternalWarning(_self, 18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, CORRELATION_HEADER_ERROR, {\r\n fetchDiagnosticsMessage: _getFailedFetchDiagnosticsMessage(response),\r\n exception: dumpObj(e)\r\n });\r\n }\r\n }\r\n }\r\n function _reportDependencyInternal(initializers, core, ajaxData, dependency, properties, systemProperties) {\r\n var result = true;\r\n var initializersCount = initializers[_DYN_LENGTH /* @min:%2elength */];\r\n if (initializersCount > 0) {\r\n var details = {\r\n item: dependency,\r\n properties: properties,\r\n sysProperties: systemProperties,\r\n context: ajaxData ? ajaxData[_DYN_CONTEXT /* @min:%2econtext */] : null,\r\n aborted: ajaxData ? !!ajaxData[_DYN_ABORTED /* @min:%2eaborted */] : false\r\n };\r\n result = _processDependencyContainer(core, initializers, details, \"initializer\");\r\n }\r\n if (result) {\r\n _self[_DYN_TRACK_DEPENDENCY_DAT4 /* @min:%2etrackDependencyDataInternal */](dependency, properties, systemProperties);\r\n }\r\n }\r\n });\r\n return _this;\r\n }\r\n// Removed Stub for AjaxMonitor.prototype.initialize.\r\n AjaxMonitor.prototype.processTelemetry = function (item, itemCtx) {\r\n this.processNext(item, itemCtx);\r\n };\r\n// Removed Stub for AjaxMonitor.prototype.trackDependencyData.\r\n// Removed Stub for AjaxMonitor.prototype.includeCorrelationHeaders.\r\n// Removed Stub for AjaxMonitor.prototype.addDependencyListener.\r\n /**\r\n * Add an dependency telemetry initializer callback function to allow populating additional properties or drop the request.\r\n * It is called after the dependency call has completed and any available performance details are available. A dependency\r\n * initializer is similar to the TelemetryInitializer function but it allows you to block the reporting of the dependency\r\n * request so that it doesn't count against the `maxAjaxCallsPerView`.\r\n * @param dependencyInitializer - The Dependency Telemetry Initializer function\r\n * @returns - A IDependencyInitializerHandler to enable the initializer to be removed\r\n */\r\n AjaxMonitor.prototype.addDependencyInitializer = function (dependencyInitializer) {\r\n return null;\r\n };\r\n// Removed Stub for AjaxMonitor.prototype.trackDependencyDataInternal.\r\n AjaxMonitor.identifier = \"AjaxDependencyPlugin\";\r\n AjaxMonitor.getDefaultConfig = _getDefaultConfig;\r\n AjaxMonitor.getEmptyConfig = _getEmptyConfig;\r\n return AjaxMonitor;\r\n}(BaseTelemetryPlugin));\r\nexport { AjaxMonitor };\r\n","/*\n * Application Insights JavaScript SDK - Dependencies Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { Extensions, dataSanitizeUrl, dateTimeUtilsDuration, msToTimeSpan, urlGetAbsoluteUrl, urlGetCompleteUrl } from \"@microsoft/applicationinsights-common\";\r\nimport { arrForEach, isNullOrUndefined, isNumber, isString, normalizeJsName, objForEachKey, objKeys } from \"@microsoft/applicationinsights-core-js\";\r\nimport { STR_DURATION, STR_PROPERTIES } from \"./InternalConstants\";\r\nimport { _DYN_ABORTED, _DYN_ABORT_DONE, _DYN_AJAX_TOTAL_DURATION, _DYN_CORRELATION_CONTEXT, _DYN_ERROR_STATUS_TEXT, _DYN_EVENT_TRACE_CTX, _DYN_GET_ABSOLUTE_URL, _DYN_GET_PART_APROPS, _DYN_GET_TRACE_FLAGS, _DYN_GET_TRACE_ID, _DYN_HEADER_MAP, _DYN_LENGTH, _DYN_METHOD, _DYN_NAME, _DYN_OPEN_DONE, _DYN_PERF_MARK, _DYN_PERF_TIMING, _DYN_REQUEST_HEADERS, _DYN_REQUEST_SENT_TIME, _DYN_REQUEST_URL, _DYN_RESPONSE, _DYN_RESPONSE_FINISHED_TI15, _DYN_SEND_DONE, _DYN_SPAN_ID, _DYN_SPAN_ID1, _DYN_START_TIME, _DYN_STATE_CHANGE_ATTACHE14, _DYN_STATUS, _DYN_STATUS_TEXT, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN_TRACE_ID0, _DYN__CREATE_TRACK_ITEM } from \"./__DynamicConstants\";\r\n/** @ignore */\r\nfunction _calcPerfDuration(resourceEntry, start, end) {\r\n var result = 0;\r\n var from = resourceEntry[start];\r\n var to = resourceEntry[end];\r\n if (from && to) {\r\n result = dateTimeUtilsDuration(from, to);\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _setPerfDuration(props, name, resourceEntry, start, end) {\r\n var result = 0;\r\n var value = _calcPerfDuration(resourceEntry, start, end);\r\n if (value) {\r\n result = _setPerfValue(props, name, msToTimeSpan(value));\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _setPerfValue(props, name, value) {\r\n var strPerf = \"ajaxPerf\";\r\n var result = 0;\r\n if (props && name && value) {\r\n var perfData = props[strPerf] = (props[strPerf] || {});\r\n perfData[name] = value;\r\n result = 1;\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _populatePerfData(ajaxData, dependency) {\r\n /*\r\n * https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API/Using_the_Resource_Timing_API\r\n * | -startTime\r\n * | -redirectStart\r\n * | | -redirectEnd\r\n * | | | -fetchStart\r\n * | | | | -domainLookupStart\r\n * | | | | |- domainLookupEnd\r\n * | | | | | | -connectStart\r\n * | | | | | | | -secureConnectionStart\r\n * | | | | | | | | -connectEnd\r\n * | | | | | | | | | -requestStart\r\n * | | | | | | | | | | | -responseStart\r\n * | | | | | | | | | | | | | -responseEnd\r\n * +------------+-+---+----------------+-+--+--------+-+-----------+-+------------+-+\r\n * |--redirect--| |---|--domainLookup--| |--connect--| |--request--| |--response--| |\r\n * |-------------------networkConnect----------------|\r\n * | |---------sentRequest--------|\r\n * |------------------------------------perfTotal-----------------------------------|\r\n */\r\n var resourceEntry = ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */];\r\n var props = dependency[STR_PROPERTIES /* @min:%2eproperties */] || {};\r\n var propsSet = 0;\r\n var strName = \"name\";\r\n var strStart = \"Start\";\r\n var strEnd = \"End\";\r\n var strDomainLookup = \"domainLookup\";\r\n var strConnect = \"connect\";\r\n var strRedirect = \"redirect\";\r\n var strRequest = \"request\";\r\n var strResponse = \"response\";\r\n var strStartTime = \"startTime\";\r\n var strDomainLookupStart = strDomainLookup + strStart;\r\n var strDomainLookupEnd = strDomainLookup + strEnd;\r\n var strConnectStart = strConnect + strStart;\r\n var strConnectEnd = strConnect + strEnd;\r\n var strRequestStart = strRequest + strStart;\r\n var strRequestEnd = strRequest + strEnd;\r\n var strResponseStart = strResponse + strStart;\r\n var strResponseEnd = strResponse + strEnd;\r\n var strRedirectStart = strRedirect + strStart;\r\n var strRedirectEnd = strRedirect = strEnd;\r\n var strTransferSize = \"transferSize\";\r\n var strEncodedBodySize = \"encodedBodySize\";\r\n var strDecodedBodySize = \"decodedBodySize\";\r\n var strServerTiming = \"serverTiming\";\r\n if (resourceEntry) {\r\n // redirect\r\n propsSet |= _setPerfDuration(props, strRedirect, resourceEntry, strRedirectStart, strRedirectEnd);\r\n // domainLookup\r\n propsSet |= _setPerfDuration(props, strDomainLookup, resourceEntry, strDomainLookupStart, strDomainLookupEnd);\r\n // connect\r\n propsSet |= _setPerfDuration(props, strConnect, resourceEntry, strConnectStart, strConnectEnd);\r\n // request\r\n propsSet |= _setPerfDuration(props, strRequest, resourceEntry, strRequestStart, strRequestEnd);\r\n // response\r\n propsSet |= _setPerfDuration(props, strResponse, resourceEntry, strResponseStart, strResponseEnd);\r\n // Network connection time\r\n propsSet |= _setPerfDuration(props, \"networkConnect\", resourceEntry, strStartTime, strConnectEnd);\r\n // Sent Request\r\n propsSet |= _setPerfDuration(props, \"sentRequest\", resourceEntry, strRequestStart, strResponseEnd);\r\n // PerfTotal / Duration\r\n var duration = resourceEntry[STR_DURATION /* @min:%2eduration */];\r\n if (!duration) {\r\n duration = _calcPerfDuration(resourceEntry, strStartTime, strResponseEnd) || 0;\r\n }\r\n propsSet |= _setPerfValue(props, STR_DURATION, duration);\r\n propsSet |= _setPerfValue(props, \"perfTotal\", duration);\r\n var serverTiming = resourceEntry[strServerTiming];\r\n if (serverTiming) {\r\n var server_1 = {};\r\n arrForEach(serverTiming, function (value, idx) {\r\n var name = normalizeJsName(value[strName] || \"\" + idx);\r\n var newValue = server_1[name] || {};\r\n objForEachKey(value, function (key, val) {\r\n if (key !== strName && isString(val) || isNumber(val)) {\r\n if (newValue[key]) {\r\n val = newValue[key] + \";\" + val;\r\n }\r\n if (val || !isString(val)) {\r\n // Only set the value if it has a value and it's not an empty string\r\n newValue[key] = val;\r\n }\r\n }\r\n });\r\n server_1[name] = newValue;\r\n });\r\n propsSet |= _setPerfValue(props, strServerTiming, server_1);\r\n }\r\n propsSet |= _setPerfValue(props, strTransferSize, resourceEntry[strTransferSize]);\r\n propsSet |= _setPerfValue(props, strEncodedBodySize, resourceEntry[strEncodedBodySize]);\r\n propsSet |= _setPerfValue(props, strDecodedBodySize, resourceEntry[strDecodedBodySize]);\r\n }\r\n else {\r\n if (ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */]) {\r\n propsSet |= _setPerfValue(props, \"missing\", ajaxData.perfAttempts);\r\n }\r\n }\r\n if (propsSet) {\r\n dependency[STR_PROPERTIES /* @min:%2eproperties */] = props;\r\n }\r\n}\r\nvar XHRMonitoringState = /** @class */ (function () {\r\n function XHRMonitoringState() {\r\n var self = this;\r\n self[_DYN_OPEN_DONE /* @min:%2eopenDone */] = false;\r\n self.setRequestHeaderDone = false;\r\n self[_DYN_SEND_DONE /* @min:%2esendDone */] = false;\r\n self[_DYN_ABORT_DONE /* @min:%2eabortDone */] = false;\r\n // True, if onreadyStateChangeCallback function attached to xhr, otherwise false\r\n self[_DYN_STATE_CHANGE_ATTACHE14 /* @min:%2estateChangeAttached */] = false;\r\n }\r\n return XHRMonitoringState;\r\n}());\r\nexport { XHRMonitoringState };\r\nvar ajaxRecord = /** @class */ (function () {\r\n function ajaxRecord(traceId, spanId, logger, traceCtx) {\r\n var _a;\r\n var self = this;\r\n var _logger = logger;\r\n var strResponseText = \"responseText\";\r\n // Assigning the initial/default values within the constructor to avoid typescript from creating a bunch of\r\n // this.XXXX = null\r\n self[_DYN_PERF_MARK /* @min:%2eperfMark */] = null;\r\n self.completed = false;\r\n self.requestHeadersSize = null;\r\n self[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = null;\r\n self.responseReceivingDuration = null;\r\n self.callbackDuration = null;\r\n self[_DYN_AJAX_TOTAL_DURATION /* @min:%2eajaxTotalDuration */] = null;\r\n self[_DYN_ABORTED /* @min:%2eaborted */] = 0;\r\n self.pageUrl = null;\r\n self[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = null;\r\n self.requestSize = 0;\r\n self[_DYN_METHOD /* @min:%2emethod */] = null;\r\n self[_DYN_STATUS /* @min:%2estatus */] = null;\r\n self[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = null;\r\n self.responseStartedTime = null;\r\n self[_DYN_RESPONSE_FINISHED_TI15 /* @min:%2eresponseFinishedTime */] = null;\r\n self.callbackFinishedTime = null;\r\n self.endTime = null;\r\n self.xhrMonitoringState = new XHRMonitoringState();\r\n self.clientFailure = 0;\r\n self[_DYN_TRACE_ID /* @min:%2etraceID */] = traceId;\r\n self[_DYN_SPAN_ID /* @min:%2espanID */] = spanId;\r\n self[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = traceCtx === null || traceCtx === void 0 ? void 0 : traceCtx.getTraceFlags();\r\n if (traceCtx) {\r\n self[_DYN_EVENT_TRACE_CTX /* @min:%2eeventTraceCtx */] = (_a = {},\r\n _a[_DYN_TRACE_ID0 /* @min:traceId */] = traceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */](),\r\n _a[_DYN_SPAN_ID1 /* @min:spanId */] = traceCtx.getSpanId(),\r\n _a[_DYN_TRACE_FLAGS /* @min:traceFlags */] = traceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */](),\r\n _a);\r\n }\r\n else {\r\n self[_DYN_EVENT_TRACE_CTX /* @min:%2eeventTraceCtx */] = null;\r\n }\r\n dynamicProto(ajaxRecord, self, function (self) {\r\n self.getAbsoluteUrl = function () {\r\n return self[_DYN_REQUEST_URL /* @min:%2erequestUrl */] ? urlGetAbsoluteUrl(self[_DYN_REQUEST_URL /* @min:%2erequestUrl */]) : null;\r\n };\r\n self.getPathName = function () {\r\n return self[_DYN_REQUEST_URL /* @min:%2erequestUrl */] ? dataSanitizeUrl(_logger, urlGetCompleteUrl(self[_DYN_METHOD /* @min:%2emethod */], self[_DYN_REQUEST_URL /* @min:%2erequestUrl */])) : null;\r\n };\r\n self[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */] = function (ajaxType, enableRequestHeaderTracking, getResponse) {\r\n var _a;\r\n // round to 3 decimal points\r\n self.ajaxTotalDuration = Math.round(dateTimeUtilsDuration(self.requestSentTime, self.responseFinishedTime) * 1000) / 1000;\r\n if (self[_DYN_AJAX_TOTAL_DURATION /* @min:%2eajaxTotalDuration */] < 0) {\r\n return null;\r\n }\r\n var dependency = (_a = {\r\n id: \"|\" + self[_DYN_TRACE_ID /* @min:%2etraceID */] + \".\" + self[_DYN_SPAN_ID /* @min:%2espanID */],\r\n target: self[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */]()\r\n },\r\n _a[_DYN_NAME /* @min:name */] = self.getPathName(),\r\n _a.type = ajaxType,\r\n _a[_DYN_START_TIME /* @min:startTime */] = null,\r\n _a.duration = self[_DYN_AJAX_TOTAL_DURATION /* @min:%2eajaxTotalDuration */],\r\n _a.success = (+(self[_DYN_STATUS /* @min:%2estatus */])) >= 200 && (+(self[_DYN_STATUS /* @min:%2estatus */])) < 400,\r\n _a.responseCode = (+(self[_DYN_STATUS /* @min:%2estatus */])),\r\n _a[STR_PROPERTIES] = { HttpMethod: self[_DYN_METHOD /* @min:%2emethod */] },\r\n _a);\r\n var props = dependency[STR_PROPERTIES];\r\n if (self[_DYN_ABORTED /* @min:%2eaborted */]) {\r\n props[_DYN_ABORTED /* @min:%2eaborted */] = true;\r\n }\r\n if (self[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */]) {\r\n // Set the correct dependency start time\r\n dependency[_DYN_START_TIME /* @min:%2estartTime */] = new Date();\r\n dependency[_DYN_START_TIME /* @min:%2estartTime */].setTime(self[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */]);\r\n }\r\n // Add Ajax perf details if available\r\n _populatePerfData(self, dependency);\r\n if (enableRequestHeaderTracking) {\r\n if (objKeys(self.requestHeaders)[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n props[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = self[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */];\r\n }\r\n }\r\n if (getResponse) {\r\n var response = getResponse();\r\n if (response) {\r\n // enrich dependency target with correlation context from the server\r\n var correlationContext = response[_DYN_CORRELATION_CONTEXT /* @min:%2ecorrelationContext */];\r\n if (correlationContext) {\r\n dependency.correlationContext = /* dependency.target + \" | \" + */ correlationContext;\r\n }\r\n if (response[_DYN_HEADER_MAP /* @min:%2eheaderMap */]) {\r\n if (objKeys(response.headerMap)[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n props.responseHeaders = response[_DYN_HEADER_MAP /* @min:%2eheaderMap */];\r\n }\r\n }\r\n if (self[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */]) {\r\n if (self[_DYN_STATUS /* @min:%2estatus */] >= 400) {\r\n var responseType = response.type;\r\n if (responseType === \"\" || responseType === \"text\") {\r\n props.responseText = response.responseText ? response[_DYN_STATUS_TEXT /* @min:%2estatusText */] + \" - \" + response[strResponseText] : response[_DYN_STATUS_TEXT /* @min:%2estatusText */];\r\n }\r\n if (responseType === \"json\") {\r\n props.responseText = response.response ? response[_DYN_STATUS_TEXT /* @min:%2estatusText */] + \" - \" + JSON.stringify(response[_DYN_RESPONSE /* @min:%2eresponse */]) : response[_DYN_STATUS_TEXT /* @min:%2estatusText */];\r\n }\r\n }\r\n else if (self[_DYN_STATUS /* @min:%2estatus */] === 0) {\r\n props.responseText = response[_DYN_STATUS_TEXT /* @min:%2estatusText */] || \"\";\r\n }\r\n }\r\n }\r\n }\r\n return dependency;\r\n };\r\n self[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */] = function () {\r\n var _a;\r\n var partA = null;\r\n var traceCtx = self[_DYN_EVENT_TRACE_CTX /* @min:%2eeventTraceCtx */];\r\n if (traceCtx && (traceCtx[_DYN_TRACE_ID0 /* @min:%2etraceId */] || traceCtx[_DYN_SPAN_ID1 /* @min:%2espanId */])) {\r\n partA = {};\r\n var traceExt = partA[Extensions.TraceExt] = (_a = {},\r\n _a[_DYN_TRACE_ID /* @min:traceID */] = traceCtx[_DYN_TRACE_ID0 /* @min:%2etraceId */],\r\n _a.parentID = traceCtx[_DYN_SPAN_ID1 /* @min:%2espanId */],\r\n _a);\r\n if (!isNullOrUndefined(traceCtx[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */])) {\r\n traceExt[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = traceCtx[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\r\n }\r\n }\r\n return partA;\r\n };\r\n });\r\n }\r\n// Removed Stub for ajaxRecord.prototype.getAbsoluteUrl.\r\n// Removed Stub for ajaxRecord.prototype.getPathName.\r\n// Removed Stub for ajaxRecord.prototype.CreateTrackItem.\r\n// Removed Stub for ajaxRecord.prototype.getPartAProps.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n ajaxRecord.__ieDyn=1;\n\n return ajaxRecord;\r\n}());\r\nexport { ajaxRecord };\r\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nvar Application = /** @class */ (function () {\r\n function Application() {\r\n }\r\n return Application;\r\n}());\r\nexport { Application };\r\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nvar Device = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the Device class\r\n */\r\n function Device() {\r\n // don't attempt to fingerprint browsers\r\n this.id = \"browser\";\r\n // Device type is a dimension in our data platform\r\n // Setting it to 'Browser' allows to separate client and server dependencies/exceptions\r\n this.deviceClass = \"Browser\";\r\n }\r\n return Device;\r\n}());\r\nexport { Device };\r\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { _DYN_SDK_EXTENSION } from \"../__DynamicConstants\";\r\nvar Version = '2.8.11';\r\nvar Internal = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the internal telemetry data class.\r\n */\r\n function Internal(config) {\r\n this.sdkVersion = (config[_DYN_SDK_EXTENSION /* @min:%2esdkExtension */] && config[_DYN_SDK_EXTENSION /* @min:%2esdkExtension */]() ? config[_DYN_SDK_EXTENSION /* @min:%2esdkExtension */]() + \"_\" : \"\") + \"javascript:\" + Version;\r\n }\r\n return Internal;\r\n}());\r\nexport { Internal };\r\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nvar Location = /** @class */ (function () {\r\n function Location() {\r\n }\r\n return Location;\r\n}());\r\nexport { Location };\r\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { utlCanUseLocalStorage, utlGetLocalStorage, utlSetLocalStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, dateNow, dumpObj, getExceptionName, isFunction, newId, safeGetCookieMgr, safeGetLogger } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_ACQUISITION_DATE, _DYN_AUTOMATIC_SESSION, _DYN_CONFIG, _DYN_COOKIE_DOMAIN, _DYN_GET_NEW_ID, _DYN_ID_LENGTH, _DYN_JOIN, _DYN_LENGTH, _DYN_NAME_PREFIX, _DYN_RENEWAL_DATE, _DYN_SESSION_COOKIE_POSTF6, _DYN_SESSION_EXPIRATION_M7, _DYN_SESSION_RENEWAL_MS, _DYN_UPDATE } from \"../__DynamicConstants\";\r\nvar cookieNameConst = \"ai_session\";\r\nvar Session = /** @class */ (function () {\r\n function Session() {\r\n }\r\n return Session;\r\n}());\r\nexport { Session };\r\nvar _SessionManager = /** @class */ (function () {\r\n function _SessionManager(config, core) {\r\n var self = this;\r\n var _storageNamePrefix;\r\n var _cookieUpdatedTimestamp;\r\n var _logger = safeGetLogger(core);\r\n var _cookieManager = safeGetCookieMgr(core);\r\n dynamicProto(_SessionManager, self, function (_self) {\r\n if (!config) {\r\n config = {};\r\n }\r\n if (!isFunction(config[_DYN_SESSION_EXPIRATION_M7 /* @min:%2esessionExpirationMs */])) {\r\n config[_DYN_SESSION_EXPIRATION_M7 /* @min:%2esessionExpirationMs */] = function () { return _SessionManager.acquisitionSpan; };\r\n }\r\n if (!isFunction(config[_DYN_SESSION_RENEWAL_MS /* @min:%2esessionRenewalMs */])) {\r\n config[_DYN_SESSION_RENEWAL_MS /* @min:%2esessionRenewalMs */] = function () { return _SessionManager.renewalSpan; };\r\n }\r\n _self[_DYN_CONFIG /* @min:%2econfig */] = config;\r\n // sessionCookiePostfix takes the preference if it is configured, otherwise takes namePrefix if configured.\r\n var sessionCookiePostfix = (_self.config[_DYN_SESSION_COOKIE_POSTF6 /* @min:%2esessionCookiePostfix */] && _self[_DYN_CONFIG /* @min:%2econfig */][_DYN_SESSION_COOKIE_POSTF6 /* @min:%2esessionCookiePostfix */]()) ?\r\n _self.config[_DYN_SESSION_COOKIE_POSTF6 /* @min:%2esessionCookiePostfix */]() :\r\n ((_self.config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */] && _self[_DYN_CONFIG /* @min:%2econfig */][_DYN_NAME_PREFIX /* @min:%2enamePrefix */]()) ? _self[_DYN_CONFIG /* @min:%2econfig */][_DYN_NAME_PREFIX /* @min:%2enamePrefix */]() : \"\");\r\n _storageNamePrefix = function () { return cookieNameConst + sessionCookiePostfix; };\r\n _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */] = new Session();\r\n _self[_DYN_UPDATE /* @min:%2eupdate */] = function () {\r\n // Always using Date getTime() as there is a bug in older IE instances that causes the performance timings to have the hi-bit set eg 0x800000000 causing\r\n // the number to be incorrect.\r\n var nowMs = dateNow();\r\n var isExpired = false;\r\n var session = _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */];\r\n if (!session.id) {\r\n isExpired = !_initializeAutomaticSession(session, nowMs);\r\n }\r\n var sessionExpirationMs = _self.config[_DYN_SESSION_EXPIRATION_M7 /* @min:%2esessionExpirationMs */]();\r\n if (!isExpired && sessionExpirationMs > 0) {\r\n var sessionRenewalMs = _self.config[_DYN_SESSION_RENEWAL_MS /* @min:%2esessionRenewalMs */]();\r\n var timeSinceAcqMs = nowMs - session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */];\r\n var timeSinceRenewalMs = nowMs - session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */];\r\n isExpired = timeSinceAcqMs < 0 || timeSinceRenewalMs < 0; // expired if the acquisition or last renewal are in the future\r\n isExpired = isExpired || timeSinceAcqMs > sessionExpirationMs; // expired if the time since acquisition is more than session Expiration\r\n isExpired = isExpired || timeSinceRenewalMs > sessionRenewalMs; // expired if the time since last renewal is more than renewal period\r\n }\r\n // renew if acquisitionSpan or renewalSpan has elapsed\r\n if (isExpired) {\r\n // update automaticSession so session state has correct id\r\n _renew(nowMs);\r\n }\r\n else {\r\n // do not update the cookie more often than cookieUpdateInterval\r\n if (!_cookieUpdatedTimestamp || nowMs - _cookieUpdatedTimestamp > _SessionManager.cookieUpdateInterval) {\r\n _setCookie(session, nowMs);\r\n }\r\n }\r\n };\r\n /**\r\n * Record the current state of the automatic session and store it in our cookie string format\r\n * into the browser's local storage. This is used to restore the session data when the cookie\r\n * expires.\r\n */\r\n _self.backup = function () {\r\n var session = _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */];\r\n _setStorage(session.id, session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */], session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */]);\r\n };\r\n /**\r\n * Use config.namePrefix + ai_session cookie data or local storage data (when the cookie is unavailable) to\r\n * initialize the automatic session.\r\n * @returns true if values set otherwise false\r\n */\r\n function _initializeAutomaticSession(session, now) {\r\n var isValid = false;\r\n var cookieValue = _cookieManager.get(_storageNamePrefix());\r\n if (cookieValue && isFunction(cookieValue.split)) {\r\n isValid = _initializeAutomaticSessionWithData(session, cookieValue);\r\n }\r\n else {\r\n // There's no cookie, but we might have session data in local storage\r\n // This can happen if the session expired or the user actively deleted the cookie\r\n // We only want to recover data if the cookie is missing from expiry. We should respect the user's wishes if the cookie was deleted actively.\r\n // The User class handles this for us and deletes our local storage object if the persistent user cookie was removed.\r\n var storageValue = utlGetLocalStorage(_logger, _storageNamePrefix());\r\n if (storageValue) {\r\n isValid = _initializeAutomaticSessionWithData(session, storageValue);\r\n }\r\n }\r\n return isValid || !!session.id;\r\n }\r\n /**\r\n * Extract id, acquisitionDate, and renewalDate from an ai_session payload string and\r\n * use this data to initialize automaticSession.\r\n *\r\n * @param {string} sessionData - The string stored in an ai_session cookie or local storage backup\r\n * @returns true if values set otherwise false\r\n */\r\n function _initializeAutomaticSessionWithData(session, sessionData) {\r\n var isValid = false;\r\n var sessionReset = \", session will be reset\";\r\n var tokens = sessionData.split(\"|\");\r\n if (tokens[_DYN_LENGTH /* @min:%2elength */] >= 2) {\r\n try {\r\n var acqMs = +tokens[1] || 0;\r\n var renewalMs = +tokens[2] || 0;\r\n if (isNaN(acqMs) || acqMs <= 0) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 27 /* _eInternalMessageId.SessionRenewalDateIsZero */, \"AI session acquisition date is 0\" + sessionReset);\r\n }\r\n else if (isNaN(renewalMs) || renewalMs <= 0) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 27 /* _eInternalMessageId.SessionRenewalDateIsZero */, \"AI session renewal date is 0\" + sessionReset);\r\n }\r\n else if (tokens[0]) {\r\n // Everything looks valid so set the values\r\n session.id = tokens[0];\r\n session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */] = acqMs;\r\n session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */] = renewalMs;\r\n isValid = true;\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 9 /* _eInternalMessageId.ErrorParsingAISessionCookie */, \"Error parsing ai_session value [\" + (sessionData || \"\") + \"]\" + sessionReset + \" - \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return isValid;\r\n }\r\n function _renew(nowMs) {\r\n var theConfig = (_self[_DYN_CONFIG /* @min:%2econfig */] || {});\r\n var getNewId = (theConfig[_DYN_GET_NEW_ID /* @min:%2egetNewId */] ? theConfig[_DYN_GET_NEW_ID /* @min:%2egetNewId */]() : null) || newId;\r\n _self.automaticSession.id = getNewId(theConfig[_DYN_ID_LENGTH /* @min:%2eidLength */] ? theConfig[_DYN_ID_LENGTH /* @min:%2eidLength */]() : 22);\r\n _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */][_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */] = nowMs;\r\n _setCookie(_self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */], nowMs);\r\n // If this browser does not support local storage, fire an internal log to keep track of it at this point\r\n if (!utlCanUseLocalStorage()) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 0 /* _eInternalMessageId.BrowserDoesNotSupportLocalStorage */, \"Browser does not support local storage. Session durations will be inaccurate.\");\r\n }\r\n }\r\n function _setCookie(session, nowMs) {\r\n var acq = session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */];\r\n session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */] = nowMs;\r\n var config = _self[_DYN_CONFIG /* @min:%2econfig */];\r\n var renewalPeriodMs = config[_DYN_SESSION_RENEWAL_MS /* @min:%2esessionRenewalMs */]();\r\n // Set cookie to expire after the session expiry time passes or the session renewal deadline, whichever is sooner\r\n // Expiring the cookie will cause the session to expire even if the user isn't on the page\r\n var acqTimeLeftMs = (acq + config[_DYN_SESSION_EXPIRATION_M7 /* @min:%2esessionExpirationMs */]()) - nowMs;\r\n var cookie = [session.id, acq, nowMs];\r\n var maxAgeSec = 0;\r\n if (acqTimeLeftMs < renewalPeriodMs) {\r\n maxAgeSec = acqTimeLeftMs / 1000;\r\n }\r\n else {\r\n maxAgeSec = renewalPeriodMs / 1000;\r\n }\r\n var cookieDomain = config[_DYN_COOKIE_DOMAIN /* @min:%2ecookieDomain */] ? config[_DYN_COOKIE_DOMAIN /* @min:%2ecookieDomain */]() : null;\r\n // if sessionExpirationMs is set to 0, it means the expiry is set to 0 for this session cookie\r\n // A cookie with 0 expiry in the session cookie will never expire for that browser session. If the browser is closed the cookie expires.\r\n // Depending on the browser, another instance does not inherit this cookie, however, another tab will\r\n _cookieManager.set(_storageNamePrefix(), cookie.join(\"|\"), config[_DYN_SESSION_EXPIRATION_M7 /* @min:%2esessionExpirationMs */]() > 0 ? maxAgeSec : null, cookieDomain);\r\n _cookieUpdatedTimestamp = nowMs;\r\n }\r\n function _setStorage(guid, acq, renewal) {\r\n // Keep data in local storage to retain the last session id, allowing us to cleanly end the session when it expires\r\n // Browsers that don't support local storage won't be able to end sessions cleanly from the client\r\n // The server will notice this and end the sessions itself, with loss of accurate session duration\r\n utlSetLocalStorage(_logger, _storageNamePrefix(), [guid, acq, renewal][_DYN_JOIN /* @min:%2ejoin */](\"|\"));\r\n }\r\n });\r\n }\r\n// Removed Stub for _SessionManager.prototype.update.\r\n// Removed Stub for _SessionManager.prototype.backup.\r\n _SessionManager.acquisitionSpan = 86400000; // 24 hours in ms\r\n _SessionManager.renewalSpan = 1800000; // 30 minutes in ms\r\n _SessionManager.cookieUpdateInterval = 60000; // 1 minute in ms\r\n return _SessionManager;\r\n}());\r\nexport { _SessionManager };\r\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport { dataSanitizeString } from \"@microsoft/applicationinsights-common\";\r\nimport { generateW3CId, getLocation } from \"@microsoft/applicationinsights-core-js\";\r\nvar TelemetryTrace = /** @class */ (function () {\r\n function TelemetryTrace(id, parentId, name, logger) {\r\n var _self = this;\r\n _self.traceID = id || generateW3CId();\r\n _self.parentID = parentId;\r\n var location = getLocation();\r\n if (!name && location && location.pathname) {\r\n name = location.pathname;\r\n }\r\n _self.name = dataSanitizeString(logger, name);\r\n }\r\n return TelemetryTrace;\r\n}());\r\nexport { TelemetryTrace };\r\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { utlRemoveStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, newId, safeGetCookieMgr, safeGetLogger, toISOString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_ACCOUNT_ID, _DYN_AUTHENTICATED_ID, _DYN_AUTH_USER_COOKIE_NAM8, _DYN_CONFIG, _DYN_COOKIE_SEPARATOR, _DYN_GET_NEW_ID, _DYN_ID_LENGTH, _DYN_IS_NEW_USER, _DYN_IS_USER_COOKIE_SET, _DYN_JOIN, _DYN_LENGTH, _DYN_NAME_PREFIX, _DYN_UPDATE, _DYN_USER_COOKIE_POSTFIX } from \"../__DynamicConstants\";\r\nfunction _validateUserInput(id) {\r\n // Validate:\r\n // 1. Id is a non-empty string.\r\n // 2. It does not contain special characters for cookies.\r\n if (typeof id !== \"string\" ||\r\n !id ||\r\n id.match(/,|;|=| |\\|/)) {\r\n return false;\r\n }\r\n return true;\r\n}\r\nvar User = /** @class */ (function () {\r\n function User(config, core) {\r\n /**\r\n * A flag indicating whether this represents a new user\r\n */\r\n this.isNewUser = false;\r\n /**\r\n * A flag indicating whether the user cookie has been set\r\n */\r\n this.isUserCookieSet = false;\r\n var _logger = safeGetLogger(core);\r\n var _cookieManager = safeGetCookieMgr(core);\r\n var _storageNamePrefix;\r\n dynamicProto(User, this, function (_self) {\r\n _self[_DYN_CONFIG /* @min:%2econfig */] = config;\r\n var userCookiePostfix = (_self.config[_DYN_USER_COOKIE_POSTFIX /* @min:%2euserCookiePostfix */] && _self[_DYN_CONFIG /* @min:%2econfig */][_DYN_USER_COOKIE_POSTFIX /* @min:%2euserCookiePostfix */]()) ? _self[_DYN_CONFIG /* @min:%2econfig */][_DYN_USER_COOKIE_POSTFIX /* @min:%2euserCookiePostfix */]() : \"\";\r\n _storageNamePrefix = function () { return User.userCookieName + userCookiePostfix; };\r\n // get userId or create new one if none exists\r\n var cookie = _cookieManager.get(_storageNamePrefix());\r\n if (cookie) {\r\n _self[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = false;\r\n var params = cookie.split(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);\r\n if (params[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _self.id = params[0];\r\n // we already have a cookie\r\n _self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */] = !!_self.id;\r\n }\r\n }\r\n function _generateNewId() {\r\n var theConfig = (config || {});\r\n var getNewId = (theConfig[_DYN_GET_NEW_ID /* @min:%2egetNewId */] ? theConfig[_DYN_GET_NEW_ID /* @min:%2egetNewId */]() : null) || newId;\r\n var id = getNewId(theConfig[_DYN_ID_LENGTH /* @min:%2eidLength */] ? config[_DYN_ID_LENGTH /* @min:%2eidLength */]() : 22);\r\n return id;\r\n }\r\n function _generateNewCookie(userId) {\r\n var acqStr = toISOString(new Date());\r\n _self.accountAcquisitionDate = acqStr;\r\n _self[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = true;\r\n var newCookie = [userId, acqStr];\r\n return newCookie;\r\n }\r\n function _setUserCookie(cookie) {\r\n // without expiration, cookies expire at the end of the session\r\n // set it to 365 days from now\r\n // 365 * 24 * 60 * 60 = 31536000\r\n var oneYear = 31536000;\r\n _self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */] = _cookieManager.set(_storageNamePrefix(), cookie, oneYear);\r\n }\r\n if (!_self.id) {\r\n _self.id = _generateNewId();\r\n var newCookie = _generateNewCookie(_self.id);\r\n _setUserCookie(newCookie[_DYN_JOIN /* @min:%2ejoin */](User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]));\r\n // If we have an config.namePrefix() + ai_session in local storage this means the user actively removed our cookies.\r\n // We should respect their wishes and clear ourselves from local storage\r\n var name_1 = config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */] && config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */]() ? config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */]() + \"ai_session\" : \"ai_session\";\r\n utlRemoveStorage(_logger, name_1);\r\n }\r\n // We still take the account id from the ctor param for backward compatibility.\r\n // But if the the customer set the accountId through the newer setAuthenticatedUserContext API, we will override it.\r\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = config[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] ? config[_DYN_ACCOUNT_ID /* @min:%2eaccountId */]() : undefined;\r\n // Get the auth user id and account id from the cookie if exists\r\n // Cookie is in the pattern: |\r\n var authCookie = _cookieManager.get(User[_DYN_AUTH_USER_COOKIE_NAM8 /* @min:%2eauthUserCookieName */]);\r\n if (authCookie) {\r\n authCookie = decodeURI(authCookie);\r\n var authCookieString = authCookie.split(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);\r\n if (authCookieString[0]) {\r\n _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = authCookieString[0];\r\n }\r\n if (authCookieString[_DYN_LENGTH /* @min:%2elength */] > 1 && authCookieString[1]) {\r\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = authCookieString[1];\r\n }\r\n }\r\n _self.setAuthenticatedUserContext = function (authenticatedUserId, accountId, storeInCookie) {\r\n if (storeInCookie === void 0) { storeInCookie = false; }\r\n // Validate inputs to ensure no cookie control characters.\r\n var isInvalidInput = !_validateUserInput(authenticatedUserId) || (accountId && !_validateUserInput(accountId));\r\n if (isInvalidInput) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 60 /* _eInternalMessageId.SetAuthContextFailedAccountName */, \"Setting auth user context failed. \" +\r\n \"User auth/account id should be of type string, and not contain commas, semi-colons, equal signs, spaces, or vertical-bars.\", true);\r\n return;\r\n }\r\n // Create cookie string.\r\n _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = authenticatedUserId;\r\n var authCookie = _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */];\r\n if (accountId) {\r\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = accountId;\r\n authCookie = [_self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */], _self.accountId][_DYN_JOIN /* @min:%2ejoin */](User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);\r\n }\r\n if (storeInCookie) {\r\n // Set the cookie. No expiration date because this is a session cookie (expires when browser closed).\r\n // Encoding the cookie to handle unexpected unicode characters.\r\n _cookieManager.set(User[_DYN_AUTH_USER_COOKIE_NAM8 /* @min:%2eauthUserCookieName */], encodeURI(authCookie));\r\n }\r\n };\r\n /**\r\n * Clears the authenticated user id and the account id from the user context.\r\n * @returns {}\r\n */\r\n _self.clearAuthenticatedUserContext = function () {\r\n _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = null;\r\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = null;\r\n _cookieManager.del(User[_DYN_AUTH_USER_COOKIE_NAM8 /* @min:%2eauthUserCookieName */]);\r\n };\r\n _self[_DYN_UPDATE /* @min:%2eupdate */] = function (userId) {\r\n // Optimizations to avoid setting and processing the cookie when not needed\r\n if (_self.id !== userId || !_self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */]) {\r\n var user_id = userId ? userId : _generateNewId();\r\n var user_cookie = _generateNewCookie(user_id);\r\n _setUserCookie(user_cookie[_DYN_JOIN /* @min:%2ejoin */](User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]));\r\n }\r\n };\r\n });\r\n }\r\n// Removed Stub for User.prototype.setAuthenticatedUserContext.\r\n// Removed Stub for User.prototype.clearAuthenticatedUserContext.\r\n// Removed Stub for User.prototype.update.\r\n User.cookieSeparator = \"|\";\r\n User.userCookieName = \"ai_user\";\r\n User.authUserCookieName = \"ai_authUser\";\r\n return User;\r\n}());\r\nexport { User };\r\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n/**\r\n* PropertiesPlugin.ts\r\n* @copyright Microsoft 2018\r\n*/\r\nimport { __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { BreezeChannelIdentifier, PageView, PropertiesPluginIdentifier, createDistributedTraceContextFromTrace } from \"@microsoft/applicationinsights-common\";\r\nimport { BaseTelemetryPlugin, _InternalLogMessage, _logInternalMessage, createProcessTelemetryContext, getNavigator, getSetValue, isNullOrUndefined, objForEachKey } from \"@microsoft/applicationinsights-core-js\";\r\nimport { TelemetryContext } from \"./TelemetryContext\";\r\nimport { _DYN_ACCOUNT_ID, _DYN_APPLY_APPLICATION_CO1, _DYN_APPLY_DEVICE_CONTEXT, _DYN_APPLY_INTERNAL_CONTE5, _DYN_APPLY_LOCATION_CONTE4, _DYN_APPLY_OPERATING_SYST3, _DYN_APPLY_OPERATION_CONT2, _DYN_APPLY_SESSION_CONTEX0, _DYN_APPLY_USER_CONTEXT, _DYN_COOKIE_DOMAIN, _DYN_GET_NEW_ID, _DYN_GET_SESSION_ID, _DYN_GET_TRACE_CTX, _DYN_ID_LENGTH, _DYN_IS_NEW_USER, _DYN_IS_USER_COOKIE_SET, _DYN_NAME_PREFIX, _DYN_SDK_EXTENSION, _DYN_SESSION_COOKIE_POSTF6, _DYN_SESSION_MANAGER, _DYN_TELEMETRY_TRACE, _DYN_UPDATE, _DYN_USER_COOKIE_POSTFIX } from \"./__DynamicConstants\";\r\nvar PropertiesPlugin = /** @class */ (function (_super) {\r\n __extends(PropertiesPlugin, _super);\r\n function PropertiesPlugin() {\r\n var _this = _super.call(this) || this;\r\n _this.priority = 110;\r\n _this.identifier = PropertiesPluginIdentifier;\r\n var _extensionConfig;\r\n var _distributedTraceCtx;\r\n var _previousTraceCtx;\r\n dynamicProto(PropertiesPlugin, _this, function (_self, _base) {\r\n _initDefaults();\r\n _self.initialize = function (config, core, extensions, pluginChain) {\r\n _base.initialize(config, core, extensions, pluginChain);\r\n _populateDefaults(config);\r\n };\r\n /**\r\n * Add Part A fields to the event\r\n * @param event The event that needs to be processed\r\n */\r\n _self.processTelemetry = function (event, itemCtx) {\r\n if (isNullOrUndefined(event)) {\r\n // TODO(barustum): throw an internal event once we have support for internal logging\r\n }\r\n else {\r\n itemCtx = _self._getTelCtx(itemCtx);\r\n // If the envelope is PageView, reset the internal message count so that we can send internal telemetry for the new page.\r\n if (event.name === PageView.envelopeType) {\r\n itemCtx.diagLog().resetInternalMessageCount();\r\n }\r\n var theContext = (_self.context || {});\r\n if (theContext.session) {\r\n // If customer did not provide custom session id update the session manager\r\n if (typeof _self.context.session.id !== \"string\" && theContext[_DYN_SESSION_MANAGER /* @min:%2esessionManager */]) {\r\n theContext[_DYN_SESSION_MANAGER /* @min:%2esessionManager */][_DYN_UPDATE /* @min:%2eupdate */]();\r\n }\r\n }\r\n var userCtx = theContext.user;\r\n if (userCtx && !userCtx[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */]) {\r\n userCtx[_DYN_UPDATE /* @min:%2eupdate */](theContext.user.id);\r\n }\r\n _processTelemetryInternal(event, itemCtx);\r\n if (userCtx && userCtx[_DYN_IS_NEW_USER /* @min:%2eisNewUser */]) {\r\n userCtx[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = false;\r\n var message = new _InternalLogMessage(72 /* _eInternalMessageId.SendBrowserInfoOnUserInit */, ((getNavigator() || {}).userAgent || \"\"));\r\n _logInternalMessage(itemCtx.diagLog(), 1 /* eLoggingSeverity.CRITICAL */, message);\r\n }\r\n _self.processNext(event, itemCtx);\r\n }\r\n };\r\n _self._doTeardown = function (unloadCtx, unloadState) {\r\n var core = (unloadCtx || {}).core();\r\n if (core && core[_DYN_GET_TRACE_CTX /* @min:%2egetTraceCtx */]) {\r\n var traceCtx = core[_DYN_GET_TRACE_CTX /* @min:%2egetTraceCtx */](false);\r\n if (traceCtx === _distributedTraceCtx) {\r\n core.setTraceCtx(_previousTraceCtx);\r\n }\r\n }\r\n _initDefaults();\r\n };\r\n function _initDefaults() {\r\n _extensionConfig = null;\r\n _distributedTraceCtx = null;\r\n _previousTraceCtx = null;\r\n }\r\n function _populateDefaults(config) {\r\n var identifier = _self.identifier;\r\n var core = _self.core;\r\n var ctx = createProcessTelemetryContext(null, config, core);\r\n var defaultConfig = PropertiesPlugin.getDefaultConfig();\r\n _extensionConfig = _extensionConfig || {};\r\n objForEachKey(defaultConfig, function (field, value) {\r\n _extensionConfig[field] = function () { return ctx.getConfig(identifier, field, value()); };\r\n });\r\n _previousTraceCtx = core[_DYN_GET_TRACE_CTX /* @min:%2egetTraceCtx */](false);\r\n _self.context = new TelemetryContext(core, _extensionConfig, _previousTraceCtx);\r\n _distributedTraceCtx = createDistributedTraceContextFromTrace(_self.context[_DYN_TELEMETRY_TRACE /* @min:%2etelemetryTrace */], _previousTraceCtx);\r\n core.setTraceCtx(_distributedTraceCtx);\r\n _self.context.appId = function () {\r\n var breezeChannel = core.getPlugin(BreezeChannelIdentifier);\r\n return breezeChannel ? breezeChannel.plugin[\"_appId\"] : null;\r\n };\r\n // Test hook to allow accessing the internal values -- explicitly not defined as an available property on the class\r\n _self[\"_extConfig\"] = _extensionConfig;\r\n }\r\n function _processTelemetryInternal(evt, itemCtx) {\r\n // Set Part A fields\r\n getSetValue(evt, \"tags\", []);\r\n getSetValue(evt, \"ext\", {});\r\n var ctx = _self.context;\r\n ctx[_DYN_APPLY_SESSION_CONTEX0 /* @min:%2eapplySessionContext */](evt, itemCtx);\r\n ctx[_DYN_APPLY_APPLICATION_CO1 /* @min:%2eapplyApplicationContext */](evt, itemCtx);\r\n ctx[_DYN_APPLY_DEVICE_CONTEXT /* @min:%2eapplyDeviceContext */](evt, itemCtx);\r\n ctx[_DYN_APPLY_OPERATION_CONT2 /* @min:%2eapplyOperationContext */](evt, itemCtx);\r\n ctx[_DYN_APPLY_USER_CONTEXT /* @min:%2eapplyUserContext */](evt, itemCtx);\r\n ctx[_DYN_APPLY_OPERATING_SYST3 /* @min:%2eapplyOperatingSystemContxt */](evt, itemCtx);\r\n ctx.applyWebContext(evt, itemCtx);\r\n ctx[_DYN_APPLY_LOCATION_CONTE4 /* @min:%2eapplyLocationContext */](evt, itemCtx); // legacy tags\r\n ctx[_DYN_APPLY_INTERNAL_CONTE5 /* @min:%2eapplyInternalContext */](evt, itemCtx); // legacy tags\r\n ctx.cleanUp(evt, itemCtx);\r\n }\r\n });\r\n return _this;\r\n }\r\n PropertiesPlugin.getDefaultConfig = function () {\r\n var _a;\r\n var defaultValue;\r\n var nullValue = null;\r\n var defaultConfig = (_a = {\r\n instrumentationKey: function () { return defaultValue; }\r\n },\r\n _a[_DYN_ACCOUNT_ID /* @min:accountId */] = function () { return nullValue; },\r\n _a.sessionRenewalMs = function () { return 30 * 60 * 1000; },\r\n _a.samplingPercentage = function () { return 100; },\r\n _a.sessionExpirationMs = function () { return 24 * 60 * 60 * 1000; },\r\n _a[_DYN_COOKIE_DOMAIN /* @min:cookieDomain */] = function () { return nullValue; },\r\n _a[_DYN_SDK_EXTENSION /* @min:sdkExtension */] = function () { return nullValue; },\r\n _a.isBrowserLinkTrackingEnabled = function () { return false; },\r\n _a.appId = function () { return nullValue; },\r\n _a[_DYN_GET_SESSION_ID /* @min:getSessionId */] = function () { return nullValue; },\r\n _a[_DYN_NAME_PREFIX /* @min:namePrefix */] = function () { return defaultValue; },\r\n _a[_DYN_SESSION_COOKIE_POSTF6 /* @min:sessionCookiePostfix */] = function () { return defaultValue; },\r\n _a[_DYN_USER_COOKIE_POSTFIX /* @min:userCookiePostfix */] = function () { return defaultValue; },\r\n _a[_DYN_ID_LENGTH /* @min:idLength */] = function () { return 22; },\r\n _a[_DYN_GET_NEW_ID /* @min:getNewId */] = function () { return nullValue; },\r\n _a);\r\n return defaultConfig;\r\n };\r\n// Removed Stub for PropertiesPlugin.prototype.initialize.\r\n// Removed Stub for PropertiesPlugin.prototype.processTelemetry.\r\n return PropertiesPlugin;\r\n}(BaseTelemetryPlugin));\r\nexport default PropertiesPlugin;\r\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n/**\r\n* TelemetryContext.ts\r\n* @copyright Microsoft 2018\r\n*/\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { CtxTagKeys, Extensions, PageView } from \"@microsoft/applicationinsights-common\";\r\nimport { _InternalLogMessage, getSetValue, hasWindow, isNullOrUndefined, isString, objKeys, setValue } from \"@microsoft/applicationinsights-core-js\";\r\nimport { Application } from \"./Context/Application\";\r\nimport { Device } from \"./Context/Device\";\r\nimport { Internal } from \"./Context/Internal\";\r\nimport { Location } from \"./Context/Location\";\r\nimport { Session, _SessionManager } from \"./Context/Session\";\r\nimport { TelemetryTrace } from \"./Context/TelemetryTrace\";\r\nimport { User } from \"./Context/User\";\r\nimport { _DYN_ACCOUNT_ID, _DYN_APPLY_APPLICATION_CO1, _DYN_APPLY_DEVICE_CONTEXT, _DYN_APPLY_INTERNAL_CONTE5, _DYN_APPLY_LOCATION_CONTE4, _DYN_APPLY_OPERATING_SYST3, _DYN_APPLY_OPERATION_CONT2, _DYN_APPLY_SESSION_CONTEX0, _DYN_APPLY_USER_CONTEXT, _DYN_AUTHENTICATED_ID, _DYN_AUTOMATIC_SESSION, _DYN_GET_SESSION_ID, _DYN_LENGTH, _DYN_SESSION_MANAGER, _DYN_TELEMETRY_TRACE } from \"./__DynamicConstants\";\r\nvar strExt = \"ext\";\r\nvar strTags = \"tags\";\r\nfunction _removeEmpty(target, name) {\r\n if (target && target[name] && objKeys(target[name])[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n delete target[name];\r\n }\r\n}\r\nvar TelemetryContext = /** @class */ (function () {\r\n function TelemetryContext(core, defaultConfig, previousTraceCtx) {\r\n var _this = this;\r\n var logger = core.logger;\r\n this.appId = function () { return null; };\r\n this[_DYN_GET_SESSION_ID /* @min:%2egetSessionId */] = function () { return null; };\r\n dynamicProto(TelemetryContext, this, function (_self) {\r\n _self.application = new Application();\r\n _self.internal = new Internal(defaultConfig);\r\n if (hasWindow()) {\r\n _self[_DYN_SESSION_MANAGER /* @min:%2esessionManager */] = new _SessionManager(defaultConfig, core);\r\n _self.device = new Device();\r\n _self.location = new Location();\r\n _self.user = new User(defaultConfig, core);\r\n var traceId = void 0;\r\n var parentId = void 0;\r\n var name_1;\r\n if (previousTraceCtx) {\r\n traceId = previousTraceCtx.getTraceId();\r\n parentId = previousTraceCtx.getSpanId();\r\n name_1 = previousTraceCtx.getName();\r\n }\r\n _self[_DYN_TELEMETRY_TRACE /* @min:%2etelemetryTrace */] = new TelemetryTrace(traceId, parentId, name_1, logger);\r\n _self.session = new Session();\r\n }\r\n _self[_DYN_GET_SESSION_ID /* @min:%2egetSessionId */] = function () {\r\n var session = _self.session;\r\n var sesId = null;\r\n // If customer set session info, apply their context; otherwise apply context automatically generated\r\n if (session && isString(session.id)) {\r\n sesId = session.id;\r\n }\r\n else {\r\n // Gets the automatic session if it exists or an empty object\r\n var autoSession = (_self[_DYN_SESSION_MANAGER /* @min:%2esessionManager */] || {})[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */];\r\n sesId = autoSession && isString(autoSession.id) ? autoSession.id : null;\r\n }\r\n return sesId;\r\n };\r\n _self[_DYN_APPLY_SESSION_CONTEX0 /* @min:%2eapplySessionContext */] = function (evt, itemCtx) {\r\n setValue(getSetValue(evt.ext, Extensions.AppExt), \"sesId\", _self[_DYN_GET_SESSION_ID /* @min:%2egetSessionId */](), isString);\r\n };\r\n _self[_DYN_APPLY_OPERATING_SYST3 /* @min:%2eapplyOperatingSystemContxt */] = function (evt, itemCtx) {\r\n setValue(evt.ext, Extensions.OSExt, _self.os);\r\n };\r\n _self[_DYN_APPLY_APPLICATION_CO1 /* @min:%2eapplyApplicationContext */] = function (evt, itemCtx) {\r\n var application = _self.application;\r\n if (application) {\r\n // evt.ext.app\r\n var tags = getSetValue(evt, strTags);\r\n setValue(tags, CtxTagKeys.applicationVersion, application.ver, isString);\r\n setValue(tags, CtxTagKeys.applicationBuild, application.build, isString);\r\n }\r\n };\r\n _self[_DYN_APPLY_DEVICE_CONTEXT /* @min:%2eapplyDeviceContext */] = function (evt, itemCtx) {\r\n var device = _self.device;\r\n if (device) {\r\n // evt.ext.device\r\n var extDevice = getSetValue(getSetValue(evt, strExt), Extensions.DeviceExt);\r\n setValue(extDevice, \"localId\", device.id, isString);\r\n setValue(extDevice, \"ip\", device.ip, isString);\r\n setValue(extDevice, \"model\", device.model, isString);\r\n setValue(extDevice, \"deviceClass\", device.deviceClass, isString);\r\n }\r\n };\r\n _self[_DYN_APPLY_INTERNAL_CONTE5 /* @min:%2eapplyInternalContext */] = function (evt, itemCtx) {\r\n var internal = _self.internal;\r\n if (internal) {\r\n var tags = getSetValue(evt, strTags);\r\n setValue(tags, CtxTagKeys.internalAgentVersion, internal.agentVersion, isString); // not mapped in CS 4.0\r\n setValue(tags, CtxTagKeys.internalSdkVersion, internal.sdkVersion, isString);\r\n if (evt.baseType === _InternalLogMessage.dataType || evt.baseType === PageView.dataType) {\r\n setValue(tags, CtxTagKeys.internalSnippet, internal.snippetVer, isString);\r\n setValue(tags, CtxTagKeys.internalSdkSrc, internal.sdkSrc, isString);\r\n }\r\n }\r\n };\r\n _self[_DYN_APPLY_LOCATION_CONTE4 /* @min:%2eapplyLocationContext */] = function (evt, itemCtx) {\r\n var location = _this.location;\r\n if (location) {\r\n setValue(getSetValue(evt, strTags, []), CtxTagKeys.locationIp, location.ip, isString);\r\n }\r\n };\r\n _self[_DYN_APPLY_OPERATION_CONT2 /* @min:%2eapplyOperationContext */] = function (evt, itemCtx) {\r\n var telemetryTrace = _self[_DYN_TELEMETRY_TRACE /* @min:%2etelemetryTrace */];\r\n if (telemetryTrace) {\r\n var extTrace = getSetValue(getSetValue(evt, strExt), Extensions.TraceExt, { traceID: undefined, parentID: undefined });\r\n setValue(extTrace, \"traceID\", telemetryTrace.traceID, isString, isNullOrUndefined);\r\n setValue(extTrace, \"name\", telemetryTrace.name, isString, isNullOrUndefined);\r\n setValue(extTrace, \"parentID\", telemetryTrace.parentID, isString, isNullOrUndefined);\r\n }\r\n };\r\n _self.applyWebContext = function (evt, itemCtx) {\r\n var web = _this.web;\r\n if (web) {\r\n setValue(getSetValue(evt, strExt), Extensions.WebExt, web);\r\n }\r\n };\r\n _self[_DYN_APPLY_USER_CONTEXT /* @min:%2eapplyUserContext */] = function (evt, itemCtx) {\r\n var user = _self.user;\r\n if (user) {\r\n var tags = getSetValue(evt, strTags, []);\r\n // stays in tags\r\n setValue(tags, CtxTagKeys.userAccountId, user[_DYN_ACCOUNT_ID /* @min:%2eaccountId */], isString);\r\n // CS 4.0\r\n var extUser = getSetValue(getSetValue(evt, strExt), Extensions.UserExt);\r\n setValue(extUser, \"id\", user.id, isString);\r\n setValue(extUser, \"authId\", user[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */], isString);\r\n }\r\n };\r\n _self.cleanUp = function (evt, itemCtx) {\r\n var ext = evt.ext;\r\n if (ext) {\r\n _removeEmpty(ext, Extensions.DeviceExt);\r\n _removeEmpty(ext, Extensions.UserExt);\r\n _removeEmpty(ext, Extensions.WebExt);\r\n _removeEmpty(ext, Extensions.OSExt);\r\n _removeEmpty(ext, Extensions.AppExt);\r\n _removeEmpty(ext, Extensions.TraceExt);\r\n }\r\n };\r\n });\r\n }\r\n// Removed Stub for TelemetryContext.prototype.applySessionContext.\r\n// Removed Stub for TelemetryContext.prototype.applyOperatingSystemContxt.\r\n// Removed Stub for TelemetryContext.prototype.applyApplicationContext.\r\n// Removed Stub for TelemetryContext.prototype.applyDeviceContext.\r\n// Removed Stub for TelemetryContext.prototype.applyInternalContext.\r\n// Removed Stub for TelemetryContext.prototype.applyLocationContext.\r\n// Removed Stub for TelemetryContext.prototype.applyOperationContext.\r\n// Removed Stub for TelemetryContext.prototype.applyWebContext.\r\n// Removed Stub for TelemetryContext.prototype.applyUserContext.\r\n// Removed Stub for TelemetryContext.prototype.cleanUp.\r\n // This is a workaround for an IE8 bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n // this will be removed when ES3 support is dropped.\n TelemetryContext.__ieDyn=1;\n\n return TelemetryContext;\r\n}());\r\nexport { TelemetryContext };\r\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_SESSION_MANAGER = \"sessionManager\"; // Count: 3\r\nexport var _DYN_UPDATE = \"update\"; // Count: 4\r\nexport var _DYN_IS_USER_COOKIE_SET = \"isUserCookieSet\"; // Count: 4\r\nexport var _DYN_IS_NEW_USER = \"isNewUser\"; // Count: 4\r\nexport var _DYN_GET_TRACE_CTX = \"getTraceCtx\"; // Count: 3\r\nexport var _DYN_TELEMETRY_TRACE = \"telemetryTrace\"; // Count: 3\r\nexport var _DYN_APPLY_SESSION_CONTEX0 = \"applySessionContext\"; // Count: 2\r\nexport var _DYN_APPLY_APPLICATION_CO1 = \"applyApplicationContext\"; // Count: 2\r\nexport var _DYN_APPLY_DEVICE_CONTEXT = \"applyDeviceContext\"; // Count: 2\r\nexport var _DYN_APPLY_OPERATION_CONT2 = \"applyOperationContext\"; // Count: 2\r\nexport var _DYN_APPLY_USER_CONTEXT = \"applyUserContext\"; // Count: 2\r\nexport var _DYN_APPLY_OPERATING_SYST3 = \"applyOperatingSystemContxt\"; // Count: 2\r\nexport var _DYN_APPLY_LOCATION_CONTE4 = \"applyLocationContext\"; // Count: 2\r\nexport var _DYN_APPLY_INTERNAL_CONTE5 = \"applyInternalContext\"; // Count: 2\r\nexport var _DYN_ACCOUNT_ID = \"accountId\"; // Count: 8\r\nexport var _DYN_SDK_EXTENSION = \"sdkExtension\"; // Count: 4\r\nexport var _DYN_GET_SESSION_ID = \"getSessionId\"; // Count: 4\r\nexport var _DYN_NAME_PREFIX = \"namePrefix\"; // Count: 7\r\nexport var _DYN_SESSION_COOKIE_POSTF6 = \"sessionCookiePostfix\"; // Count: 4\r\nexport var _DYN_USER_COOKIE_POSTFIX = \"userCookiePostfix\"; // Count: 4\r\nexport var _DYN_ID_LENGTH = \"idLength\"; // Count: 5\r\nexport var _DYN_GET_NEW_ID = \"getNewId\"; // Count: 6\r\nexport var _DYN_LENGTH = \"length\"; // Count: 4\r\nexport var _DYN_AUTOMATIC_SESSION = \"automaticSession\"; // Count: 5\r\nexport var _DYN_AUTHENTICATED_ID = \"authenticatedId\"; // Count: 6\r\nexport var _DYN_SESSION_EXPIRATION_M7 = \"sessionExpirationMs\"; // Count: 5\r\nexport var _DYN_SESSION_RENEWAL_MS = \"sessionRenewalMs\"; // Count: 4\r\nexport var _DYN_CONFIG = \"config\"; // Count: 4\r\nexport var _DYN_ACQUISITION_DATE = \"acquisitionDate\"; // Count: 5\r\nexport var _DYN_RENEWAL_DATE = \"renewalDate\"; // Count: 4\r\nexport var _DYN_COOKIE_DOMAIN = \"cookieDomain\"; // Count: 3\r\nexport var _DYN_JOIN = \"join\"; // Count: 5\r\nexport var _DYN_COOKIE_SEPARATOR = \"cookieSeparator\"; // Count: 5\r\nexport var _DYN_AUTH_USER_COOKIE_NAM8 = \"authUserCookieName\"; // Count: 3\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nexport var strShimFunction = \"function\";\r\nexport var strShimObject = \"object\";\r\nexport var strShimUndefined = \"undefined\";\r\nexport var strShimPrototype = \"prototype\";\r\nexport var strShimHasOwnProperty = \"hasOwnProperty\";\r\nexport var strDefault = \"default\";\r\nexport var ObjClass = Object;\r\nexport var ObjProto = ObjClass[strShimPrototype];\r\nexport var ObjAssign = ObjClass[\"assign\"];\r\nexport var ObjCreate = ObjClass[\"create\"];\r\nexport var ObjDefineProperty = ObjClass[\"defineProperty\"];\r\nexport var ObjHasOwnProperty = ObjProto[strShimHasOwnProperty];\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { ObjCreate, strShimFunction, strShimObject, strShimPrototype, strShimUndefined } from \"./Constants\";\r\nvar _cachedGlobal = null;\r\n/**\r\n * Returns the current global scope object, for a normal web page this will be the current\r\n * window, for a Web Worker this will be current worker global scope via \"self\". The internal\r\n * implementation returns the first available instance object in the following order\r\n * - globalThis (New standard)\r\n * - self (Will return the current window instance for supported browsers)\r\n * - window (fallback for older browser implementations)\r\n * - global (NodeJS standard)\r\n * - (When all else fails)\r\n * While the return type is a Window for the normal case, not all environments will support all\r\n * of the properties or functions.\r\n */\r\nexport function getGlobal(useCached) {\r\n if (useCached === void 0) { useCached = true; }\r\n var result = useCached === false ? null : _cachedGlobal;\r\n if (!result) {\r\n if (typeof globalThis !== strShimUndefined) {\r\n result = globalThis;\r\n }\r\n if (!result && typeof self !== strShimUndefined) {\r\n result = self;\r\n }\r\n if (!result && typeof window !== strShimUndefined) {\r\n result = window;\r\n }\r\n if (!result && typeof global !== strShimUndefined) {\r\n result = global;\r\n }\r\n _cachedGlobal = result;\r\n }\r\n return result;\r\n}\r\nexport function throwTypeError(message) {\r\n throw new TypeError(message);\r\n}\r\n/**\r\n * Creates an object that has the specified prototype, and that optionally contains specified properties. This helper exists to avoid adding a polyfil\r\n * for older browsers that do not define Object.create eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation.\r\n * Note: For consistency this will not use the Object.create implementation if it exists as this would cause a testing requirement to test with and without the implementations\r\n * @param obj Object to use as a prototype. May be null\r\n */\r\nexport function objCreateFn(obj) {\r\n var func = ObjCreate;\r\n // Use build in Object.create\r\n if (func) {\r\n // Use Object create method if it exists\r\n return func(obj);\r\n }\r\n if (obj == null) {\r\n return {};\r\n }\r\n var type = typeof obj;\r\n if (type !== strShimObject && type !== strShimFunction) {\r\n throwTypeError(\"Object prototype may only be an Object:\" + obj);\r\n }\r\n function tmpFunc() { }\r\n tmpFunc[strShimPrototype] = obj;\r\n return new tmpFunc();\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { ObjAssign, ObjClass, ObjCreate, ObjDefineProperty, ObjHasOwnProperty, ObjProto, strDefault, strShimFunction, strShimHasOwnProperty, strShimPrototype } from \"./Constants\";\r\nimport { getGlobal, objCreateFn, throwTypeError } from \"./Helpers\";\r\n// Most of these functions have been directly shamelessly \"lifted\" from the https://github.com/@microsoft/tslib and\r\n// modified to be ES3 compatible and applying several minification and tree-shaking techniques so that Application Insights\r\n// can successfully use TypeScript \"importHelpers\" which imports tslib during compilation but it will use these at runtime\r\n// Which is also why all of the functions have not been included as Application Insights currently doesn't use or require\r\n// them.\r\nexport var SymbolObj = (getGlobal() || {})[\"Symbol\"];\r\nexport var ReflectObj = (getGlobal() || {})[\"Reflect\"];\r\nexport var __hasSymbol = !!SymbolObj;\r\nexport var __hasReflect = !!ReflectObj;\r\nvar strDecorate = \"decorate\";\r\nvar strMetadata = \"metadata\";\r\nvar strGetOwnPropertySymbols = \"getOwnPropertySymbols\";\r\nvar strIterator = \"iterator\";\r\nexport var __objAssignFnImpl = function (t) {\r\n // tslint:disable-next-line: ban-comma-operator\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) {\r\n if (ObjProto[strShimHasOwnProperty].call(s, p)) {\r\n t[p] = s[p];\r\n }\r\n }\r\n }\r\n return t;\r\n};\r\nexport var __assignFn = ObjAssign || __objAssignFnImpl;\r\n// tslint:disable-next-line: only-arrow-functions\r\nvar extendStaticsFn = function (d, b) {\r\n extendStaticsFn = ObjClass[\"setPrototypeOf\"] ||\r\n // tslint:disable-next-line: only-arrow-functions\r\n ({ __proto__: [] } instanceof Array && function (d, b) {\r\n d.__proto__ = b;\r\n }) ||\r\n // tslint:disable-next-line: only-arrow-functions\r\n function (d, b) {\r\n for (var p in b) {\r\n if (b[strShimHasOwnProperty](p)) {\r\n d[p] = b[p];\r\n }\r\n }\r\n };\r\n return extendStaticsFn(d, b);\r\n};\r\nexport function __extendsFn(d, b) {\r\n if (typeof b !== strShimFunction && b !== null) {\r\n throwTypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n }\r\n extendStaticsFn(d, b);\r\n function __() {\r\n this.constructor = d;\r\n }\r\n // tslint:disable-next-line: ban-comma-operator\r\n d[strShimPrototype] = b === null ? objCreateFn(b) : (__[strShimPrototype] = b[strShimPrototype], new __());\r\n}\r\nexport function __restFn(s, e) {\r\n var t = {};\r\n for (var k in s) {\r\n if (ObjHasOwnProperty.call(s, k) && e.indexOf(k) < 0) {\r\n t[k] = s[k];\r\n }\r\n }\r\n if (s != null && typeof ObjClass[strGetOwnPropertySymbols] === strShimFunction) {\r\n for (var i = 0, p = ObjClass[strGetOwnPropertySymbols](s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && ObjProto[\"propertyIsEnumerable\"].call(s, p[i])) {\r\n t[p[i]] = s[p[i]];\r\n }\r\n }\r\n }\r\n return t;\r\n}\r\nexport function __decorateFn(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = ObjClass[\"getOwnPropertyDescriptor\"](target, key) : desc, d;\r\n if (__hasReflect && typeof ReflectObj[strDecorate] === strShimFunction) {\r\n r = ReflectObj[strDecorate](decorators, target, key, desc);\r\n }\r\n else {\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n // eslint-disable-next-line no-cond-assign\r\n if (d = decorators[i]) {\r\n r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n }\r\n }\r\n }\r\n // tslint:disable-next-line:ban-comma-operator\r\n return c > 3 && r && ObjDefineProperty(target, key, r), r;\r\n}\r\nexport function __paramFn(paramIndex, decorator) {\r\n return function (target, key) {\r\n decorator(target, key, paramIndex);\r\n };\r\n}\r\nexport function __metadataFn(metadataKey, metadataValue) {\r\n if (__hasReflect && ReflectObj[strMetadata] === strShimFunction) {\r\n return ReflectObj[strMetadata](metadataKey, metadataValue);\r\n }\r\n}\r\nexport function __exportStarFn(m, o) {\r\n for (var p in m) {\r\n if (p !== strDefault && !ObjHasOwnProperty.call(o, p)) {\r\n __createBindingFn(o, m, p);\r\n }\r\n }\r\n}\r\nexport function __createBindingFn(o, m, k, k2) {\r\n if (k2 === undefined) {\r\n k2 = k;\r\n }\r\n if (!!ObjCreate) {\r\n ObjDefineProperty(o, k2, {\r\n enumerable: true,\r\n get: function () {\r\n return m[k];\r\n }\r\n });\r\n }\r\n else {\r\n o[k2] = m[k];\r\n }\r\n}\r\nexport function __valuesFn(o) {\r\n var s = typeof SymbolObj === strShimFunction && SymbolObj[strIterator], m = s && o[s], i = 0;\r\n if (m) {\r\n return m.call(o);\r\n }\r\n if (o && typeof o.length === \"number\") {\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) {\r\n o = void 0;\r\n }\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n }\r\n throwTypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\nexport function __readFn(o, n) {\r\n var m = typeof SymbolObj === strShimFunction && o[SymbolObj[strIterator]];\r\n if (!m) {\r\n return o;\r\n }\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {\r\n ar.push(r.value);\r\n }\r\n }\r\n catch (error) {\r\n e = {\r\n error: error\r\n };\r\n }\r\n finally {\r\n try {\r\n // tslint:disable-next-line:no-conditional-assignment\r\n if (r && !r.done && (m = i[\"return\"])) {\r\n m.call(i);\r\n }\r\n }\r\n finally {\r\n if (e) {\r\n // eslint-disable-next-line no-unsafe-finally\r\n throw e.error;\r\n }\r\n }\r\n }\r\n return ar;\r\n}\r\n/** @deprecated */\r\nexport function __spreadArraysFn() {\r\n var theArgs = arguments;\r\n // Calculate new total size\r\n for (var s = 0, i = 0, il = theArgs.length; i < il; i++) {\r\n s += theArgs[i].length;\r\n }\r\n // Create new full array\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++) {\r\n for (var a = theArgs[i], j = 0, jl = a.length; j < jl; j++, k++) {\r\n r[k] = a[j];\r\n }\r\n }\r\n return r;\r\n}\r\nexport function __spreadArrayFn(to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) {\r\n to[j] = from[i];\r\n }\r\n return to;\r\n}\r\nexport function __makeTemplateObjectFn(cooked, raw) {\r\n if (ObjDefineProperty) {\r\n ObjDefineProperty(cooked, \"raw\", { value: raw });\r\n }\r\n else {\r\n cooked.raw = raw;\r\n }\r\n return cooked;\r\n}\r\nexport function __importStarFn(mod) {\r\n if (mod && mod.__esModule) {\r\n return mod;\r\n }\r\n var result = {};\r\n if (mod != null) {\r\n for (var k in mod) {\r\n if (k !== strDefault && Object.prototype.hasOwnProperty.call(mod, k)) {\r\n __createBindingFn(result, mod, k);\r\n }\r\n }\r\n }\r\n // Set default module\r\n if (!!ObjCreate) {\r\n ObjDefineProperty(result, strDefault, { enumerable: true, value: mod });\r\n }\r\n else {\r\n result[strDefault] = mod;\r\n }\r\n return result;\r\n}\r\nexport function __importDefaultFn(mod) {\r\n return (mod && mod.__esModule) ? mod : { strDefault: mod };\r\n}\r\n","/*\n * Application Insights JavaScript SDK - Web, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n\"use strict\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { AnalyticsPlugin } from \"@microsoft/applicationinsights-analytics-js\";\r\nimport { Sender } from \"@microsoft/applicationinsights-channel-js\";\r\nimport { AnalyticsPluginIdentifier, BreezeChannelIdentifier, ConfigurationManager, ConnectionStringParser, ContextTagKeys, CorrelationIdHelper, CtxTagKeys, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, Data, DataSanitizer, DateTimeUtils, DisabledPropertyName, DistributedTracingModes, Envelope, Event, Exception, Extensions, HttpMethod, Metric, PageView, PageViewPerformance, ProcessLegacy, PropertiesPluginIdentifier, RemoteDependencyData, RequestHeaders, SampleRate, SeverityLevel, TelemetryItemCreator, Trace, UrlHelper, Util, parseConnectionString } from \"@microsoft/applicationinsights-common\";\r\nimport { AppInsightsCore, _throwInternal, addPageHideEventListener, addPageUnloadEventListener, arrForEach, arrIndexOf, createUniqueNamespace, doPerf, hasDocument, hasWindow, isArray, isFunction, isNullOrUndefined, isReactNative, isString, mergeEvtNamespace, objForEachKey, proxyAssign, proxyFunctions, removePageHideEventListener, removePageUnloadEventListener, throwError } from \"@microsoft/applicationinsights-core-js\";\r\nimport { AjaxPlugin as DependenciesPlugin } from \"@microsoft/applicationinsights-dependencies-js\";\r\nimport { PropertiesPlugin } from \"@microsoft/applicationinsights-properties-js\";\r\nimport { STR_ADD_TELEMETRY_INITIALIZER, STR_CLEAR_AUTHENTICATED_USER_CONTEXT, STR_EVT_NAMESPACE, STR_FLUSH, STR_GET_COOKIE_MGR, STR_GET_PLUGIN, STR_POLL_INTERNAL_LOGS, STR_SET_AUTHENTICATED_USER_CONTEXT, STR_SNIPPET, STR_START_TRACK_EVENT, STR_START_TRACK_PAGE, STR_STOP_TRACK_EVENT, STR_STOP_TRACK_PAGE, STR_TRACK_DEPENDENCY_DATA, STR_TRACK_EVENT, STR_TRACK_EXCEPTION, STR_TRACK_METRIC, STR_TRACK_PAGE_VIEW, STR_TRACK_TRACE } from \"./InternalConstants\";\r\nimport { _DYN_ADD_HOUSEKEEPING_BEF20, _DYN_APP_INSIGHTS, _DYN_CONFIG, _DYN_CONNECTION_STRING, _DYN_CONTEXT, _DYN_DIAGNOSTIC_LOG_INTER4, _DYN_DISABLE_FLUSH_ON_BEF11, _DYN_DISABLE_FLUSH_ON_UNL12, _DYN_DISABLE_IKEY_DEPRECA18, _DYN_ENDPOINT_URL, _DYN_GET_TRANSMISSION_CON19, _DYN_INDEX_OF, _DYN_INSTRUMENTATION_KEY, _DYN_LOAD_APP_INSIGHTS, _DYN_ONUNLOAD_FLUSH, _DYN_PUSH, _DYN_QUEUE, _DYN_UPDATE_SNIPPET_DEFIN0, _DYN_VERSION } from \"./__DynamicConstants\";\r\nvar _internalSdkSrc;\r\n// This is an exclude list of properties that should not be updated during initialization\r\n// They include a combination of private and internal property names\r\nvar _ignoreUpdateSnippetProperties = [\r\n STR_SNIPPET, \"dependencies\", \"properties\", \"_snippetVersion\", \"appInsightsNew\", \"getSKUDefaults\"\r\n];\r\n// Re-exposing the Common classes as Telemetry, the list was taken by reviewing the generated code for the build while using\r\n// the previous configuration :-\r\n// import * as Common from \"@microsoft/applicationinsights-common\"\r\n// export const Telemetry = Common;\r\nvar fieldType = {\r\n Default: 0 /* FieldType.Default */,\r\n Required: 1 /* FieldType.Required */,\r\n Array: 2 /* FieldType.Array */,\r\n Hidden: 4 /* FieldType.Hidden */\r\n};\r\n/**\r\n * Telemetry type classes, e.g. PageView, Exception, etc\r\n */\r\nexport var Telemetry = {\r\n __proto__: null,\r\n PropertiesPluginIdentifier: PropertiesPluginIdentifier,\r\n BreezeChannelIdentifier: BreezeChannelIdentifier,\r\n AnalyticsPluginIdentifier: AnalyticsPluginIdentifier,\r\n Util: Util,\r\n CorrelationIdHelper: CorrelationIdHelper,\r\n UrlHelper: UrlHelper,\r\n DateTimeUtils: DateTimeUtils,\r\n ConnectionStringParser: ConnectionStringParser,\r\n FieldType: fieldType,\r\n RequestHeaders: RequestHeaders,\r\n DisabledPropertyName: DisabledPropertyName,\r\n ProcessLegacy: ProcessLegacy,\r\n SampleRate: SampleRate,\r\n HttpMethod: HttpMethod,\r\n DEFAULT_BREEZE_ENDPOINT: DEFAULT_BREEZE_ENDPOINT,\r\n Envelope: Envelope,\r\n Event: Event,\r\n Exception: Exception,\r\n Metric: Metric,\r\n PageView: PageView,\r\n RemoteDependencyData: RemoteDependencyData,\r\n Trace: Trace,\r\n PageViewPerformance: PageViewPerformance,\r\n Data: Data,\r\n SeverityLevel: SeverityLevel,\r\n ConfigurationManager: ConfigurationManager,\r\n ContextTagKeys: ContextTagKeys,\r\n DataSanitizer: DataSanitizer,\r\n TelemetryItemCreator: TelemetryItemCreator,\r\n CtxTagKeys: CtxTagKeys,\r\n Extensions: Extensions,\r\n DistributedTracingModes: DistributedTracingModes\r\n};\r\n/**\r\n * Application Insights API\r\n * @class Initialization\r\n * @implements {IApplicationInsights}\r\n */\r\nvar Initialization = /** @class */ (function () {\r\n function Initialization(snippet) {\r\n var _this = this;\r\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\r\n var dependencies;\r\n var properties;\r\n var _sender;\r\n var _snippetVersion;\r\n var _evtNamespace;\r\n var _houseKeepingNamespace;\r\n var _core;\r\n dynamicProto(Initialization, this, function (_self) {\r\n _initDefaults();\r\n // initialize the queue and config in case they are undefined\r\n _snippetVersion = \"\" + (snippet.sv || snippet[_DYN_VERSION /* @min:%2eversion */] || \"\");\r\n snippet[_DYN_QUEUE /* @min:%2equeue */] = snippet[_DYN_QUEUE /* @min:%2equeue */] || [];\r\n snippet[_DYN_VERSION /* @min:%2eversion */] = snippet[_DYN_VERSION /* @min:%2eversion */] || 2.0; // Default to new version\r\n var config = snippet[_DYN_CONFIG /* @min:%2econfig */] || {};\r\n if (config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */]) {\r\n var cs = parseConnectionString(config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */]);\r\n var ingest = cs.ingestionendpoint;\r\n config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */] = ingest ? (ingest + DEFAULT_BREEZE_PATH) : config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */]; // only add /v2/track when from connectionstring\r\n config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */] = cs.instrumentationkey || config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];\r\n }\r\n _self[_DYN_APP_INSIGHTS /* @min:%2eappInsights */] = new AnalyticsPlugin();\r\n properties = new PropertiesPlugin();\r\n dependencies = new DependenciesPlugin();\r\n _sender = new Sender();\r\n _core = new AppInsightsCore();\r\n _self.core = _core;\r\n var isErrMessageDisabled = isNullOrUndefined(config[_DYN_DISABLE_IKEY_DEPRECA18 /* @min:%2edisableIkeyDeprecationMessage */]) ? true : config[_DYN_DISABLE_IKEY_DEPRECA18 /* @min:%2edisableIkeyDeprecationMessage */];\r\n if (!config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */] && !isErrMessageDisabled) {\r\n _throwInternal(_core.logger, 1 /* eLoggingSeverity.CRITICAL */, 106 /* _eInternalMessageId.InstrumentationKeyDeprecation */, \"Instrumentation key support will end soon, see aka.ms/IkeyMigrate\");\r\n }\r\n _self[STR_SNIPPET /* @min:%2esnippet */] = snippet;\r\n _self[_DYN_CONFIG /* @min:%2econfig */] = config;\r\n _getSKUDefaults();\r\n _self[STR_FLUSH /* @min:%2eflush */] = function (async) {\r\n if (async === void 0) { async = true; }\r\n doPerf(_core, function () { return \"AISKU.flush\"; }, function () {\r\n arrForEach(_core[_DYN_GET_TRANSMISSION_CON19 /* @min:%2egetTransmissionControls */](), function (channels) {\r\n arrForEach(channels, function (channel) {\r\n channel[STR_FLUSH /* @min:%2eflush */](async);\r\n });\r\n });\r\n }, null, async);\r\n };\r\n _self[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */] = function (async) {\r\n if (async === void 0) { async = true; }\r\n arrForEach(_core[_DYN_GET_TRANSMISSION_CON19 /* @min:%2egetTransmissionControls */](), function (channels) {\r\n arrForEach(channels, function (channel) {\r\n if (channel[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */]) {\r\n channel[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */]();\r\n }\r\n else {\r\n channel[STR_FLUSH /* @min:%2eflush */](async);\r\n }\r\n });\r\n });\r\n };\r\n _self[_DYN_LOAD_APP_INSIGHTS /* @min:%2eloadAppInsights */] = function (legacyMode, logger, notificationManager) {\r\n if (legacyMode === void 0) { legacyMode = false; }\r\n function _updateSnippetProperties(snippet) {\r\n if (snippet) {\r\n var snippetVer = \"\";\r\n if (!isNullOrUndefined(_snippetVersion)) {\r\n snippetVer += _snippetVersion;\r\n }\r\n if (legacyMode) {\r\n snippetVer += \".lg\";\r\n }\r\n if (_self[_DYN_CONTEXT /* @min:%2econtext */] && _self[_DYN_CONTEXT /* @min:%2econtext */].internal) {\r\n _self[_DYN_CONTEXT /* @min:%2econtext */].internal.snippetVer = snippetVer || \"-\";\r\n }\r\n // apply updated properties to the global instance (snippet)\r\n objForEachKey(_self, function (field, value) {\r\n if (isString(field) &&\r\n !isFunction(value) &&\r\n field && field[0] !== \"_\" && // Don't copy \"internal\" values\r\n arrIndexOf(_ignoreUpdateSnippetProperties, field) === -1) {\r\n snippet[field] = value;\r\n }\r\n });\r\n }\r\n }\r\n // dont allow additional channels/other extensions for legacy mode; legacy mode is only to allow users to switch with no code changes!\r\n if (legacyMode && _self[_DYN_CONFIG /* @min:%2econfig */].extensions && _self[_DYN_CONFIG /* @min:%2econfig */].extensions.length > 0) {\r\n throwError(\"Extensions not allowed in legacy mode\");\r\n }\r\n doPerf(_self.core, function () { return \"AISKU.loadAppInsights\"; }, function () {\r\n var extensions = [];\r\n extensions[_DYN_PUSH /* @min:%2epush */](_sender);\r\n extensions[_DYN_PUSH /* @min:%2epush */](properties);\r\n extensions[_DYN_PUSH /* @min:%2epush */](dependencies);\r\n extensions[_DYN_PUSH /* @min:%2epush */](_self[_DYN_APP_INSIGHTS /* @min:%2eappInsights */]);\r\n // initialize core\r\n _core.initialize(_self[_DYN_CONFIG /* @min:%2econfig */], extensions, logger, notificationManager);\r\n _self[_DYN_CONTEXT /* @min:%2econtext */] = properties[_DYN_CONTEXT /* @min:%2econtext */];\r\n if (_internalSdkSrc && _self[_DYN_CONTEXT /* @min:%2econtext */]) {\r\n _self[_DYN_CONTEXT /* @min:%2econtext */].internal.sdkSrc = _internalSdkSrc;\r\n }\r\n _updateSnippetProperties(_self[STR_SNIPPET /* @min:%2esnippet */]);\r\n // Empty queue of all api calls logged prior to sdk download\r\n _self.emptyQueue();\r\n _self[STR_POLL_INTERNAL_LOGS /* @min:%2epollInternalLogs */]();\r\n _self[_DYN_ADD_HOUSEKEEPING_BEF20 /* @min:%2eaddHousekeepingBeforeUnload */](_this);\r\n });\r\n return _self;\r\n };\r\n _self[_DYN_UPDATE_SNIPPET_DEFIN0 /* @min:%2eupdateSnippetDefinitions */] = function (snippet) {\r\n // apply full appInsights to the global instance\r\n // Note: This must be called before loadAppInsights is called\r\n proxyAssign(snippet, _self, function (name) {\r\n // Not excluding names prefixed with \"_\" as we need to proxy some functions like _onError\r\n return name && arrIndexOf(_ignoreUpdateSnippetProperties, name) === -1;\r\n });\r\n };\r\n _self.emptyQueue = function () {\r\n // call functions that were queued before the main script was loaded\r\n try {\r\n if (isArray(_self.snippet[_DYN_QUEUE /* @min:%2equeue */])) {\r\n // note: do not check length in the for-loop conditional in case something goes wrong and the stub methods are not overridden.\r\n var length_1 = _self.snippet[_DYN_QUEUE /* @min:%2equeue */].length;\r\n for (var i = 0; i < length_1; i++) {\r\n var call = _self.snippet[_DYN_QUEUE /* @min:%2equeue */][i];\r\n call();\r\n }\r\n _self.snippet[_DYN_QUEUE /* @min:%2equeue */] = undefined;\r\n delete _self.snippet[_DYN_QUEUE /* @min:%2equeue */];\r\n }\r\n }\r\n catch (exception) {\r\n var properties_1 = {};\r\n if (exception && isFunction(exception.toString)) {\r\n properties_1.exception = exception.toString();\r\n }\r\n // need from core\r\n // Microsoft.ApplicationInsights._InternalLogging.throwInternal(\r\n // eLoggingSeverity.WARNING,\r\n // _eInternalMessageId.FailedToSendQueuedTelemetry,\r\n // \"Failed to send queued telemetry\",\r\n // properties);\r\n }\r\n };\r\n _self[_DYN_ADD_HOUSEKEEPING_BEF20 /* @min:%2eaddHousekeepingBeforeUnload */] = function (appInsightsInstance) {\r\n // Add callback to push events when the user navigates away\r\n if (hasWindow() || hasDocument()) {\r\n var performHousekeeping = function () {\r\n // Adds the ability to flush all data before the page unloads.\r\n // Note: This approach tries to push a sync request with all the pending events onbeforeunload.\r\n // Firefox does not respect this.Other browsers DO push out the call with < 100% hit rate.\r\n // Telemetry here will help us analyze how effective this approach is.\r\n // Another approach would be to make this call sync with a acceptable timeout to reduce the\r\n // impact on user experience.\r\n // appInsightsInstance.context._sender.triggerSend();\r\n appInsightsInstance[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */](false);\r\n // Back up the current session to local storage\r\n // This lets us close expired sessions after the cookies themselves expire\r\n if (isFunction(_this.core[STR_GET_PLUGIN /* @min:%2egetPlugin */])) {\r\n var loadedPlugin = _this.core[STR_GET_PLUGIN /* @min:%2egetPlugin */](PropertiesPluginIdentifier);\r\n if (loadedPlugin) {\r\n var propertiesPlugin = loadedPlugin.plugin;\r\n if (propertiesPlugin && propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */] && propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */]._sessionManager) {\r\n propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */]._sessionManager.backup();\r\n }\r\n }\r\n }\r\n };\r\n var added = false;\r\n var excludePageUnloadEvents = appInsightsInstance.appInsights[_DYN_CONFIG /* @min:%2econfig */].disablePageUnloadEvents;\r\n if (!_houseKeepingNamespace) {\r\n _houseKeepingNamespace = mergeEvtNamespace(_evtNamespace, _core[STR_EVT_NAMESPACE /* @min:%2eevtNamespace */] && _core[STR_EVT_NAMESPACE /* @min:%2eevtNamespace */]());\r\n }\r\n if (!appInsightsInstance.appInsights.config[_DYN_DISABLE_FLUSH_ON_BEF11 /* @min:%2edisableFlushOnBeforeUnload */]) {\r\n // Hook the unload event for the document, window and body to ensure that the client events are flushed to the server\r\n // As just hooking the window does not always fire (on chrome) for page navigation's.\r\n if (addPageUnloadEventListener(performHousekeeping, excludePageUnloadEvents, _houseKeepingNamespace)) {\r\n added = true;\r\n }\r\n // We also need to hook the pagehide and visibilitychange events as not all versions of Safari support load/unload events.\r\n if (addPageHideEventListener(performHousekeeping, excludePageUnloadEvents, _houseKeepingNamespace)) {\r\n added = true;\r\n }\r\n // A reactNative app may not have a window and therefore the beforeunload/pagehide events -- so don't\r\n // log the failure in this case\r\n if (!added && !isReactNative()) {\r\n _throwInternal(appInsightsInstance[_DYN_APP_INSIGHTS /* @min:%2eappInsights */].core.logger, 1 /* eLoggingSeverity.CRITICAL */, 19 /* _eInternalMessageId.FailedToAddHandlerForOnBeforeUnload */, \"Could not add handler for beforeunload and pagehide\");\r\n }\r\n }\r\n if (!added && !appInsightsInstance.appInsights.config[_DYN_DISABLE_FLUSH_ON_UNL12 /* @min:%2edisableFlushOnUnload */]) {\r\n // If we didn't add the normal set then attempt to add the pagehide and visibilitychange only\r\n addPageHideEventListener(performHousekeeping, excludePageUnloadEvents, _houseKeepingNamespace);\r\n }\r\n }\r\n };\r\n _self.getSender = function () {\r\n return _sender;\r\n };\r\n _self.unload = function (isAsync, unloadComplete, cbTimeout) {\r\n _self[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */](isAsync);\r\n // Remove any registered event handlers\r\n if (_houseKeepingNamespace) {\r\n removePageUnloadEventListener(null, _houseKeepingNamespace);\r\n removePageHideEventListener(null, _houseKeepingNamespace);\r\n }\r\n _core.unload && _core.unload(isAsync, unloadComplete, cbTimeout);\r\n };\r\n proxyFunctions(_self, _self[_DYN_APP_INSIGHTS /* @min:%2eappInsights */], [\r\n STR_GET_COOKIE_MGR,\r\n STR_TRACK_EVENT,\r\n STR_TRACK_PAGE_VIEW,\r\n \"trackPageViewPerformance\",\r\n STR_TRACK_EXCEPTION,\r\n \"_onerror\",\r\n STR_TRACK_TRACE,\r\n STR_TRACK_METRIC,\r\n STR_START_TRACK_PAGE,\r\n STR_STOP_TRACK_PAGE,\r\n STR_START_TRACK_EVENT,\r\n STR_STOP_TRACK_EVENT\r\n ]);\r\n proxyFunctions(_self, _getCurrentDependencies, [\r\n STR_TRACK_DEPENDENCY_DATA,\r\n \"addDependencyListener\",\r\n \"addDependencyInitializer\"\r\n ]);\r\n proxyFunctions(_self, _core, [\r\n STR_ADD_TELEMETRY_INITIALIZER,\r\n STR_POLL_INTERNAL_LOGS,\r\n \"stopPollingInternalLogs\",\r\n STR_GET_PLUGIN,\r\n \"addPlugin\",\r\n STR_EVT_NAMESPACE,\r\n \"addUnloadCb\",\r\n \"getTraceCtx\"\r\n ]);\r\n proxyFunctions(_self, function () {\r\n var context = properties[_DYN_CONTEXT /* @min:%2econtext */];\r\n return context ? context.user : null;\r\n }, [\r\n STR_SET_AUTHENTICATED_USER_CONTEXT,\r\n STR_CLEAR_AUTHENTICATED_USER_CONTEXT\r\n ]);\r\n function _getSKUDefaults() {\r\n _self.config[_DYN_DIAGNOSTIC_LOG_INTER4 /* @min:%2ediagnosticLogInterval */] =\r\n _self.config[_DYN_DIAGNOSTIC_LOG_INTER4 /* @min:%2ediagnosticLogInterval */] && _self[_DYN_CONFIG /* @min:%2econfig */][_DYN_DIAGNOSTIC_LOG_INTER4 /* @min:%2ediagnosticLogInterval */] > 0 ? _self[_DYN_CONFIG /* @min:%2econfig */][_DYN_DIAGNOSTIC_LOG_INTER4 /* @min:%2ediagnosticLogInterval */] : 10000;\r\n }\r\n // Using a function to support the dynamic adding / removal of plugins, so this will always return the current value\r\n function _getCurrentDependencies() {\r\n return dependencies;\r\n }\r\n function _initDefaults() {\r\n _evtNamespace = createUniqueNamespace(\"AISKU\");\r\n _houseKeepingNamespace = null;\r\n dependencies = null;\r\n properties = null;\r\n _sender = null;\r\n _snippetVersion = null;\r\n }\r\n });\r\n }\r\n // Analytics Plugin\r\n// Removed Stub for Initialization.prototype.getCookieMgr.\r\n// Removed Stub for Initialization.prototype.trackEvent.\r\n// Removed Stub for Initialization.prototype.trackPageView.\r\n// Removed Stub for Initialization.prototype.trackPageViewPerformance.\r\n// Removed Stub for Initialization.prototype.trackException.\r\n// Removed Stub for Initialization.prototype._onerror.\r\n// Removed Stub for Initialization.prototype.trackTrace.\r\n// Removed Stub for Initialization.prototype.trackMetric.\r\n// Removed Stub for Initialization.prototype.startTrackPage.\r\n// Removed Stub for Initialization.prototype.stopTrackPage.\r\n// Removed Stub for Initialization.prototype.startTrackEvent.\r\n// Removed Stub for Initialization.prototype.stopTrackEvent.\r\n// Removed Stub for Initialization.prototype.addTelemetryInitializer.\r\n // Properties Plugin\r\n// Removed Stub for Initialization.prototype.setAuthenticatedUserContext.\r\n// Removed Stub for Initialization.prototype.clearAuthenticatedUserContext.\r\n // Dependencies Plugin\r\n// Removed Stub for Initialization.prototype.trackDependencyData.\r\n // Misc\r\n// Removed Stub for Initialization.prototype.flush.\r\n// Removed Stub for Initialization.prototype.onunloadFlush.\r\n// Removed Stub for Initialization.prototype.loadAppInsights.\r\n// Removed Stub for Initialization.prototype.updateSnippetDefinitions.\r\n// Removed Stub for Initialization.prototype.emptyQueue.\r\n// Removed Stub for Initialization.prototype.pollInternalLogs.\r\n// Removed Stub for Initialization.prototype.stopPollingInternalLogs.\r\n// Removed Stub for Initialization.prototype.addHousekeepingBeforeUnload.\r\n// Removed Stub for Initialization.prototype.getSender.\r\n// Removed Stub for Initialization.prototype.unload.\r\n// Removed Stub for Initialization.prototype.getPlugin.\r\n// Removed Stub for Initialization.prototype.addPlugin.\r\n// Removed Stub for Initialization.prototype.evtNamespace.\r\n// Removed Stub for Initialization.prototype.addUnloadCb.\r\n// Removed Stub for Initialization.prototype.addDependencyListener.\r\n /**\r\n * Add an dependency telemetry initializer callback function to allow populating additional properties or drop the request.\r\n * It is called after the dependency call has completed and any available performance details are available. A dependency\r\n * initializer is similar to the TelemetryInitializer function but it allows you to block the reporting of the dependency\r\n * request so that it doesn't count against the `maxAjaxCallsPerView`.\r\n * @param dependencyInitializer - The Dependency Telemetry Initializer function\r\n * @returns - A IDependencyInitializerHandler to enable the initializer to be removed\r\n */\r\n Initialization.prototype.addDependencyInitializer = function (dependencyInitializer) {\r\n return null;\r\n };\r\n// Removed Stub for Initialization.prototype.getTraceCtx.\r\n return Initialization;\r\n}());\r\nexport { Initialization };\r\n// tslint:disable-next-line\r\n(function () {\r\n var sdkSrc = null;\r\n var isModule = false;\r\n var cdns = [\r\n \"://js.monitor.azure.com/\",\r\n \"://az416426.vo.msecnd.net/\"\r\n ];\r\n try {\r\n // Try and determine whether the sdk is being loaded from the CDN\r\n // currentScript is only valid during initial processing\r\n var scrpt = (document || {}).currentScript;\r\n if (scrpt) {\r\n sdkSrc = scrpt.src;\r\n // } else {\r\n // // We need to update to at least typescript 2.9 for this to work :-(\r\n // // Leaving as a stub for now so after we upgrade this breadcrumb is available\r\n // let meta = import.meta;\r\n // sdkSrc = (meta || {}).url;\r\n // isModule = true;\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n if (sdkSrc) {\r\n try {\r\n var url = sdkSrc.toLowerCase();\r\n if (url) {\r\n var src = \"\";\r\n for (var idx = 0; idx < cdns.length; idx++) {\r\n if (url[_DYN_INDEX_OF /* @min:%2eindexOf */](cdns[idx]) !== -1) {\r\n src = \"cdn\" + (idx + 1);\r\n if (url[_DYN_INDEX_OF /* @min:%2eindexOf */](\"/scripts/\") === -1) {\r\n if (url[_DYN_INDEX_OF /* @min:%2eindexOf */](\"/next/\") !== -1) {\r\n src += \"-next\";\r\n }\r\n else if (url[_DYN_INDEX_OF /* @min:%2eindexOf */](\"/beta/\") !== -1) {\r\n src += \"-beta\";\r\n }\r\n }\r\n _internalSdkSrc = src + (isModule ? \".mod\" : \"\");\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n }\r\n})();\r\n","/*\n * Application Insights JavaScript SDK - Web, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)\r\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\r\nvar _AUTHENTICATED_USER_CONTEXT = \"AuthenticatedUserContext\";\r\nvar _TRACK = \"track\";\r\nexport var STR_EMPTY = \"\";\r\nexport var STR_SNIPPET = \"snippet\";\r\nexport var STR_GET_COOKIE_MGR = \"getCookieMgr\";\r\nexport var STR_START_TRACK_PAGE = \"startTrackPage\";\r\nexport var STR_STOP_TRACK_PAGE = \"stopTrackPage\";\r\nexport var STR_FLUSH = \"flush\";\r\nexport var STR_START_TRACK_EVENT = \"startTrackEvent\";\r\nexport var STR_STOP_TRACK_EVENT = \"stopTrackEvent\";\r\nexport var STR_ADD_TELEMETRY_INITIALIZER = \"addTelemetryInitializer\";\r\nexport var STR_ADD_TELEMETRY_INITIALIZERS = STR_ADD_TELEMETRY_INITIALIZER + \"s\";\r\nexport var STR_POLL_INTERNAL_LOGS = \"pollInternalLogs\";\r\nexport var STR_GET_PLUGIN = \"getPlugin\";\r\nexport var STR_EVT_NAMESPACE = \"evtNamespace\";\r\nexport var STR_TRACK_EVENT = _TRACK + \"Event\";\r\nexport var STR_TRACK_TRACE = _TRACK + \"Trace\";\r\nexport var STR_TRACK_METRIC = _TRACK + \"Metric\";\r\nexport var STR_TRACK_PAGE_VIEW = _TRACK + \"PageView\";\r\nexport var STR_TRACK_EXCEPTION = _TRACK + \"Exception\";\r\nexport var STR_TRACK_DEPENDENCY_DATA = _TRACK + \"DependencyData\";\r\nexport var STR_SET_AUTHENTICATED_USER_CONTEXT = \"set\" + _AUTHENTICATED_USER_CONTEXT;\r\nexport var STR_CLEAR_AUTHENTICATED_USER_CONTEXT = \"clear\" + _AUTHENTICATED_USER_CONTEXT;\r\n","/*\n * Application Insights JavaScript SDK - Web, 2.8.11\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\r\n\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_UPDATE_SNIPPET_DEFIN0 = \"updateSnippetDefinitions\"; // Count: 4\r\nexport var _DYN_LOAD_APP_INSIGHTS = \"loadAppInsights\"; // Count: 4\r\nexport var _DYN_ENDPOINT_URL = \"endpointUrl\"; // Count: 4\r\nexport var _DYN_MAX_BATCH_SIZE_IN_BY1 = \"maxBatchSizeInBytes\"; // Count: 3\r\nexport var _DYN_MAX_BATCH_INTERVAL = \"maxBatchInterval\"; // Count: 3\r\nexport var _DYN_DISABLE_EXCEPTION_TR2 = \"disableExceptionTracking\"; // Count: 2\r\nexport var _DYN_DISABLE_TELEMETRY = \"disableTelemetry\"; // Count: 2\r\nexport var _DYN_EMIT_LINE_DELIMITED_3 = \"emitLineDelimitedJson\"; // Count: 2\r\nexport var _DYN_DIAGNOSTIC_LOG_INTER4 = \"diagnosticLogInterval\"; // Count: 6\r\nexport var _DYN_AUTO_TRACK_PAGE_VISI5 = \"autoTrackPageVisitTime\"; // Count: 2\r\nexport var _DYN_SAMPLING_PERCENTAGE = \"samplingPercentage\"; // Count: 4\r\nexport var _DYN_DISABLE_AJAX_TRACKIN6 = \"disableAjaxTracking\"; // Count: 2\r\nexport var _DYN_MAX_AJAX_CALLS_PER_V7 = \"maxAjaxCallsPerView\"; // Count: 3\r\nexport var _DYN_IS_BEACON_API_DISABL8 = \"isBeaconApiDisabled\"; // Count: 2\r\nexport var _DYN_DISABLE_CORRELATION_9 = \"disableCorrelationHeaders\"; // Count: 2\r\nexport var _DYN_CORRELATION_HEADER_E10 = \"correlationHeaderExcludedDomains\"; // Count: 2\r\nexport var _DYN_DISABLE_FLUSH_ON_BEF11 = \"disableFlushOnBeforeUnload\"; // Count: 4\r\nexport var _DYN_DISABLE_FLUSH_ON_UNL12 = \"disableFlushOnUnload\"; // Count: 3\r\nexport var _DYN_ENABLE_SESSION_STORA13 = \"enableSessionStorageBuffer\"; // Count: 2\r\nexport var _DYN_IS_COOKIE_USE_DISABL14 = \"isCookieUseDisabled\"; // Count: 2\r\nexport var _DYN_IS_STORAGE_USE_DISAB15 = \"isStorageUseDisabled\"; // Count: 2\r\nexport var _DYN_IS_BROWSER_LINK_TRAC16 = \"isBrowserLinkTrackingEnabled\"; // Count: 2\r\nexport var _DYN_ENABLE_CORS_CORRELAT17 = \"enableCorsCorrelation\"; // Count: 2\r\nexport var _DYN_CONFIG = \"config\"; // Count: 6\r\nexport var _DYN_CONTEXT = \"context\"; // Count: 8\r\nexport var _DYN_PUSH = \"push\"; // Count: 5\r\nexport var _DYN_VERSION = \"version\"; // Count: 6\r\nexport var _DYN_QUEUE = \"queue\"; // Count: 6\r\nexport var _DYN_CONNECTION_STRING = \"connectionString\"; // Count: 3\r\nexport var _DYN_INSTRUMENTATION_KEY = \"instrumentationKey\"; // Count: 2\r\nexport var _DYN_APP_INSIGHTS = \"appInsights\"; // Count: 3\r\nexport var _DYN_DISABLE_IKEY_DEPRECA18 = \"disableIkeyDeprecationMessage\"; // Count: 2\r\nexport var _DYN_GET_TRANSMISSION_CON19 = \"getTransmissionControls\"; // Count: 2\r\nexport var _DYN_ONUNLOAD_FLUSH = \"onunloadFlush\"; // Count: 6\r\nexport var _DYN_ADD_HOUSEKEEPING_BEF20 = \"addHousekeepingBeforeUnload\"; // Count: 2\r\nexport var _DYN_INDEX_OF = \"indexOf\"; // Count: 4\r\n","/*!\n * Microsoft Dynamic Proto Utility, 1.1.8\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nvar _a;\r\nvar UNDEFINED = \"undefined\";\r\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\r\nvar Constructor = 'constructor';\r\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\r\nvar Prototype = 'prototype';\r\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\r\nvar strFunction = 'function';\r\n/**\r\n * Used to define the name of the instance function lookup table\r\n * @ignore\r\n */\r\nvar DynInstFuncTable = '_dynInstFuncs';\r\n/**\r\n * Name used to tag the dynamic prototype function\r\n * @ignore\r\n */\r\nvar DynProxyTag = '_isDynProxy';\r\n/**\r\n * Name added to a prototype to define the dynamic prototype \"class\" name used to lookup the function table\r\n * @ignore\r\n */\r\nvar DynClassName = '_dynClass';\r\n/**\r\n * Prefix added to the classname to avoid any name clashes with other instance level properties\r\n * @ignore\r\n */\r\nvar DynClassNamePrefix = '_dynCls$';\r\n/**\r\n * A tag which is used to check if we have already to attempted to set the instance function if one is not present\r\n * @ignore\r\n */\r\nvar DynInstChkTag = '_dynInstChk';\r\n/**\r\n * A tag which is used to check if we are allows to try and set an instance function is one is not present. Using the same\r\n * tag name as the function level but a different const name for readability only.\r\n */\r\nvar DynAllowInstChkTag = DynInstChkTag;\r\n/**\r\n * The global (imported) instances where the global performance options are stored\r\n */\r\nvar DynProtoDefaultOptions = '_dfOpts';\r\n/**\r\n * Value used as the name of a class when it cannot be determined\r\n * @ignore\r\n */\r\nvar UnknownValue = '_unknown_';\r\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\r\nvar str__Proto = \"__proto__\";\r\n/**\r\n * The polyfill version of __proto__ so that it doesn't cause issues for anyone not expecting it to exist\r\n */\r\nvar DynProtoBaseProto = \"_dyn\" + str__Proto;\r\n/**\r\n * Runtime Global holder for dynamicProto settings\r\n */\r\nvar DynProtoGlobalSettings = \"__dynProto$Gbl\";\r\n/**\r\n * Track the current prototype for IE8 as you can't look back to get the prototype\r\n */\r\nvar DynProtoCurrent = \"_dynInstProto\";\r\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\r\nvar strUseBaseInst = 'useBaseInst';\r\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\r\nvar strSetInstFuncs = 'setInstFuncs';\r\nvar Obj = Object;\r\n/**\r\n * Pre-lookup to check if we are running on a modern browser (i.e. not IE8)\r\n * @ignore\r\n */\r\nvar _objGetPrototypeOf = Obj[\"getPrototypeOf\"];\r\n/**\r\n * Pre-lookup to check for the existence of this function\r\n */\r\nvar _objGetOwnProps = Obj[\"getOwnPropertyNames\"];\r\n/**\r\n * Gets the runtime global reference\r\n * @returns\r\n */\r\nfunction _getGlobal() {\r\n var result;\r\n if (typeof globalThis !== UNDEFINED) {\r\n result = globalThis;\r\n }\r\n if (!result && typeof self !== UNDEFINED) {\r\n result = self;\r\n }\r\n if (!result && typeof window !== UNDEFINED) {\r\n result = window;\r\n }\r\n if (!result && typeof global !== UNDEFINED) {\r\n result = global;\r\n }\r\n return result || {};\r\n}\r\n// Since 1.1.7 moving these to the runtime global to work around mixed version and module issues\r\n// See Issue https://github.com/microsoft/DynamicProto-JS/issues/57 for details\r\nvar _gbl = _getGlobal();\r\nvar _gblInst = _gbl[DynProtoGlobalSettings] || (_gbl[DynProtoGlobalSettings] = {\r\n o: (_a = {},\r\n _a[strSetInstFuncs] = true,\r\n _a[strUseBaseInst] = true,\r\n _a),\r\n n: 1000 // Start new global index @ 1000 so we \"fix\" some cases when mixed with 1.1.6 or earlier\r\n});\r\n/**\r\n * Helper to check if the object contains a property of the name\r\n * @ignore\r\n */\r\nfunction _hasOwnProperty(obj, prop) {\r\n return obj && Obj[Prototype].hasOwnProperty.call(obj, prop);\r\n}\r\n/**\r\n * Helper used to check whether the target is an Object prototype or Array prototype\r\n * @ignore\r\n */\r\nfunction _isObjectOrArrayPrototype(target) {\r\n return target && (target === Obj[Prototype] || target === Array[Prototype]);\r\n}\r\n/**\r\n * Helper used to check whether the target is an Object prototype, Array prototype or Function prototype\r\n * @ignore\r\n */\r\nfunction _isObjectArrayOrFunctionPrototype(target) {\r\n return _isObjectOrArrayPrototype(target) || target === Function[Prototype];\r\n}\r\n/**\r\n * Helper used to get the prototype of the target object as getPrototypeOf is not available in an ES3 environment.\r\n * @ignore\r\n */\r\nfunction _getObjProto(target) {\r\n var newProto;\r\n if (target) {\r\n // This method doesn't exist in older browsers (e.g. IE8)\r\n if (_objGetPrototypeOf) {\r\n return _objGetPrototypeOf(target);\r\n }\r\n var curProto = target[str__Proto] || target[Prototype] || (target[Constructor] ? target[Constructor][Prototype] : null);\r\n // Using the pre-calculated value as IE8 doesn't support looking up the prototype of a prototype and thus fails for more than 1 base class\r\n newProto = target[DynProtoBaseProto] || curProto;\r\n if (!_hasOwnProperty(target, DynProtoBaseProto)) {\r\n // As this prototype doesn't have this property then this is from an inherited class so newProto is the base to return so save it\r\n // so we can look it up value (which for a multiple hierarchy dynamicProto will be the base class)\r\n delete target[DynProtoCurrent]; // Delete any current value allocated to this instance so we pick up the value from prototype hierarchy\r\n newProto = target[DynProtoBaseProto] = target[DynProtoCurrent] || target[DynProtoBaseProto];\r\n target[DynProtoCurrent] = curProto;\r\n }\r\n }\r\n return newProto;\r\n}\r\n/**\r\n * Helper to get the properties of an object, including none enumerable ones as functions on a prototype in ES6\r\n * are not enumerable.\r\n * @param target\r\n */\r\nfunction _forEachProp(target, func) {\r\n var props = [];\r\n if (_objGetOwnProps) {\r\n props = _objGetOwnProps(target);\r\n }\r\n else {\r\n for (var name_1 in target) {\r\n if (typeof name_1 === \"string\" && _hasOwnProperty(target, name_1)) {\r\n props.push(name_1);\r\n }\r\n }\r\n }\r\n if (props && props.length > 0) {\r\n for (var lp = 0; lp < props.length; lp++) {\r\n func(props[lp]);\r\n }\r\n }\r\n}\r\n/**\r\n * Helper function to check whether the provided function name is a potential candidate for dynamic\r\n * callback and prototype generation.\r\n * @param target The target object, may be a prototype or class object\r\n * @param funcName The function name\r\n * @param skipOwn Skips the check for own property\r\n * @ignore\r\n */\r\nfunction _isDynamicCandidate(target, funcName, skipOwn) {\r\n return (funcName !== Constructor && typeof target[funcName] === strFunction && (skipOwn || _hasOwnProperty(target, funcName)));\r\n}\r\n/**\r\n * Helper to throw a TypeError exception\r\n * @param message the message\r\n * @ignore\r\n */\r\nfunction _throwTypeError(message) {\r\n throw new TypeError(\"DynamicProto: \" + message);\r\n}\r\n/**\r\n * Returns a collection of the instance functions that are defined directly on the thisTarget object, it does\r\n * not return any inherited functions\r\n * @param thisTarget The object to get the instance functions from\r\n * @ignore\r\n */\r\nfunction _getInstanceFuncs(thisTarget) {\r\n // Get the base proto\r\n var instFuncs = {};\r\n // Save any existing instance functions\r\n _forEachProp(thisTarget, function (name) {\r\n // Don't include any dynamic prototype instances - as we only want the real functions\r\n if (!instFuncs[name] && _isDynamicCandidate(thisTarget, name, false)) {\r\n // Create an instance callback for passing the base function to the caller\r\n instFuncs[name] = thisTarget[name];\r\n }\r\n });\r\n return instFuncs;\r\n}\r\n/**\r\n * Returns whether the value is included in the array\r\n * @param values The array of values\r\n * @param value The value\r\n */\r\nfunction _hasVisited(values, value) {\r\n for (var lp = values.length - 1; lp >= 0; lp--) {\r\n if (values[lp] === value) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\n/**\r\n * Returns an object that contains callback functions for all \"base/super\" functions, this is used to \"save\"\r\n * enabling calling super.xxx() functions without requiring that the base \"class\" has defined a prototype references\r\n * @param target The current instance\r\n * @ignore\r\n */\r\nfunction _getBaseFuncs(classProto, thisTarget, instFuncs, useBaseInst) {\r\n function _instFuncProxy(target, funcHost, funcName) {\r\n var theFunc = funcHost[funcName];\r\n if (theFunc[DynProxyTag] && useBaseInst) {\r\n // grab and reuse the hosted looking function (if available) otherwise the original passed function\r\n var instFuncTable = target[DynInstFuncTable] || {};\r\n if (instFuncTable[DynAllowInstChkTag] !== false) {\r\n theFunc = (instFuncTable[funcHost[DynClassName]] || {})[funcName] || theFunc;\r\n }\r\n }\r\n return function () {\r\n // eslint-disable-next-line prefer-rest-params\r\n return theFunc.apply(target, arguments);\r\n };\r\n }\r\n // Start creating a new baseFuncs by creating proxies for the instance functions (as they may get replaced)\r\n var baseFuncs = {};\r\n _forEachProp(instFuncs, function (name) {\r\n // Create an instance callback for passing the base function to the caller\r\n baseFuncs[name] = _instFuncProxy(thisTarget, instFuncs, name);\r\n });\r\n // Get the base prototype functions\r\n var baseProto = _getObjProto(classProto);\r\n var visited = [];\r\n // Don't include base object functions for Object, Array or Function\r\n while (baseProto && !_isObjectArrayOrFunctionPrototype(baseProto) && !_hasVisited(visited, baseProto)) {\r\n // look for prototype functions\r\n _forEachProp(baseProto, function (name) {\r\n // Don't include any dynamic prototype instances - as we only want the real functions\r\n // For IE 7/8 the prototype lookup doesn't provide the full chain so we need to bypass the \r\n // hasOwnProperty check we get all of the methods, main difference is that IE7/8 doesn't return\r\n // the Object prototype methods while bypassing the check\r\n if (!baseFuncs[name] && _isDynamicCandidate(baseProto, name, !_objGetPrototypeOf)) {\r\n // Create an instance callback for passing the base function to the caller\r\n baseFuncs[name] = _instFuncProxy(thisTarget, baseProto, name);\r\n }\r\n });\r\n // We need to find all possible functions that might be overloaded by walking the entire prototype chain\r\n // This avoids the caller from needing to check whether it's direct base class implements the function or not\r\n // by walking the entire chain it simplifies the usage and issues from upgrading any of the base classes.\r\n visited.push(baseProto);\r\n baseProto = _getObjProto(baseProto);\r\n }\r\n return baseFuncs;\r\n}\r\nfunction _getInstFunc(target, funcName, proto, currentDynProtoProxy) {\r\n var instFunc = null;\r\n // We need to check whether the class name is defined directly on this prototype otherwise\r\n // it will walk the proto chain and return any parent proto classname.\r\n if (target && _hasOwnProperty(proto, DynClassName)) {\r\n var instFuncTable = target[DynInstFuncTable] || {};\r\n instFunc = (instFuncTable[proto[DynClassName]] || {})[funcName];\r\n if (!instFunc) {\r\n // Avoid stack overflow from recursive calling the same function\r\n _throwTypeError(\"Missing [\" + funcName + \"] \" + strFunction);\r\n }\r\n // We have the instance function, lets check it we can speed up further calls\r\n // by adding the instance function back directly on the instance (avoiding the dynamic func lookup)\r\n if (!instFunc[DynInstChkTag] && instFuncTable[DynAllowInstChkTag] !== false) {\r\n // If the instance already has an instance function we can't replace it\r\n var canAddInst = !_hasOwnProperty(target, funcName);\r\n // Get current prototype\r\n var objProto = _getObjProto(target);\r\n var visited = [];\r\n // Lookup the function starting at the top (instance level prototype) and traverse down, if the first matching function\r\n // if nothing is found or if the first hit is a dynamic proto instance then we can safely add an instance shortcut\r\n while (canAddInst && objProto && !_isObjectArrayOrFunctionPrototype(objProto) && !_hasVisited(visited, objProto)) {\r\n var protoFunc = objProto[funcName];\r\n if (protoFunc) {\r\n canAddInst = (protoFunc === currentDynProtoProxy);\r\n break;\r\n }\r\n // We need to find all possible initial functions to ensure that we don't bypass a valid override function\r\n visited.push(objProto);\r\n objProto = _getObjProto(objProto);\r\n }\r\n try {\r\n if (canAddInst) {\r\n // This instance doesn't have an instance func and the class hierarchy does have a higher level prototype version\r\n // so it's safe to directly assign for any subsequent calls (for better performance)\r\n target[funcName] = instFunc;\r\n }\r\n // Block further attempts to set the instance function for any\r\n instFunc[DynInstChkTag] = 1;\r\n }\r\n catch (e) {\r\n // Don't crash if the object is readonly or the runtime doesn't allow changing this\r\n // And set a flag so we don't try again for any function\r\n instFuncTable[DynAllowInstChkTag] = false;\r\n }\r\n }\r\n }\r\n return instFunc;\r\n}\r\nfunction _getProtoFunc(funcName, proto, currentDynProtoProxy) {\r\n var protoFunc = proto[funcName];\r\n // Check that the prototype function is not a self reference -- try to avoid stack overflow!\r\n if (protoFunc === currentDynProtoProxy) {\r\n // It is so lookup the base prototype\r\n protoFunc = _getObjProto(proto)[funcName];\r\n }\r\n if (typeof protoFunc !== strFunction) {\r\n _throwTypeError(\"[\" + funcName + \"] is not a \" + strFunction);\r\n }\r\n return protoFunc;\r\n}\r\n/**\r\n * Add the required dynamic prototype methods to the the class prototype\r\n * @param proto - The class prototype\r\n * @param className - The instance classname\r\n * @param target - The target instance\r\n * @param baseInstFuncs - The base instance functions\r\n * @param setInstanceFunc - Flag to allow prototype function to reset the instance function if one does not exist\r\n * @ignore\r\n */\r\nfunction _populatePrototype(proto, className, target, baseInstFuncs, setInstanceFunc) {\r\n function _createDynamicPrototype(proto, funcName) {\r\n var dynProtoProxy = function () {\r\n // Use the instance or prototype function\r\n var instFunc = _getInstFunc(this, funcName, proto, dynProtoProxy) || _getProtoFunc(funcName, proto, dynProtoProxy);\r\n // eslint-disable-next-line prefer-rest-params\r\n return instFunc.apply(this, arguments);\r\n };\r\n // Tag this function as a proxy to support replacing dynamic proxy elements (primary use case is for unit testing\r\n // via which can dynamically replace the prototype function reference)\r\n dynProtoProxy[DynProxyTag] = 1;\r\n return dynProtoProxy;\r\n }\r\n if (!_isObjectOrArrayPrototype(proto)) {\r\n var instFuncTable = target[DynInstFuncTable] = target[DynInstFuncTable] || {};\r\n var instFuncs_1 = instFuncTable[className] = (instFuncTable[className] || {}); // fetch and assign if as it may not exist yet\r\n // Set whether we are allow to lookup instances, if someone has set to false then do not re-enable\r\n if (instFuncTable[DynAllowInstChkTag] !== false) {\r\n instFuncTable[DynAllowInstChkTag] = !!setInstanceFunc;\r\n }\r\n _forEachProp(target, function (name) {\r\n // Only add overridden functions\r\n if (_isDynamicCandidate(target, name, false) && target[name] !== baseInstFuncs[name]) {\r\n // Save the instance Function to the lookup table and remove it from the instance as it's not a dynamic proto function\r\n instFuncs_1[name] = target[name];\r\n delete target[name];\r\n // Add a dynamic proto if one doesn't exist or if a prototype function exists and it's not a dynamic one\r\n if (!_hasOwnProperty(proto, name) || (proto[name] && !proto[name][DynProxyTag])) {\r\n proto[name] = _createDynamicPrototype(proto, name);\r\n }\r\n }\r\n });\r\n }\r\n}\r\n/**\r\n * Checks whether the passed prototype object appears to be correct by walking the prototype hierarchy of the instance\r\n * @param classProto The class prototype instance\r\n * @param thisTarget The current instance that will be checked whether the passed prototype instance is in the hierarchy\r\n * @ignore\r\n */\r\nfunction _checkPrototype(classProto, thisTarget) {\r\n // This method doesn't existing in older browsers (e.g. IE8)\r\n if (_objGetPrototypeOf) {\r\n // As this is primarily a coding time check, don't bother checking if running in IE8 or lower\r\n var visited = [];\r\n var thisProto = _getObjProto(thisTarget);\r\n while (thisProto && !_isObjectArrayOrFunctionPrototype(thisProto) && !_hasVisited(visited, thisProto)) {\r\n if (thisProto === classProto) {\r\n return true;\r\n }\r\n // This avoids the caller from needing to check whether it's direct base class implements the function or not\r\n // by walking the entire chain it simplifies the usage and issues from upgrading any of the base classes.\r\n visited.push(thisProto);\r\n thisProto = _getObjProto(thisProto);\r\n }\r\n return false;\r\n }\r\n // If objGetPrototypeOf doesn't exist then just assume everything is ok.\r\n return true;\r\n}\r\n/**\r\n * Gets the current prototype name using the ES6 name if available otherwise falling back to a use unknown as the name.\r\n * It's not critical for this to return a name, it's used to decorate the generated unique name for easier debugging only.\r\n * @param target\r\n * @param unknownValue\r\n * @ignore\r\n */\r\nfunction _getObjName(target, unknownValue) {\r\n if (_hasOwnProperty(target, Prototype)) {\r\n // Look like a prototype\r\n return target.name || unknownValue || UnknownValue;\r\n }\r\n return (((target || {})[Constructor]) || {}).name || unknownValue || UnknownValue;\r\n}\r\n/**\r\n * Helper function when creating dynamic (inline) functions for classes, this helper performs the following tasks :-\r\n * - Saves references to all defined base class functions\r\n * - Calls the delegateFunc with the current target (this) and a base object reference that can be used to call all \"super\" functions.\r\n * - Will populate the class prototype for all overridden functions to support class extension that call the prototype instance.\r\n * Callers should use this helper when declaring all function within the constructor of a class, as mentioned above the delegateFunc is\r\n * passed both the target \"this\" and an object that can be used to call any base (super) functions, using this based object in place of\r\n * super.XXX() (which gets expanded to _super.prototype.XXX()) provides a better minification outcome and also ensures the correct \"this\"\r\n * context is maintained as TypeScript creates incorrect references using super.XXXX() for dynamically defined functions i.e. Functions\r\n * defined in the constructor or some other function (rather than declared as complete typescript functions).\r\n * ### Usage\r\n * ```typescript\r\n * import dynamicProto from \"@microsoft/dynamicproto-js\";\r\n * class ExampleClass extends BaseClass {\r\n * constructor() {\r\n * dynamicProto(ExampleClass, this, (_self, base) => {\r\n * // This will define a function that will be converted to a prototype function\r\n * _self.newFunc = () => {\r\n * // Access any \"this\" instance property\r\n * if (_self.someProperty) {\r\n * ...\r\n * }\r\n * }\r\n * // This will define a function that will be converted to a prototype function\r\n * _self.myFunction = () => {\r\n * // Access any \"this\" instance property\r\n * if (_self.someProperty) {\r\n * // Call the base version of the function that we are overriding\r\n * base.myFunction();\r\n * }\r\n * ...\r\n * }\r\n * _self.initialize = () => {\r\n * ...\r\n * }\r\n * // Warnings: While the following will work as _self is simply a reference to\r\n * // this, if anyone overrides myFunction() the overridden will be called first\r\n * // as the normal JavaScript method resolution will occur and the defined\r\n * // _self.initialize() function is actually gets removed from the instance and\r\n * // a proxy prototype version is created to reference the created method.\r\n * _self.initialize();\r\n * });\r\n * }\r\n * }\r\n * ```\r\n * @typeparam DPType This is the generic type of the class, used to keep intellisense valid\r\n * @typeparam DPCls The type that contains the prototype of the current class\r\n * @param theClass - This is the current class instance which contains the prototype for the current class\r\n * @param target - The current \"this\" (target) reference, when the class has been extended this.prototype will not be the 'theClass' value.\r\n * @param delegateFunc - The callback function (closure) that will create the dynamic function\r\n * @param options - Additional options to configure how the dynamic prototype operates\r\n */\r\nfunction dynamicProto(theClass, target, delegateFunc, options) {\r\n // Make sure that the passed theClass argument looks correct\r\n if (!_hasOwnProperty(theClass, Prototype)) {\r\n _throwTypeError(\"theClass is an invalid class definition.\");\r\n }\r\n // Quick check to make sure that the passed theClass argument looks correct (this is a common copy/paste error)\r\n var classProto = theClass[Prototype];\r\n if (!_checkPrototype(classProto, target)) {\r\n _throwTypeError(\"[\" + _getObjName(theClass) + \"] not in hierarchy of [\" + _getObjName(target) + \"]\");\r\n }\r\n var className = null;\r\n if (_hasOwnProperty(classProto, DynClassName)) {\r\n // Only grab the class name if it's defined on this prototype (i.e. don't walk the prototype chain)\r\n className = classProto[DynClassName];\r\n }\r\n else {\r\n // As not all browser support name on the prototype creating a unique dynamic one if we have not already\r\n // assigned one, so we can use a simple string as the lookup rather than an object for the dynamic instance\r\n // function table lookup.\r\n className = DynClassNamePrefix + _getObjName(theClass, \"_\") + \"$\" + _gblInst.n;\r\n _gblInst.n++;\r\n classProto[DynClassName] = className;\r\n }\r\n var perfOptions = dynamicProto[DynProtoDefaultOptions];\r\n var useBaseInst = !!perfOptions[strUseBaseInst];\r\n if (useBaseInst && options && options[strUseBaseInst] !== undefined) {\r\n useBaseInst = !!options[strUseBaseInst];\r\n }\r\n // Get the current instance functions\r\n var instFuncs = _getInstanceFuncs(target);\r\n // Get all of the functions for any base instance (before they are potentially overridden)\r\n var baseFuncs = _getBaseFuncs(classProto, target, instFuncs, useBaseInst);\r\n // Execute the delegate passing in both the current target \"this\" and \"base\" function references\r\n // Note casting the same type as we don't actually have the base class here and this will provide some intellisense support\r\n delegateFunc(target, baseFuncs);\r\n // Don't allow setting instance functions for older IE instances\r\n var setInstanceFunc = !!_objGetPrototypeOf && !!perfOptions[strSetInstFuncs];\r\n if (setInstanceFunc && options) {\r\n setInstanceFunc = !!options[strSetInstFuncs];\r\n }\r\n // Populate the Prototype for any overridden instance functions\r\n _populatePrototype(classProto, className, target, instFuncs, setInstanceFunc !== false);\r\n}\r\n/**\r\n * Exposes the default global options to allow global configuration, if the global values are disabled these will override\r\n * any passed values. This is primarily exposed to support unit-testing without the need for individual classes to expose\r\n * their internal usage of dynamic proto.\r\n */\r\ndynamicProto[DynProtoDefaultOptions] = _gblInst.o;\n\nexport { dynamicProto as default };\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController\r\n// We don't actually ever use the API being polyfilled, we always use the polyfill because\r\n// it's a very new API right now.\r\n// Not exported from index.\r\n/** @private */\r\nexport class AbortController {\r\n constructor() {\r\n this._isAborted = false;\r\n this.onabort = null;\r\n }\r\n abort() {\r\n if (!this._isAborted) {\r\n this._isAborted = true;\r\n if (this.onabort) {\r\n this.onabort();\r\n }\r\n }\r\n }\r\n get signal() {\r\n return this;\r\n }\r\n get aborted() {\r\n return this._isAborted;\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { AbortError } from \"./Errors\";\r\nimport { FetchHttpClient } from \"./FetchHttpClient\";\r\nimport { HttpClient } from \"./HttpClient\";\r\nimport { Platform } from \"./Utils\";\r\nimport { XhrHttpClient } from \"./XhrHttpClient\";\r\n/** Default implementation of {@link @microsoft/signalr.HttpClient}. */\r\nexport class DefaultHttpClient extends HttpClient {\r\n /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */\r\n constructor(logger) {\r\n super();\r\n if (typeof fetch !== \"undefined\" || Platform.isNode) {\r\n this._httpClient = new FetchHttpClient(logger);\r\n }\r\n else if (typeof XMLHttpRequest !== \"undefined\") {\r\n this._httpClient = new XhrHttpClient(logger);\r\n }\r\n else {\r\n throw new Error(\"No usable HttpClient found.\");\r\n }\r\n }\r\n /** @inheritDoc */\r\n send(request) {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n return Promise.reject(new AbortError());\r\n }\r\n if (!request.method) {\r\n return Promise.reject(new Error(\"No method defined.\"));\r\n }\r\n if (!request.url) {\r\n return Promise.reject(new Error(\"No url defined.\"));\r\n }\r\n return this._httpClient.send(request);\r\n }\r\n getCookieString(url) {\r\n return this._httpClient.getCookieString(url);\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n// 0, 2, 10, 30 second delays before reconnect attempts.\r\nconst DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];\r\n/** @private */\r\nexport class DefaultReconnectPolicy {\r\n constructor(retryDelays) {\r\n this._retryDelays = retryDelays !== undefined ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;\r\n }\r\n nextRetryDelayInMilliseconds(retryContext) {\r\n return this._retryDelays[retryContext.previousRetryCount];\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n/** Error thrown when an HTTP request fails. */\r\nexport class HttpError extends Error {\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n * @param {number} statusCode The HTTP status code represented by this error.\r\n */\r\n constructor(errorMessage, statusCode) {\r\n const trueProto = new.target.prototype;\r\n super(`${errorMessage}: Status code '${statusCode}'`);\r\n this.statusCode = statusCode;\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when a timeout elapses. */\r\nexport class TimeoutError extends Error {\r\n /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage = \"A timeout occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when an action is aborted. */\r\nexport class AbortError extends Error {\r\n /** Constructs a new instance of {@link AbortError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage = \"An abort occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when the selected transport is unsupported by the browser. */\r\n/** @private */\r\nexport class UnsupportedTransportError extends Error {\r\n /** Constructs a new instance of {@link @microsoft/signalr.UnsupportedTransportError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occured on.\r\n */\r\n constructor(message, transport) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.transport = transport;\r\n this.errorType = 'UnsupportedTransportError';\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when the selected transport is disabled by the browser. */\r\n/** @private */\r\nexport class DisabledTransportError extends Error {\r\n /** Constructs a new instance of {@link @microsoft/signalr.DisabledTransportError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occured on.\r\n */\r\n constructor(message, transport) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.transport = transport;\r\n this.errorType = 'DisabledTransportError';\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when the selected transport cannot be started. */\r\n/** @private */\r\nexport class FailedToStartTransportError extends Error {\r\n /** Constructs a new instance of {@link @microsoft/signalr.FailedToStartTransportError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occured on.\r\n */\r\n constructor(message, transport) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.transport = transport;\r\n this.errorType = 'FailedToStartTransportError';\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when the negotiation with the server failed to complete. */\r\n/** @private */\r\nexport class FailedToNegotiateWithServerError extends Error {\r\n /** Constructs a new instance of {@link @microsoft/signalr.FailedToNegotiateWithServerError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n */\r\n constructor(message) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.errorType = 'FailedToNegotiateWithServerError';\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when multiple errors have occured. */\r\n/** @private */\r\nexport class AggregateErrors extends Error {\r\n /** Constructs a new instance of {@link @microsoft/signalr.AggregateErrors}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {Error[]} innerErrors The collection of errors this error is aggregating.\r\n */\r\n constructor(message, innerErrors) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.innerErrors = innerErrors;\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { AbortError, HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpResponse } from \"./HttpClient\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { Platform, getGlobalThis } from \"./Utils\";\r\nexport class FetchHttpClient extends HttpClient {\r\n constructor(logger) {\r\n super();\r\n this._logger = logger;\r\n if (typeof fetch === \"undefined\") {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n // Cookies aren't automatically handled in Node so we need to add a CookieJar to preserve cookies across requests\r\n this._jar = new (requireFunc(\"tough-cookie\")).CookieJar();\r\n this._fetchType = requireFunc(\"node-fetch\");\r\n // node-fetch doesn't have a nice API for getting and setting cookies\r\n // fetch-cookie will wrap a fetch implementation with a default CookieJar or a provided one\r\n this._fetchType = requireFunc(\"fetch-cookie\")(this._fetchType, this._jar);\r\n }\r\n else {\r\n this._fetchType = fetch.bind(getGlobalThis());\r\n }\r\n if (typeof AbortController === \"undefined\") {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n // Node needs EventListener methods on AbortController which our custom polyfill doesn't provide\r\n this._abortControllerType = requireFunc(\"abort-controller\");\r\n }\r\n else {\r\n this._abortControllerType = AbortController;\r\n }\r\n }\r\n /** @inheritDoc */\r\n async send(request) {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n throw new AbortError();\r\n }\r\n if (!request.method) {\r\n throw new Error(\"No method defined.\");\r\n }\r\n if (!request.url) {\r\n throw new Error(\"No url defined.\");\r\n }\r\n const abortController = new this._abortControllerType();\r\n let error;\r\n // Hook our abortSignal into the abort controller\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = () => {\r\n abortController.abort();\r\n error = new AbortError();\r\n };\r\n }\r\n // If a timeout has been passed in, setup a timeout to call abort\r\n // Type needs to be any to fit window.setTimeout and NodeJS.setTimeout\r\n let timeoutId = null;\r\n if (request.timeout) {\r\n const msTimeout = request.timeout;\r\n timeoutId = setTimeout(() => {\r\n abortController.abort();\r\n this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);\r\n error = new TimeoutError();\r\n }, msTimeout);\r\n }\r\n let response;\r\n try {\r\n response = await this._fetchType(request.url, {\r\n body: request.content,\r\n cache: \"no-cache\",\r\n credentials: request.withCredentials === true ? \"include\" : \"same-origin\",\r\n headers: {\r\n \"Content-Type\": \"text/plain;charset=UTF-8\",\r\n \"X-Requested-With\": \"XMLHttpRequest\",\r\n ...request.headers,\r\n },\r\n method: request.method,\r\n mode: \"cors\",\r\n redirect: \"follow\",\r\n signal: abortController.signal,\r\n });\r\n }\r\n catch (e) {\r\n if (error) {\r\n throw error;\r\n }\r\n this._logger.log(LogLevel.Warning, `Error from HTTP request. ${e}.`);\r\n throw e;\r\n }\r\n finally {\r\n if (timeoutId) {\r\n clearTimeout(timeoutId);\r\n }\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = null;\r\n }\r\n }\r\n if (!response.ok) {\r\n const errorMessage = await deserializeContent(response, \"text\");\r\n throw new HttpError(errorMessage || response.statusText, response.status);\r\n }\r\n const content = deserializeContent(response, request.responseType);\r\n const payload = await content;\r\n return new HttpResponse(response.status, response.statusText, payload);\r\n }\r\n getCookieString(url) {\r\n let cookies = \"\";\r\n if (Platform.isNode && this._jar) {\r\n // @ts-ignore: unused variable\r\n this._jar.getCookies(url, (e, c) => cookies = c.join(\"; \"));\r\n }\r\n return cookies;\r\n }\r\n}\r\nfunction deserializeContent(response, responseType) {\r\n let content;\r\n switch (responseType) {\r\n case \"arraybuffer\":\r\n content = response.arrayBuffer();\r\n break;\r\n case \"text\":\r\n content = response.text();\r\n break;\r\n case \"blob\":\r\n case \"document\":\r\n case \"json\":\r\n throw new Error(`${responseType} is not supported.`);\r\n default:\r\n content = response.text();\r\n break;\r\n }\r\n return content;\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { TextMessageFormat } from \"./TextMessageFormat\";\r\nimport { isArrayBuffer } from \"./Utils\";\r\n/** @private */\r\nexport class HandshakeProtocol {\r\n // Handshake request is always JSON\r\n writeHandshakeRequest(handshakeRequest) {\r\n return TextMessageFormat.write(JSON.stringify(handshakeRequest));\r\n }\r\n parseHandshakeResponse(data) {\r\n let messageData;\r\n let remainingData;\r\n if (isArrayBuffer(data)) {\r\n // Format is binary but still need to read JSON text from handshake response\r\n const binaryData = new Uint8Array(data);\r\n const separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);\r\n if (separatorIndex === -1) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n // content before separator is handshake response\r\n // optional content after is additional messages\r\n const responseLength = separatorIndex + 1;\r\n messageData = String.fromCharCode.apply(null, Array.prototype.slice.call(binaryData.slice(0, responseLength)));\r\n remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;\r\n }\r\n else {\r\n const textData = data;\r\n const separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);\r\n if (separatorIndex === -1) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n // content before separator is handshake response\r\n // optional content after is additional messages\r\n const responseLength = separatorIndex + 1;\r\n messageData = textData.substring(0, responseLength);\r\n remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;\r\n }\r\n // At this point we should have just the single handshake message\r\n const messages = TextMessageFormat.parse(messageData);\r\n const response = JSON.parse(messages[0]);\r\n if (response.type) {\r\n throw new Error(\"Expected a handshake response from the server.\");\r\n }\r\n const responseMessage = response;\r\n // multiple messages could have arrived with handshake\r\n // return additional data to be parsed as usual, or null if all parsed\r\n return [remainingData, responseMessage];\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nexport class HeaderNames {\r\n}\r\nHeaderNames.Authorization = \"Authorization\";\r\nHeaderNames.Cookie = \"Cookie\";\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n/** Represents an HTTP response. */\r\nexport class HttpResponse {\r\n constructor(statusCode, statusText, content) {\r\n this.statusCode = statusCode;\r\n this.statusText = statusText;\r\n this.content = content;\r\n }\r\n}\r\n/** Abstraction over an HTTP client.\r\n *\r\n * This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms.\r\n */\r\nexport class HttpClient {\r\n get(url, options) {\r\n return this.send({\r\n ...options,\r\n method: \"GET\",\r\n url,\r\n });\r\n }\r\n post(url, options) {\r\n return this.send({\r\n ...options,\r\n method: \"POST\",\r\n url,\r\n });\r\n }\r\n delete(url, options) {\r\n return this.send({\r\n ...options,\r\n method: \"DELETE\",\r\n url,\r\n });\r\n }\r\n /** Gets all cookies that apply to the specified URL.\r\n *\r\n * @param url The URL that the cookies are valid for.\r\n * @returns {string} A string containing all the key-value cookie pairs for the specified URL.\r\n */\r\n // @ts-ignore\r\n getCookieString(url) {\r\n return \"\";\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { DefaultHttpClient } from \"./DefaultHttpClient\";\r\nimport { AggregateErrors, DisabledTransportError, FailedToNegotiateWithServerError, FailedToStartTransportError, HttpError, UnsupportedTransportError } from \"./Errors\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { HttpTransportType, TransferFormat } from \"./ITransport\";\r\nimport { LongPollingTransport } from \"./LongPollingTransport\";\r\nimport { ServerSentEventsTransport } from \"./ServerSentEventsTransport\";\r\nimport { Arg, createLogger, getUserAgentHeader, Platform } from \"./Utils\";\r\nimport { WebSocketTransport } from \"./WebSocketTransport\";\r\nconst MAX_REDIRECTS = 100;\r\n/** @private */\r\nexport class HttpConnection {\r\n constructor(url, options = {}) {\r\n this._stopPromiseResolver = () => { };\r\n this.features = {};\r\n this._negotiateVersion = 1;\r\n Arg.isRequired(url, \"url\");\r\n this._logger = createLogger(options.logger);\r\n this.baseUrl = this._resolveUrl(url);\r\n options = options || {};\r\n options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent;\r\n if (typeof options.withCredentials === \"boolean\" || options.withCredentials === undefined) {\r\n options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials;\r\n }\r\n else {\r\n throw new Error(\"withCredentials option was not a 'boolean' or 'undefined' value\");\r\n }\r\n options.timeout = options.timeout === undefined ? 100 * 1000 : options.timeout;\r\n let webSocketModule = null;\r\n let eventSourceModule = null;\r\n if (Platform.isNode && typeof require !== \"undefined\") {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n webSocketModule = requireFunc(\"ws\");\r\n eventSourceModule = requireFunc(\"eventsource\");\r\n }\r\n if (!Platform.isNode && typeof WebSocket !== \"undefined\" && !options.WebSocket) {\r\n options.WebSocket = WebSocket;\r\n }\r\n else if (Platform.isNode && !options.WebSocket) {\r\n if (webSocketModule) {\r\n options.WebSocket = webSocketModule;\r\n }\r\n }\r\n if (!Platform.isNode && typeof EventSource !== \"undefined\" && !options.EventSource) {\r\n options.EventSource = EventSource;\r\n }\r\n else if (Platform.isNode && !options.EventSource) {\r\n if (typeof eventSourceModule !== \"undefined\") {\r\n options.EventSource = eventSourceModule;\r\n }\r\n }\r\n this._httpClient = options.httpClient || new DefaultHttpClient(this._logger);\r\n this._connectionState = \"Disconnected\" /* Disconnected */;\r\n this._connectionStarted = false;\r\n this._options = options;\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n async start(transferFormat) {\r\n transferFormat = transferFormat || TransferFormat.Binary;\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n this._logger.log(LogLevel.Debug, `Starting connection with transfer format '${TransferFormat[transferFormat]}'.`);\r\n if (this._connectionState !== \"Disconnected\" /* Disconnected */) {\r\n return Promise.reject(new Error(\"Cannot start an HttpConnection that is not in the 'Disconnected' state.\"));\r\n }\r\n this._connectionState = \"Connecting\" /* Connecting */;\r\n this._startInternalPromise = this._startInternal(transferFormat);\r\n await this._startInternalPromise;\r\n // The TypeScript compiler thinks that connectionState must be Connecting here. The TypeScript compiler is wrong.\r\n if (this._connectionState === \"Disconnecting\" /* Disconnecting */) {\r\n // stop() was called and transitioned the client into the Disconnecting state.\r\n const message = \"Failed to start the HttpConnection before stop() was called.\";\r\n this._logger.log(LogLevel.Error, message);\r\n // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.\r\n await this._stopPromise;\r\n return Promise.reject(new Error(message));\r\n }\r\n else if (this._connectionState !== \"Connected\" /* Connected */) {\r\n // stop() was called and transitioned the client into the Disconnecting state.\r\n const message = \"HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!\";\r\n this._logger.log(LogLevel.Error, message);\r\n return Promise.reject(new Error(message));\r\n }\r\n this._connectionStarted = true;\r\n }\r\n send(data) {\r\n if (this._connectionState !== \"Connected\" /* Connected */) {\r\n return Promise.reject(new Error(\"Cannot send data if the connection is not in the 'Connected' State.\"));\r\n }\r\n if (!this._sendQueue) {\r\n this._sendQueue = new TransportSendQueue(this.transport);\r\n }\r\n // Transport will not be null if state is connected\r\n return this._sendQueue.send(data);\r\n }\r\n async stop(error) {\r\n if (this._connectionState === \"Disconnected\" /* Disconnected */) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnected state.`);\r\n return Promise.resolve();\r\n }\r\n if (this._connectionState === \"Disconnecting\" /* Disconnecting */) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);\r\n return this._stopPromise;\r\n }\r\n this._connectionState = \"Disconnecting\" /* Disconnecting */;\r\n this._stopPromise = new Promise((resolve) => {\r\n // Don't complete stop() until stopConnection() completes.\r\n this._stopPromiseResolver = resolve;\r\n });\r\n // stopInternal should never throw so just observe it.\r\n await this._stopInternal(error);\r\n await this._stopPromise;\r\n }\r\n async _stopInternal(error) {\r\n // Set error as soon as possible otherwise there is a race between\r\n // the transport closing and providing an error and the error from a close message\r\n // We would prefer the close message error.\r\n this._stopError = error;\r\n try {\r\n await this._startInternalPromise;\r\n }\r\n catch (e) {\r\n // This exception is returned to the user as a rejected Promise from the start method.\r\n }\r\n // The transport's onclose will trigger stopConnection which will run our onclose event.\r\n // The transport should always be set if currently connected. If it wasn't set, it's likely because\r\n // stop was called during start() and start() failed.\r\n if (this.transport) {\r\n try {\r\n await this.transport.stop();\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `HttpConnection.transport.stop() threw error '${e}'.`);\r\n this._stopConnection();\r\n }\r\n this.transport = undefined;\r\n }\r\n else {\r\n this._logger.log(LogLevel.Debug, \"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.\");\r\n }\r\n }\r\n async _startInternal(transferFormat) {\r\n // Store the original base url and the access token factory since they may change\r\n // as part of negotiating\r\n let url = this.baseUrl;\r\n this._accessTokenFactory = this._options.accessTokenFactory;\r\n try {\r\n if (this._options.skipNegotiation) {\r\n if (this._options.transport === HttpTransportType.WebSockets) {\r\n // No need to add a connection ID in this case\r\n this.transport = this._constructTransport(HttpTransportType.WebSockets);\r\n // We should just call connect directly in this case.\r\n // No fallback or negotiate in this case.\r\n await this._startTransport(url, transferFormat);\r\n }\r\n else {\r\n throw new Error(\"Negotiation can only be skipped when using the WebSocket transport directly.\");\r\n }\r\n }\r\n else {\r\n let negotiateResponse = null;\r\n let redirects = 0;\r\n do {\r\n negotiateResponse = await this._getNegotiationResponse(url);\r\n // the user tries to stop the connection when it is being started\r\n if (this._connectionState === \"Disconnecting\" /* Disconnecting */ || this._connectionState === \"Disconnected\" /* Disconnected */) {\r\n throw new Error(\"The connection was stopped during negotiation.\");\r\n }\r\n if (negotiateResponse.error) {\r\n throw new Error(negotiateResponse.error);\r\n }\r\n if (negotiateResponse.ProtocolVersion) {\r\n throw new Error(\"Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.\");\r\n }\r\n if (negotiateResponse.url) {\r\n url = negotiateResponse.url;\r\n }\r\n if (negotiateResponse.accessToken) {\r\n // Replace the current access token factory with one that uses\r\n // the returned access token\r\n const accessToken = negotiateResponse.accessToken;\r\n this._accessTokenFactory = () => accessToken;\r\n }\r\n redirects++;\r\n } while (negotiateResponse.url && redirects < MAX_REDIRECTS);\r\n if (redirects === MAX_REDIRECTS && negotiateResponse.url) {\r\n throw new Error(\"Negotiate redirection limit exceeded.\");\r\n }\r\n await this._createTransport(url, this._options.transport, negotiateResponse, transferFormat);\r\n }\r\n if (this.transport instanceof LongPollingTransport) {\r\n this.features.inherentKeepAlive = true;\r\n }\r\n if (this._connectionState === \"Connecting\" /* Connecting */) {\r\n // Ensure the connection transitions to the connected state prior to completing this.startInternalPromise.\r\n // start() will handle the case when stop was called and startInternal exits still in the disconnecting state.\r\n this._logger.log(LogLevel.Debug, \"The HttpConnection connected successfully.\");\r\n this._connectionState = \"Connected\" /* Connected */;\r\n }\r\n // stop() is waiting on us via this.startInternalPromise so keep this.transport around so it can clean up.\r\n // This is the only case startInternal can exit in neither the connected nor disconnected state because stopConnection()\r\n // will transition to the disconnected state. start() will wait for the transition using the stopPromise.\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, \"Failed to start the connection: \" + e);\r\n this._connectionState = \"Disconnected\" /* Disconnected */;\r\n this.transport = undefined;\r\n // if start fails, any active calls to stop assume that start will complete the stop promise\r\n this._stopPromiseResolver();\r\n return Promise.reject(e);\r\n }\r\n }\r\n async _getNegotiationResponse(url) {\r\n const headers = {};\r\n if (this._accessTokenFactory) {\r\n const token = await this._accessTokenFactory();\r\n if (token) {\r\n headers[HeaderNames.Authorization] = `Bearer ${token}`;\r\n }\r\n }\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n const negotiateUrl = this._resolveNegotiateUrl(url);\r\n this._logger.log(LogLevel.Debug, `Sending negotiation request: ${negotiateUrl}.`);\r\n try {\r\n const response = await this._httpClient.post(negotiateUrl, {\r\n content: \"\",\r\n headers: { ...headers, ...this._options.headers },\r\n timeout: this._options.timeout,\r\n withCredentials: this._options.withCredentials,\r\n });\r\n if (response.statusCode !== 200) {\r\n return Promise.reject(new Error(`Unexpected status code returned from negotiate '${response.statusCode}'`));\r\n }\r\n const negotiateResponse = JSON.parse(response.content);\r\n if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {\r\n // Negotiate version 0 doesn't use connectionToken\r\n // So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version\r\n negotiateResponse.connectionToken = negotiateResponse.connectionId;\r\n }\r\n return negotiateResponse;\r\n }\r\n catch (e) {\r\n let errorMessage = \"Failed to complete negotiation with the server: \" + e;\r\n if (e instanceof HttpError) {\r\n if (e.statusCode === 404) {\r\n errorMessage = errorMessage + \" Either this is not a SignalR endpoint or there is a proxy blocking the connection.\";\r\n }\r\n }\r\n this._logger.log(LogLevel.Error, errorMessage);\r\n return Promise.reject(new FailedToNegotiateWithServerError(errorMessage));\r\n }\r\n }\r\n _createConnectUrl(url, connectionToken) {\r\n if (!connectionToken) {\r\n return url;\r\n }\r\n return url + (url.indexOf(\"?\") === -1 ? \"?\" : \"&\") + `id=${connectionToken}`;\r\n }\r\n async _createTransport(url, requestedTransport, negotiateResponse, requestedTransferFormat) {\r\n let connectUrl = this._createConnectUrl(url, negotiateResponse.connectionToken);\r\n if (this._isITransport(requestedTransport)) {\r\n this._logger.log(LogLevel.Debug, \"Connection was provided an instance of ITransport, using that directly.\");\r\n this.transport = requestedTransport;\r\n await this._startTransport(connectUrl, requestedTransferFormat);\r\n this.connectionId = negotiateResponse.connectionId;\r\n return;\r\n }\r\n const transportExceptions = [];\r\n const transports = negotiateResponse.availableTransports || [];\r\n let negotiate = negotiateResponse;\r\n for (const endpoint of transports) {\r\n const transportOrError = this._resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat);\r\n if (transportOrError instanceof Error) {\r\n // Store the error and continue, we don't want to cause a re-negotiate in these cases\r\n transportExceptions.push(`${endpoint.transport} failed:`);\r\n transportExceptions.push(transportOrError);\r\n }\r\n else if (this._isITransport(transportOrError)) {\r\n this.transport = transportOrError;\r\n if (!negotiate) {\r\n try {\r\n negotiate = await this._getNegotiationResponse(url);\r\n }\r\n catch (ex) {\r\n return Promise.reject(ex);\r\n }\r\n connectUrl = this._createConnectUrl(url, negotiate.connectionToken);\r\n }\r\n try {\r\n await this._startTransport(connectUrl, requestedTransferFormat);\r\n this.connectionId = negotiate.connectionId;\r\n return;\r\n }\r\n catch (ex) {\r\n this._logger.log(LogLevel.Error, `Failed to start the transport '${endpoint.transport}': ${ex}`);\r\n negotiate = undefined;\r\n transportExceptions.push(new FailedToStartTransportError(`${endpoint.transport} failed: ${ex}`, HttpTransportType[endpoint.transport]));\r\n if (this._connectionState !== \"Connecting\" /* Connecting */) {\r\n const message = \"Failed to select transport before stop() was called.\";\r\n this._logger.log(LogLevel.Debug, message);\r\n return Promise.reject(new Error(message));\r\n }\r\n }\r\n }\r\n }\r\n if (transportExceptions.length > 0) {\r\n return Promise.reject(new AggregateErrors(`Unable to connect to the server with any of the available transports. ${transportExceptions.join(\" \")}`, transportExceptions));\r\n }\r\n return Promise.reject(new Error(\"None of the transports supported by the client are supported by the server.\"));\r\n }\r\n _constructTransport(transport) {\r\n switch (transport) {\r\n case HttpTransportType.WebSockets:\r\n if (!this._options.WebSocket) {\r\n throw new Error(\"'WebSocket' is not supported in your environment.\");\r\n }\r\n return new WebSocketTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options.logMessageContent, this._options.WebSocket, this._options.headers || {});\r\n case HttpTransportType.ServerSentEvents:\r\n if (!this._options.EventSource) {\r\n throw new Error(\"'EventSource' is not supported in your environment.\");\r\n }\r\n return new ServerSentEventsTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options);\r\n case HttpTransportType.LongPolling:\r\n return new LongPollingTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options);\r\n default:\r\n throw new Error(`Unknown transport: ${transport}.`);\r\n }\r\n }\r\n _startTransport(url, transferFormat) {\r\n this.transport.onreceive = this.onreceive;\r\n this.transport.onclose = (e) => this._stopConnection(e);\r\n return this.transport.connect(url, transferFormat);\r\n }\r\n _resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat) {\r\n const transport = HttpTransportType[endpoint.transport];\r\n if (transport === null || transport === undefined) {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`);\r\n return new Error(`Skipping transport '${endpoint.transport}' because it is not supported by this client.`);\r\n }\r\n else {\r\n if (transportMatches(requestedTransport, transport)) {\r\n const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]);\r\n if (transferFormats.indexOf(requestedTransferFormat) >= 0) {\r\n if ((transport === HttpTransportType.WebSockets && !this._options.WebSocket) ||\r\n (transport === HttpTransportType.ServerSentEvents && !this._options.EventSource)) {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`);\r\n return new UnsupportedTransportError(`'${HttpTransportType[transport]}' is not supported in your environment.`, transport);\r\n }\r\n else {\r\n this._logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);\r\n try {\r\n return this._constructTransport(transport);\r\n }\r\n catch (ex) {\r\n return ex;\r\n }\r\n }\r\n }\r\n else {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`);\r\n return new Error(`'${HttpTransportType[transport]}' does not support ${TransferFormat[requestedTransferFormat]}.`);\r\n }\r\n }\r\n else {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`);\r\n return new DisabledTransportError(`'${HttpTransportType[transport]}' is disabled by the client.`, transport);\r\n }\r\n }\r\n }\r\n _isITransport(transport) {\r\n return transport && typeof (transport) === \"object\" && \"connect\" in transport;\r\n }\r\n _stopConnection(error) {\r\n this._logger.log(LogLevel.Debug, `HttpConnection.stopConnection(${error}) called while in state ${this._connectionState}.`);\r\n this.transport = undefined;\r\n // If we have a stopError, it takes precedence over the error from the transport\r\n error = this._stopError || error;\r\n this._stopError = undefined;\r\n if (this._connectionState === \"Disconnected\" /* Disconnected */) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is already in the disconnected state.`);\r\n return;\r\n }\r\n if (this._connectionState === \"Connecting\" /* Connecting */) {\r\n this._logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is still in the connecting state.`);\r\n throw new Error(`HttpConnection.stopConnection(${error}) was called while the connection is still in the connecting state.`);\r\n }\r\n if (this._connectionState === \"Disconnecting\" /* Disconnecting */) {\r\n // A call to stop() induced this call to stopConnection and needs to be completed.\r\n // Any stop() awaiters will be scheduled to continue after the onclose callback fires.\r\n this._stopPromiseResolver();\r\n }\r\n if (error) {\r\n this._logger.log(LogLevel.Error, `Connection disconnected with error '${error}'.`);\r\n }\r\n else {\r\n this._logger.log(LogLevel.Information, \"Connection disconnected.\");\r\n }\r\n if (this._sendQueue) {\r\n this._sendQueue.stop().catch((e) => {\r\n this._logger.log(LogLevel.Error, `TransportSendQueue.stop() threw error '${e}'.`);\r\n });\r\n this._sendQueue = undefined;\r\n }\r\n this.connectionId = undefined;\r\n this._connectionState = \"Disconnected\" /* Disconnected */;\r\n if (this._connectionStarted) {\r\n this._connectionStarted = false;\r\n try {\r\n if (this.onclose) {\r\n this.onclose(error);\r\n }\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `HttpConnection.onclose(${error}) threw error '${e}'.`);\r\n }\r\n }\r\n }\r\n _resolveUrl(url) {\r\n // startsWith is not supported in IE\r\n if (url.lastIndexOf(\"https://\", 0) === 0 || url.lastIndexOf(\"http://\", 0) === 0) {\r\n return url;\r\n }\r\n if (!Platform.isBrowser) {\r\n throw new Error(`Cannot resolve '${url}'.`);\r\n }\r\n // Setting the url to the href propery of an anchor tag handles normalization\r\n // for us. There are 3 main cases.\r\n // 1. Relative path normalization e.g \"b\" -> \"http://localhost:5000/a/b\"\r\n // 2. Absolute path normalization e.g \"/a/b\" -> \"http://localhost:5000/a/b\"\r\n // 3. Networkpath reference normalization e.g \"//localhost:5000/a/b\" -> \"http://localhost:5000/a/b\"\r\n const aTag = window.document.createElement(\"a\");\r\n aTag.href = url;\r\n this._logger.log(LogLevel.Information, `Normalizing '${url}' to '${aTag.href}'.`);\r\n return aTag.href;\r\n }\r\n _resolveNegotiateUrl(url) {\r\n const index = url.indexOf(\"?\");\r\n let negotiateUrl = url.substring(0, index === -1 ? url.length : index);\r\n if (negotiateUrl[negotiateUrl.length - 1] !== \"/\") {\r\n negotiateUrl += \"/\";\r\n }\r\n negotiateUrl += \"negotiate\";\r\n negotiateUrl += index === -1 ? \"\" : url.substring(index);\r\n if (negotiateUrl.indexOf(\"negotiateVersion\") === -1) {\r\n negotiateUrl += index === -1 ? \"?\" : \"&\";\r\n negotiateUrl += \"negotiateVersion=\" + this._negotiateVersion;\r\n }\r\n return negotiateUrl;\r\n }\r\n}\r\nfunction transportMatches(requestedTransport, actualTransport) {\r\n return !requestedTransport || ((actualTransport & requestedTransport) !== 0);\r\n}\r\n/** @private */\r\nexport class TransportSendQueue {\r\n constructor(_transport) {\r\n this._transport = _transport;\r\n this._buffer = [];\r\n this._executing = true;\r\n this._sendBufferedData = new PromiseSource();\r\n this._transportResult = new PromiseSource();\r\n this._sendLoopPromise = this._sendLoop();\r\n }\r\n send(data) {\r\n this._bufferData(data);\r\n if (!this._transportResult) {\r\n this._transportResult = new PromiseSource();\r\n }\r\n return this._transportResult.promise;\r\n }\r\n stop() {\r\n this._executing = false;\r\n this._sendBufferedData.resolve();\r\n return this._sendLoopPromise;\r\n }\r\n _bufferData(data) {\r\n if (this._buffer.length && typeof (this._buffer[0]) !== typeof (data)) {\r\n throw new Error(`Expected data to be of type ${typeof (this._buffer)} but was of type ${typeof (data)}`);\r\n }\r\n this._buffer.push(data);\r\n this._sendBufferedData.resolve();\r\n }\r\n async _sendLoop() {\r\n while (true) {\r\n await this._sendBufferedData.promise;\r\n if (!this._executing) {\r\n if (this._transportResult) {\r\n this._transportResult.reject(\"Connection stopped.\");\r\n }\r\n break;\r\n }\r\n this._sendBufferedData = new PromiseSource();\r\n const transportResult = this._transportResult;\r\n this._transportResult = undefined;\r\n const data = typeof (this._buffer[0]) === \"string\" ?\r\n this._buffer.join(\"\") :\r\n TransportSendQueue._concatBuffers(this._buffer);\r\n this._buffer.length = 0;\r\n try {\r\n await this._transport.send(data);\r\n transportResult.resolve();\r\n }\r\n catch (error) {\r\n transportResult.reject(error);\r\n }\r\n }\r\n }\r\n static _concatBuffers(arrayBuffers) {\r\n const totalLength = arrayBuffers.map((b) => b.byteLength).reduce((a, b) => a + b);\r\n const result = new Uint8Array(totalLength);\r\n let offset = 0;\r\n for (const item of arrayBuffers) {\r\n result.set(new Uint8Array(item), offset);\r\n offset += item.byteLength;\r\n }\r\n return result.buffer;\r\n }\r\n}\r\nclass PromiseSource {\r\n constructor() {\r\n this.promise = new Promise((resolve, reject) => [this._resolver, this._rejecter] = [resolve, reject]);\r\n }\r\n resolve() {\r\n this._resolver();\r\n }\r\n reject(reason) {\r\n this._rejecter(reason);\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { HandshakeProtocol } from \"./HandshakeProtocol\";\r\nimport { MessageType } from \"./IHubProtocol\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { Subject } from \"./Subject\";\r\nimport { Arg, getErrorString, Platform } from \"./Utils\";\r\nconst DEFAULT_TIMEOUT_IN_MS = 30 * 1000;\r\nconst DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000;\r\n/** Describes the current state of the {@link HubConnection} to the server. */\r\nexport var HubConnectionState;\r\n(function (HubConnectionState) {\r\n /** The hub connection is disconnected. */\r\n HubConnectionState[\"Disconnected\"] = \"Disconnected\";\r\n /** The hub connection is connecting. */\r\n HubConnectionState[\"Connecting\"] = \"Connecting\";\r\n /** The hub connection is connected. */\r\n HubConnectionState[\"Connected\"] = \"Connected\";\r\n /** The hub connection is disconnecting. */\r\n HubConnectionState[\"Disconnecting\"] = \"Disconnecting\";\r\n /** The hub connection is reconnecting. */\r\n HubConnectionState[\"Reconnecting\"] = \"Reconnecting\";\r\n})(HubConnectionState || (HubConnectionState = {}));\r\n/** Represents a connection to a SignalR Hub. */\r\nexport class HubConnection {\r\n constructor(connection, logger, protocol, reconnectPolicy) {\r\n this._nextKeepAlive = 0;\r\n this._freezeEventListener = () => {\r\n this._logger.log(LogLevel.Warning, \"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep\");\r\n };\r\n Arg.isRequired(connection, \"connection\");\r\n Arg.isRequired(logger, \"logger\");\r\n Arg.isRequired(protocol, \"protocol\");\r\n this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS;\r\n this.keepAliveIntervalInMilliseconds = DEFAULT_PING_INTERVAL_IN_MS;\r\n this._logger = logger;\r\n this._protocol = protocol;\r\n this.connection = connection;\r\n this._reconnectPolicy = reconnectPolicy;\r\n this._handshakeProtocol = new HandshakeProtocol();\r\n this.connection.onreceive = (data) => this._processIncomingData(data);\r\n this.connection.onclose = (error) => this._connectionClosed(error);\r\n this._callbacks = {};\r\n this._methods = {};\r\n this._closedCallbacks = [];\r\n this._reconnectingCallbacks = [];\r\n this._reconnectedCallbacks = [];\r\n this._invocationId = 0;\r\n this._receivedHandshakeResponse = false;\r\n this._connectionState = HubConnectionState.Disconnected;\r\n this._connectionStarted = false;\r\n this._cachedPingMessage = this._protocol.writeMessage({ type: MessageType.Ping });\r\n }\r\n /** @internal */\r\n // Using a public static factory method means we can have a private constructor and an _internal_\r\n // create method that can be used by HubConnectionBuilder. An \"internal\" constructor would just\r\n // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a\r\n // public parameter-less constructor.\r\n static create(connection, logger, protocol, reconnectPolicy) {\r\n return new HubConnection(connection, logger, protocol, reconnectPolicy);\r\n }\r\n /** Indicates the state of the {@link HubConnection} to the server. */\r\n get state() {\r\n return this._connectionState;\r\n }\r\n /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either\r\n * in the disconnected state or if the negotiation step was skipped.\r\n */\r\n get connectionId() {\r\n return this.connection ? (this.connection.connectionId || null) : null;\r\n }\r\n /** Indicates the url of the {@link HubConnection} to the server. */\r\n get baseUrl() {\r\n return this.connection.baseUrl || \"\";\r\n }\r\n /**\r\n * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or\r\n * Reconnecting states.\r\n * @param {string} url The url to connect to.\r\n */\r\n set baseUrl(url) {\r\n if (this._connectionState !== HubConnectionState.Disconnected && this._connectionState !== HubConnectionState.Reconnecting) {\r\n throw new Error(\"The HubConnection must be in the Disconnected or Reconnecting state to change the url.\");\r\n }\r\n if (!url) {\r\n throw new Error(\"The HubConnection url must be a valid url.\");\r\n }\r\n this.connection.baseUrl = url;\r\n }\r\n /** Starts the connection.\r\n *\r\n * @returns {Promise} A Promise that resolves when the connection has been successfully established, or rejects with an error.\r\n */\r\n start() {\r\n this._startPromise = this._startWithStateTransitions();\r\n return this._startPromise;\r\n }\r\n async _startWithStateTransitions() {\r\n if (this._connectionState !== HubConnectionState.Disconnected) {\r\n return Promise.reject(new Error(\"Cannot start a HubConnection that is not in the 'Disconnected' state.\"));\r\n }\r\n this._connectionState = HubConnectionState.Connecting;\r\n this._logger.log(LogLevel.Debug, \"Starting HubConnection.\");\r\n try {\r\n await this._startInternal();\r\n if (Platform.isBrowser) {\r\n // Log when the browser freezes the tab so users know why their connection unexpectedly stopped working\r\n window.document.addEventListener(\"freeze\", this._freezeEventListener);\r\n }\r\n this._connectionState = HubConnectionState.Connected;\r\n this._connectionStarted = true;\r\n this._logger.log(LogLevel.Debug, \"HubConnection connected successfully.\");\r\n }\r\n catch (e) {\r\n this._connectionState = HubConnectionState.Disconnected;\r\n this._logger.log(LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`);\r\n return Promise.reject(e);\r\n }\r\n }\r\n async _startInternal() {\r\n this._stopDuringStartError = undefined;\r\n this._receivedHandshakeResponse = false;\r\n // Set up the promise before any connection is (re)started otherwise it could race with received messages\r\n const handshakePromise = new Promise((resolve, reject) => {\r\n this._handshakeResolver = resolve;\r\n this._handshakeRejecter = reject;\r\n });\r\n await this.connection.start(this._protocol.transferFormat);\r\n try {\r\n const handshakeRequest = {\r\n protocol: this._protocol.name,\r\n version: this._protocol.version,\r\n };\r\n this._logger.log(LogLevel.Debug, \"Sending handshake request.\");\r\n await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(handshakeRequest));\r\n this._logger.log(LogLevel.Information, `Using HubProtocol '${this._protocol.name}'.`);\r\n // defensively cleanup timeout in case we receive a message from the server before we finish start\r\n this._cleanupTimeout();\r\n this._resetTimeoutPeriod();\r\n this._resetKeepAliveInterval();\r\n await handshakePromise;\r\n // It's important to check the stopDuringStartError instead of just relying on the handshakePromise\r\n // being rejected on close, because this continuation can run after both the handshake completed successfully\r\n // and the connection was closed.\r\n if (this._stopDuringStartError) {\r\n // It's important to throw instead of returning a rejected promise, because we don't want to allow any state\r\n // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise\r\n // will cause the calling continuation to get scheduled to run later.\r\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\r\n throw this._stopDuringStartError;\r\n }\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`);\r\n this._cleanupTimeout();\r\n this._cleanupPingTimer();\r\n // HttpConnection.stop() should not complete until after the onclose callback is invoked.\r\n // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.\r\n await this.connection.stop(e);\r\n throw e;\r\n }\r\n }\r\n /** Stops the connection.\r\n *\r\n * @returns {Promise} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.\r\n */\r\n async stop() {\r\n // Capture the start promise before the connection might be restarted in an onclose callback.\r\n const startPromise = this._startPromise;\r\n this._stopPromise = this._stopInternal();\r\n await this._stopPromise;\r\n try {\r\n // Awaiting undefined continues immediately\r\n await startPromise;\r\n }\r\n catch (e) {\r\n // This exception is returned to the user as a rejected Promise from the start method.\r\n }\r\n }\r\n _stopInternal(error) {\r\n if (this._connectionState === HubConnectionState.Disconnected) {\r\n this._logger.log(LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`);\r\n return Promise.resolve();\r\n }\r\n if (this._connectionState === HubConnectionState.Disconnecting) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);\r\n return this._stopPromise;\r\n }\r\n this._connectionState = HubConnectionState.Disconnecting;\r\n this._logger.log(LogLevel.Debug, \"Stopping HubConnection.\");\r\n if (this._reconnectDelayHandle) {\r\n // We're in a reconnect delay which means the underlying connection is currently already stopped.\r\n // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and\r\n // fire the onclose callbacks.\r\n this._logger.log(LogLevel.Debug, \"Connection stopped during reconnect delay. Done reconnecting.\");\r\n clearTimeout(this._reconnectDelayHandle);\r\n this._reconnectDelayHandle = undefined;\r\n this._completeClose();\r\n return Promise.resolve();\r\n }\r\n this._cleanupTimeout();\r\n this._cleanupPingTimer();\r\n this._stopDuringStartError = error || new Error(\"The connection was stopped before the hub handshake could complete.\");\r\n // HttpConnection.stop() should not complete until after either HttpConnection.start() fails\r\n // or the onclose callback is invoked. The onclose callback will transition the HubConnection\r\n // to the disconnected state if need be before HttpConnection.stop() completes.\r\n return this.connection.stop(error);\r\n }\r\n /** Invokes a streaming hub method on the server using the specified name and arguments.\r\n *\r\n * @typeparam T The type of the items returned by the server.\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {IStreamResult} An object that yields results from the server as they are received.\r\n */\r\n stream(methodName, ...args) {\r\n const [streams, streamIds] = this._replaceStreamingParams(args);\r\n const invocationDescriptor = this._createStreamInvocation(methodName, args, streamIds);\r\n // eslint-disable-next-line prefer-const\r\n let promiseQueue;\r\n const subject = new Subject();\r\n subject.cancelCallback = () => {\r\n const cancelInvocation = this._createCancelInvocation(invocationDescriptor.invocationId);\r\n delete this._callbacks[invocationDescriptor.invocationId];\r\n return promiseQueue.then(() => {\r\n return this._sendWithProtocol(cancelInvocation);\r\n });\r\n };\r\n this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {\r\n if (error) {\r\n subject.error(error);\r\n return;\r\n }\r\n else if (invocationEvent) {\r\n // invocationEvent will not be null when an error is not passed to the callback\r\n if (invocationEvent.type === MessageType.Completion) {\r\n if (invocationEvent.error) {\r\n subject.error(new Error(invocationEvent.error));\r\n }\r\n else {\r\n subject.complete();\r\n }\r\n }\r\n else {\r\n subject.next((invocationEvent.item));\r\n }\r\n }\r\n };\r\n promiseQueue = this._sendWithProtocol(invocationDescriptor)\r\n .catch((e) => {\r\n subject.error(e);\r\n delete this._callbacks[invocationDescriptor.invocationId];\r\n });\r\n this._launchStreams(streams, promiseQueue);\r\n return subject;\r\n }\r\n _sendMessage(message) {\r\n this._resetKeepAliveInterval();\r\n return this.connection.send(message);\r\n }\r\n /**\r\n * Sends a js object to the server.\r\n * @param message The js object to serialize and send.\r\n */\r\n _sendWithProtocol(message) {\r\n return this._sendMessage(this._protocol.writeMessage(message));\r\n }\r\n /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.\r\n *\r\n * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still\r\n * be processing the invocation.\r\n *\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {Promise} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.\r\n */\r\n send(methodName, ...args) {\r\n const [streams, streamIds] = this._replaceStreamingParams(args);\r\n const sendPromise = this._sendWithProtocol(this._createInvocation(methodName, args, true, streamIds));\r\n this._launchStreams(streams, sendPromise);\r\n return sendPromise;\r\n }\r\n /** Invokes a hub method on the server using the specified name and arguments.\r\n *\r\n * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise\r\n * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of\r\n * resolving the Promise.\r\n *\r\n * @typeparam T The expected return type.\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {Promise} A Promise that resolves with the result of the server method (if any), or rejects with an error.\r\n */\r\n invoke(methodName, ...args) {\r\n const [streams, streamIds] = this._replaceStreamingParams(args);\r\n const invocationDescriptor = this._createInvocation(methodName, args, false, streamIds);\r\n const p = new Promise((resolve, reject) => {\r\n // invocationId will always have a value for a non-blocking invocation\r\n this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {\r\n if (error) {\r\n reject(error);\r\n return;\r\n }\r\n else if (invocationEvent) {\r\n // invocationEvent will not be null when an error is not passed to the callback\r\n if (invocationEvent.type === MessageType.Completion) {\r\n if (invocationEvent.error) {\r\n reject(new Error(invocationEvent.error));\r\n }\r\n else {\r\n resolve(invocationEvent.result);\r\n }\r\n }\r\n else {\r\n reject(new Error(`Unexpected message type: ${invocationEvent.type}`));\r\n }\r\n }\r\n };\r\n const promiseQueue = this._sendWithProtocol(invocationDescriptor)\r\n .catch((e) => {\r\n reject(e);\r\n // invocationId will always have a value for a non-blocking invocation\r\n delete this._callbacks[invocationDescriptor.invocationId];\r\n });\r\n this._launchStreams(streams, promiseQueue);\r\n });\r\n return p;\r\n }\r\n /** Registers a handler that will be invoked when the hub method with the specified method name is invoked.\r\n *\r\n * @param {string} methodName The name of the hub method to define.\r\n * @param {Function} newMethod The handler that will be raised when the hub method is invoked.\r\n */\r\n on(methodName, newMethod) {\r\n if (!methodName || !newMethod) {\r\n return;\r\n }\r\n methodName = methodName.toLowerCase();\r\n if (!this._methods[methodName]) {\r\n this._methods[methodName] = [];\r\n }\r\n // Preventing adding the same handler multiple times.\r\n if (this._methods[methodName].indexOf(newMethod) !== -1) {\r\n return;\r\n }\r\n this._methods[methodName].push(newMethod);\r\n }\r\n off(methodName, method) {\r\n if (!methodName) {\r\n return;\r\n }\r\n methodName = methodName.toLowerCase();\r\n const handlers = this._methods[methodName];\r\n if (!handlers) {\r\n return;\r\n }\r\n if (method) {\r\n const removeIdx = handlers.indexOf(method);\r\n if (removeIdx !== -1) {\r\n handlers.splice(removeIdx, 1);\r\n if (handlers.length === 0) {\r\n delete this._methods[methodName];\r\n }\r\n }\r\n }\r\n else {\r\n delete this._methods[methodName];\r\n }\r\n }\r\n /** Registers a handler that will be invoked when the connection is closed.\r\n *\r\n * @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any).\r\n */\r\n onclose(callback) {\r\n if (callback) {\r\n this._closedCallbacks.push(callback);\r\n }\r\n }\r\n /** Registers a handler that will be invoked when the connection starts reconnecting.\r\n *\r\n * @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any).\r\n */\r\n onreconnecting(callback) {\r\n if (callback) {\r\n this._reconnectingCallbacks.push(callback);\r\n }\r\n }\r\n /** Registers a handler that will be invoked when the connection successfully reconnects.\r\n *\r\n * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.\r\n */\r\n onreconnected(callback) {\r\n if (callback) {\r\n this._reconnectedCallbacks.push(callback);\r\n }\r\n }\r\n _processIncomingData(data) {\r\n this._cleanupTimeout();\r\n if (!this._receivedHandshakeResponse) {\r\n data = this._processHandshakeResponse(data);\r\n this._receivedHandshakeResponse = true;\r\n }\r\n // Data may have all been read when processing handshake response\r\n if (data) {\r\n // Parse the messages\r\n const messages = this._protocol.parseMessages(data, this._logger);\r\n for (const message of messages) {\r\n switch (message.type) {\r\n case MessageType.Invocation:\r\n this._invokeClientMethod(message);\r\n break;\r\n case MessageType.StreamItem:\r\n case MessageType.Completion: {\r\n const callback = this._callbacks[message.invocationId];\r\n if (callback) {\r\n if (message.type === MessageType.Completion) {\r\n delete this._callbacks[message.invocationId];\r\n }\r\n try {\r\n callback(message);\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `Stream callback threw error: ${getErrorString(e)}`);\r\n }\r\n }\r\n break;\r\n }\r\n case MessageType.Ping:\r\n // Don't care about pings\r\n break;\r\n case MessageType.Close: {\r\n this._logger.log(LogLevel.Information, \"Close message received from server.\");\r\n const error = message.error ? new Error(\"Server returned an error on close: \" + message.error) : undefined;\r\n if (message.allowReconnect === true) {\r\n // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,\r\n // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.connection.stop(error);\r\n }\r\n else {\r\n // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.\r\n this._stopPromise = this._stopInternal(error);\r\n }\r\n break;\r\n }\r\n default:\r\n this._logger.log(LogLevel.Warning, `Invalid message type: ${message.type}.`);\r\n break;\r\n }\r\n }\r\n }\r\n this._resetTimeoutPeriod();\r\n }\r\n _processHandshakeResponse(data) {\r\n let responseMessage;\r\n let remainingData;\r\n try {\r\n [remainingData, responseMessage] = this._handshakeProtocol.parseHandshakeResponse(data);\r\n }\r\n catch (e) {\r\n const message = \"Error parsing handshake response: \" + e;\r\n this._logger.log(LogLevel.Error, message);\r\n const error = new Error(message);\r\n this._handshakeRejecter(error);\r\n throw error;\r\n }\r\n if (responseMessage.error) {\r\n const message = \"Server returned handshake error: \" + responseMessage.error;\r\n this._logger.log(LogLevel.Error, message);\r\n const error = new Error(message);\r\n this._handshakeRejecter(error);\r\n throw error;\r\n }\r\n else {\r\n this._logger.log(LogLevel.Debug, \"Server handshake complete.\");\r\n }\r\n this._handshakeResolver();\r\n return remainingData;\r\n }\r\n _resetKeepAliveInterval() {\r\n if (this.connection.features.inherentKeepAlive) {\r\n return;\r\n }\r\n // Set the time we want the next keep alive to be sent\r\n // Timer will be setup on next message receive\r\n this._nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds;\r\n this._cleanupPingTimer();\r\n }\r\n _resetTimeoutPeriod() {\r\n if (!this.connection.features || !this.connection.features.inherentKeepAlive) {\r\n // Set the timeout timer\r\n this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);\r\n // Set keepAlive timer if there isn't one\r\n if (this._pingServerHandle === undefined) {\r\n let nextPing = this._nextKeepAlive - new Date().getTime();\r\n if (nextPing < 0) {\r\n nextPing = 0;\r\n }\r\n // The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute\r\n this._pingServerHandle = setTimeout(async () => {\r\n if (this._connectionState === HubConnectionState.Connected) {\r\n try {\r\n await this._sendMessage(this._cachedPingMessage);\r\n }\r\n catch {\r\n // We don't care about the error. It should be seen elsewhere in the client.\r\n // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering\r\n this._cleanupPingTimer();\r\n }\r\n }\r\n }, nextPing);\r\n }\r\n }\r\n }\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n serverTimeout() {\r\n // The server hasn't talked to us in a while. It doesn't like us anymore ... :(\r\n // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.connection.stop(new Error(\"Server timeout elapsed without receiving a message from the server.\"));\r\n }\r\n _invokeClientMethod(invocationMessage) {\r\n const methods = this._methods[invocationMessage.target.toLowerCase()];\r\n if (methods) {\r\n try {\r\n methods.forEach((m) => m.apply(this, invocationMessage.arguments));\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `A callback for the method ${invocationMessage.target.toLowerCase()} threw error '${e}'.`);\r\n }\r\n if (invocationMessage.invocationId) {\r\n // This is not supported in v1. So we return an error to avoid blocking the server waiting for the response.\r\n const message = \"Server requested a response, which is not supported in this version of the client.\";\r\n this._logger.log(LogLevel.Error, message);\r\n // We don't want to wait on the stop itself.\r\n this._stopPromise = this._stopInternal(new Error(message));\r\n }\r\n }\r\n else {\r\n this._logger.log(LogLevel.Warning, `No client method with the name '${invocationMessage.target}' found.`);\r\n }\r\n }\r\n _connectionClosed(error) {\r\n this._logger.log(LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this._connectionState}.`);\r\n // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.\r\n this._stopDuringStartError = this._stopDuringStartError || error || new Error(\"The underlying connection was closed before the hub handshake could complete.\");\r\n // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.\r\n // If it has already completed, this should just noop.\r\n if (this._handshakeResolver) {\r\n this._handshakeResolver();\r\n }\r\n this._cancelCallbacksWithError(error || new Error(\"Invocation canceled due to the underlying connection being closed.\"));\r\n this._cleanupTimeout();\r\n this._cleanupPingTimer();\r\n if (this._connectionState === HubConnectionState.Disconnecting) {\r\n this._completeClose(error);\r\n }\r\n else if (this._connectionState === HubConnectionState.Connected && this._reconnectPolicy) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this._reconnect(error);\r\n }\r\n else if (this._connectionState === HubConnectionState.Connected) {\r\n this._completeClose(error);\r\n }\r\n // If none of the above if conditions were true were called the HubConnection must be in either:\r\n // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.\r\n // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt\r\n // and potentially continue the reconnect() loop.\r\n // 3. The Disconnected state in which case we're already done.\r\n }\r\n _completeClose(error) {\r\n if (this._connectionStarted) {\r\n this._connectionState = HubConnectionState.Disconnected;\r\n this._connectionStarted = false;\r\n if (Platform.isBrowser) {\r\n window.document.removeEventListener(\"freeze\", this._freezeEventListener);\r\n }\r\n try {\r\n this._closedCallbacks.forEach((c) => c.apply(this, [error]));\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`);\r\n }\r\n }\r\n }\r\n async _reconnect(error) {\r\n const reconnectStartTime = Date.now();\r\n let previousReconnectAttempts = 0;\r\n let retryError = error !== undefined ? error : new Error(\"Attempting to reconnect due to a unknown error.\");\r\n let nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, 0, retryError);\r\n if (nextRetryDelay === null) {\r\n this._logger.log(LogLevel.Debug, \"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.\");\r\n this._completeClose(error);\r\n return;\r\n }\r\n this._connectionState = HubConnectionState.Reconnecting;\r\n if (error) {\r\n this._logger.log(LogLevel.Information, `Connection reconnecting because of error '${error}'.`);\r\n }\r\n else {\r\n this._logger.log(LogLevel.Information, \"Connection reconnecting.\");\r\n }\r\n if (this._reconnectingCallbacks.length !== 0) {\r\n try {\r\n this._reconnectingCallbacks.forEach((c) => c.apply(this, [error]));\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`);\r\n }\r\n // Exit early if an onreconnecting callback called connection.stop().\r\n if (this._connectionState !== HubConnectionState.Reconnecting) {\r\n this._logger.log(LogLevel.Debug, \"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.\");\r\n return;\r\n }\r\n }\r\n while (nextRetryDelay !== null) {\r\n this._logger.log(LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts} will start in ${nextRetryDelay} ms.`);\r\n await new Promise((resolve) => {\r\n this._reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);\r\n });\r\n this._reconnectDelayHandle = undefined;\r\n if (this._connectionState !== HubConnectionState.Reconnecting) {\r\n this._logger.log(LogLevel.Debug, \"Connection left the reconnecting state during reconnect delay. Done reconnecting.\");\r\n return;\r\n }\r\n try {\r\n await this._startInternal();\r\n this._connectionState = HubConnectionState.Connected;\r\n this._logger.log(LogLevel.Information, \"HubConnection reconnected successfully.\");\r\n if (this._reconnectedCallbacks.length !== 0) {\r\n try {\r\n this._reconnectedCallbacks.forEach((c) => c.apply(this, [this.connection.connectionId]));\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`);\r\n }\r\n }\r\n return;\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`);\r\n if (this._connectionState !== HubConnectionState.Reconnecting) {\r\n this._logger.log(LogLevel.Debug, `Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`);\r\n // The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong.\r\n if (this._connectionState === HubConnectionState.Disconnecting) {\r\n this._completeClose();\r\n }\r\n return;\r\n }\r\n retryError = e instanceof Error ? e : new Error(e.toString());\r\n nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);\r\n }\r\n }\r\n this._logger.log(LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`);\r\n this._completeClose();\r\n }\r\n _getNextRetryDelay(previousRetryCount, elapsedMilliseconds, retryReason) {\r\n try {\r\n return this._reconnectPolicy.nextRetryDelayInMilliseconds({\r\n elapsedMilliseconds,\r\n previousRetryCount,\r\n retryReason,\r\n });\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`);\r\n return null;\r\n }\r\n }\r\n _cancelCallbacksWithError(error) {\r\n const callbacks = this._callbacks;\r\n this._callbacks = {};\r\n Object.keys(callbacks)\r\n .forEach((key) => {\r\n const callback = callbacks[key];\r\n try {\r\n callback(null, error);\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `Stream 'error' callback called with '${error}' threw error: ${getErrorString(e)}`);\r\n }\r\n });\r\n }\r\n _cleanupPingTimer() {\r\n if (this._pingServerHandle) {\r\n clearTimeout(this._pingServerHandle);\r\n this._pingServerHandle = undefined;\r\n }\r\n }\r\n _cleanupTimeout() {\r\n if (this._timeoutHandle) {\r\n clearTimeout(this._timeoutHandle);\r\n }\r\n }\r\n _createInvocation(methodName, args, nonblocking, streamIds) {\r\n if (nonblocking) {\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n else {\r\n return {\r\n arguments: args,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n }\r\n else {\r\n const invocationId = this._invocationId;\r\n this._invocationId++;\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n else {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n }\r\n }\r\n _launchStreams(streams, promiseQueue) {\r\n if (streams.length === 0) {\r\n return;\r\n }\r\n // Synchronize stream data so they arrive in-order on the server\r\n if (!promiseQueue) {\r\n promiseQueue = Promise.resolve();\r\n }\r\n // We want to iterate over the keys, since the keys are the stream ids\r\n // eslint-disable-next-line guard-for-in\r\n for (const streamId in streams) {\r\n streams[streamId].subscribe({\r\n complete: () => {\r\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId)));\r\n },\r\n error: (err) => {\r\n let message;\r\n if (err instanceof Error) {\r\n message = err.message;\r\n }\r\n else if (err && err.toString) {\r\n message = err.toString();\r\n }\r\n else {\r\n message = \"Unknown error\";\r\n }\r\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId, message)));\r\n },\r\n next: (item) => {\r\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createStreamItemMessage(streamId, item)));\r\n },\r\n });\r\n }\r\n }\r\n _replaceStreamingParams(args) {\r\n const streams = [];\r\n const streamIds = [];\r\n for (let i = 0; i < args.length; i++) {\r\n const argument = args[i];\r\n if (this._isObservable(argument)) {\r\n const streamId = this._invocationId;\r\n this._invocationId++;\r\n // Store the stream for later use\r\n streams[streamId] = argument;\r\n streamIds.push(streamId.toString());\r\n // remove stream from args\r\n args.splice(i, 1);\r\n }\r\n }\r\n return [streams, streamIds];\r\n }\r\n _isObservable(arg) {\r\n // This allows other stream implementations to just work (like rxjs)\r\n return arg && arg.subscribe && typeof arg.subscribe === \"function\";\r\n }\r\n _createStreamInvocation(methodName, args, streamIds) {\r\n const invocationId = this._invocationId;\r\n this._invocationId++;\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.StreamInvocation,\r\n };\r\n }\r\n else {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n target: methodName,\r\n type: MessageType.StreamInvocation,\r\n };\r\n }\r\n }\r\n _createCancelInvocation(id) {\r\n return {\r\n invocationId: id,\r\n type: MessageType.CancelInvocation,\r\n };\r\n }\r\n _createStreamItemMessage(id, item) {\r\n return {\r\n invocationId: id,\r\n item,\r\n type: MessageType.StreamItem,\r\n };\r\n }\r\n _createCompletionMessage(id, error, result) {\r\n if (error) {\r\n return {\r\n error,\r\n invocationId: id,\r\n type: MessageType.Completion,\r\n };\r\n }\r\n return {\r\n invocationId: id,\r\n result,\r\n type: MessageType.Completion,\r\n };\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { DefaultReconnectPolicy } from \"./DefaultReconnectPolicy\";\r\nimport { HttpConnection } from \"./HttpConnection\";\r\nimport { HubConnection } from \"./HubConnection\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { JsonHubProtocol } from \"./JsonHubProtocol\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { Arg, ConsoleLogger } from \"./Utils\";\r\nconst LogLevelNameMapping = {\r\n trace: LogLevel.Trace,\r\n debug: LogLevel.Debug,\r\n info: LogLevel.Information,\r\n information: LogLevel.Information,\r\n warn: LogLevel.Warning,\r\n warning: LogLevel.Warning,\r\n error: LogLevel.Error,\r\n critical: LogLevel.Critical,\r\n none: LogLevel.None,\r\n};\r\nfunction parseLogLevel(name) {\r\n // Case-insensitive matching via lower-casing\r\n // Yes, I know case-folding is a complicated problem in Unicode, but we only support\r\n // the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse.\r\n const mapping = LogLevelNameMapping[name.toLowerCase()];\r\n if (typeof mapping !== \"undefined\") {\r\n return mapping;\r\n }\r\n else {\r\n throw new Error(`Unknown log level: ${name}`);\r\n }\r\n}\r\n/** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */\r\nexport class HubConnectionBuilder {\r\n configureLogging(logging) {\r\n Arg.isRequired(logging, \"logging\");\r\n if (isLogger(logging)) {\r\n this.logger = logging;\r\n }\r\n else if (typeof logging === \"string\") {\r\n const logLevel = parseLogLevel(logging);\r\n this.logger = new ConsoleLogger(logLevel);\r\n }\r\n else {\r\n this.logger = new ConsoleLogger(logging);\r\n }\r\n return this;\r\n }\r\n withUrl(url, transportTypeOrOptions) {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isNotEmpty(url, \"url\");\r\n this.url = url;\r\n // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed\r\n // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called.\r\n if (typeof transportTypeOrOptions === \"object\") {\r\n this.httpConnectionOptions = { ...this.httpConnectionOptions, ...transportTypeOrOptions };\r\n }\r\n else {\r\n this.httpConnectionOptions = {\r\n ...this.httpConnectionOptions,\r\n transport: transportTypeOrOptions,\r\n };\r\n }\r\n return this;\r\n }\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol.\r\n *\r\n * @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use.\r\n */\r\n withHubProtocol(protocol) {\r\n Arg.isRequired(protocol, \"protocol\");\r\n this.protocol = protocol;\r\n return this;\r\n }\r\n withAutomaticReconnect(retryDelaysOrReconnectPolicy) {\r\n if (this.reconnectPolicy) {\r\n throw new Error(\"A reconnectPolicy has already been set.\");\r\n }\r\n if (!retryDelaysOrReconnectPolicy) {\r\n this.reconnectPolicy = new DefaultReconnectPolicy();\r\n }\r\n else if (Array.isArray(retryDelaysOrReconnectPolicy)) {\r\n this.reconnectPolicy = new DefaultReconnectPolicy(retryDelaysOrReconnectPolicy);\r\n }\r\n else {\r\n this.reconnectPolicy = retryDelaysOrReconnectPolicy;\r\n }\r\n return this;\r\n }\r\n /** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder.\r\n *\r\n * @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}.\r\n */\r\n build() {\r\n // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one\r\n // provided to configureLogger\r\n const httpConnectionOptions = this.httpConnectionOptions || {};\r\n // If it's 'null', the user **explicitly** asked for null, don't mess with it.\r\n if (httpConnectionOptions.logger === undefined) {\r\n // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it.\r\n httpConnectionOptions.logger = this.logger;\r\n }\r\n // Now create the connection\r\n if (!this.url) {\r\n throw new Error(\"The 'HubConnectionBuilder.withUrl' method must be called before building the connection.\");\r\n }\r\n const connection = new HttpConnection(this.url, httpConnectionOptions);\r\n return HubConnection.create(connection, this.logger || NullLogger.instance, this.protocol || new JsonHubProtocol(), this.reconnectPolicy);\r\n }\r\n}\r\nfunction isLogger(logger) {\r\n return logger.log !== undefined;\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n/** Defines the type of a Hub Message. */\r\nexport var MessageType;\r\n(function (MessageType) {\r\n /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */\r\n MessageType[MessageType[\"Invocation\"] = 1] = \"Invocation\";\r\n /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */\r\n MessageType[MessageType[\"StreamItem\"] = 2] = \"StreamItem\";\r\n /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */\r\n MessageType[MessageType[\"Completion\"] = 3] = \"Completion\";\r\n /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */\r\n MessageType[MessageType[\"StreamInvocation\"] = 4] = \"StreamInvocation\";\r\n /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */\r\n MessageType[MessageType[\"CancelInvocation\"] = 5] = \"CancelInvocation\";\r\n /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */\r\n MessageType[MessageType[\"Ping\"] = 6] = \"Ping\";\r\n /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */\r\n MessageType[MessageType[\"Close\"] = 7] = \"Close\";\r\n})(MessageType || (MessageType = {}));\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n// These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here.\r\n/** Indicates the severity of a log message.\r\n *\r\n * Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc.\r\n */\r\nexport var LogLevel;\r\n(function (LogLevel) {\r\n /** Log level for very low severity diagnostic messages. */\r\n LogLevel[LogLevel[\"Trace\"] = 0] = \"Trace\";\r\n /** Log level for low severity diagnostic messages. */\r\n LogLevel[LogLevel[\"Debug\"] = 1] = \"Debug\";\r\n /** Log level for informational diagnostic messages. */\r\n LogLevel[LogLevel[\"Information\"] = 2] = \"Information\";\r\n /** Log level for diagnostic messages that indicate a non-fatal problem. */\r\n LogLevel[LogLevel[\"Warning\"] = 3] = \"Warning\";\r\n /** Log level for diagnostic messages that indicate a failure in the current operation. */\r\n LogLevel[LogLevel[\"Error\"] = 4] = \"Error\";\r\n /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */\r\n LogLevel[LogLevel[\"Critical\"] = 5] = \"Critical\";\r\n /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */\r\n LogLevel[LogLevel[\"None\"] = 6] = \"None\";\r\n})(LogLevel || (LogLevel = {}));\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n// This will be treated as a bit flag in the future, so we keep it using power-of-two values.\r\n/** Specifies a specific HTTP transport type. */\r\nexport var HttpTransportType;\r\n(function (HttpTransportType) {\r\n /** Specifies no transport preference. */\r\n HttpTransportType[HttpTransportType[\"None\"] = 0] = \"None\";\r\n /** Specifies the WebSockets transport. */\r\n HttpTransportType[HttpTransportType[\"WebSockets\"] = 1] = \"WebSockets\";\r\n /** Specifies the Server-Sent Events transport. */\r\n HttpTransportType[HttpTransportType[\"ServerSentEvents\"] = 2] = \"ServerSentEvents\";\r\n /** Specifies the Long Polling transport. */\r\n HttpTransportType[HttpTransportType[\"LongPolling\"] = 4] = \"LongPolling\";\r\n})(HttpTransportType || (HttpTransportType = {}));\r\n/** Specifies the transfer format for a connection. */\r\nexport var TransferFormat;\r\n(function (TransferFormat) {\r\n /** Specifies that only text data will be transmitted over the connection. */\r\n TransferFormat[TransferFormat[\"Text\"] = 1] = \"Text\";\r\n /** Specifies that binary data will be transmitted over the connection. */\r\n TransferFormat[TransferFormat[\"Binary\"] = 2] = \"Binary\";\r\n})(TransferFormat || (TransferFormat = {}));\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { MessageType } from \"./IHubProtocol\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { TextMessageFormat } from \"./TextMessageFormat\";\r\nconst JSON_HUB_PROTOCOL_NAME = \"json\";\r\n/** Implements the JSON Hub Protocol. */\r\nexport class JsonHubProtocol {\r\n constructor() {\r\n /** @inheritDoc */\r\n this.name = JSON_HUB_PROTOCOL_NAME;\r\n /** @inheritDoc */\r\n this.version = 1;\r\n /** @inheritDoc */\r\n this.transferFormat = TransferFormat.Text;\r\n }\r\n /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.\r\n *\r\n * @param {string} input A string containing the serialized representation.\r\n * @param {ILogger} logger A logger that will be used to log messages that occur during parsing.\r\n */\r\n parseMessages(input, logger) {\r\n // The interface does allow \"ArrayBuffer\" to be passed in, but this implementation does not. So let's throw a useful error.\r\n if (typeof input !== \"string\") {\r\n throw new Error(\"Invalid input for JSON hub protocol. Expected a string.\");\r\n }\r\n if (!input) {\r\n return [];\r\n }\r\n if (logger === null) {\r\n logger = NullLogger.instance;\r\n }\r\n // Parse the messages\r\n const messages = TextMessageFormat.parse(input);\r\n const hubMessages = [];\r\n for (const message of messages) {\r\n const parsedMessage = JSON.parse(message);\r\n if (typeof parsedMessage.type !== \"number\") {\r\n throw new Error(\"Invalid payload.\");\r\n }\r\n switch (parsedMessage.type) {\r\n case MessageType.Invocation:\r\n this._isInvocationMessage(parsedMessage);\r\n break;\r\n case MessageType.StreamItem:\r\n this._isStreamItemMessage(parsedMessage);\r\n break;\r\n case MessageType.Completion:\r\n this._isCompletionMessage(parsedMessage);\r\n break;\r\n case MessageType.Ping:\r\n // Single value, no need to validate\r\n break;\r\n case MessageType.Close:\r\n // All optional values, no need to validate\r\n break;\r\n default:\r\n // Future protocol changes can add message types, old clients can ignore them\r\n logger.log(LogLevel.Information, \"Unknown message type '\" + parsedMessage.type + \"' ignored.\");\r\n continue;\r\n }\r\n hubMessages.push(parsedMessage);\r\n }\r\n return hubMessages;\r\n }\r\n /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.\r\n *\r\n * @param {HubMessage} message The message to write.\r\n * @returns {string} A string containing the serialized representation of the message.\r\n */\r\n writeMessage(message) {\r\n return TextMessageFormat.write(JSON.stringify(message));\r\n }\r\n _isInvocationMessage(message) {\r\n this._assertNotEmptyString(message.target, \"Invalid payload for Invocation message.\");\r\n if (message.invocationId !== undefined) {\r\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for Invocation message.\");\r\n }\r\n }\r\n _isStreamItemMessage(message) {\r\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for StreamItem message.\");\r\n if (message.item === undefined) {\r\n throw new Error(\"Invalid payload for StreamItem message.\");\r\n }\r\n }\r\n _isCompletionMessage(message) {\r\n if (message.result && message.error) {\r\n throw new Error(\"Invalid payload for Completion message.\");\r\n }\r\n if (!message.result && message.error) {\r\n this._assertNotEmptyString(message.error, \"Invalid payload for Completion message.\");\r\n }\r\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for Completion message.\");\r\n }\r\n _assertNotEmptyString(value, errorMessage) {\r\n if (typeof value !== \"string\" || value === \"\") {\r\n throw new Error(errorMessage);\r\n }\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n/** A logger that does nothing when log messages are sent to it. */\r\nexport class NullLogger {\r\n constructor() { }\r\n /** @inheritDoc */\r\n // eslint-disable-next-line\r\n log(_logLevel, _message) {\r\n }\r\n}\r\n/** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */\r\nNullLogger.instance = new NullLogger();\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { AbortController } from \"./AbortController\";\r\nimport { HttpError, TimeoutError } from \"./Errors\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, sendMessage } from \"./Utils\";\r\n// Not exported from 'index', this type is internal.\r\n/** @private */\r\nexport class LongPollingTransport {\r\n constructor(httpClient, accessTokenFactory, logger, options) {\r\n this._httpClient = httpClient;\r\n this._accessTokenFactory = accessTokenFactory;\r\n this._logger = logger;\r\n this._pollAbort = new AbortController();\r\n this._options = options;\r\n this._running = false;\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n // This is an internal type, not exported from 'index' so this is really just internal.\r\n get pollAborted() {\r\n return this._pollAbort.aborted;\r\n }\r\n async connect(url, transferFormat) {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n this._url = url;\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Connecting.\");\r\n // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property)\r\n if (transferFormat === TransferFormat.Binary &&\r\n (typeof XMLHttpRequest !== \"undefined\" && typeof new XMLHttpRequest().responseType !== \"string\")) {\r\n throw new Error(\"Binary protocols over XmlHttpRequest not implementing advanced features are not supported.\");\r\n }\r\n const [name, value] = getUserAgentHeader();\r\n const headers = { [name]: value, ...this._options.headers };\r\n const pollOptions = {\r\n abortSignal: this._pollAbort.signal,\r\n headers,\r\n timeout: 100000,\r\n withCredentials: this._options.withCredentials,\r\n };\r\n if (transferFormat === TransferFormat.Binary) {\r\n pollOptions.responseType = \"arraybuffer\";\r\n }\r\n const token = await this._getAccessToken();\r\n this._updateHeaderToken(pollOptions, token);\r\n // Make initial long polling request\r\n // Server uses first long polling request to finish initializing connection and it returns without data\r\n const pollUrl = `${url}&_=${Date.now()}`;\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);\r\n const response = await this._httpClient.get(pollUrl, pollOptions);\r\n if (response.statusCode !== 200) {\r\n this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);\r\n // Mark running as false so that the poll immediately ends and runs the close logic\r\n this._closeError = new HttpError(response.statusText || \"\", response.statusCode);\r\n this._running = false;\r\n }\r\n else {\r\n this._running = true;\r\n }\r\n this._receiving = this._poll(this._url, pollOptions);\r\n }\r\n async _getAccessToken() {\r\n if (this._accessTokenFactory) {\r\n return await this._accessTokenFactory();\r\n }\r\n return null;\r\n }\r\n _updateHeaderToken(request, token) {\r\n if (!request.headers) {\r\n request.headers = {};\r\n }\r\n if (token) {\r\n request.headers[HeaderNames.Authorization] = `Bearer ${token}`;\r\n return;\r\n }\r\n if (request.headers[HeaderNames.Authorization]) {\r\n delete request.headers[HeaderNames.Authorization];\r\n }\r\n }\r\n async _poll(url, pollOptions) {\r\n try {\r\n while (this._running) {\r\n // We have to get the access token on each poll, in case it changes\r\n const token = await this._getAccessToken();\r\n this._updateHeaderToken(pollOptions, token);\r\n try {\r\n const pollUrl = `${url}&_=${Date.now()}`;\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);\r\n const response = await this._httpClient.get(pollUrl, pollOptions);\r\n if (response.statusCode === 204) {\r\n this._logger.log(LogLevel.Information, \"(LongPolling transport) Poll terminated by server.\");\r\n this._running = false;\r\n }\r\n else if (response.statusCode !== 200) {\r\n this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);\r\n // Unexpected status code\r\n this._closeError = new HttpError(response.statusText || \"\", response.statusCode);\r\n this._running = false;\r\n }\r\n else {\r\n // Process the response\r\n if (response.content) {\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) data received. ${getDataDetail(response.content, this._options.logMessageContent)}.`);\r\n if (this.onreceive) {\r\n this.onreceive(response.content);\r\n }\r\n }\r\n else {\r\n // This is another way timeout manifest.\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Poll timed out, reissuing.\");\r\n }\r\n }\r\n }\r\n catch (e) {\r\n if (!this._running) {\r\n // Log but disregard errors that occur after stopping\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) Poll errored after shutdown: ${e.message}`);\r\n }\r\n else {\r\n if (e instanceof TimeoutError) {\r\n // Ignore timeouts and reissue the poll.\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Poll timed out, reissuing.\");\r\n }\r\n else {\r\n // Close the connection with the error as the result.\r\n this._closeError = e;\r\n this._running = false;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n finally {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Polling complete.\");\r\n // We will reach here with pollAborted==false when the server returned a response causing the transport to stop.\r\n // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent.\r\n if (!this.pollAborted) {\r\n this._raiseOnClose();\r\n }\r\n }\r\n }\r\n async send(data) {\r\n if (!this._running) {\r\n return Promise.reject(new Error(\"Cannot send until the transport is connected\"));\r\n }\r\n return sendMessage(this._logger, \"LongPolling\", this._httpClient, this._url, this._accessTokenFactory, data, this._options);\r\n }\r\n async stop() {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Stopping polling.\");\r\n // Tell receiving loop to stop, abort any current request, and then wait for it to finish\r\n this._running = false;\r\n this._pollAbort.abort();\r\n try {\r\n await this._receiving;\r\n // Send DELETE to clean up long polling on the server\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) sending DELETE request to ${this._url}.`);\r\n const headers = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n const deleteOptions = {\r\n headers: { ...headers, ...this._options.headers },\r\n timeout: this._options.timeout,\r\n withCredentials: this._options.withCredentials,\r\n };\r\n const token = await this._getAccessToken();\r\n this._updateHeaderToken(deleteOptions, token);\r\n await this._httpClient.delete(this._url, deleteOptions);\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) DELETE request sent.\");\r\n }\r\n finally {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Stop finished.\");\r\n // Raise close event here instead of in polling\r\n // It needs to happen after the DELETE request is sent\r\n this._raiseOnClose();\r\n }\r\n }\r\n _raiseOnClose() {\r\n if (this.onclose) {\r\n let logMessage = \"(LongPolling transport) Firing onclose event.\";\r\n if (this._closeError) {\r\n logMessage += \" Error: \" + this._closeError;\r\n }\r\n this._logger.log(LogLevel.Trace, logMessage);\r\n this.onclose(this._closeError);\r\n }\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, Platform, sendMessage } from \"./Utils\";\r\n/** @private */\r\nexport class ServerSentEventsTransport {\r\n constructor(httpClient, accessTokenFactory, logger, options) {\r\n this._httpClient = httpClient;\r\n this._accessTokenFactory = accessTokenFactory;\r\n this._logger = logger;\r\n this._options = options;\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n async connect(url, transferFormat) {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n this._logger.log(LogLevel.Trace, \"(SSE transport) Connecting.\");\r\n // set url before accessTokenFactory because this.url is only for send and we set the auth header instead of the query string for send\r\n this._url = url;\r\n if (this._accessTokenFactory) {\r\n const token = await this._accessTokenFactory();\r\n if (token) {\r\n url += (url.indexOf(\"?\") < 0 ? \"?\" : \"&\") + `access_token=${encodeURIComponent(token)}`;\r\n }\r\n }\r\n return new Promise((resolve, reject) => {\r\n let opened = false;\r\n if (transferFormat !== TransferFormat.Text) {\r\n reject(new Error(\"The Server-Sent Events transport only supports the 'Text' transfer format\"));\r\n return;\r\n }\r\n let eventSource;\r\n if (Platform.isBrowser || Platform.isWebWorker) {\r\n eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials });\r\n }\r\n else {\r\n // Non-browser passes cookies via the dictionary\r\n const cookies = this._httpClient.getCookieString(url);\r\n const headers = {};\r\n headers.Cookie = cookies;\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials, headers: { ...headers, ...this._options.headers } });\r\n }\r\n try {\r\n eventSource.onmessage = (e) => {\r\n if (this.onreceive) {\r\n try {\r\n this._logger.log(LogLevel.Trace, `(SSE transport) data received. ${getDataDetail(e.data, this._options.logMessageContent)}.`);\r\n this.onreceive(e.data);\r\n }\r\n catch (error) {\r\n this._close(error);\r\n return;\r\n }\r\n }\r\n };\r\n // @ts-ignore: not using event on purpose\r\n eventSource.onerror = (e) => {\r\n // EventSource doesn't give any useful information about server side closes.\r\n if (opened) {\r\n this._close();\r\n }\r\n else {\r\n reject(new Error(\"EventSource failed to connect. The connection could not be found on the server,\"\r\n + \" either the connection ID is not present on the server, or a proxy is refusing/buffering the connection.\"\r\n + \" If you have multiple servers check that sticky sessions are enabled.\"));\r\n }\r\n };\r\n eventSource.onopen = () => {\r\n this._logger.log(LogLevel.Information, `SSE connected to ${this._url}`);\r\n this._eventSource = eventSource;\r\n opened = true;\r\n resolve();\r\n };\r\n }\r\n catch (e) {\r\n reject(e);\r\n return;\r\n }\r\n });\r\n }\r\n async send(data) {\r\n if (!this._eventSource) {\r\n return Promise.reject(new Error(\"Cannot send until the transport is connected\"));\r\n }\r\n return sendMessage(this._logger, \"SSE\", this._httpClient, this._url, this._accessTokenFactory, data, this._options);\r\n }\r\n stop() {\r\n this._close();\r\n return Promise.resolve();\r\n }\r\n _close(e) {\r\n if (this._eventSource) {\r\n this._eventSource.close();\r\n this._eventSource = undefined;\r\n if (this.onclose) {\r\n this.onclose(e);\r\n }\r\n }\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { SubjectSubscription } from \"./Utils\";\r\n/** Stream implementation to stream items to the server. */\r\nexport class Subject {\r\n constructor() {\r\n this.observers = [];\r\n }\r\n next(item) {\r\n for (const observer of this.observers) {\r\n observer.next(item);\r\n }\r\n }\r\n error(err) {\r\n for (const observer of this.observers) {\r\n if (observer.error) {\r\n observer.error(err);\r\n }\r\n }\r\n }\r\n complete() {\r\n for (const observer of this.observers) {\r\n if (observer.complete) {\r\n observer.complete();\r\n }\r\n }\r\n }\r\n subscribe(observer) {\r\n this.observers.push(observer);\r\n return new SubjectSubscription(this, observer);\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n// Not exported from index\r\n/** @private */\r\nexport class TextMessageFormat {\r\n static write(output) {\r\n return `${output}${TextMessageFormat.RecordSeparator}`;\r\n }\r\n static parse(input) {\r\n if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n const messages = input.split(TextMessageFormat.RecordSeparator);\r\n messages.pop();\r\n return messages;\r\n }\r\n}\r\nTextMessageFormat.RecordSeparatorCode = 0x1e;\r\nTextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { NullLogger } from \"./Loggers\";\r\n// Version token that will be replaced by the prepack command\r\n/** The version of the SignalR client. */\r\nexport const VERSION = \"6.0.15\";\r\n/** @private */\r\nexport class Arg {\r\n static isRequired(val, name) {\r\n if (val === null || val === undefined) {\r\n throw new Error(`The '${name}' argument is required.`);\r\n }\r\n }\r\n static isNotEmpty(val, name) {\r\n if (!val || val.match(/^\\s*$/)) {\r\n throw new Error(`The '${name}' argument should not be empty.`);\r\n }\r\n }\r\n static isIn(val, values, name) {\r\n // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself.\r\n if (!(val in values)) {\r\n throw new Error(`Unknown ${name} value: ${val}.`);\r\n }\r\n }\r\n}\r\n/** @private */\r\nexport class Platform {\r\n // react-native has a window but no document so we should check both\r\n static get isBrowser() {\r\n return typeof window === \"object\" && typeof window.document === \"object\";\r\n }\r\n // WebWorkers don't have a window object so the isBrowser check would fail\r\n static get isWebWorker() {\r\n return typeof self === \"object\" && \"importScripts\" in self;\r\n }\r\n // react-native has a window but no document\r\n static get isReactNative() {\r\n return typeof window === \"object\" && typeof window.document === \"undefined\";\r\n }\r\n // Node apps shouldn't have a window object, but WebWorkers don't either\r\n // so we need to check for both WebWorker and window\r\n static get isNode() {\r\n return !this.isBrowser && !this.isWebWorker && !this.isReactNative;\r\n }\r\n}\r\n/** @private */\r\nexport function getDataDetail(data, includeContent) {\r\n let detail = \"\";\r\n if (isArrayBuffer(data)) {\r\n detail = `Binary data of length ${data.byteLength}`;\r\n if (includeContent) {\r\n detail += `. Content: '${formatArrayBuffer(data)}'`;\r\n }\r\n }\r\n else if (typeof data === \"string\") {\r\n detail = `String data of length ${data.length}`;\r\n if (includeContent) {\r\n detail += `. Content: '${data}'`;\r\n }\r\n }\r\n return detail;\r\n}\r\n/** @private */\r\nexport function formatArrayBuffer(data) {\r\n const view = new Uint8Array(data);\r\n // Uint8Array.map only supports returning another Uint8Array?\r\n let str = \"\";\r\n view.forEach((num) => {\r\n const pad = num < 16 ? \"0\" : \"\";\r\n str += `0x${pad}${num.toString(16)} `;\r\n });\r\n // Trim of trailing space.\r\n return str.substr(0, str.length - 1);\r\n}\r\n// Also in signalr-protocol-msgpack/Utils.ts\r\n/** @private */\r\nexport function isArrayBuffer(val) {\r\n return val && typeof ArrayBuffer !== \"undefined\" &&\r\n (val instanceof ArrayBuffer ||\r\n // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof\r\n (val.constructor && val.constructor.name === \"ArrayBuffer\"));\r\n}\r\n/** @private */\r\nexport async function sendMessage(logger, transportName, httpClient, url, accessTokenFactory, content, options) {\r\n let headers = {};\r\n if (accessTokenFactory) {\r\n const token = await accessTokenFactory();\r\n if (token) {\r\n headers = {\r\n [\"Authorization\"]: `Bearer ${token}`,\r\n };\r\n }\r\n }\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n logger.log(LogLevel.Trace, `(${transportName} transport) sending data. ${getDataDetail(content, options.logMessageContent)}.`);\r\n const responseType = isArrayBuffer(content) ? \"arraybuffer\" : \"text\";\r\n const response = await httpClient.post(url, {\r\n content,\r\n headers: { ...headers, ...options.headers },\r\n responseType,\r\n timeout: options.timeout,\r\n withCredentials: options.withCredentials,\r\n });\r\n logger.log(LogLevel.Trace, `(${transportName} transport) request complete. Response status: ${response.statusCode}.`);\r\n}\r\n/** @private */\r\nexport function createLogger(logger) {\r\n if (logger === undefined) {\r\n return new ConsoleLogger(LogLevel.Information);\r\n }\r\n if (logger === null) {\r\n return NullLogger.instance;\r\n }\r\n if (logger.log !== undefined) {\r\n return logger;\r\n }\r\n return new ConsoleLogger(logger);\r\n}\r\n/** @private */\r\nexport class SubjectSubscription {\r\n constructor(subject, observer) {\r\n this._subject = subject;\r\n this._observer = observer;\r\n }\r\n dispose() {\r\n const index = this._subject.observers.indexOf(this._observer);\r\n if (index > -1) {\r\n this._subject.observers.splice(index, 1);\r\n }\r\n if (this._subject.observers.length === 0 && this._subject.cancelCallback) {\r\n this._subject.cancelCallback().catch((_) => { });\r\n }\r\n }\r\n}\r\n/** @private */\r\nexport class ConsoleLogger {\r\n constructor(minimumLogLevel) {\r\n this._minLevel = minimumLogLevel;\r\n this.out = console;\r\n }\r\n log(logLevel, message) {\r\n if (logLevel >= this._minLevel) {\r\n const msg = `[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`;\r\n switch (logLevel) {\r\n case LogLevel.Critical:\r\n case LogLevel.Error:\r\n this.out.error(msg);\r\n break;\r\n case LogLevel.Warning:\r\n this.out.warn(msg);\r\n break;\r\n case LogLevel.Information:\r\n this.out.info(msg);\r\n break;\r\n default:\r\n // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug\r\n this.out.log(msg);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n/** @private */\r\nexport function getUserAgentHeader() {\r\n let userAgentHeaderName = \"X-SignalR-User-Agent\";\r\n if (Platform.isNode) {\r\n userAgentHeaderName = \"User-Agent\";\r\n }\r\n return [userAgentHeaderName, constructUserAgent(VERSION, getOsName(), getRuntime(), getRuntimeVersion())];\r\n}\r\n/** @private */\r\nexport function constructUserAgent(version, os, runtime, runtimeVersion) {\r\n // Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version])\r\n let userAgent = \"Microsoft SignalR/\";\r\n const majorAndMinor = version.split(\".\");\r\n userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`;\r\n userAgent += ` (${version}; `;\r\n if (os && os !== \"\") {\r\n userAgent += `${os}; `;\r\n }\r\n else {\r\n userAgent += \"Unknown OS; \";\r\n }\r\n userAgent += `${runtime}`;\r\n if (runtimeVersion) {\r\n userAgent += `; ${runtimeVersion}`;\r\n }\r\n else {\r\n userAgent += \"; Unknown Runtime Version\";\r\n }\r\n userAgent += \")\";\r\n return userAgent;\r\n}\r\n// eslint-disable-next-line spaced-comment\r\n/*#__PURE__*/ function getOsName() {\r\n if (Platform.isNode) {\r\n switch (process.platform) {\r\n case \"win32\":\r\n return \"Windows NT\";\r\n case \"darwin\":\r\n return \"macOS\";\r\n case \"linux\":\r\n return \"Linux\";\r\n default:\r\n return process.platform;\r\n }\r\n }\r\n else {\r\n return \"\";\r\n }\r\n}\r\n// eslint-disable-next-line spaced-comment\r\n/*#__PURE__*/ function getRuntimeVersion() {\r\n if (Platform.isNode) {\r\n return process.versions.node;\r\n }\r\n return undefined;\r\n}\r\nfunction getRuntime() {\r\n if (Platform.isNode) {\r\n return \"NodeJS\";\r\n }\r\n else {\r\n return \"Browser\";\r\n }\r\n}\r\n/** @private */\r\nexport function getErrorString(e) {\r\n if (e.stack) {\r\n return e.stack;\r\n }\r\n else if (e.message) {\r\n return e.message;\r\n }\r\n return `${e}`;\r\n}\r\n/** @private */\r\nexport function getGlobalThis() {\r\n // globalThis is semi-new and not available in Node until v12\r\n if (typeof globalThis !== \"undefined\") {\r\n return globalThis;\r\n }\r\n if (typeof self !== \"undefined\") {\r\n return self;\r\n }\r\n if (typeof window !== \"undefined\") {\r\n return window;\r\n }\r\n if (typeof global !== \"undefined\") {\r\n return global;\r\n }\r\n throw new Error(\"could not find global\");\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, Platform } from \"./Utils\";\r\n/** @private */\r\nexport class WebSocketTransport {\r\n constructor(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor, headers) {\r\n this._logger = logger;\r\n this._accessTokenFactory = accessTokenFactory;\r\n this._logMessageContent = logMessageContent;\r\n this._webSocketConstructor = webSocketConstructor;\r\n this._httpClient = httpClient;\r\n this.onreceive = null;\r\n this.onclose = null;\r\n this._headers = headers;\r\n }\r\n async connect(url, transferFormat) {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n this._logger.log(LogLevel.Trace, \"(WebSockets transport) Connecting.\");\r\n if (this._accessTokenFactory) {\r\n const token = await this._accessTokenFactory();\r\n if (token) {\r\n url += (url.indexOf(\"?\") < 0 ? \"?\" : \"&\") + `access_token=${encodeURIComponent(token)}`;\r\n }\r\n }\r\n return new Promise((resolve, reject) => {\r\n url = url.replace(/^http/, \"ws\");\r\n let webSocket;\r\n const cookies = this._httpClient.getCookieString(url);\r\n let opened = false;\r\n if (Platform.isNode) {\r\n const headers = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n if (cookies) {\r\n headers[HeaderNames.Cookie] = `${cookies}`;\r\n }\r\n // Only pass headers when in non-browser environments\r\n webSocket = new this._webSocketConstructor(url, undefined, {\r\n headers: { ...headers, ...this._headers },\r\n });\r\n }\r\n if (!webSocket) {\r\n // Chrome is not happy with passing 'undefined' as protocol\r\n webSocket = new this._webSocketConstructor(url);\r\n }\r\n if (transferFormat === TransferFormat.Binary) {\r\n webSocket.binaryType = \"arraybuffer\";\r\n }\r\n webSocket.onopen = (_event) => {\r\n this._logger.log(LogLevel.Information, `WebSocket connected to ${url}.`);\r\n this._webSocket = webSocket;\r\n opened = true;\r\n resolve();\r\n };\r\n webSocket.onerror = (event) => {\r\n let error = null;\r\n // ErrorEvent is a browser only type we need to check if the type exists before using it\r\n if (typeof ErrorEvent !== \"undefined\" && event instanceof ErrorEvent) {\r\n error = event.error;\r\n }\r\n else {\r\n error = \"There was an error with the transport\";\r\n }\r\n this._logger.log(LogLevel.Information, `(WebSockets transport) ${error}.`);\r\n };\r\n webSocket.onmessage = (message) => {\r\n this._logger.log(LogLevel.Trace, `(WebSockets transport) data received. ${getDataDetail(message.data, this._logMessageContent)}.`);\r\n if (this.onreceive) {\r\n try {\r\n this.onreceive(message.data);\r\n }\r\n catch (error) {\r\n this._close(error);\r\n return;\r\n }\r\n }\r\n };\r\n webSocket.onclose = (event) => {\r\n // Don't call close handler if connection was never established\r\n // We'll reject the connect call instead\r\n if (opened) {\r\n this._close(event);\r\n }\r\n else {\r\n let error = null;\r\n // ErrorEvent is a browser only type we need to check if the type exists before using it\r\n if (typeof ErrorEvent !== \"undefined\" && event instanceof ErrorEvent) {\r\n error = event.error;\r\n }\r\n else {\r\n error = \"WebSocket failed to connect. The connection could not be found on the server,\"\r\n + \" either the endpoint may not be a SignalR endpoint,\"\r\n + \" the connection ID is not present on the server, or there is a proxy blocking WebSockets.\"\r\n + \" If you have multiple servers check that sticky sessions are enabled.\";\r\n }\r\n reject(new Error(error));\r\n }\r\n };\r\n });\r\n }\r\n send(data) {\r\n if (this._webSocket && this._webSocket.readyState === this._webSocketConstructor.OPEN) {\r\n this._logger.log(LogLevel.Trace, `(WebSockets transport) sending data. ${getDataDetail(data, this._logMessageContent)}.`);\r\n this._webSocket.send(data);\r\n return Promise.resolve();\r\n }\r\n return Promise.reject(\"WebSocket is not in the OPEN state\");\r\n }\r\n stop() {\r\n if (this._webSocket) {\r\n // Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning\r\n // This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects\r\n this._close(undefined);\r\n }\r\n return Promise.resolve();\r\n }\r\n _close(event) {\r\n // webSocket will be null if the transport did not start successfully\r\n if (this._webSocket) {\r\n // Clear websocket handlers because we are considering the socket closed now\r\n this._webSocket.onclose = () => { };\r\n this._webSocket.onmessage = () => { };\r\n this._webSocket.onerror = () => { };\r\n this._webSocket.close();\r\n this._webSocket = undefined;\r\n }\r\n this._logger.log(LogLevel.Trace, \"(WebSockets transport) socket closed.\");\r\n if (this.onclose) {\r\n if (this._isCloseEvent(event) && (event.wasClean === false || event.code !== 1000)) {\r\n this.onclose(new Error(`WebSocket closed with status code: ${event.code} (${event.reason || \"no reason given\"}).`));\r\n }\r\n else if (event instanceof Error) {\r\n this.onclose(event);\r\n }\r\n else {\r\n this.onclose();\r\n }\r\n }\r\n }\r\n _isCloseEvent(event) {\r\n return event && typeof event.wasClean === \"boolean\" && typeof event.code === \"number\";\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\nimport { AbortError, HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpResponse } from \"./HttpClient\";\r\nimport { LogLevel } from \"./ILogger\";\r\nexport class XhrHttpClient extends HttpClient {\r\n constructor(logger) {\r\n super();\r\n this._logger = logger;\r\n }\r\n /** @inheritDoc */\r\n send(request) {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n return Promise.reject(new AbortError());\r\n }\r\n if (!request.method) {\r\n return Promise.reject(new Error(\"No method defined.\"));\r\n }\r\n if (!request.url) {\r\n return Promise.reject(new Error(\"No url defined.\"));\r\n }\r\n return new Promise((resolve, reject) => {\r\n const xhr = new XMLHttpRequest();\r\n xhr.open(request.method, request.url, true);\r\n xhr.withCredentials = request.withCredentials === undefined ? true : request.withCredentials;\r\n xhr.setRequestHeader(\"X-Requested-With\", \"XMLHttpRequest\");\r\n // Explicitly setting the Content-Type header for React Native on Android platform.\r\n xhr.setRequestHeader(\"Content-Type\", \"text/plain;charset=UTF-8\");\r\n const headers = request.headers;\r\n if (headers) {\r\n Object.keys(headers)\r\n .forEach((header) => {\r\n xhr.setRequestHeader(header, headers[header]);\r\n });\r\n }\r\n if (request.responseType) {\r\n xhr.responseType = request.responseType;\r\n }\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = () => {\r\n xhr.abort();\r\n reject(new AbortError());\r\n };\r\n }\r\n if (request.timeout) {\r\n xhr.timeout = request.timeout;\r\n }\r\n xhr.onload = () => {\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = null;\r\n }\r\n if (xhr.status >= 200 && xhr.status < 300) {\r\n resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));\r\n }\r\n else {\r\n reject(new HttpError(xhr.response || xhr.responseText || xhr.statusText, xhr.status));\r\n }\r\n };\r\n xhr.onerror = () => {\r\n this._logger.log(LogLevel.Warning, `Error from HTTP request. ${xhr.status}: ${xhr.statusText}.`);\r\n reject(new HttpError(xhr.statusText, xhr.status));\r\n };\r\n xhr.ontimeout = () => {\r\n this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);\r\n reject(new TimeoutError());\r\n };\r\n xhr.send(request.content || \"\");\r\n });\r\n }\r\n}\r\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nimport { DiagAPI } from './diag';\nvar API_NAME = 'context';\nvar NOOP_CONTEXT_MANAGER = new NoopContextManager();\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nvar ContextAPI = /** @class */ (function () {\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n function ContextAPI() {\n }\n /** Get the singleton instance of the Context API */\n ContextAPI.getInstance = function () {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n return this._instance;\n };\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n ContextAPI.prototype.setGlobalContextManager = function (contextManager) {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n };\n /**\n * Get the currently active context\n */\n ContextAPI.prototype.active = function () {\n return this._getContextManager().active();\n };\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n ContextAPI.prototype.with = function (context, fn, thisArg) {\n var _a;\n var args = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n args[_i - 3] = arguments[_i];\n }\n return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], __read(args), false));\n };\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n ContextAPI.prototype.bind = function (context, target) {\n return this._getContextManager().bind(context, target);\n };\n ContextAPI.prototype._getContextManager = function () {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n };\n /** Disable and remove the global context manager */\n ContextAPI.prototype.disable = function () {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n };\n return ContextAPI;\n}());\nexport { ContextAPI };\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport { DiagLogLevel, } from '../diag/types';\nimport { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nvar API_NAME = 'diag';\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nvar DiagAPI = /** @class */ (function () {\n /**\n * Private internal constructor\n * @private\n */\n function DiagAPI() {\n function _logProxy(funcName) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger)\n return;\n return logger[funcName].apply(logger, __spreadArray([], __read(args), false));\n };\n }\n // Using self local variable for minification purposes as 'this' cannot be minified\n var self = this;\n // DiagAPI specific functions\n var setLogger = function (logger, optionsOrLogLevel) {\n var _a, _b, _c;\n if (optionsOrLogLevel === void 0) { optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }; }\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation');\n self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);\n return false;\n }\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n var oldLogger = getGlobal('diag');\n var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : '';\n oldLogger.warn(\"Current logger will be overwritten from \" + stack);\n newLogger.warn(\"Current logger will overwrite one already registered from \" + stack);\n }\n return registerGlobal('diag', newLogger, self, true);\n };\n self.setLogger = setLogger;\n self.disable = function () {\n unregisterGlobal(API_NAME, self);\n };\n self.createComponentLogger = function (options) {\n return new DiagComponentLogger(options);\n };\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n /** Get the singleton instance of the DiagAPI API */\n DiagAPI.instance = function () {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n return this._instance;\n };\n return DiagAPI;\n}());\nexport { DiagAPI };\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport { isSpanContextValid, wrapSpanContext, } from '../trace/spancontext-utils';\nimport { deleteSpan, getActiveSpan, getSpan, getSpanContext, setSpan, setSpanContext, } from '../trace/context-utils';\nimport { DiagAPI } from './diag';\nvar API_NAME = 'trace';\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n */\nvar TraceAPI = /** @class */ (function () {\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n function TraceAPI() {\n this._proxyTracerProvider = new ProxyTracerProvider();\n this.wrapSpanContext = wrapSpanContext;\n this.isSpanContextValid = isSpanContextValid;\n this.deleteSpan = deleteSpan;\n this.getSpan = getSpan;\n this.getActiveSpan = getActiveSpan;\n this.getSpanContext = getSpanContext;\n this.setSpan = setSpan;\n this.setSpanContext = setSpanContext;\n }\n /** Get the singleton instance of the Trace API */\n TraceAPI.getInstance = function () {\n if (!this._instance) {\n this._instance = new TraceAPI();\n }\n return this._instance;\n };\n /**\n * Set the current global tracer.\n *\n * @returns true if the tracer provider was successfully registered, else false\n */\n TraceAPI.prototype.setGlobalTracerProvider = function (provider) {\n var success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance());\n if (success) {\n this._proxyTracerProvider.setDelegate(provider);\n }\n return success;\n };\n /**\n * Returns the global tracer provider.\n */\n TraceAPI.prototype.getTracerProvider = function () {\n return getGlobal(API_NAME) || this._proxyTracerProvider;\n };\n /**\n * Returns a tracer from the global tracer provider.\n */\n TraceAPI.prototype.getTracer = function (name, version) {\n return this.getTracerProvider().getTracer(name, version);\n };\n /** Remove the global tracer provider */\n TraceAPI.prototype.disable = function () {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n this._proxyTracerProvider = new ProxyTracerProvider();\n };\n return TraceAPI;\n}());\nexport { TraceAPI };\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport var context = ContextAPI.getInstance();\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { ROOT_CONTEXT } from './context';\nvar NoopContextManager = /** @class */ (function () {\n function NoopContextManager() {\n }\n NoopContextManager.prototype.active = function () {\n return ROOT_CONTEXT;\n };\n NoopContextManager.prototype.with = function (_context, fn, thisArg) {\n var args = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n args[_i - 3] = arguments[_i];\n }\n return fn.call.apply(fn, __spreadArray([thisArg], __read(args), false));\n };\n NoopContextManager.prototype.bind = function (_context, target) {\n return target;\n };\n NoopContextManager.prototype.enable = function () {\n return this;\n };\n NoopContextManager.prototype.disable = function () {\n return this;\n };\n return NoopContextManager;\n}());\nexport { NoopContextManager };\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\nvar BaseContext = /** @class */ (function () {\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n function BaseContext(parentContext) {\n // for minification\n var self = this;\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n self.getValue = function (key) { return self._currentContext.get(key); };\n self.setValue = function (key, value) {\n var context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n self.deleteValue = function (key) {\n var context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n return BaseContext;\n}());\n/** The root context is used as the default parent context when there is no active context */\nexport var ROOT_CONTEXT = new BaseContext();\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { getGlobal } from '../internal/global-utils';\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nvar DiagComponentLogger = /** @class */ (function () {\n function DiagComponentLogger(props) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n DiagComponentLogger.prototype.debug = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logProxy('debug', this._namespace, args);\n };\n DiagComponentLogger.prototype.error = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logProxy('error', this._namespace, args);\n };\n DiagComponentLogger.prototype.info = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logProxy('info', this._namespace, args);\n };\n DiagComponentLogger.prototype.warn = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logProxy('warn', this._namespace, args);\n };\n DiagComponentLogger.prototype.verbose = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logProxy('verbose', this._namespace, args);\n };\n return DiagComponentLogger;\n}());\nexport { DiagComponentLogger };\nfunction logProxy(funcName, namespace, args) {\n var logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n args.unshift(namespace);\n return logger[funcName].apply(logger, __spreadArray([], __read(args), false));\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DiagLogLevel } from '../types';\nexport function createLogLevelDiagLogger(maxLevel, logger) {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n }\n else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n // In case the logger is null or undefined\n logger = logger || {};\n function _filterFunc(funcName, theLevel) {\n var theFunc = logger[funcName];\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () { };\n }\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport var DiagLogLevel;\n(function (DiagLogLevel) {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n DiagLogLevel[DiagLogLevel[\"NONE\"] = 0] = \"NONE\";\n /** Identifies an error scenario */\n DiagLogLevel[DiagLogLevel[\"ERROR\"] = 30] = \"ERROR\";\n /** Identifies a warning scenario */\n DiagLogLevel[DiagLogLevel[\"WARN\"] = 50] = \"WARN\";\n /** General informational log message */\n DiagLogLevel[DiagLogLevel[\"INFO\"] = 60] = \"INFO\";\n /** General debug log message */\n DiagLogLevel[DiagLogLevel[\"DEBUG\"] = 70] = \"DEBUG\";\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n DiagLogLevel[DiagLogLevel[\"VERBOSE\"] = 80] = \"VERBOSE\";\n /** Used to set the logging level to include all logging */\n DiagLogLevel[DiagLogLevel[\"ALL\"] = 9999] = \"ALL\";\n})(DiagLogLevel || (DiagLogLevel = {}));\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { _globalThis } from '../platform';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\nvar major = VERSION.split('.')[0];\nvar GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\"opentelemetry.js.api.\" + major);\nvar _global = _globalThis;\nexport function registerGlobal(type, instance, diag, allowOverride) {\n var _a;\n if (allowOverride === void 0) { allowOverride = false; }\n var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {\n version: VERSION,\n });\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n var err = new Error(\"@opentelemetry/api: Attempted duplicate registration of API: \" + type);\n diag.error(err.stack || err.message);\n return false;\n }\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n var err = new Error(\"@opentelemetry/api: Registration of version v\" + api.version + \" for \" + type + \" does not match previously registered API v\" + VERSION);\n diag.error(err.stack || err.message);\n return false;\n }\n api[type] = instance;\n diag.debug(\"@opentelemetry/api: Registered a global for \" + type + \" v\" + VERSION + \".\");\n return true;\n}\nexport function getGlobal(type) {\n var _a, _b;\n var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];\n}\nexport function unregisterGlobal(type, diag) {\n diag.debug(\"@opentelemetry/api: Unregistering a global for \" + type + \" v\" + VERSION + \".\");\n var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n if (api) {\n delete api[type];\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { VERSION } from '../version';\nvar re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(ownVersion) {\n var acceptedVersions = new Set([ownVersion]);\n var rejectedVersions = new Set();\n var myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return function () { return false; };\n }\n var ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion) {\n return globalVersion === ownVersion;\n };\n }\n function _reject(v) {\n rejectedVersions.add(v);\n return false;\n }\n function _accept(v) {\n acceptedVersions.add(v);\n return true;\n }\n return function isCompatible(globalVersion) {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n var globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n var globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n if (ownVersionParsed.major === 0) {\n if (ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch) {\n return _accept(globalVersion);\n }\n return _reject(globalVersion);\n }\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n return _reject(globalVersion);\n };\n}\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport var isCompatible = _makeCompatibilityCheck(VERSION);\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Updates to this file should also be replicated to @opentelemetry/core too.\n/**\n * - globalThis (New standard)\n * - self (Will return the current window instance for supported browsers)\n * - window (fallback for older browser implementations)\n * - global (NodeJS implementation)\n * -