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O4kF,mBACZ9mF,QAASkC,OAAO6kF,eAChBlsD,kBAAmB34B,OAAO8kF,kBAC1BtoD,wBAAyB,EACzBa,uBAAuB,EACvBK,oBAAqB,mB","sources":["webpack://market-storefront/./node_modules/@datadog/browser-core/esm/boot/init.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/browser/addEventListener.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/browser/pageExitObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/browser/runOnReadyState.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/configuration/intakeSites.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/connectivity/connectivity.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/error/error.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/error/error.types.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/telemetry/rawTelemetryEvent.types.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/telemetry/telemetry.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/boundedBuffer.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/catchUserErrors.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/display.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/experimentalFeatures.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/getGlobalObject.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/getZoneJsOriginalValue.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/instrumentMethod.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/mergeInto.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/monitor.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/observable.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/requestIdleCallback.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/sendToExtension.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/serialisation/jsonStringify.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/serialisation/sanitize.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/stackTrace/computeStackTrace.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/stackTrace/handlingStack.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/timer.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/arrayUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/browserDetection.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/byteUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/functionUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/numberUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/objectUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/polyfills.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/responseUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/timeUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/typeUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/urlPolyfill.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/transport/eventBridge.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/transport/sendWithRetryStrategy.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/transport/httpRequest.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/context/customerDataTracker.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/context/contextManager.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/trackingConsent.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/context/storeContextManager.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/encoder.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/user/user.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/boot/displayAlreadyInitializedError.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/utils/stringUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/vital/vitalCollection.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/plugins.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/browser/fetchObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/browser/cookie.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/synthetics/syntheticsWorkerValues.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/session/storeStrategies/sessionStoreStrategy.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/session/sessionConstants.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/session/sessionStateValidation.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/session/sessionState.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/session/oldCookiesMigration.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/session/storeStrategies/sessionInCookie.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/session/storeStrategies/sessionInLocalStorage.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/session/sessionStoreOperations.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/session/sessionStore.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/configuration/endpointBuilder.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/configuration/tags.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/configuration/transportConfiguration.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/configuration/configuration.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/matchOption.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/crypto.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/tracing/identifier.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/tracing/tracer.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/tracing/sampler.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/configuration/configuration.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/configuration/remoteConfiguration.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/boot/preStartRum.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/boot/rumPublicApi.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/contexts/commonContext.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/domMutationObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/eventRateLimiter/createEventRateLimiter.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/contexts/syntheticsContext.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/limitModification.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/assembly.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/lifeCycle.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/abstractLifeCycle.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/valueHistory.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/contexts/viewHistory.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/browser/xhrObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/resource/resourceUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/requestCollection.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/readBytesFromStream.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/discardNegativeDuration.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/trackEventCounts.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/firstInputPolyfill.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/performanceObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/waitPageActivityEnd.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/htmlDomUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/privacy.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/action/getActionNameFromElement.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/getSelectorFromElement.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/action/clickChain.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/action/listenActionEvents.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/action/computeFrustration.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/action/interactionSelectorCache.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/action/trackClickActions.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/action/actionCollection.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/error/trackRuntimeError.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/console/consoleObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/report/reportObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/error/errorCollection.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/error/trackConsoleError.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/error/trackReportError.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/tools/taskQueue.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/resource/matchRequestResourceEntry.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/tracing/getDocumentTraceId.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/performanceUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/resource/retrieveInitialDocumentResourceTiming.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/resource/resourceCollection.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackFirstContentfulPaint.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackNavigationTimings.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackLargestContentfulPaint.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackFirstHidden.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackInitialViewMetrics.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackFirstInput.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackCumulativeLayoutShift.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/interactionCountPolyfill.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackInteractionToNextPaint.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/scroll.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/viewportObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackScrollMetrics.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackCommonViewMetrics.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackLoadingTime.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/trackViews.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/trackViewEventCounts.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/view/viewCollection.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/domain/session/sessionManager.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/rumSessionManager.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/transport/batch.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/transport/flushController.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/transport/startRumBatch.js","webpack://market-storefront/./node_modules/@datadog/browser-core/esm/transport/startBatchWithReplica.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/contexts/urlContexts.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/locationChangeObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/contexts/featureFlagContext.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/startCustomerDataTelemetry.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/contexts/pageStateHistory.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/cookieObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/contexts/ciVisibilityContext.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/boot/startRum.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/transport/startRumEventBridge.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/browser/windowOpenObservable.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/contexts/displayContext.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/longAnimationFrame/longAnimationFrameCollection.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/longTask/longTaskCollection.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/contexts/internalContext.js","webpack://market-storefront/./node_modules/@datadog/browser-rum-core/esm/domain/getSessionReplayUrl.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializationUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/types/sessionReplayConstants.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializeStyleSheets.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializeAttribute.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializeAttributes.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializeNode.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializeDocument.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/eventsUtils.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/viewports.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/assembly.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackMove.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackMouseInteraction.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackScroll.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackViewportResize.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackMediaInteraction.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackStyleSheet.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackFocus.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackFrustration.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackViewEnd.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackInput.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/mutationBatch.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackMutation.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/shadowRootsController.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/record.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/elementsScrollPositions.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/startFullSnapshots.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/record/recordIds.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/segmentCollection/segment.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/segmentCollection/segmentCollection.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/segmentCollection/buildReplayPayload.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/boot/startRecording.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/startRecordBridge.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/replayStats.js","webpack://market-storefront/webpack/bootstrap","webpack://market-storefront/webpack/runtime/define property getters","webpack://market-storefront/webpack/runtime/hasOwnProperty shorthand","webpack://market-storefront/webpack/runtime/make namespace object","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/deflate/deflateEncoder.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/deflate/deflateWorker.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/boot/isBrowserSupported.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/domain/getSessionReplayLink.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/boot/postStartStrategy.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/entries/main.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/boot/recorderApi.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/boot/preStartStrategy.js","webpack://market-storefront/./node_modules/@datadog/browser-rum/esm/boot/lazyLoadRecorder.js","webpack://market-storefront/./app/javascript/packs/datadog.js"],"sourcesContent":["import { catchUserErrors } from '../tools/catchUserErrors';\nimport { setDebugMode } from '../tools/monitor';\nimport { display } from '../tools/display';\nexport function makePublicApi(stub) {\n    const publicApi = {\n        version: \"6.1.0\",\n        // This API method is intentionally not monitored, since the only thing executed is the\n        // user-provided 'callback'.  All SDK usages executed in the callback should be monitored, and\n        // we don't want to interfere with the user uncaught exceptions.\n        onReady(callback) {\n            callback();\n        },\n        ...stub,\n    };\n    // Add a \"hidden\" property to set debug mode. We define it that way to hide it\n    // as much as possible but of course it's not a real protection.\n    Object.defineProperty(publicApi, '_setDebug', {\n        get() {\n            return setDebugMode;\n        },\n        enumerable: false,\n    });\n    return publicApi;\n}\nexport function defineGlobal(global, name, api) {\n    const existingGlobalVariable = global[name];\n    if (existingGlobalVariable && !existingGlobalVariable.q && existingGlobalVariable.version) {\n        display.warn('SDK is loaded more than once. This is unsupported and might have unexpected behavior.');\n    }\n    global[name] = api;\n    if (existingGlobalVariable && existingGlobalVariable.q) {\n        existingGlobalVariable.q.forEach((fn) => catchUserErrors(fn, 'onReady callback threw an error:')());\n    }\n}\n//# sourceMappingURL=init.js.map","import { monitor } from '../tools/monitor';\nimport { getZoneJsOriginalValue } from '../tools/getZoneJsOriginalValue';\n/**\n * Add an event listener to an event target object (Window, Element, mock object...).  This provides\n * a few conveniences compared to using `element.addEventListener` directly:\n *\n * * supports IE11 by: using an option object only if needed and emulating the `once` option\n *\n * * wraps the listener with a `monitor` function\n *\n * * returns a `stop` function to remove the listener\n */\nexport function addEventListener(configuration, eventTarget, eventName, listener, options) {\n    return addEventListeners(configuration, eventTarget, [eventName], listener, options);\n}\n/**\n * Add event listeners to an event target object (Window, Element, mock object...).  This provides\n * a few conveniences compared to using `element.addEventListener` directly:\n *\n * * supports IE11 by: using an option object only if needed and emulating the `once` option\n *\n * * wraps the listener with a `monitor` function\n *\n * * returns a `stop` function to remove the listener\n *\n * * with `once: true`, the listener will be called at most once, even if different events are listened\n */\nexport function addEventListeners(configuration, eventTarget, eventNames, listener, { once, capture, passive } = {}) {\n    const listenerWithMonitor = monitor((event) => {\n        if (!event.isTrusted && !event.__ddIsTrusted && !configuration.allowUntrustedEvents) {\n            return;\n        }\n        if (once) {\n            stop();\n        }\n        listener(event);\n    });\n    const options = passive ? { capture, passive } : capture;\n    // Use the window.EventTarget.prototype when possible to avoid wrong overrides (e.g: https://github.com/salesforce/lwc/issues/1824)\n    const listenerTarget = window.EventTarget && eventTarget instanceof EventTarget ? window.EventTarget.prototype : eventTarget;\n    const add = getZoneJsOriginalValue(listenerTarget, 'addEventListener');\n    eventNames.forEach((eventName) => add.call(eventTarget, eventName, listenerWithMonitor, options));\n    function stop() {\n        const remove = getZoneJsOriginalValue(listenerTarget, 'removeEventListener');\n        eventNames.forEach((eventName) => remove.call(eventTarget, eventName, listenerWithMonitor, options));\n    }\n    return {\n        stop,\n    };\n}\n//# sourceMappingURL=addEventListener.js.map","import { Observable } from '../tools/observable';\nimport { objectValues } from '../tools/utils/polyfills';\nimport { addEventListeners, addEventListener } from './addEventListener';\nexport const PageExitReason = {\n    HIDDEN: 'visibility_hidden',\n    UNLOADING: 'before_unload',\n    PAGEHIDE: 'page_hide',\n    FROZEN: 'page_frozen',\n};\nexport function createPageExitObservable(configuration) {\n    return new Observable((observable) => {\n        const { stop: stopListeners } = addEventListeners(configuration, window, [\"visibilitychange\" /* DOM_EVENT.VISIBILITY_CHANGE */, \"freeze\" /* DOM_EVENT.FREEZE */], (event) => {\n            if (event.type === \"visibilitychange\" /* DOM_EVENT.VISIBILITY_CHANGE */ && document.visibilityState === 'hidden') {\n                /**\n                 * Only event that guarantee to fire on mobile devices when the page transitions to background state\n                 * (e.g. when user switches to a different application, goes to homescreen, etc), or is being unloaded.\n                 */\n                observable.notify({ reason: PageExitReason.HIDDEN });\n            }\n            else if (event.type === \"freeze\" /* DOM_EVENT.FREEZE */) {\n                /**\n                 * After transitioning in background a tab can be freezed to preserve resources. (cf: https://developer.chrome.com/blog/page-lifecycle-api)\n                 * Allow to collect events happening between hidden and frozen state.\n                 */\n                observable.notify({ reason: PageExitReason.FROZEN });\n            }\n        }, { capture: true });\n        const stopBeforeUnloadListener = addEventListener(configuration, window, \"beforeunload\" /* DOM_EVENT.BEFORE_UNLOAD */, () => {\n            observable.notify({ reason: PageExitReason.UNLOADING });\n        }).stop;\n        return () => {\n            stopListeners();\n            stopBeforeUnloadListener();\n        };\n    });\n}\nexport function isPageExitReason(reason) {\n    return objectValues(PageExitReason).includes(reason);\n}\n//# sourceMappingURL=pageExitObservable.js.map","import { noop } from '../tools/utils/functionUtils';\nimport { addEventListener } from './addEventListener';\nexport function runOnReadyState(configuration, expectedReadyState, callback) {\n    if (document.readyState === expectedReadyState || document.readyState === 'complete') {\n        callback();\n        return { stop: noop };\n    }\n    const eventName = expectedReadyState === 'complete' ? \"load\" /* DOM_EVENT.LOAD */ : \"DOMContentLoaded\" /* DOM_EVENT.DOM_CONTENT_LOADED */;\n    return addEventListener(configuration, window, eventName, callback, { once: true });\n}\nexport function asyncRunOnReadyState(configuration, expectedReadyState) {\n    return new Promise((resolve) => {\n        runOnReadyState(configuration, expectedReadyState, resolve);\n    });\n}\n//# sourceMappingURL=runOnReadyState.js.map","export const INTAKE_SITE_STAGING = 'datad0g.com';\nexport const INTAKE_SITE_FED_STAGING = 'dd0g-gov.com';\nexport const INTAKE_SITE_US1 = 'datadoghq.com';\nexport const INTAKE_SITE_EU1 = 'datadoghq.eu';\nexport const INTAKE_SITE_US1_FED = 'ddog-gov.com';\nexport const PCI_INTAKE_HOST_US1 = 'pci.browser-intake-datadoghq.com';\nexport const INTAKE_URL_PARAMETERS = ['ddsource', 'ddtags'];\n//# sourceMappingURL=intakeSites.js.map","export function getConnectivity() {\n    var _a;\n    const navigator = window.navigator;\n    return {\n        status: navigator.onLine ? 'connected' : 'not_connected',\n        interfaces: navigator.connection && navigator.connection.type ? [navigator.connection.type] : undefined,\n        effective_type: (_a = navigator.connection) === null || _a === void 0 ? void 0 : _a.effectiveType,\n    };\n}\n//# sourceMappingURL=connectivity.js.map","import { sanitize } from '../../tools/serialisation/sanitize';\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify';\nimport { computeStackTrace } from '../../tools/stackTrace/computeStackTrace';\nimport { toStackTraceString } from '../../tools/stackTrace/handlingStack';\nexport const NO_ERROR_STACK_PRESENT_MESSAGE = 'No stack, consider using an instance of Error';\nexport function computeRawError({ stackTrace, originalError, handlingStack, componentStack, startClocks, nonErrorPrefix, source, handling, }) {\n    const isErrorInstance = isError(originalError);\n    const message = computeMessage(stackTrace, isErrorInstance, nonErrorPrefix, originalError);\n    const stack = hasUsableStack(isErrorInstance, stackTrace)\n        ? toStackTraceString(stackTrace)\n        : NO_ERROR_STACK_PRESENT_MESSAGE;\n    const causes = isErrorInstance ? flattenErrorCauses(originalError, source) : undefined;\n    const type = stackTrace ? stackTrace.name : undefined;\n    const fingerprint = tryToGetFingerprint(originalError);\n    return {\n        startClocks,\n        source,\n        handling,\n        handlingStack,\n        componentStack,\n        originalError,\n        type,\n        message,\n        stack,\n        causes,\n        fingerprint,\n    };\n}\nfunction computeMessage(stackTrace, isErrorInstance, nonErrorPrefix, originalError) {\n    // Favor stackTrace message only if tracekit has really been able to extract something meaningful (message + name)\n    // TODO rework tracekit integration to avoid scattering error building logic\n    return (stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.message) && (stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.name)\n        ? stackTrace.message\n        : !isErrorInstance\n            ? `${nonErrorPrefix} ${jsonStringify(sanitize(originalError))}`\n            : 'Empty message';\n}\nfunction hasUsableStack(isErrorInstance, stackTrace) {\n    if (stackTrace === undefined) {\n        return false;\n    }\n    if (isErrorInstance) {\n        return true;\n    }\n    // handle cases where tracekit return stack = [] or stack = [{url: undefined, line: undefined, column: undefined}]\n    // TODO rework tracekit integration to avoid generating those unusable stack\n    return stackTrace.stack.length > 0 && (stackTrace.stack.length > 1 || stackTrace.stack[0].url !== undefined);\n}\nexport function tryToGetFingerprint(originalError) {\n    return isError(originalError) && 'dd_fingerprint' in originalError ? String(originalError.dd_fingerprint) : undefined;\n}\nexport function getFileFromStackTraceString(stack) {\n    var _a;\n    return (_a = /@ (.+)/.exec(stack)) === null || _a === void 0 ? void 0 : _a[1];\n}\nexport function isError(error) {\n    return error instanceof Error || Object.prototype.toString.call(error) === '[object Error]';\n}\nexport function flattenErrorCauses(error, parentSource) {\n    let currentError = error;\n    const causes = [];\n    while (isError(currentError === null || currentError === void 0 ? void 0 : currentError.cause) && causes.length < 10) {\n        const stackTrace = computeStackTrace(currentError.cause);\n        causes.push({\n            message: currentError.cause.message,\n            source: parentSource,\n            type: stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.name,\n            stack: stackTrace && toStackTraceString(stackTrace),\n        });\n        currentError = currentError.cause;\n    }\n    return causes.length ? causes : undefined;\n}\n//# sourceMappingURL=error.js.map","export const ErrorSource = {\n    AGENT: 'agent',\n    CONSOLE: 'console',\n    CUSTOM: 'custom',\n    LOGGER: 'logger',\n    NETWORK: 'network',\n    SOURCE: 'source',\n    REPORT: 'report',\n};\n//# sourceMappingURL=error.types.js.map","export const TelemetryType = {\n    log: 'log',\n    configuration: 'configuration',\n    usage: 'usage',\n};\n//# sourceMappingURL=rawTelemetryEvent.types.js.map","import { ConsoleApiName } from '../../tools/display';\nimport { NO_ERROR_STACK_PRESENT_MESSAGE, isError } from '../error/error';\nimport { toStackTraceString } from '../../tools/stackTrace/handlingStack';\nimport { getExperimentalFeatures } from '../../tools/experimentalFeatures';\nimport { INTAKE_SITE_STAGING, INTAKE_SITE_US1_FED } from '../configuration';\nimport { Observable } from '../../tools/observable';\nimport { timeStampNow } from '../../tools/utils/timeUtils';\nimport { displayIfDebugEnabled, startMonitorErrorCollection } from '../../tools/monitor';\nimport { sendToExtension } from '../../tools/sendToExtension';\nimport { performDraw } from '../../tools/utils/numberUtils';\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify';\nimport { combine } from '../../tools/mergeInto';\nimport { computeStackTrace } from '../../tools/stackTrace/computeStackTrace';\nimport { getConnectivity } from '../connectivity';\nimport { createBoundedBuffer } from '../../tools/boundedBuffer';\nimport { TelemetryType } from './rawTelemetryEvent.types';\nconst ALLOWED_FRAME_URLS = [\n    'https://www.datadoghq-browser-agent.com',\n    'https://www.datad0g-browser-agent.com',\n    'https://d3uc069fcn7uxw.cloudfront.net',\n    'https://d20xtzwzcl0ceb.cloudfront.net',\n    'http://localhost',\n    '<anonymous>',\n];\nconst TELEMETRY_EXCLUDED_SITES = [INTAKE_SITE_US1_FED];\n// eslint-disable-next-line local-rules/disallow-side-effects\nlet preStartTelemetryBuffer = createBoundedBuffer();\nlet onRawTelemetryEventCollected = (event) => {\n    preStartTelemetryBuffer.add(() => onRawTelemetryEventCollected(event));\n};\nexport function startTelemetry(telemetryService, configuration) {\n    let contextProvider;\n    const observable = new Observable();\n    const alreadySentEvents = new Set();\n    const telemetryEnabled = !TELEMETRY_EXCLUDED_SITES.includes(configuration.site) && performDraw(configuration.telemetrySampleRate);\n    const telemetryEnabledPerType = {\n        [TelemetryType.log]: telemetryEnabled,\n        [TelemetryType.configuration]: telemetryEnabled && performDraw(configuration.telemetryConfigurationSampleRate),\n        [TelemetryType.usage]: telemetryEnabled && performDraw(configuration.telemetryUsageSampleRate),\n    };\n    const runtimeEnvInfo = getRuntimeEnvInfo();\n    onRawTelemetryEventCollected = (rawEvent) => {\n        const stringifiedEvent = jsonStringify(rawEvent);\n        if (telemetryEnabledPerType[rawEvent.type] &&\n            alreadySentEvents.size < configuration.maxTelemetryEventsPerPage &&\n            !alreadySentEvents.has(stringifiedEvent)) {\n            const event = toTelemetryEvent(telemetryService, rawEvent, runtimeEnvInfo);\n            observable.notify(event);\n            sendToExtension('telemetry', event);\n            alreadySentEvents.add(stringifiedEvent);\n        }\n    };\n    startMonitorErrorCollection(addTelemetryError);\n    function toTelemetryEvent(telemetryService, event, runtimeEnvInfo) {\n        return combine({\n            type: 'telemetry',\n            date: timeStampNow(),\n            service: telemetryService,\n            version: \"6.1.0\",\n            source: 'browser',\n            _dd: {\n                format_version: 2,\n            },\n            telemetry: combine(event, {\n                runtime_env: runtimeEnvInfo,\n                connectivity: getConnectivity(),\n                sdk_setup: \"npm\",\n            }),\n            experimental_features: Array.from(getExperimentalFeatures()),\n        }, contextProvider !== undefined ? contextProvider() : {});\n    }\n    return {\n        setContextProvider: (provider) => {\n            contextProvider = provider;\n        },\n        observable,\n        enabled: telemetryEnabled,\n    };\n}\nfunction getRuntimeEnvInfo() {\n    return {\n        is_local_file: window.location.protocol === 'file:',\n        is_worker: 'WorkerGlobalScope' in self,\n    };\n}\nexport function startFakeTelemetry() {\n    const events = [];\n    onRawTelemetryEventCollected = (event) => {\n        events.push(event);\n    };\n    return events;\n}\n// need to be called after telemetry context is provided and observers are registered\nexport function drainPreStartTelemetry() {\n    preStartTelemetryBuffer.drain();\n}\nexport function resetTelemetry() {\n    preStartTelemetryBuffer = createBoundedBuffer();\n    onRawTelemetryEventCollected = (event) => {\n        preStartTelemetryBuffer.add(() => onRawTelemetryEventCollected(event));\n    };\n}\n/**\n * Avoid mixing telemetry events from different data centers\n * but keep replicating staging events for reliability\n */\nexport function isTelemetryReplicationAllowed(configuration) {\n    return configuration.site === INTAKE_SITE_STAGING;\n}\nexport function addTelemetryDebug(message, context) {\n    displayIfDebugEnabled(ConsoleApiName.debug, message, context);\n    onRawTelemetryEventCollected({\n        type: TelemetryType.log,\n        message,\n        status: \"debug\" /* StatusType.debug */,\n        ...context,\n    });\n}\nexport function addTelemetryError(e, context) {\n    onRawTelemetryEventCollected({\n        type: TelemetryType.log,\n        status: \"error\" /* StatusType.error */,\n        ...formatError(e),\n        ...context,\n    });\n}\nexport function addTelemetryConfiguration(configuration) {\n    onRawTelemetryEventCollected({\n        type: TelemetryType.configuration,\n        configuration,\n    });\n}\nexport function addTelemetryUsage(usage) {\n    onRawTelemetryEventCollected({\n        type: TelemetryType.usage,\n        usage,\n    });\n}\nexport function formatError(e) {\n    if (isError(e)) {\n        const stackTrace = computeStackTrace(e);\n        return {\n            error: {\n                kind: stackTrace.name,\n                stack: toStackTraceString(scrubCustomerFrames(stackTrace)),\n            },\n            message: stackTrace.message,\n        };\n    }\n    return {\n        error: {\n            stack: NO_ERROR_STACK_PRESENT_MESSAGE,\n        },\n        message: `${\"Uncaught\" /* NonErrorPrefix.UNCAUGHT */} ${jsonStringify(e)}`,\n    };\n}\nexport function scrubCustomerFrames(stackTrace) {\n    stackTrace.stack = stackTrace.stack.filter((frame) => !frame.url || ALLOWED_FRAME_URLS.some((allowedFrameUrl) => frame.url.startsWith(allowedFrameUrl)));\n    return stackTrace;\n}\n//# sourceMappingURL=telemetry.js.map","import { removeItem } from './utils/arrayUtils';\nconst BUFFER_LIMIT = 500;\nexport function createBoundedBuffer() {\n    const buffer = [];\n    const add = (callback) => {\n        const length = buffer.push(callback);\n        if (length > BUFFER_LIMIT) {\n            buffer.splice(0, 1);\n        }\n    };\n    const remove = (callback) => {\n        removeItem(buffer, callback);\n    };\n    const drain = (arg) => {\n        buffer.forEach((callback) => callback(arg));\n        buffer.length = 0;\n    };\n    return {\n        add,\n        remove,\n        drain,\n    };\n}\n//# sourceMappingURL=boundedBuffer.js.map","import { display } from './display';\nexport function catchUserErrors(fn, errorMsg) {\n    return (...args) => {\n        try {\n            return fn(...args);\n        }\n        catch (err) {\n            display.error(errorMsg, err);\n        }\n    };\n}\n//# sourceMappingURL=catchUserErrors.js.map","/* eslint-disable local-rules/disallow-side-effects */\n/**\n * Keep references on console methods to avoid triggering patched behaviors\n *\n * NB: in some setup, console could already be patched by another SDK.\n * In this case, some display messages can be sent by the other SDK\n * but we should be safe from infinite loop nonetheless.\n */\nexport const ConsoleApiName = {\n    log: 'log',\n    debug: 'debug',\n    info: 'info',\n    warn: 'warn',\n    error: 'error',\n};\n/**\n * When building JS bundles, some users might use a plugin[1] or configuration[2] to remove\n * \"console.*\" references. This causes some issue as we expect `console.*` to be defined.\n * As a workaround, let's use a variable alias, so those expressions won't be taken into account by\n * simple static analysis.\n *\n * [1]: https://babeljs.io/docs/babel-plugin-transform-remove-console/\n * [2]: https://github.com/terser/terser#compress-options (look for drop_console)\n */\nexport const globalConsole = console;\nexport const originalConsoleMethods = {};\nObject.keys(ConsoleApiName).forEach((name) => {\n    originalConsoleMethods[name] = globalConsole[name];\n});\nconst PREFIX = 'Datadog Browser SDK:';\nexport const display = {\n    debug: originalConsoleMethods.debug.bind(globalConsole, PREFIX),\n    log: originalConsoleMethods.log.bind(globalConsole, PREFIX),\n    info: originalConsoleMethods.info.bind(globalConsole, PREFIX),\n    warn: originalConsoleMethods.warn.bind(globalConsole, PREFIX),\n    error: originalConsoleMethods.error.bind(globalConsole, PREFIX),\n};\nexport const DOCS_ORIGIN = 'https://docs.datadoghq.com';\nexport const DOCS_TROUBLESHOOTING = `${DOCS_ORIGIN}/real_user_monitoring/browser/troubleshooting`;\nexport const MORE_DETAILS = 'More details:';\n//# sourceMappingURL=display.js.map","/**\n * LIMITATION:\n * For NPM setup, this feature flag singleton is shared between RUM and Logs product.\n * This means that an experimental flag set on the RUM product will be set on the Logs product.\n * So keep in mind that in certain configurations, your experimental feature flag may affect other products.\n *\n * FORMAT:\n * All feature flags should be snake_cased\n */\n// We want to use a real enum (i.e. not a const enum) here, to be able to check whether an arbitrary\n// string is an expected feature flag\nimport { objectHasValue } from './utils/objectUtils';\n// eslint-disable-next-line no-restricted-syntax\nexport var ExperimentalFeature;\n(function (ExperimentalFeature) {\n    ExperimentalFeature[\"WRITABLE_RESOURCE_GRAPHQL\"] = \"writable_resource_graphql\";\n    ExperimentalFeature[\"REMOTE_CONFIGURATION\"] = \"remote_configuration\";\n    ExperimentalFeature[\"ACTION_NAME_MASKING\"] = \"action_name_masking\";\n    ExperimentalFeature[\"CONSISTENT_TRACE_SAMPLING\"] = \"consistent_trace_sampling\";\n})(ExperimentalFeature || (ExperimentalFeature = {}));\nconst enabledExperimentalFeatures = new Set();\nexport function initFeatureFlags(enableExperimentalFeatures) {\n    if (Array.isArray(enableExperimentalFeatures)) {\n        addExperimentalFeatures(enableExperimentalFeatures.filter((flag) => objectHasValue(ExperimentalFeature, flag)));\n    }\n}\nexport function addExperimentalFeatures(enabledFeatures) {\n    enabledFeatures.forEach((flag) => {\n        enabledExperimentalFeatures.add(flag);\n    });\n}\nexport function isExperimentalFeatureEnabled(featureName) {\n    return enabledExperimentalFeatures.has(featureName);\n}\nexport function resetExperimentalFeatures() {\n    enabledExperimentalFeatures.clear();\n}\nexport function getExperimentalFeatures() {\n    return enabledExperimentalFeatures;\n}\n//# sourceMappingURL=experimentalFeatures.js.map","/**\n * inspired by https://mathiasbynens.be/notes/globalthis\n */\nexport function getGlobalObject() {\n    if (typeof globalThis === 'object') {\n        return globalThis;\n    }\n    Object.defineProperty(Object.prototype, '_dd_temp_', {\n        get() {\n            return this;\n        },\n        configurable: true,\n    });\n    // @ts-ignore _dd_temp is defined using defineProperty\n    let globalObject = _dd_temp_;\n    // @ts-ignore _dd_temp is defined using defineProperty\n    delete Object.prototype._dd_temp_;\n    if (typeof globalObject !== 'object') {\n        // on safari _dd_temp_ is available on window but not globally\n        // fallback on other browser globals check\n        if (typeof self === 'object') {\n            globalObject = self;\n        }\n        else if (typeof window === 'object') {\n            globalObject = window;\n        }\n        else {\n            globalObject = {};\n        }\n    }\n    return globalObject;\n}\n//# sourceMappingURL=getGlobalObject.js.map","import { getGlobalObject } from './getGlobalObject';\n/**\n * Gets the original value for a DOM API that was potentially patched by Zone.js.\n *\n * Zone.js[1] is a library that patches a bunch of JS and DOM APIs. It usually stores the original\n * value of the patched functions/constructors/methods in a hidden property prefixed by\n * __zone_symbol__.\n *\n * In multiple occasions, we observed that Zone.js is the culprit of important issues leading to\n * browser resource exhaustion (memory leak, high CPU usage). This method is used as a workaround to\n * use the original DOM API instead of the one patched by Zone.js.\n *\n * [1]: https://github.com/angular/angular/tree/main/packages/zone.js\n */\nexport function getZoneJsOriginalValue(target, name) {\n    const browserWindow = getGlobalObject();\n    let original;\n    if (browserWindow.Zone && typeof browserWindow.Zone.__symbol__ === 'function') {\n        original = target[browserWindow.Zone.__symbol__(name)];\n    }\n    if (!original) {\n        original = target[name];\n    }\n    return original;\n}\n//# sourceMappingURL=getZoneJsOriginalValue.js.map","import { setTimeout } from './timer';\nimport { callMonitored } from './monitor';\nimport { noop } from './utils/functionUtils';\nimport { createHandlingStack } from './stackTrace/handlingStack';\n/**\n * Instruments a method on a object, calling the given callback before the original method is\n * invoked. The callback receives an object with information about the method call.\n *\n * This function makes sure that we are \"good citizens\" regarding third party instrumentations: when\n * removing the instrumentation, the original method is usually restored, but if a third party\n * instrumentation was set after ours, we keep it in place and just replace our instrumentation with\n * a noop.\n *\n * Note: it is generally better to instrument methods that are \"owned\" by the object instead of ones\n * that are inherited from the prototype chain. Example:\n * * do:    `instrumentMethod(Array.prototype, 'push', ...)`\n * * don't: `instrumentMethod([], 'push', ...)`\n *\n * This method is also used to set event handler properties (ex: window.onerror = ...), as it has\n * the same requirements as instrumenting a method:\n * * if the event handler is already set by a third party, we need to call it and not just blindly\n * override it.\n * * if the event handler is set by a third party after us, we need to keep it in place when\n * removing ours.\n *\n * @example\n *\n *  instrumentMethod(window, 'fetch', ({ target, parameters, onPostCall }) => {\n *    console.log('Before calling fetch on', target, 'with parameters', parameters)\n *\n *    onPostCall((result) => {\n *      console.log('After fetch calling on', target, 'with parameters', parameters, 'and result', result)\n *    })\n *  })\n */\nexport function instrumentMethod(targetPrototype, method, onPreCall, { computeHandlingStack } = {}) {\n    let original = targetPrototype[method];\n    if (typeof original !== 'function') {\n        if (method in targetPrototype && method.startsWith('on')) {\n            original = noop;\n        }\n        else {\n            return { stop: noop };\n        }\n    }\n    let stopped = false;\n    const instrumentation = function () {\n        if (stopped) {\n            // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call\n            return original.apply(this, arguments);\n        }\n        const parameters = Array.from(arguments);\n        let postCallCallback;\n        callMonitored(onPreCall, null, [\n            {\n                target: this,\n                parameters,\n                onPostCall: (callback) => {\n                    postCallCallback = callback;\n                },\n                handlingStack: computeHandlingStack ? createHandlingStack() : undefined,\n            },\n        ]);\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n        const result = original.apply(this, parameters);\n        if (postCallCallback) {\n            callMonitored(postCallCallback, null, [result]);\n        }\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n        return result;\n    };\n    targetPrototype[method] = instrumentation;\n    return {\n        stop: () => {\n            stopped = true;\n            // If the instrumentation has been removed by a third party, keep the last one\n            if (targetPrototype[method] === instrumentation) {\n                targetPrototype[method] = original;\n            }\n        },\n    };\n}\nexport function instrumentSetter(targetPrototype, property, after) {\n    const originalDescriptor = Object.getOwnPropertyDescriptor(targetPrototype, property);\n    if (!originalDescriptor || !originalDescriptor.set || !originalDescriptor.configurable) {\n        return { stop: noop };\n    }\n    const stoppedInstrumentation = noop;\n    let instrumentation = (target, value) => {\n        // put hooked setter into event loop to avoid of set latency\n        setTimeout(() => {\n            if (instrumentation !== stoppedInstrumentation) {\n                after(target, value);\n            }\n        }, 0);\n    };\n    const instrumentationWrapper = function (value) {\n        originalDescriptor.set.call(this, value);\n        instrumentation(this, value);\n    };\n    Object.defineProperty(targetPrototype, property, {\n        set: instrumentationWrapper,\n    });\n    return {\n        stop: () => {\n            var _a;\n            if (((_a = Object.getOwnPropertyDescriptor(targetPrototype, property)) === null || _a === void 0 ? void 0 : _a.set) === instrumentationWrapper) {\n                Object.defineProperty(targetPrototype, property, originalDescriptor);\n            }\n            instrumentation = stoppedInstrumentation;\n        },\n    };\n}\n//# sourceMappingURL=instrumentMethod.js.map","import { getType } from './utils/typeUtils';\n/**\n * Iterate over source and affect its sub values into destination, recursively.\n * If the source and destination can't be merged, return source.\n */\nexport function mergeInto(destination, source, circularReferenceChecker = createCircularReferenceChecker()) {\n    // ignore the source if it is undefined\n    if (source === undefined) {\n        return destination;\n    }\n    if (typeof source !== 'object' || source === null) {\n        // primitive values - just return source\n        return source;\n    }\n    else if (source instanceof Date) {\n        return new Date(source.getTime());\n    }\n    else if (source instanceof RegExp) {\n        const flags = source.flags ||\n            // old browsers compatibility\n            [\n                source.global ? 'g' : '',\n                source.ignoreCase ? 'i' : '',\n                source.multiline ? 'm' : '',\n                source.sticky ? 'y' : '',\n                source.unicode ? 'u' : '',\n            ].join('');\n        return new RegExp(source.source, flags);\n    }\n    if (circularReferenceChecker.hasAlreadyBeenSeen(source)) {\n        // remove circular references\n        return undefined;\n    }\n    else if (Array.isArray(source)) {\n        const merged = Array.isArray(destination) ? destination : [];\n        for (let i = 0; i < source.length; ++i) {\n            merged[i] = mergeInto(merged[i], source[i], circularReferenceChecker);\n        }\n        return merged;\n    }\n    const merged = getType(destination) === 'object' ? destination : {};\n    for (const key in source) {\n        if (Object.prototype.hasOwnProperty.call(source, key)) {\n            merged[key] = mergeInto(merged[key], source[key], circularReferenceChecker);\n        }\n    }\n    return merged;\n}\n/**\n * A simplistic implementation of a deep clone algorithm.\n * Caveats:\n * - It doesn't maintain prototype chains - don't use with instances of custom classes.\n * - It doesn't handle Map and Set\n */\nexport function deepClone(value) {\n    return mergeInto(undefined, value);\n}\nexport function combine(...sources) {\n    let destination;\n    for (const source of sources) {\n        // Ignore any undefined or null sources.\n        if (source === undefined || source === null) {\n            continue;\n        }\n        destination = mergeInto(destination, source);\n    }\n    return destination;\n}\nfunction createCircularReferenceChecker() {\n    if (typeof WeakSet !== 'undefined') {\n        const set = new WeakSet();\n        return {\n            hasAlreadyBeenSeen(value) {\n                const has = set.has(value);\n                if (!has) {\n                    set.add(value);\n                }\n                return has;\n            },\n        };\n    }\n    const array = [];\n    return {\n        hasAlreadyBeenSeen(value) {\n            const has = array.indexOf(value) >= 0;\n            if (!has) {\n                array.push(value);\n            }\n            return has;\n        },\n    };\n}\n//# sourceMappingURL=mergeInto.js.map","import { display } from './display';\nlet onMonitorErrorCollected;\nlet debugMode = false;\nexport function startMonitorErrorCollection(newOnMonitorErrorCollected) {\n    onMonitorErrorCollected = newOnMonitorErrorCollected;\n}\nexport function setDebugMode(newDebugMode) {\n    debugMode = newDebugMode;\n}\nexport function resetMonitor() {\n    onMonitorErrorCollected = undefined;\n    debugMode = false;\n}\nexport function monitored(_, __, descriptor) {\n    const originalMethod = descriptor.value;\n    descriptor.value = function (...args) {\n        const decorated = onMonitorErrorCollected ? monitor(originalMethod) : originalMethod;\n        return decorated.apply(this, args);\n    };\n}\nexport function monitor(fn) {\n    return function () {\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n        return callMonitored(fn, this, arguments);\n    }; // consider output type has input type\n}\nexport function callMonitored(fn, context, args) {\n    try {\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n        return fn.apply(context, args);\n    }\n    catch (e) {\n        monitorError(e);\n    }\n}\nexport function monitorError(e) {\n    displayIfDebugEnabled(e);\n    if (onMonitorErrorCollected) {\n        try {\n            onMonitorErrorCollected(e);\n        }\n        catch (e) {\n            displayIfDebugEnabled(e);\n        }\n    }\n}\nexport function displayIfDebugEnabled(...args) {\n    if (debugMode) {\n        display.error('[MONITOR]', ...args);\n    }\n}\n//# sourceMappingURL=monitor.js.map","// eslint-disable-next-line no-restricted-syntax\nexport class Observable {\n    constructor(onFirstSubscribe) {\n        this.onFirstSubscribe = onFirstSubscribe;\n        this.observers = [];\n    }\n    subscribe(f) {\n        this.observers.push(f);\n        if (this.observers.length === 1 && this.onFirstSubscribe) {\n            this.onLastUnsubscribe = this.onFirstSubscribe(this) || undefined;\n        }\n        return {\n            unsubscribe: () => {\n                this.observers = this.observers.filter((other) => f !== other);\n                if (!this.observers.length && this.onLastUnsubscribe) {\n                    this.onLastUnsubscribe();\n                }\n            },\n        };\n    }\n    notify(data) {\n        this.observers.forEach((observer) => observer(data));\n    }\n}\nexport function mergeObservables(...observables) {\n    return new Observable((globalObservable) => {\n        const subscriptions = observables.map((observable) => observable.subscribe((data) => globalObservable.notify(data)));\n        return () => subscriptions.forEach((subscription) => subscription.unsubscribe());\n    });\n}\n//# sourceMappingURL=observable.js.map","import { setTimeout, clearTimeout } from './timer';\nimport { monitor } from './monitor';\nimport { dateNow } from './utils/timeUtils';\n/**\n * 'requestIdleCallback' with a shim.\n */\nexport function requestIdleCallback(callback, opts) {\n    // Note: check both 'requestIdleCallback' and 'cancelIdleCallback' existence because some polyfills only implement 'requestIdleCallback'.\n    if (window.requestIdleCallback && window.cancelIdleCallback) {\n        const id = window.requestIdleCallback(monitor(callback), opts);\n        return () => window.cancelIdleCallback(id);\n    }\n    return requestIdleCallbackShim(callback);\n}\nexport const MAX_TASK_TIME = 50;\n/*\n * Shim from https://developer.chrome.com/blog/using-requestidlecallback#checking_for_requestidlecallback\n * Note: there is no simple way to support the \"timeout\" option, so we ignore it.\n */\nexport function requestIdleCallbackShim(callback) {\n    const start = dateNow();\n    const timeoutId = setTimeout(() => {\n        callback({\n            didTimeout: false,\n            timeRemaining: () => Math.max(0, MAX_TASK_TIME - (dateNow() - start)),\n        });\n    }, 0);\n    return () => clearTimeout(timeoutId);\n}\n//# sourceMappingURL=requestIdleCallback.js.map","export function sendToExtension(type, payload) {\n    const callback = window.__ddBrowserSdkExtensionCallback;\n    if (callback) {\n        callback({ type, payload });\n    }\n}\n//# sourceMappingURL=sendToExtension.js.map","import { noop } from '../utils/functionUtils';\n/**\n * Custom implementation of JSON.stringify that ignores some toJSON methods. We need to do that\n * because some sites badly override toJSON on certain objects. Removing all toJSON methods from\n * nested values would be too costly, so we just detach them from the root value, and native classes\n * used to build JSON values (Array and Object).\n *\n * Note: this still assumes that JSON.stringify is correct.\n */\nexport function jsonStringify(value, replacer, space) {\n    if (typeof value !== 'object' || value === null) {\n        return JSON.stringify(value);\n    }\n    // Note: The order matter here. We need to detach toJSON methods on parent classes before their\n    // subclasses.\n    const restoreObjectPrototypeToJson = detachToJsonMethod(Object.prototype);\n    const restoreArrayPrototypeToJson = detachToJsonMethod(Array.prototype);\n    const restoreValuePrototypeToJson = detachToJsonMethod(Object.getPrototypeOf(value));\n    const restoreValueToJson = detachToJsonMethod(value);\n    try {\n        return JSON.stringify(value, replacer, space);\n    }\n    catch (_a) {\n        return '<error: unable to serialize object>';\n    }\n    finally {\n        restoreObjectPrototypeToJson();\n        restoreArrayPrototypeToJson();\n        restoreValuePrototypeToJson();\n        restoreValueToJson();\n    }\n}\nexport function detachToJsonMethod(value) {\n    const object = value;\n    const objectToJson = object.toJSON;\n    if (objectToJson) {\n        delete object.toJSON;\n        return () => {\n            object.toJSON = objectToJson;\n        };\n    }\n    return noop;\n}\n//# sourceMappingURL=jsonStringify.js.map","import { display } from '../display';\nimport { ONE_KIBI_BYTE } from '../utils/byteUtils';\nimport { detachToJsonMethod } from './jsonStringify';\n// The maximum size of a single event is 256KiB. By default, we ensure that user-provided data\n// going through sanitize fits inside our events, while leaving room for other contexts, metadata, ...\nconst SANITIZE_DEFAULT_MAX_CHARACTER_COUNT = 220 * ONE_KIBI_BYTE;\n// Symbol for the root element of the JSONPath used for visited objects\nconst JSON_PATH_ROOT_ELEMENT = '$';\n// When serializing (using JSON.stringify) a key of an object, { key: 42 } gets wrapped in quotes as \"key\".\n// With the separator (:), we need to add 3 characters to the count.\nconst KEY_DECORATION_LENGTH = 3;\nexport function sanitize(source, maxCharacterCount = SANITIZE_DEFAULT_MAX_CHARACTER_COUNT) {\n    // Unbind any toJSON function we may have on [] or {} prototypes\n    const restoreObjectPrototypeToJson = detachToJsonMethod(Object.prototype);\n    const restoreArrayPrototypeToJson = detachToJsonMethod(Array.prototype);\n    // Initial call to sanitizeProcessor - will populate containerQueue if source is an Array or a plain Object\n    const containerQueue = [];\n    const visitedObjectsWithPath = new WeakMap();\n    const sanitizedData = sanitizeProcessor(source, JSON_PATH_ROOT_ELEMENT, undefined, containerQueue, visitedObjectsWithPath);\n    const serializedSanitizedData = JSON.stringify(sanitizedData);\n    let accumulatedCharacterCount = serializedSanitizedData ? serializedSanitizedData.length : 0;\n    if (accumulatedCharacterCount > maxCharacterCount) {\n        warnOverCharacterLimit(maxCharacterCount, 'discarded', source);\n        return undefined;\n    }\n    while (containerQueue.length > 0 && accumulatedCharacterCount < maxCharacterCount) {\n        const containerToProcess = containerQueue.shift();\n        let separatorLength = 0; // 0 for the first element, 1 for subsequent elements\n        // Arrays and Objects have to be handled distinctly to ensure\n        // we do not pick up non-numerical properties from Arrays\n        if (Array.isArray(containerToProcess.source)) {\n            for (let key = 0; key < containerToProcess.source.length; key++) {\n                const targetData = sanitizeProcessor(containerToProcess.source[key], containerToProcess.path, key, containerQueue, visitedObjectsWithPath);\n                if (targetData !== undefined) {\n                    accumulatedCharacterCount += JSON.stringify(targetData).length;\n                }\n                else {\n                    // When an element of an Array (targetData) is undefined, it is serialized as null:\n                    // JSON.stringify([undefined]) => '[null]' - This accounts for 4 characters\n                    accumulatedCharacterCount += 4;\n                }\n                accumulatedCharacterCount += separatorLength;\n                separatorLength = 1;\n                if (accumulatedCharacterCount > maxCharacterCount) {\n                    warnOverCharacterLimit(maxCharacterCount, 'truncated', source);\n                    break;\n                }\n                ;\n                containerToProcess.target[key] = targetData;\n            }\n        }\n        else {\n            for (const key in containerToProcess.source) {\n                if (Object.prototype.hasOwnProperty.call(containerToProcess.source, key)) {\n                    const targetData = sanitizeProcessor(containerToProcess.source[key], containerToProcess.path, key, containerQueue, visitedObjectsWithPath);\n                    // When a property of an object has an undefined value, it will be dropped during serialization:\n                    // JSON.stringify({a:undefined}) => '{}'\n                    if (targetData !== undefined) {\n                        accumulatedCharacterCount +=\n                            JSON.stringify(targetData).length + separatorLength + key.length + KEY_DECORATION_LENGTH;\n                        separatorLength = 1;\n                    }\n                    if (accumulatedCharacterCount > maxCharacterCount) {\n                        warnOverCharacterLimit(maxCharacterCount, 'truncated', source);\n                        break;\n                    }\n                    ;\n                    containerToProcess.target[key] = targetData;\n                }\n            }\n        }\n    }\n    // Rebind detached toJSON functions\n    restoreObjectPrototypeToJson();\n    restoreArrayPrototypeToJson();\n    return sanitizedData;\n}\n/**\n * Internal function to factorize the process common to the\n * initial call to sanitize, and iterations for Arrays and Objects\n *\n */\nfunction sanitizeProcessor(source, parentPath, key, queue, visitedObjectsWithPath) {\n    // Start by handling toJSON, as we want to sanitize its output\n    const sourceToSanitize = tryToApplyToJSON(source);\n    if (!sourceToSanitize || typeof sourceToSanitize !== 'object') {\n        return sanitizePrimitivesAndFunctions(sourceToSanitize);\n    }\n    const sanitizedSource = sanitizeObjects(sourceToSanitize);\n    if (sanitizedSource !== '[Object]' && sanitizedSource !== '[Array]' && sanitizedSource !== '[Error]') {\n        return sanitizedSource;\n    }\n    // Handle potential cyclic references\n    // We need to use source as sourceToSanitize could be a reference to a new object\n    // At this stage, we know the source is an object type\n    const sourceAsObject = source;\n    if (visitedObjectsWithPath.has(sourceAsObject)) {\n        return `[Reference seen at ${visitedObjectsWithPath.get(sourceAsObject)}]`;\n    }\n    // Add processed source to queue\n    const currentPath = key !== undefined ? `${parentPath}.${key}` : parentPath;\n    const target = Array.isArray(sourceToSanitize) ? [] : {};\n    visitedObjectsWithPath.set(sourceAsObject, currentPath);\n    queue.push({ source: sourceToSanitize, target, path: currentPath });\n    return target;\n}\n/**\n * Handles sanitization of simple, non-object types\n *\n */\nfunction sanitizePrimitivesAndFunctions(value) {\n    // BigInt cannot be serialized by JSON.stringify(), convert it to a string representation\n    if (typeof value === 'bigint') {\n        return `[BigInt] ${value.toString()}`;\n    }\n    // Functions cannot be serialized by JSON.stringify(). Moreover, if a faulty toJSON is present, it needs to be converted\n    // so it won't prevent stringify from serializing later\n    if (typeof value === 'function') {\n        return `[Function] ${value.name || 'unknown'}`;\n    }\n    // JSON.stringify() does not serialize symbols.\n    if (typeof value === 'symbol') {\n        return `[Symbol] ${value.description || value.toString()}`;\n    }\n    return value;\n}\n/**\n * Handles sanitization of object types\n *\n * LIMITATIONS\n * - If a class defines a toStringTag Symbol, it will fall in the catch-all method and prevent enumeration of properties.\n * To avoid this, a toJSON method can be defined.\n */\nfunction sanitizeObjects(value) {\n    try {\n        if (value instanceof Event) {\n            return sanitizeEvent(value);\n        }\n        if (value instanceof RegExp) {\n            return `[RegExp] ${value.toString()}`;\n        }\n        // Handle all remaining object types in a generic way\n        const result = Object.prototype.toString.call(value);\n        const match = result.match(/\\[object (.*)\\]/);\n        if (match && match[1]) {\n            return `[${match[1]}]`;\n        }\n    }\n    catch (_a) {\n        // If the previous serialization attempts failed, and we cannot convert using\n        // Object.prototype.toString, declare the value unserializable\n    }\n    return '[Unserializable]';\n}\nfunction sanitizeEvent(event) {\n    return {\n        type: event.type,\n        isTrusted: event.isTrusted,\n        currentTarget: event.currentTarget ? sanitizeObjects(event.currentTarget) : null,\n        target: event.target ? sanitizeObjects(event.target) : null,\n    };\n}\n/**\n * Checks if a toJSON function exists and tries to execute it\n *\n */\nfunction tryToApplyToJSON(value) {\n    const object = value;\n    if (object && typeof object.toJSON === 'function') {\n        try {\n            return object.toJSON();\n        }\n        catch (_a) {\n            // If toJSON fails, we continue by trying to serialize the value manually\n        }\n    }\n    return value;\n}\n/**\n * Helper function to display the warning when the accumulated character count is over the limit\n */\nfunction warnOverCharacterLimit(maxCharacterCount, changeType, source) {\n    display.warn(`The data provided has been ${changeType} as it is over the limit of ${maxCharacterCount} characters:`, source);\n}\n//# sourceMappingURL=sanitize.js.map","/**\n * Cross-browser stack trace computation.\n *\n * Reference implementation: https://github.com/csnover/TraceKit/blob/04530298073c3823de72deb0b97e7b38ca7bcb59/tracekit.js\n */\nconst UNKNOWN_FUNCTION = '?';\nexport function computeStackTrace(ex) {\n    const stack = [];\n    let stackProperty = tryToGetString(ex, 'stack');\n    const exString = String(ex);\n    if (stackProperty && stackProperty.startsWith(exString)) {\n        stackProperty = stackProperty.slice(exString.length);\n    }\n    if (stackProperty) {\n        stackProperty.split('\\n').forEach((line) => {\n            const stackFrame = parseChromeLine(line) || parseChromeAnonymousLine(line) || parseWinLine(line) || parseGeckoLine(line);\n            if (stackFrame) {\n                if (!stackFrame.func && stackFrame.line) {\n                    stackFrame.func = UNKNOWN_FUNCTION;\n                }\n                stack.push(stackFrame);\n            }\n        });\n    }\n    return {\n        message: tryToGetString(ex, 'message'),\n        name: tryToGetString(ex, 'name'),\n        stack,\n    };\n}\nconst fileUrl = '((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)';\nconst filePosition = '(?::(\\\\d+))';\nconst CHROME_LINE_RE = new RegExp(`^\\\\s*at (.*?) ?\\\\(${fileUrl}${filePosition}?${filePosition}?\\\\)?\\\\s*$`, 'i');\nconst CHROME_EVAL_RE = new RegExp(`\\\\((\\\\S*)${filePosition}${filePosition}\\\\)`);\nfunction parseChromeLine(line) {\n    const parts = CHROME_LINE_RE.exec(line);\n    if (!parts) {\n        return;\n    }\n    const isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line\n    const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n    const submatch = CHROME_EVAL_RE.exec(parts[2]);\n    if (isEval && submatch) {\n        // throw out eval line/column and use top-most line/column number\n        parts[2] = submatch[1]; // url\n        parts[3] = submatch[2]; // line\n        parts[4] = submatch[3]; // column\n    }\n    return {\n        args: isNative ? [parts[2]] : [],\n        column: parts[4] ? +parts[4] : undefined,\n        func: parts[1] || UNKNOWN_FUNCTION,\n        line: parts[3] ? +parts[3] : undefined,\n        url: !isNative ? parts[2] : undefined,\n    };\n}\nconst CHROME_ANONYMOUS_FUNCTION_RE = new RegExp(`^\\\\s*at ?${fileUrl}${filePosition}?${filePosition}??\\\\s*$`, 'i');\nfunction parseChromeAnonymousLine(line) {\n    const parts = CHROME_ANONYMOUS_FUNCTION_RE.exec(line);\n    if (!parts) {\n        return;\n    }\n    return {\n        args: [],\n        column: parts[3] ? +parts[3] : undefined,\n        func: UNKNOWN_FUNCTION,\n        line: parts[2] ? +parts[2] : undefined,\n        url: parts[1],\n    };\n}\nconst WINJS_LINE_RE = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\nfunction parseWinLine(line) {\n    const parts = WINJS_LINE_RE.exec(line);\n    if (!parts) {\n        return;\n    }\n    return {\n        args: [],\n        column: parts[4] ? +parts[4] : undefined,\n        func: parts[1] || UNKNOWN_FUNCTION,\n        line: +parts[3],\n        url: parts[2],\n    };\n}\nconst GECKO_LINE_RE = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst GECKO_EVAL_RE = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\nfunction parseGeckoLine(line) {\n    const parts = GECKO_LINE_RE.exec(line);\n    if (!parts) {\n        return;\n    }\n    const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n    const submatch = GECKO_EVAL_RE.exec(parts[3]);\n    if (isEval && submatch) {\n        // throw out eval line/column and use top-most line number\n        parts[3] = submatch[1];\n        parts[4] = submatch[2];\n        parts[5] = undefined; // no column when eval\n    }\n    return {\n        args: parts[2] ? parts[2].split(',') : [],\n        column: parts[5] ? +parts[5] : undefined,\n        func: parts[1] || UNKNOWN_FUNCTION,\n        line: parts[4] ? +parts[4] : undefined,\n        url: parts[3],\n    };\n}\nfunction tryToGetString(candidate, property) {\n    if (typeof candidate !== 'object' || !candidate || !(property in candidate)) {\n        return undefined;\n    }\n    const value = candidate[property];\n    return typeof value === 'string' ? value : undefined;\n}\nexport function computeStackTraceFromOnErrorMessage(messageObj, url, line, column) {\n    const stack = [{ url, column, line }];\n    const { name, message } = tryToParseMessage(messageObj);\n    return {\n        name,\n        message,\n        stack,\n    };\n}\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types\nconst ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;\nfunction tryToParseMessage(messageObj) {\n    let name;\n    let message;\n    if ({}.toString.call(messageObj) === '[object String]') {\n        ;\n        [, name, message] = ERROR_TYPES_RE.exec(messageObj);\n    }\n    return { name, message };\n}\n//# sourceMappingURL=computeStackTrace.js.map","import { callMonitored } from '../monitor';\nimport { computeStackTrace } from './computeStackTrace';\n/**\n * Creates a stacktrace without SDK internal frames.\n * Constraints:\n * - Has to be called at the utmost position of the call stack.\n * - No monitored function should encapsulate it, that is why we need to use callMonitored inside it.\n */\nexport function createHandlingStack() {\n    /**\n     * Skip the two internal frames:\n     * - SDK API (console.error, ...)\n     * - this function\n     * in order to keep only the user calls\n     */\n    const internalFramesToSkip = 2;\n    const error = new Error();\n    let formattedStack;\n    callMonitored(() => {\n        const stackTrace = computeStackTrace(error);\n        stackTrace.stack = stackTrace.stack.slice(internalFramesToSkip);\n        formattedStack = toStackTraceString(stackTrace);\n    });\n    return formattedStack;\n}\nexport function toStackTraceString(stack) {\n    let result = formatErrorMessage(stack);\n    stack.stack.forEach((frame) => {\n        const func = frame.func === '?' ? '<anonymous>' : frame.func;\n        const args = frame.args && frame.args.length > 0 ? `(${frame.args.join(', ')})` : '';\n        const line = frame.line ? `:${frame.line}` : '';\n        const column = frame.line && frame.column ? `:${frame.column}` : '';\n        result += `\\n  at ${func}${args} @ ${frame.url}${line}${column}`;\n    });\n    return result;\n}\nexport function formatErrorMessage(stack) {\n    return `${stack.name || 'Error'}: ${stack.message}`;\n}\n//# sourceMappingURL=handlingStack.js.map","import { getZoneJsOriginalValue } from './getZoneJsOriginalValue';\nimport { monitor } from './monitor';\nimport { getGlobalObject } from './getGlobalObject';\nexport function setTimeout(callback, delay) {\n    return getZoneJsOriginalValue(getGlobalObject(), 'setTimeout')(monitor(callback), delay);\n}\nexport function clearTimeout(timeoutId) {\n    getZoneJsOriginalValue(getGlobalObject(), 'clearTimeout')(timeoutId);\n}\nexport function setInterval(callback, delay) {\n    return getZoneJsOriginalValue(getGlobalObject(), 'setInterval')(monitor(callback), delay);\n}\nexport function clearInterval(timeoutId) {\n    getZoneJsOriginalValue(getGlobalObject(), 'clearInterval')(timeoutId);\n}\n//# sourceMappingURL=timer.js.map","export function removeDuplicates(array) {\n    const set = new Set();\n    array.forEach((item) => set.add(item));\n    return Array.from(set);\n}\nexport function removeItem(array, item) {\n    const index = array.indexOf(item);\n    if (index >= 0) {\n        array.splice(index, 1);\n    }\n}\n//# sourceMappingURL=arrayUtils.js.map","export function isChromium() {\n    return detectBrowserCached() === 0 /* Browser.CHROMIUM */;\n}\nexport function isSafari() {\n    return detectBrowserCached() === 1 /* Browser.SAFARI */;\n}\nlet browserCache;\nfunction detectBrowserCached() {\n    return browserCache !== null && browserCache !== void 0 ? browserCache : (browserCache = detectBrowser());\n}\n// Exported only for tests\nexport function detectBrowser(browserWindow = window) {\n    var _a;\n    const userAgent = browserWindow.navigator.userAgent;\n    if (browserWindow.chrome || /HeadlessChrome/.test(userAgent)) {\n        return 0 /* Browser.CHROMIUM */;\n    }\n    if (\n    // navigator.vendor is deprecated, but it is the most resilient way we found to detect\n    // \"Apple maintained browsers\" (AKA Safari). If one day it gets removed, we still have the\n    // useragent test as a semi-working fallback.\n    ((_a = browserWindow.navigator.vendor) === null || _a === void 0 ? void 0 : _a.indexOf('Apple')) === 0 ||\n        (/safari/i.test(userAgent) && !/chrome|android/i.test(userAgent))) {\n        return 1 /* Browser.SAFARI */;\n    }\n    return 2 /* Browser.OTHER */;\n}\n//# sourceMappingURL=browserDetection.js.map","export const ONE_KIBI_BYTE = 1024;\nexport const ONE_MEBI_BYTE = 1024 * ONE_KIBI_BYTE;\n// eslint-disable-next-line no-control-regex\nconst HAS_MULTI_BYTES_CHARACTERS = /[^\\u0000-\\u007F]/;\nexport function computeBytesCount(candidate) {\n    // Accurate bytes count computations can degrade performances when there is a lot of events to process\n    if (!HAS_MULTI_BYTES_CHARACTERS.test(candidate)) {\n        return candidate.length;\n    }\n    if (window.TextEncoder !== undefined) {\n        return new TextEncoder().encode(candidate).length;\n    }\n    return new Blob([candidate]).size;\n}\nexport function concatBuffers(buffers) {\n    const length = buffers.reduce((total, buffer) => total + buffer.length, 0);\n    const result = new Uint8Array(length);\n    let offset = 0;\n    for (const buffer of buffers) {\n        result.set(buffer, offset);\n        offset += buffer.length;\n    }\n    return result;\n}\n//# sourceMappingURL=byteUtils.js.map","import { setTimeout, clearTimeout } from '../timer';\n// use lodash API\nexport function throttle(fn, wait, options) {\n    const needLeadingExecution = options && options.leading !== undefined ? options.leading : true;\n    const needTrailingExecution = options && options.trailing !== undefined ? options.trailing : true;\n    let inWaitPeriod = false;\n    let pendingExecutionWithParameters;\n    let pendingTimeoutId;\n    return {\n        throttled: (...parameters) => {\n            if (inWaitPeriod) {\n                pendingExecutionWithParameters = parameters;\n                return;\n            }\n            if (needLeadingExecution) {\n                fn(...parameters);\n            }\n            else {\n                pendingExecutionWithParameters = parameters;\n            }\n            inWaitPeriod = true;\n            pendingTimeoutId = setTimeout(() => {\n                if (needTrailingExecution && pendingExecutionWithParameters) {\n                    fn(...pendingExecutionWithParameters);\n                }\n                inWaitPeriod = false;\n                pendingExecutionWithParameters = undefined;\n            }, wait);\n        },\n        cancel: () => {\n            clearTimeout(pendingTimeoutId);\n            inWaitPeriod = false;\n            pendingExecutionWithParameters = undefined;\n        },\n    };\n}\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function noop() { }\n//# sourceMappingURL=functionUtils.js.map","/**\n * Return true if the draw is successful\n * @param threshold between 0 and 100\n */\nexport function performDraw(threshold) {\n    return threshold !== 0 && Math.random() * 100 <= threshold;\n}\nexport function round(num, decimals) {\n    return +num.toFixed(decimals);\n}\nexport function isPercentage(value) {\n    return isNumber(value) && value >= 0 && value <= 100;\n}\nexport function isNumber(value) {\n    return typeof value === 'number';\n}\n//# sourceMappingURL=numberUtils.js.map","export function shallowClone(object) {\n    return { ...object };\n}\nexport function objectHasValue(object, value) {\n    return Object.keys(object).some((key) => object[key] === value);\n}\nexport function isEmptyObject(object) {\n    return Object.keys(object).length === 0;\n}\nexport function mapValues(object, fn) {\n    const newObject = {};\n    for (const key of Object.keys(object)) {\n        newObject[key] = fn(object[key]);\n    }\n    return newObject;\n}\n//# sourceMappingURL=objectUtils.js.map","export function findLast(array, predicate) {\n    for (let i = array.length - 1; i >= 0; i -= 1) {\n        const item = array[i];\n        if (predicate(item, i, array)) {\n            return item;\n        }\n    }\n    return undefined;\n}\n// Keep the following wrapper functions as it can be mangled and will result in smaller bundle size that using\n// the native Object.values and Object.entries directly\nexport function objectValues(object) {\n    return Object.values(object);\n}\nexport function objectEntries(object) {\n    return Object.entries(object);\n}\n//# sourceMappingURL=polyfills.js.map","export function isServerError(status) {\n    return status >= 500;\n}\nexport function tryToClone(response) {\n    try {\n        return response.clone();\n    }\n    catch (_a) {\n        // clone can throw if the response has already been used by another instrumentation or is disturbed\n        return;\n    }\n}\n//# sourceMappingURL=responseUtils.js.map","import { isNumber, round } from './numberUtils';\nexport const ONE_SECOND = 1000;\nexport const ONE_MINUTE = 60 * ONE_SECOND;\nexport const ONE_HOUR = 60 * ONE_MINUTE;\nexport const ONE_DAY = 24 * ONE_HOUR;\nexport const ONE_YEAR = 365 * ONE_DAY;\nexport function relativeToClocks(relative) {\n    return { relative, timeStamp: getCorrectedTimeStamp(relative) };\n}\nexport function timeStampToClocks(timeStamp) {\n    return { relative: getRelativeTime(timeStamp), timeStamp };\n}\nfunction getCorrectedTimeStamp(relativeTime) {\n    const correctedOrigin = (dateNow() - performance.now());\n    // apply correction only for positive drift\n    if (correctedOrigin > getNavigationStart()) {\n        return Math.round(addDuration(correctedOrigin, relativeTime));\n    }\n    return getTimeStamp(relativeTime);\n}\nexport function currentDrift() {\n    return Math.round(dateNow() - addDuration(getNavigationStart(), performance.now()));\n}\nexport function toServerDuration(duration) {\n    if (!isNumber(duration)) {\n        return duration;\n    }\n    return round(duration * 1e6, 0);\n}\nexport function dateNow() {\n    // Do not use `Date.now` because sometimes websites are wrongly \"polyfilling\" it. For example, we\n    // had some users using a very old version of `datejs`, which patched `Date.now` to return a Date\n    // instance instead of a timestamp[1]. Those users are unlikely to fix this, so let's handle this\n    // case ourselves.\n    // [1]: https://github.com/datejs/Datejs/blob/97f5c7c58c5bc5accdab8aa7602b6ac56462d778/src/core-debug.js#L14-L16\n    return new Date().getTime();\n}\nexport function timeStampNow() {\n    return dateNow();\n}\nexport function relativeNow() {\n    return performance.now();\n}\nexport function clocksNow() {\n    return { relative: relativeNow(), timeStamp: timeStampNow() };\n}\nexport function clocksOrigin() {\n    return { relative: 0, timeStamp: getNavigationStart() };\n}\nexport function elapsed(start, end) {\n    return (end - start);\n}\nexport function addDuration(a, b) {\n    return a + b;\n}\n// Get the time since the navigation was started.\nexport function getRelativeTime(timestamp) {\n    return (timestamp - getNavigationStart());\n}\nexport function getTimeStamp(relativeTime) {\n    return Math.round(addDuration(getNavigationStart(), relativeTime));\n}\nexport function looksLikeRelativeTime(time) {\n    return time < ONE_YEAR;\n}\n/**\n * Navigation start slightly change on some rare cases\n */\nlet navigationStart;\n/**\n * Notes: this does not use `performance.timeOrigin` because:\n * - It doesn't seem to reflect the actual time on which the navigation has started: it may be much farther in the past,\n * at least in Firefox 71. (see: https://bugzilla.mozilla.org/show_bug.cgi?id=1429926)\n * - It is not supported in Safari <15\n */\nfunction getNavigationStart() {\n    if (navigationStart === undefined) {\n        navigationStart = performance.timing.navigationStart;\n    }\n    return navigationStart;\n}\n//# sourceMappingURL=timeUtils.js.map","/**\n * Similar to `typeof`, but distinguish plain objects from `null` and arrays\n */\nexport function getType(value) {\n    if (value === null) {\n        return 'null';\n    }\n    if (Array.isArray(value)) {\n        return 'array';\n    }\n    return typeof value;\n}\n//# sourceMappingURL=typeUtils.js.map","import { jsonStringify } from '../serialisation/jsonStringify';\nexport function normalizeUrl(url) {\n    return buildUrl(url, location.href).href;\n}\nexport function isValidUrl(url) {\n    try {\n        return !!buildUrl(url);\n    }\n    catch (_a) {\n        return false;\n    }\n}\nexport function getPathName(url) {\n    const pathname = buildUrl(url).pathname;\n    return pathname[0] === '/' ? pathname : `/${pathname}`;\n}\nexport function buildUrl(url, base) {\n    const supportedURL = getSupportedUrl();\n    if (supportedURL) {\n        try {\n            return base !== undefined ? new supportedURL(url, base) : new supportedURL(url);\n        }\n        catch (error) {\n            throw new Error(`Failed to construct URL: ${String(error)} ${jsonStringify({ url, base })}`);\n        }\n    }\n    if (base === undefined && !/:/.test(url)) {\n        throw new Error(`Invalid URL: '${url}'`);\n    }\n    let doc = document;\n    const anchorElement = doc.createElement('a');\n    if (base !== undefined) {\n        doc = document.implementation.createHTMLDocument('');\n        const baseElement = doc.createElement('base');\n        baseElement.href = base;\n        doc.head.appendChild(baseElement);\n        doc.body.appendChild(anchorElement);\n    }\n    anchorElement.href = url;\n    return anchorElement;\n}\nconst originalURL = URL;\nlet isURLSupported;\nfunction getSupportedUrl() {\n    if (isURLSupported === undefined) {\n        try {\n            const url = new originalURL('http://test/path');\n            isURLSupported = url.href === 'http://test/path';\n        }\n        catch (_a) {\n            isURLSupported = false;\n        }\n    }\n    return isURLSupported ? originalURL : undefined;\n}\n//# sourceMappingURL=urlPolyfill.js.map","import { getGlobalObject } from '../tools/getGlobalObject';\nexport function getEventBridge() {\n    const eventBridgeGlobal = getEventBridgeGlobal();\n    if (!eventBridgeGlobal) {\n        return;\n    }\n    return {\n        getCapabilities() {\n            var _a;\n            return JSON.parse(((_a = eventBridgeGlobal.getCapabilities) === null || _a === void 0 ? void 0 : _a.call(eventBridgeGlobal)) || '[]');\n        },\n        getPrivacyLevel() {\n            var _a;\n            return (_a = eventBridgeGlobal.getPrivacyLevel) === null || _a === void 0 ? void 0 : _a.call(eventBridgeGlobal);\n        },\n        getAllowedWebViewHosts() {\n            return JSON.parse(eventBridgeGlobal.getAllowedWebViewHosts());\n        },\n        send(eventType, event, viewId) {\n            const view = viewId ? { id: viewId } : undefined;\n            eventBridgeGlobal.send(JSON.stringify({ eventType, event, view }));\n        },\n    };\n}\nexport function bridgeSupports(capability) {\n    const bridge = getEventBridge();\n    return !!bridge && bridge.getCapabilities().includes(capability);\n}\nexport function canUseEventBridge(currentHost) {\n    var _a;\n    if (currentHost === void 0) { currentHost = (_a = getGlobalObject().location) === null || _a === void 0 ? void 0 : _a.hostname; }\n    const bridge = getEventBridge();\n    return (!!bridge &&\n        bridge\n            .getAllowedWebViewHosts()\n            .some((allowedHost) => currentHost === allowedHost || currentHost.endsWith(`.${allowedHost}`)));\n}\nfunction getEventBridgeGlobal() {\n    return getGlobalObject().DatadogEventBridge;\n}\n//# sourceMappingURL=eventBridge.js.map","import { setTimeout } from '../tools/timer';\nimport { clocksNow, ONE_MINUTE, ONE_SECOND } from '../tools/utils/timeUtils';\nimport { ONE_MEBI_BYTE, ONE_KIBI_BYTE } from '../tools/utils/byteUtils';\nimport { isServerError } from '../tools/utils/responseUtils';\nimport { ErrorSource } from '../domain/error/error.types';\nexport const MAX_ONGOING_BYTES_COUNT = 80 * ONE_KIBI_BYTE;\nexport const MAX_ONGOING_REQUESTS = 32;\nexport const MAX_QUEUE_BYTES_COUNT = 3 * ONE_MEBI_BYTE;\nexport const MAX_BACKOFF_TIME = ONE_MINUTE;\nexport const INITIAL_BACKOFF_TIME = ONE_SECOND;\nexport function sendWithRetryStrategy(payload, state, sendStrategy, trackType, reportError) {\n    if (state.transportStatus === 0 /* TransportStatus.UP */ &&\n        state.queuedPayloads.size() === 0 &&\n        state.bandwidthMonitor.canHandle(payload)) {\n        send(payload, state, sendStrategy, {\n            onSuccess: () => retryQueuedPayloads(0 /* RetryReason.AFTER_SUCCESS */, state, sendStrategy, trackType, reportError),\n            onFailure: () => {\n                state.queuedPayloads.enqueue(payload);\n                scheduleRetry(state, sendStrategy, trackType, reportError);\n            },\n        });\n    }\n    else {\n        state.queuedPayloads.enqueue(payload);\n    }\n}\nfunction scheduleRetry(state, sendStrategy, trackType, reportError) {\n    if (state.transportStatus !== 2 /* TransportStatus.DOWN */) {\n        return;\n    }\n    setTimeout(() => {\n        const payload = state.queuedPayloads.first();\n        send(payload, state, sendStrategy, {\n            onSuccess: () => {\n                state.queuedPayloads.dequeue();\n                state.currentBackoffTime = INITIAL_BACKOFF_TIME;\n                retryQueuedPayloads(1 /* RetryReason.AFTER_RESUME */, state, sendStrategy, trackType, reportError);\n            },\n            onFailure: () => {\n                state.currentBackoffTime = Math.min(MAX_BACKOFF_TIME, state.currentBackoffTime * 2);\n                scheduleRetry(state, sendStrategy, trackType, reportError);\n            },\n        });\n    }, state.currentBackoffTime);\n}\nfunction send(payload, state, sendStrategy, { onSuccess, onFailure }) {\n    state.bandwidthMonitor.add(payload);\n    sendStrategy(payload, (response) => {\n        state.bandwidthMonitor.remove(payload);\n        if (!shouldRetryRequest(response)) {\n            state.transportStatus = 0 /* TransportStatus.UP */;\n            onSuccess();\n        }\n        else {\n            // do not consider transport down if another ongoing request could succeed\n            state.transportStatus =\n                state.bandwidthMonitor.ongoingRequestCount > 0 ? 1 /* TransportStatus.FAILURE_DETECTED */ : 2 /* TransportStatus.DOWN */;\n            payload.retry = {\n                count: payload.retry ? payload.retry.count + 1 : 1,\n                lastFailureStatus: response.status,\n            };\n            onFailure();\n        }\n    });\n}\nfunction retryQueuedPayloads(reason, state, sendStrategy, trackType, reportError) {\n    if (reason === 0 /* RetryReason.AFTER_SUCCESS */ && state.queuedPayloads.isFull() && !state.queueFullReported) {\n        reportError({\n            message: `Reached max ${trackType} events size queued for upload: ${MAX_QUEUE_BYTES_COUNT / ONE_MEBI_BYTE}MiB`,\n            source: ErrorSource.AGENT,\n            startClocks: clocksNow(),\n        });\n        state.queueFullReported = true;\n    }\n    const previousQueue = state.queuedPayloads;\n    state.queuedPayloads = newPayloadQueue();\n    while (previousQueue.size() > 0) {\n        sendWithRetryStrategy(previousQueue.dequeue(), state, sendStrategy, trackType, reportError);\n    }\n}\nfunction shouldRetryRequest(response) {\n    return (response.type !== 'opaque' &&\n        ((response.status === 0 && !navigator.onLine) ||\n            response.status === 408 ||\n            response.status === 429 ||\n            isServerError(response.status)));\n}\nexport function newRetryState() {\n    return {\n        transportStatus: 0 /* TransportStatus.UP */,\n        currentBackoffTime: INITIAL_BACKOFF_TIME,\n        bandwidthMonitor: newBandwidthMonitor(),\n        queuedPayloads: newPayloadQueue(),\n        queueFullReported: false,\n    };\n}\nfunction newPayloadQueue() {\n    const queue = [];\n    return {\n        bytesCount: 0,\n        enqueue(payload) {\n            if (this.isFull()) {\n                return;\n            }\n            queue.push(payload);\n            this.bytesCount += payload.bytesCount;\n        },\n        first() {\n            return queue[0];\n        },\n        dequeue() {\n            const payload = queue.shift();\n            if (payload) {\n                this.bytesCount -= payload.bytesCount;\n            }\n            return payload;\n        },\n        size() {\n            return queue.length;\n        },\n        isFull() {\n            return this.bytesCount >= MAX_QUEUE_BYTES_COUNT;\n        },\n    };\n}\nfunction newBandwidthMonitor() {\n    return {\n        ongoingRequestCount: 0,\n        ongoingByteCount: 0,\n        canHandle(payload) {\n            return (this.ongoingRequestCount === 0 ||\n                (this.ongoingByteCount + payload.bytesCount <= MAX_ONGOING_BYTES_COUNT &&\n                    this.ongoingRequestCount < MAX_ONGOING_REQUESTS));\n        },\n        add(payload) {\n            this.ongoingRequestCount += 1;\n            this.ongoingByteCount += payload.bytesCount;\n        },\n        remove(payload) {\n            this.ongoingRequestCount -= 1;\n            this.ongoingByteCount -= payload.bytesCount;\n        },\n    };\n}\n//# sourceMappingURL=sendWithRetryStrategy.js.map","import { addTelemetryError } from '../domain/telemetry';\nimport { monitor } from '../tools/monitor';\nimport { addEventListener } from '../browser/addEventListener';\nimport { newRetryState, sendWithRetryStrategy } from './sendWithRetryStrategy';\nexport function createHttpRequest(endpointBuilder, bytesLimit, reportError) {\n    const retryState = newRetryState();\n    const sendStrategyForRetry = (payload, onResponse) => fetchKeepAliveStrategy(endpointBuilder, bytesLimit, payload, onResponse);\n    return {\n        send: (payload) => {\n            sendWithRetryStrategy(payload, retryState, sendStrategyForRetry, endpointBuilder.trackType, reportError);\n        },\n        /**\n         * Since fetch keepalive behaves like regular fetch on Firefox,\n         * keep using sendBeaconStrategy on exit\n         */\n        sendOnExit: (payload) => {\n            sendBeaconStrategy(endpointBuilder, bytesLimit, payload);\n        },\n    };\n}\nfunction sendBeaconStrategy(endpointBuilder, bytesLimit, payload) {\n    const canUseBeacon = !!navigator.sendBeacon && payload.bytesCount < bytesLimit;\n    if (canUseBeacon) {\n        try {\n            const beaconUrl = endpointBuilder.build('beacon', payload);\n            const isQueued = navigator.sendBeacon(beaconUrl, payload.data);\n            if (isQueued) {\n                return;\n            }\n        }\n        catch (e) {\n            reportBeaconError(e);\n        }\n    }\n    const xhrUrl = endpointBuilder.build('xhr', payload);\n    sendXHR(xhrUrl, payload.data);\n}\nlet hasReportedBeaconError = false;\nfunction reportBeaconError(e) {\n    if (!hasReportedBeaconError) {\n        hasReportedBeaconError = true;\n        addTelemetryError(e);\n    }\n}\nexport function fetchKeepAliveStrategy(endpointBuilder, bytesLimit, payload, onResponse) {\n    const canUseKeepAlive = isKeepAliveSupported() && payload.bytesCount < bytesLimit;\n    if (canUseKeepAlive) {\n        const fetchUrl = endpointBuilder.build('fetch', payload);\n        fetch(fetchUrl, { method: 'POST', body: payload.data, keepalive: true, mode: 'cors' }).then(monitor((response) => onResponse === null || onResponse === void 0 ? void 0 : onResponse({ status: response.status, type: response.type })), monitor(() => {\n            const xhrUrl = endpointBuilder.build('xhr', payload);\n            // failed to queue the request\n            sendXHR(xhrUrl, payload.data, onResponse);\n        }));\n    }\n    else {\n        const xhrUrl = endpointBuilder.build('xhr', payload);\n        sendXHR(xhrUrl, payload.data, onResponse);\n    }\n}\nfunction isKeepAliveSupported() {\n    // Request can throw, cf https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#errors\n    try {\n        return window.Request && 'keepalive' in new Request('http://a');\n    }\n    catch (_a) {\n        return false;\n    }\n}\nexport function sendXHR(url, data, onResponse) {\n    const request = new XMLHttpRequest();\n    request.open('POST', url, true);\n    if (data instanceof Blob) {\n        // When using a Blob instance, IE does not use its 'type' to define the 'Content-Type' header\n        // automatically, so the intake request ends up being rejected with an HTTP status 415\n        // Defining the header manually fixes this issue.\n        request.setRequestHeader('Content-Type', data.type);\n    }\n    addEventListener(\n    // allow untrusted event to acount for synthetic event dispatched by third party xhr wrapper\n    { allowUntrustedEvents: true }, request, 'loadend', () => {\n        onResponse === null || onResponse === void 0 ? void 0 : onResponse({ status: request.status });\n    }, {\n        // prevent multiple onResponse callbacks\n        // if the xhr instance is reused by a third party\n        once: true,\n    });\n    request.send(data);\n}\n//# sourceMappingURL=httpRequest.js.map","import { ONE_KIBI_BYTE, computeBytesCount } from '../../tools/utils/byteUtils';\nimport { throttle } from '../../tools/utils/functionUtils';\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify';\nimport { DOCS_TROUBLESHOOTING, MORE_DETAILS, display } from '../../tools/display';\nimport { isEmptyObject } from '../../tools/utils/objectUtils';\n// RUM and logs batch bytes limit is 16KB\n// ensure that we leave room for other event attributes and maintain a decent amount of event per batch\n// (3KB (customer data) + 1KB (other attributes)) * 4 (events per batch) = 16KB\nexport const CUSTOMER_DATA_BYTES_LIMIT = 3 * ONE_KIBI_BYTE;\n// We observed that the compression ratio is around 8 in general, but we also want to keep a margin\n// because some data might not be compressed (ex: last view update on page exit). We chose 16KiB\n// because it is also the limit of the 'batchBytesCount' that we use for RUM and Logs data, but this\n// is a bit arbitrary.\nexport const CUSTOMER_COMPRESSED_DATA_BYTES_LIMIT = 16 * ONE_KIBI_BYTE;\nexport const BYTES_COMPUTATION_THROTTLING_DELAY = 200;\nexport function createCustomerDataTrackerManager(compressionStatus = 2 /* CustomerDataCompressionStatus.Disabled */) {\n    const customerDataTrackers = new Map();\n    let alreadyWarned = false;\n    function checkCustomerDataLimit(initialBytesCount = 0) {\n        if (alreadyWarned || compressionStatus === 0 /* CustomerDataCompressionStatus.Unknown */) {\n            return;\n        }\n        const bytesCountLimit = compressionStatus === 2 /* CustomerDataCompressionStatus.Disabled */\n            ? CUSTOMER_DATA_BYTES_LIMIT\n            : CUSTOMER_COMPRESSED_DATA_BYTES_LIMIT;\n        let bytesCount = initialBytesCount;\n        customerDataTrackers.forEach((tracker) => {\n            bytesCount += tracker.getBytesCount();\n        });\n        if (bytesCount > bytesCountLimit) {\n            displayCustomerDataLimitReachedWarning(bytesCountLimit);\n            alreadyWarned = true;\n        }\n    }\n    return {\n        /**\n         * Creates a detached tracker. The manager will not store a reference to that tracker, and the\n         * bytes count will be counted independently from other detached trackers.\n         *\n         * This is particularly useful when we don't know when the tracker will be unused, so we don't\n         * leak memory (ex: when used in Logger instances).\n         */\n        createDetachedTracker: () => {\n            const tracker = createCustomerDataTracker(() => checkCustomerDataLimit(tracker.getBytesCount()));\n            return tracker;\n        },\n        /**\n         * Creates a tracker if it doesn't exist, and returns it.\n         */\n        getOrCreateTracker: (type) => {\n            if (!customerDataTrackers.has(type)) {\n                customerDataTrackers.set(type, createCustomerDataTracker(checkCustomerDataLimit));\n            }\n            return customerDataTrackers.get(type);\n        },\n        setCompressionStatus: (newCompressionStatus) => {\n            if (compressionStatus === 0 /* CustomerDataCompressionStatus.Unknown */) {\n                compressionStatus = newCompressionStatus;\n                checkCustomerDataLimit();\n            }\n        },\n        getCompressionStatus: () => compressionStatus,\n        stop: () => {\n            customerDataTrackers.forEach((tracker) => tracker.stop());\n            customerDataTrackers.clear();\n        },\n    };\n}\nexport function createCustomerDataTracker(checkCustomerDataLimit) {\n    let bytesCountCache = 0;\n    // Throttle the bytes computation to minimize the impact on performance.\n    // Especially useful if the user call context APIs synchronously multiple times in a row\n    const { throttled: computeBytesCountThrottled, cancel: cancelComputeBytesCount } = throttle((context) => {\n        bytesCountCache = computeBytesCount(jsonStringify(context));\n        checkCustomerDataLimit();\n    }, BYTES_COMPUTATION_THROTTLING_DELAY);\n    const resetBytesCount = () => {\n        cancelComputeBytesCount();\n        bytesCountCache = 0;\n    };\n    return {\n        updateCustomerData: (context) => {\n            if (isEmptyObject(context)) {\n                resetBytesCount();\n            }\n            else {\n                computeBytesCountThrottled(context);\n            }\n        },\n        resetCustomerData: resetBytesCount,\n        getBytesCount: () => bytesCountCache,\n        stop: () => {\n            cancelComputeBytesCount();\n        },\n    };\n}\nfunction displayCustomerDataLimitReachedWarning(bytesCountLimit) {\n    display.warn(`Customer data exceeds the recommended ${bytesCountLimit / ONE_KIBI_BYTE}KiB threshold. ${MORE_DETAILS} ${DOCS_TROUBLESHOOTING}/#customer-data-exceeds-the-recommended-threshold-warning`);\n}\n//# sourceMappingURL=customerDataTracker.js.map","import { deepClone } from '../../tools/mergeInto';\nimport { getType } from '../../tools/utils/typeUtils';\nimport { sanitize } from '../../tools/serialisation/sanitize';\nimport { Observable } from '../../tools/observable';\nexport function createContextManager(customerDataTracker) {\n    let context = {};\n    const changeObservable = new Observable();\n    const contextManager = {\n        getContext: () => deepClone(context),\n        setContext: (newContext) => {\n            if (getType(newContext) === 'object') {\n                context = sanitize(newContext);\n                customerDataTracker === null || customerDataTracker === void 0 ? void 0 : customerDataTracker.updateCustomerData(context);\n            }\n            else {\n                contextManager.clearContext();\n            }\n            changeObservable.notify();\n        },\n        setContextProperty: (key, property) => {\n            context[key] = sanitize(property);\n            customerDataTracker === null || customerDataTracker === void 0 ? void 0 : customerDataTracker.updateCustomerData(context);\n            changeObservable.notify();\n        },\n        removeContextProperty: (key) => {\n            delete context[key];\n            customerDataTracker === null || customerDataTracker === void 0 ? void 0 : customerDataTracker.updateCustomerData(context);\n            changeObservable.notify();\n        },\n        clearContext: () => {\n            context = {};\n            customerDataTracker === null || customerDataTracker === void 0 ? void 0 : customerDataTracker.resetCustomerData();\n            changeObservable.notify();\n        },\n        changeObservable,\n    };\n    return contextManager;\n}\n//# sourceMappingURL=contextManager.js.map","import { Observable } from '../tools/observable';\nexport const TrackingConsent = {\n    GRANTED: 'granted',\n    NOT_GRANTED: 'not-granted',\n};\nexport function createTrackingConsentState(currentConsent) {\n    const observable = new Observable();\n    return {\n        tryToInit(trackingConsent) {\n            if (!currentConsent) {\n                currentConsent = trackingConsent;\n            }\n        },\n        update(trackingConsent) {\n            currentConsent = trackingConsent;\n            observable.notify();\n        },\n        isGranted() {\n            return currentConsent === TrackingConsent.GRANTED;\n        },\n        observable,\n    };\n}\n//# sourceMappingURL=trackingConsent.js.map","import { addEventListener } from '../../browser/addEventListener';\nimport { combine } from '../../tools/mergeInto';\nconst CONTEXT_STORE_KEY_PREFIX = '_dd_c';\nconst storageListeners = [];\nexport function storeContextManager(configuration, contextManager, productKey, customerDataType) {\n    const storageKey = buildStorageKey(productKey, customerDataType);\n    storageListeners.push(addEventListener(configuration, window, \"storage\" /* DOM_EVENT.STORAGE */, ({ key }) => {\n        if (storageKey === key) {\n            synchronizeWithStorage();\n        }\n    }));\n    contextManager.changeObservable.subscribe(dumpToStorage);\n    contextManager.setContext(combine(getFromStorage(), contextManager.getContext()));\n    function synchronizeWithStorage() {\n        contextManager.setContext(getFromStorage());\n    }\n    function dumpToStorage() {\n        localStorage.setItem(storageKey, JSON.stringify(contextManager.getContext()));\n    }\n    function getFromStorage() {\n        const rawContext = localStorage.getItem(storageKey);\n        return rawContext !== null ? JSON.parse(rawContext) : {};\n    }\n}\nexport function buildStorageKey(productKey, customerDataType) {\n    return `${CONTEXT_STORE_KEY_PREFIX}_${productKey}_${customerDataType}`;\n}\nexport function removeStorageListeners() {\n    storageListeners.map((listener) => listener.stop());\n}\n//# sourceMappingURL=storeContextManager.js.map","import { computeBytesCount } from './utils/byteUtils';\nexport function createIdentityEncoder() {\n    let output = '';\n    let outputBytesCount = 0;\n    return {\n        isAsync: false,\n        get isEmpty() {\n            return !output;\n        },\n        write(data, callback) {\n            const additionalEncodedBytesCount = computeBytesCount(data);\n            outputBytesCount += additionalEncodedBytesCount;\n            output += data;\n            if (callback) {\n                callback(additionalEncodedBytesCount);\n            }\n        },\n        finish(callback) {\n            callback(this.finishSync());\n        },\n        finishSync() {\n            const result = {\n                output,\n                outputBytesCount,\n                rawBytesCount: outputBytesCount,\n                pendingData: '',\n            };\n            output = '';\n            outputBytesCount = 0;\n            return result;\n        },\n        estimateEncodedBytesCount(data) {\n            return data.length;\n        },\n    };\n}\n//# sourceMappingURL=encoder.js.map","import { display } from '../../tools/display';\nimport { getType } from '../../tools/utils/typeUtils';\n/**\n * Clone input data and ensure known user properties (id, name, email)\n * are strings, as defined here:\n * https://docs.datadoghq.com/logs/log_configuration/attributes_naming_convention/#user-related-attributes\n */\nexport function sanitizeUser(newUser) {\n    // We shallow clone only to prevent mutation of user data.\n    const user = { ...newUser };\n    const keys = ['id', 'name', 'email'];\n    keys.forEach((key) => {\n        if (key in user) {\n            /* eslint-disable @typescript-eslint/no-base-to-string */\n            user[key] = String(user[key]);\n        }\n    });\n    return user;\n}\n/**\n * Simple check to ensure user is valid\n */\nexport function checkUser(newUser) {\n    const isValid = getType(newUser) === 'object';\n    if (!isValid) {\n        display.error('Unsupported user:', newUser);\n    }\n    return isValid;\n}\nexport function generateAnonymousId() {\n    return Math.floor(Math.random() * Math.pow(36, 10))\n        .toString(36)\n        .padStart(10, '0');\n}\n//# sourceMappingURL=user.js.map","import { display } from '../tools/display';\nexport function displayAlreadyInitializedError(sdkName, initConfiguration) {\n    if (!initConfiguration.silentMultipleInit) {\n        display.error(`${sdkName} is already initialized.`);\n    }\n}\n//# sourceMappingURL=displayAlreadyInitializedError.js.map","/**\n * UUID v4\n * from https://gist.github.com/jed/982883\n */\nexport function generateUUID(placeholder) {\n    return placeholder\n        ? // eslint-disable-next-line  no-bitwise\n            (parseInt(placeholder, 10) ^ ((Math.random() * 16) >> (parseInt(placeholder, 10) / 4))).toString(16)\n        : `${1e7}-${1e3}-${4e3}-${8e3}-${1e11}`.replace(/[018]/g, generateUUID);\n}\nconst COMMA_SEPARATED_KEY_VALUE = /([\\w-]+)\\s*=\\s*([^;]+)/g;\nexport function findCommaSeparatedValue(rawString, name) {\n    COMMA_SEPARATED_KEY_VALUE.lastIndex = 0;\n    while (true) {\n        const match = COMMA_SEPARATED_KEY_VALUE.exec(rawString);\n        if (match) {\n            if (match[1] === name) {\n                return match[2];\n            }\n        }\n        else {\n            break;\n        }\n    }\n}\nexport function findCommaSeparatedValues(rawString) {\n    const result = new Map();\n    COMMA_SEPARATED_KEY_VALUE.lastIndex = 0;\n    while (true) {\n        const match = COMMA_SEPARATED_KEY_VALUE.exec(rawString);\n        if (match) {\n            result.set(match[1], match[2]);\n        }\n        else {\n            break;\n        }\n    }\n    return result;\n}\nexport function safeTruncate(candidate, length, suffix = '') {\n    const lastChar = candidate.charCodeAt(length - 1);\n    const isLastCharSurrogatePair = lastChar >= 0xd800 && lastChar <= 0xdbff;\n    const correctedLength = isLastCharSurrogatePair ? length + 1 : length;\n    if (candidate.length <= correctedLength) {\n        return candidate;\n    }\n    return `${candidate.slice(0, correctedLength)}${suffix}`;\n}\n//# sourceMappingURL=stringUtils.js.map","import { clocksNow, combine, elapsed, generateUUID, toServerDuration } from '@datadog/browser-core';\nexport function createCustomVitalsState() {\n    const vitalsByName = new Map();\n    const vitalsByReference = new WeakMap();\n    return { vitalsByName, vitalsByReference };\n}\nexport function startVitalCollection(lifeCycle, pageStateHistory, customVitalsState) {\n    function isValid(vital) {\n        return !pageStateHistory.wasInPageStateDuringPeriod(\"frozen\" /* PageState.FROZEN */, vital.startClocks.relative, vital.duration);\n    }\n    function addDurationVital(vital) {\n        if (isValid(vital)) {\n            lifeCycle.notify(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, processVital(vital, true));\n        }\n    }\n    return {\n        addDurationVital,\n        startDurationVital: (name, options = {}) => startDurationVital(customVitalsState, name, options),\n        stopDurationVital: (nameOrRef, options = {}) => {\n            stopDurationVital(addDurationVital, customVitalsState, nameOrRef, options);\n        },\n    };\n}\nexport function startDurationVital({ vitalsByName, vitalsByReference }, name, options = {}) {\n    const vital = {\n        name,\n        startClocks: clocksNow(),\n        context: options.context,\n        description: options.description,\n    };\n    // To avoid leaking implementation details of the vital, we return a reference to it.\n    const reference = { __dd_vital_reference: true };\n    vitalsByName.set(name, vital);\n    // To avoid memory leaks caused by the creation of numerous references (e.g., from improper useEffect implementations), we use a WeakMap.\n    vitalsByReference.set(reference, vital);\n    return reference;\n}\nexport function stopDurationVital(stopCallback, { vitalsByName, vitalsByReference }, nameOrRef, options = {}) {\n    const vitalStart = typeof nameOrRef === 'string' ? vitalsByName.get(nameOrRef) : vitalsByReference.get(nameOrRef);\n    if (!vitalStart) {\n        return;\n    }\n    stopCallback(buildDurationVital(vitalStart, vitalStart.startClocks, options, clocksNow()));\n    if (typeof nameOrRef === 'string') {\n        vitalsByName.delete(nameOrRef);\n    }\n    else {\n        vitalsByReference.delete(nameOrRef);\n    }\n}\nfunction buildDurationVital(vitalStart, startClocks, stopOptions, stopClocks) {\n    var _a;\n    return {\n        name: vitalStart.name,\n        type: \"duration\" /* VitalType.DURATION */,\n        startClocks,\n        duration: elapsed(startClocks.timeStamp, stopClocks.timeStamp),\n        context: combine(vitalStart.context, stopOptions.context),\n        description: (_a = stopOptions.description) !== null && _a !== void 0 ? _a : vitalStart.description,\n    };\n}\nfunction processVital(vital, valueComputedBySdk) {\n    const rawRumEvent = {\n        date: vital.startClocks.timeStamp,\n        vital: {\n            id: generateUUID(),\n            type: vital.type,\n            name: vital.name,\n            duration: toServerDuration(vital.duration),\n            description: vital.description,\n        },\n        type: \"vital\" /* RumEventType.VITAL */,\n    };\n    if (valueComputedBySdk) {\n        rawRumEvent._dd = {\n            vital: {\n                computed_value: true,\n            },\n        };\n    }\n    return {\n        rawRumEvent,\n        startTime: vital.startClocks.relative,\n        customerContext: vital.context,\n        domainContext: {},\n    };\n}\n//# sourceMappingURL=vitalCollection.js.map","export function callPluginsMethod(plugins, methodName, parameter) {\n    if (!plugins) {\n        return;\n    }\n    for (const plugin of plugins) {\n        const method = plugin[methodName];\n        if (method) {\n            method(parameter);\n        }\n    }\n}\n//# sourceMappingURL=plugins.js.map","import { instrumentMethod } from '../tools/instrumentMethod';\nimport { monitor } from '../tools/monitor';\nimport { Observable } from '../tools/observable';\nimport { clocksNow } from '../tools/utils/timeUtils';\nimport { normalizeUrl } from '../tools/utils/urlPolyfill';\nlet fetchObservable;\nexport function initFetchObservable() {\n    if (!fetchObservable) {\n        fetchObservable = createFetchObservable();\n    }\n    return fetchObservable;\n}\nexport function resetFetchObservable() {\n    fetchObservable = undefined;\n}\nfunction createFetchObservable() {\n    return new Observable((observable) => {\n        if (!window.fetch) {\n            return;\n        }\n        const { stop } = instrumentMethod(window, 'fetch', (call) => beforeSend(call, observable), {\n            computeHandlingStack: true,\n        });\n        return stop;\n    });\n}\nfunction beforeSend({ parameters, onPostCall, handlingStack }, observable) {\n    const [input, init] = parameters;\n    let methodFromParams = init && init.method;\n    if (methodFromParams === undefined && input instanceof Request) {\n        methodFromParams = input.method;\n    }\n    const method = methodFromParams !== undefined ? String(methodFromParams).toUpperCase() : 'GET';\n    const url = input instanceof Request ? input.url : normalizeUrl(String(input));\n    const startClocks = clocksNow();\n    const context = {\n        state: 'start',\n        init,\n        input,\n        method,\n        startClocks,\n        url,\n        handlingStack,\n    };\n    observable.notify(context);\n    // Those properties can be changed by observable subscribers\n    parameters[0] = context.input;\n    parameters[1] = context.init;\n    onPostCall((responsePromise) => afterSend(observable, responsePromise, context));\n}\nfunction afterSend(observable, responsePromise, startContext) {\n    const context = startContext;\n    function reportFetch(partialContext) {\n        context.state = 'resolve';\n        Object.assign(context, partialContext);\n        observable.notify(context);\n    }\n    responsePromise.then(monitor((response) => {\n        reportFetch({\n            response,\n            responseType: response.type,\n            status: response.status,\n            isAborted: false,\n        });\n    }), monitor((error) => {\n        var _a, _b;\n        reportFetch({\n            status: 0,\n            isAborted: ((_b = (_a = context.init) === null || _a === void 0 ? void 0 : _a.signal) === null || _b === void 0 ? void 0 : _b.aborted) || (error instanceof DOMException && error.code === DOMException.ABORT_ERR),\n            error,\n        });\n    }));\n}\n//# sourceMappingURL=fetchObservable.js.map","import { display } from '../tools/display';\nimport { ONE_MINUTE, ONE_SECOND } from '../tools/utils/timeUtils';\nimport { findCommaSeparatedValue, findCommaSeparatedValues, generateUUID } from '../tools/utils/stringUtils';\nexport function setCookie(name, value, expireDelay = 0, options) {\n    const date = new Date();\n    date.setTime(date.getTime() + expireDelay);\n    const expires = `expires=${date.toUTCString()}`;\n    const sameSite = options && options.crossSite ? 'none' : 'strict';\n    const domain = options && options.domain ? `;domain=${options.domain}` : '';\n    const secure = options && options.secure ? ';secure' : '';\n    const partitioned = options && options.partitioned ? ';partitioned' : '';\n    document.cookie = `${name}=${value};${expires};path=/;samesite=${sameSite}${domain}${secure}${partitioned}`;\n}\nexport function getCookie(name) {\n    return findCommaSeparatedValue(document.cookie, name);\n}\nlet initCookieParsed;\n/**\n * Returns a cached value of the cookie. Use this during SDK initialization (and whenever possible)\n * to avoid accessing document.cookie multiple times.\n */\nexport function getInitCookie(name) {\n    if (!initCookieParsed) {\n        initCookieParsed = findCommaSeparatedValues(document.cookie);\n    }\n    return initCookieParsed.get(name);\n}\nexport function resetInitCookies() {\n    initCookieParsed = undefined;\n}\nexport function deleteCookie(name, options) {\n    setCookie(name, '', 0, options);\n}\nexport function areCookiesAuthorized(options) {\n    if (document.cookie === undefined || document.cookie === null) {\n        return false;\n    }\n    try {\n        // Use a unique cookie name to avoid issues when the SDK is initialized multiple times during\n        // the test cookie lifetime\n        const testCookieName = `dd_cookie_test_${generateUUID()}`;\n        const testCookieValue = 'test';\n        setCookie(testCookieName, testCookieValue, ONE_MINUTE, options);\n        const isCookieCorrectlySet = getCookie(testCookieName) === testCookieValue;\n        deleteCookie(testCookieName, options);\n        return isCookieCorrectlySet;\n    }\n    catch (error) {\n        display.error(error);\n        return false;\n    }\n}\n/**\n * No API to retrieve it, number of levels for subdomain and suffix are unknown\n * strategy: find the minimal domain on which cookies are allowed to be set\n * https://web.dev/same-site-same-origin/#site\n */\nlet getCurrentSiteCache;\nexport function getCurrentSite() {\n    if (getCurrentSiteCache === undefined) {\n        // Use a unique cookie name to avoid issues when the SDK is initialized multiple times during\n        // the test cookie lifetime\n        const testCookieName = `dd_site_test_${generateUUID()}`;\n        const testCookieValue = 'test';\n        const domainLevels = window.location.hostname.split('.');\n        let candidateDomain = domainLevels.pop();\n        while (domainLevels.length && !getCookie(testCookieName)) {\n            candidateDomain = `${domainLevels.pop()}.${candidateDomain}`;\n            setCookie(testCookieName, testCookieValue, ONE_SECOND, { domain: candidateDomain });\n        }\n        deleteCookie(testCookieName, { domain: candidateDomain });\n        getCurrentSiteCache = candidateDomain;\n    }\n    return getCurrentSiteCache;\n}\n//# sourceMappingURL=cookie.js.map","import { getInitCookie } from '../../browser/cookie';\nexport const SYNTHETICS_TEST_ID_COOKIE_NAME = 'datadog-synthetics-public-id';\nexport const SYNTHETICS_RESULT_ID_COOKIE_NAME = 'datadog-synthetics-result-id';\nexport const SYNTHETICS_INJECTS_RUM_COOKIE_NAME = 'datadog-synthetics-injects-rum';\nexport function willSyntheticsInjectRum() {\n    return Boolean(window._DATADOG_SYNTHETICS_INJECTS_RUM || getInitCookie(SYNTHETICS_INJECTS_RUM_COOKIE_NAME));\n}\nexport function getSyntheticsTestId() {\n    const value = window._DATADOG_SYNTHETICS_PUBLIC_ID || getInitCookie(SYNTHETICS_TEST_ID_COOKIE_NAME);\n    return typeof value === 'string' ? value : undefined;\n}\nexport function getSyntheticsResultId() {\n    const value = window._DATADOG_SYNTHETICS_RESULT_ID || getInitCookie(SYNTHETICS_RESULT_ID_COOKIE_NAME);\n    return typeof value === 'string' ? value : undefined;\n}\n//# sourceMappingURL=syntheticsWorkerValues.js.map","export const SESSION_STORE_KEY = '_dd_s';\n//# sourceMappingURL=sessionStoreStrategy.js.map","import { ONE_HOUR, ONE_MINUTE, ONE_YEAR } from '../../tools/utils/timeUtils';\nexport const SESSION_TIME_OUT_DELAY = 4 * ONE_HOUR;\nexport const SESSION_EXPIRATION_DELAY = 15 * ONE_MINUTE;\nexport const SESSION_COOKIE_EXPIRATION_DELAY = ONE_YEAR;\nexport const SessionPersistence = {\n    COOKIE: 'cookie',\n    LOCAL_STORAGE: 'local-storage',\n};\n//# sourceMappingURL=sessionConstants.js.map","export const SESSION_ENTRY_REGEXP = /^([a-zA-Z]+)=([a-z0-9-]+)$/;\nexport const SESSION_ENTRY_SEPARATOR = '&';\nexport function isValidSessionString(sessionString) {\n    return (!!sessionString &&\n        (sessionString.indexOf(SESSION_ENTRY_SEPARATOR) !== -1 || SESSION_ENTRY_REGEXP.test(sessionString)));\n}\n//# sourceMappingURL=sessionStateValidation.js.map","import { isEmptyObject } from '../../tools/utils/objectUtils';\nimport { objectEntries } from '../../tools/utils/polyfills';\nimport { dateNow } from '../../tools/utils/timeUtils';\nimport { generateAnonymousId } from '../user';\nimport { SESSION_EXPIRATION_DELAY, SESSION_TIME_OUT_DELAY } from './sessionConstants';\nimport { isValidSessionString, SESSION_ENTRY_REGEXP, SESSION_ENTRY_SEPARATOR } from './sessionStateValidation';\nexport const EXPIRED = '1';\nexport function getExpiredSessionState(previousSessionState, configuration) {\n    const expiredSessionState = {\n        isExpired: EXPIRED,\n    };\n    if (configuration.trackAnonymousUser) {\n        if (previousSessionState === null || previousSessionState === void 0 ? void 0 : previousSessionState.anonymousId) {\n            expiredSessionState.anonymousId = previousSessionState === null || previousSessionState === void 0 ? void 0 : previousSessionState.anonymousId;\n        }\n        else {\n            expiredSessionState.anonymousId = generateAnonymousId();\n        }\n    }\n    return expiredSessionState;\n}\nexport function isSessionInNotStartedState(session) {\n    return isEmptyObject(session);\n}\nexport function isSessionStarted(session) {\n    return !isSessionInNotStartedState(session);\n}\nexport function isSessionInExpiredState(session) {\n    return session.isExpired !== undefined || !isActiveSession(session);\n}\n// An active session is a session in either `Tracked` or `NotTracked` state\nfunction isActiveSession(sessionState) {\n    // created and expire can be undefined for versions which was not storing them\n    // these checks could be removed when older versions will not be available/live anymore\n    return ((sessionState.created === undefined || dateNow() - Number(sessionState.created) < SESSION_TIME_OUT_DELAY) &&\n        (sessionState.expire === undefined || dateNow() < Number(sessionState.expire)));\n}\nexport function expandSessionState(session) {\n    session.expire = String(dateNow() + SESSION_EXPIRATION_DELAY);\n}\nexport function toSessionString(session) {\n    return (objectEntries(session)\n        // we use `aid` as a key for anonymousId\n        .map(([key, value]) => (key === 'anonymousId' ? `aid=${value}` : `${key}=${value}`))\n        .join(SESSION_ENTRY_SEPARATOR));\n}\nexport function toSessionState(sessionString) {\n    const session = {};\n    if (isValidSessionString(sessionString)) {\n        sessionString.split(SESSION_ENTRY_SEPARATOR).forEach((entry) => {\n            const matches = SESSION_ENTRY_REGEXP.exec(entry);\n            if (matches !== null) {\n                const [, key, value] = matches;\n                if (key === 'aid') {\n                    // we use `aid` as a key for anonymousId\n                    session.anonymousId = value;\n                }\n                else {\n                    session[key] = value;\n                }\n            }\n        });\n    }\n    return session;\n}\n//# sourceMappingURL=sessionState.js.map","import { getInitCookie } from '../../browser/cookie';\nimport { SESSION_STORE_KEY } from './storeStrategies/sessionStoreStrategy';\nimport { expandSessionState, isSessionStarted } from './sessionState';\nexport const OLD_SESSION_COOKIE_NAME = '_dd';\nexport const OLD_RUM_COOKIE_NAME = '_dd_r';\nexport const OLD_LOGS_COOKIE_NAME = '_dd_l';\n// duplicate values to avoid dependency issues\nexport const RUM_SESSION_KEY = 'rum';\nexport const LOGS_SESSION_KEY = 'logs';\n/**\n * This migration should remain in the codebase as long as older versions are available/live\n * to allow older sdk versions to be upgraded to newer versions without compatibility issues.\n */\nexport function tryOldCookiesMigration(cookieStoreStrategy) {\n    const sessionString = getInitCookie(SESSION_STORE_KEY);\n    if (!sessionString) {\n        const oldSessionId = getInitCookie(OLD_SESSION_COOKIE_NAME);\n        const oldRumType = getInitCookie(OLD_RUM_COOKIE_NAME);\n        const oldLogsType = getInitCookie(OLD_LOGS_COOKIE_NAME);\n        const session = {};\n        if (oldSessionId) {\n            session.id = oldSessionId;\n        }\n        if (oldLogsType && /^[01]$/.test(oldLogsType)) {\n            session[LOGS_SESSION_KEY] = oldLogsType;\n        }\n        if (oldRumType && /^[012]$/.test(oldRumType)) {\n            session[RUM_SESSION_KEY] = oldRumType;\n        }\n        if (isSessionStarted(session)) {\n            expandSessionState(session);\n            cookieStoreStrategy.persistSession(session);\n        }\n    }\n}\n//# sourceMappingURL=oldCookiesMigration.js.map","import { isChromium } from '../../../tools/utils/browserDetection';\nimport { getCurrentSite, areCookiesAuthorized, getCookie, setCookie } from '../../../browser/cookie';\nimport { tryOldCookiesMigration } from '../oldCookiesMigration';\nimport { SESSION_COOKIE_EXPIRATION_DELAY, SESSION_EXPIRATION_DELAY, SESSION_TIME_OUT_DELAY, SessionPersistence, } from '../sessionConstants';\nimport { toSessionString, toSessionState, getExpiredSessionState } from '../sessionState';\nimport { SESSION_STORE_KEY } from './sessionStoreStrategy';\nexport function selectCookieStrategy(initConfiguration) {\n    const cookieOptions = buildCookieOptions(initConfiguration);\n    return areCookiesAuthorized(cookieOptions) ? { type: SessionPersistence.COOKIE, cookieOptions } : undefined;\n}\nexport function initCookieStrategy(configuration, cookieOptions) {\n    const cookieStore = {\n        /**\n         * Lock strategy allows mitigating issues due to concurrent access to cookie.\n         * This issue concerns only chromium browsers and enabling this on firefox increases cookie write failures.\n         */\n        isLockEnabled: isChromium(),\n        persistSession: persistSessionCookie(cookieOptions),\n        retrieveSession: retrieveSessionCookie,\n        expireSession: (sessionState) => expireSessionCookie(cookieOptions, sessionState, configuration),\n    };\n    tryOldCookiesMigration(cookieStore);\n    return cookieStore;\n}\nfunction persistSessionCookie(options) {\n    return (session) => {\n        setCookie(SESSION_STORE_KEY, toSessionString(session), SESSION_EXPIRATION_DELAY, options);\n    };\n}\nfunction expireSessionCookie(options, sessionState, configuration) {\n    const expiredSessionState = getExpiredSessionState(sessionState, configuration);\n    // we do not extend cookie expiration date\n    setCookie(SESSION_STORE_KEY, toSessionString(expiredSessionState), configuration.trackAnonymousUser ? SESSION_COOKIE_EXPIRATION_DELAY : SESSION_TIME_OUT_DELAY, options);\n}\nfunction retrieveSessionCookie() {\n    const sessionString = getCookie(SESSION_STORE_KEY);\n    const sessionState = toSessionState(sessionString);\n    return sessionState;\n}\nexport function buildCookieOptions(initConfiguration) {\n    const cookieOptions = {};\n    cookieOptions.secure =\n        !!initConfiguration.useSecureSessionCookie || !!initConfiguration.usePartitionedCrossSiteSessionCookie;\n    cookieOptions.crossSite = !!initConfiguration.usePartitionedCrossSiteSessionCookie;\n    cookieOptions.partitioned = !!initConfiguration.usePartitionedCrossSiteSessionCookie;\n    if (initConfiguration.trackSessionAcrossSubdomains) {\n        cookieOptions.domain = getCurrentSite();\n    }\n    return cookieOptions;\n}\n//# sourceMappingURL=sessionInCookie.js.map","import { generateUUID } from '../../../tools/utils/stringUtils';\nimport { SessionPersistence } from '../sessionConstants';\nimport { toSessionString, toSessionState, getExpiredSessionState } from '../sessionState';\nimport { SESSION_STORE_KEY } from './sessionStoreStrategy';\nconst LOCAL_STORAGE_TEST_KEY = '_dd_test_';\nexport function selectLocalStorageStrategy() {\n    try {\n        const id = generateUUID();\n        const testKey = `${LOCAL_STORAGE_TEST_KEY}${id}`;\n        localStorage.setItem(testKey, id);\n        const retrievedId = localStorage.getItem(testKey);\n        localStorage.removeItem(testKey);\n        return id === retrievedId ? { type: SessionPersistence.LOCAL_STORAGE } : undefined;\n    }\n    catch (_a) {\n        return undefined;\n    }\n}\nexport function initLocalStorageStrategy(configuration) {\n    return {\n        isLockEnabled: false,\n        persistSession: persistInLocalStorage,\n        retrieveSession: retrieveSessionFromLocalStorage,\n        expireSession: (sessionState) => expireSessionFromLocalStorage(sessionState, configuration),\n    };\n}\nfunction persistInLocalStorage(sessionState) {\n    localStorage.setItem(SESSION_STORE_KEY, toSessionString(sessionState));\n}\nfunction retrieveSessionFromLocalStorage() {\n    const sessionString = localStorage.getItem(SESSION_STORE_KEY);\n    return toSessionState(sessionString);\n}\nfunction expireSessionFromLocalStorage(previousSessionState, configuration) {\n    persistInLocalStorage(getExpiredSessionState(previousSessionState, configuration));\n}\n//# sourceMappingURL=sessionInLocalStorage.js.map","import { setTimeout } from '../../tools/timer';\nimport { generateUUID } from '../../tools/utils/stringUtils';\nimport { expandSessionState, isSessionInExpiredState } from './sessionState';\nexport const LOCK_RETRY_DELAY = 10;\nexport const LOCK_MAX_TRIES = 100;\nconst bufferedOperations = [];\nlet ongoingOperations;\nexport function processSessionStoreOperations(operations, sessionStoreStrategy, numberOfRetries = 0) {\n    var _a;\n    const { isLockEnabled, persistSession, expireSession } = sessionStoreStrategy;\n    const persistWithLock = (session) => persistSession({ ...session, lock: currentLock });\n    const retrieveStore = () => {\n        const session = sessionStoreStrategy.retrieveSession();\n        const lock = session.lock;\n        if (session.lock) {\n            delete session.lock;\n        }\n        return {\n            session,\n            lock,\n        };\n    };\n    if (!ongoingOperations) {\n        ongoingOperations = operations;\n    }\n    if (operations !== ongoingOperations) {\n        bufferedOperations.push(operations);\n        return;\n    }\n    if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) {\n        next(sessionStoreStrategy);\n        return;\n    }\n    let currentLock;\n    let currentStore = retrieveStore();\n    if (isLockEnabled) {\n        // if someone has lock, retry later\n        if (currentStore.lock) {\n            retryLater(operations, sessionStoreStrategy, numberOfRetries);\n            return;\n        }\n        // acquire lock\n        currentLock = generateUUID();\n        persistWithLock(currentStore.session);\n        // if lock is not acquired, retry later\n        currentStore = retrieveStore();\n        if (currentStore.lock !== currentLock) {\n            retryLater(operations, sessionStoreStrategy, numberOfRetries);\n            return;\n        }\n    }\n    let processedSession = operations.process(currentStore.session);\n    if (isLockEnabled) {\n        // if lock corrupted after process, retry later\n        currentStore = retrieveStore();\n        if (currentStore.lock !== currentLock) {\n            retryLater(operations, sessionStoreStrategy, numberOfRetries);\n            return;\n        }\n    }\n    if (processedSession) {\n        if (isSessionInExpiredState(processedSession)) {\n            expireSession(processedSession);\n        }\n        else {\n            expandSessionState(processedSession);\n            if (isLockEnabled) {\n                persistWithLock(processedSession);\n            }\n            else {\n                persistSession(processedSession);\n            }\n        }\n    }\n    if (isLockEnabled) {\n        // correctly handle lock around expiration would require to handle this case properly at several levels\n        // since we don't have evidence of lock issues around expiration, let's just not do the corruption check for it\n        if (!(processedSession && isSessionInExpiredState(processedSession))) {\n            // if lock corrupted after persist, retry later\n            currentStore = retrieveStore();\n            if (currentStore.lock !== currentLock) {\n                retryLater(operations, sessionStoreStrategy, numberOfRetries);\n                return;\n            }\n            persistSession(currentStore.session);\n            processedSession = currentStore.session;\n        }\n    }\n    // call after even if session is not persisted in order to perform operations on\n    // up-to-date session state value => the value could have been modified by another tab\n    (_a = operations.after) === null || _a === void 0 ? void 0 : _a.call(operations, processedSession || currentStore.session);\n    next(sessionStoreStrategy);\n}\nfunction retryLater(operations, sessionStore, currentNumberOfRetries) {\n    setTimeout(() => {\n        processSessionStoreOperations(operations, sessionStore, currentNumberOfRetries + 1);\n    }, LOCK_RETRY_DELAY);\n}\nfunction next(sessionStore) {\n    ongoingOperations = undefined;\n    const nextOperations = bufferedOperations.shift();\n    if (nextOperations) {\n        processSessionStoreOperations(nextOperations, sessionStore);\n    }\n}\n//# sourceMappingURL=sessionStoreOperations.js.map","import { clearInterval, setInterval } from '../../tools/timer';\nimport { Observable } from '../../tools/observable';\nimport { ONE_SECOND, dateNow } from '../../tools/utils/timeUtils';\nimport { throttle } from '../../tools/utils/functionUtils';\nimport { generateUUID } from '../../tools/utils/stringUtils';\nimport { display } from '../../tools/display';\nimport { selectCookieStrategy, initCookieStrategy } from './storeStrategies/sessionInCookie';\nimport { getExpiredSessionState, isSessionInExpiredState, isSessionInNotStartedState, isSessionStarted, } from './sessionState';\nimport { initLocalStorageStrategy, selectLocalStorageStrategy } from './storeStrategies/sessionInLocalStorage';\nimport { processSessionStoreOperations } from './sessionStoreOperations';\nimport { SessionPersistence } from './sessionConstants';\n/**\n * Every second, the storage will be polled to check for any change that can occur\n * to the session state in another browser tab, or another window.\n * This value has been determined from our previous cookie-only implementation.\n */\nexport const STORAGE_POLL_DELAY = ONE_SECOND;\n/**\n * Selects the correct session store strategy type based on the configuration and storage\n * availability.\n */\nexport function selectSessionStoreStrategyType(initConfiguration) {\n    switch (initConfiguration.sessionPersistence) {\n        case SessionPersistence.COOKIE:\n            return selectCookieStrategy(initConfiguration);\n        case SessionPersistence.LOCAL_STORAGE:\n            return selectLocalStorageStrategy();\n        case undefined: {\n            let sessionStoreStrategyType = selectCookieStrategy(initConfiguration);\n            if (!sessionStoreStrategyType && initConfiguration.allowFallbackToLocalStorage) {\n                sessionStoreStrategyType = selectLocalStorageStrategy();\n            }\n            return sessionStoreStrategyType;\n        }\n        default:\n            display.error(`Invalid session persistence '${String(initConfiguration.sessionPersistence)}'`);\n    }\n}\n/**\n * Different session concepts:\n * - tracked, the session has an id and is updated along the user navigation\n * - not tracked, the session does not have an id but it is updated along the user navigation\n * - inactive, no session in store or session expired, waiting for a renew session\n */\nexport function startSessionStore(sessionStoreStrategyType, configuration, productKey, computeSessionState) {\n    const renewObservable = new Observable();\n    const expireObservable = new Observable();\n    const sessionStateUpdateObservable = new Observable();\n    const sessionStoreStrategy = sessionStoreStrategyType.type === SessionPersistence.COOKIE\n        ? initCookieStrategy(configuration, sessionStoreStrategyType.cookieOptions)\n        : initLocalStorageStrategy(configuration);\n    const { expireSession } = sessionStoreStrategy;\n    const watchSessionTimeoutId = setInterval(watchSession, STORAGE_POLL_DELAY);\n    let sessionCache;\n    startSession();\n    const { throttled: throttledExpandOrRenewSession, cancel: cancelExpandOrRenewSession } = throttle(() => {\n        processSessionStoreOperations({\n            process: (sessionState) => {\n                if (isSessionInNotStartedState(sessionState)) {\n                    return;\n                }\n                const synchronizedSession = synchronizeSession(sessionState);\n                expandOrRenewSessionState(synchronizedSession);\n                return synchronizedSession;\n            },\n            after: (sessionState) => {\n                if (isSessionStarted(sessionState) && !hasSessionInCache()) {\n                    renewSessionInCache(sessionState);\n                }\n                sessionCache = sessionState;\n            },\n        }, sessionStoreStrategy);\n    }, STORAGE_POLL_DELAY);\n    function expandSession() {\n        processSessionStoreOperations({\n            process: (sessionState) => (hasSessionInCache() ? synchronizeSession(sessionState) : undefined),\n        }, sessionStoreStrategy);\n    }\n    /**\n     * allows two behaviors:\n     * - if the session is active, synchronize the session cache without updating the session store\n     * - if the session is not active, clear the session store and expire the session cache\n     */\n    function watchSession() {\n        processSessionStoreOperations({\n            process: (sessionState) => isSessionInExpiredState(sessionState) ? getExpiredSessionState(sessionState, configuration) : undefined,\n            after: synchronizeSession,\n        }, sessionStoreStrategy);\n    }\n    function synchronizeSession(sessionState) {\n        if (isSessionInExpiredState(sessionState)) {\n            sessionState = getExpiredSessionState(sessionState, configuration);\n        }\n        if (hasSessionInCache()) {\n            if (isSessionInCacheOutdated(sessionState)) {\n                expireSessionInCache();\n            }\n            else {\n                sessionStateUpdateObservable.notify({ previousState: sessionCache, newState: sessionState });\n                sessionCache = sessionState;\n            }\n        }\n        return sessionState;\n    }\n    function startSession() {\n        processSessionStoreOperations({\n            process: (sessionState) => {\n                if (isSessionInNotStartedState(sessionState)) {\n                    return getExpiredSessionState(sessionState, configuration);\n                }\n            },\n            after: (sessionState) => {\n                sessionCache = sessionState;\n            },\n        }, sessionStoreStrategy);\n    }\n    function expandOrRenewSessionState(sessionState) {\n        if (isSessionInNotStartedState(sessionState)) {\n            return false;\n        }\n        const { trackingType, isTracked } = computeSessionState(sessionState[productKey]);\n        sessionState[productKey] = trackingType;\n        delete sessionState.isExpired;\n        if (isTracked && !sessionState.id) {\n            sessionState.id = generateUUID();\n            sessionState.created = String(dateNow());\n        }\n    }\n    function hasSessionInCache() {\n        return sessionCache[productKey] !== undefined;\n    }\n    function isSessionInCacheOutdated(sessionState) {\n        return sessionCache.id !== sessionState.id || sessionCache[productKey] !== sessionState[productKey];\n    }\n    function expireSessionInCache() {\n        sessionCache = getExpiredSessionState(sessionCache, configuration);\n        expireObservable.notify();\n    }\n    function renewSessionInCache(sessionState) {\n        sessionCache = sessionState;\n        renewObservable.notify();\n    }\n    function updateSessionState(partialSessionState) {\n        processSessionStoreOperations({\n            process: (sessionState) => ({ ...sessionState, ...partialSessionState }),\n            after: synchronizeSession,\n        }, sessionStoreStrategy);\n    }\n    return {\n        expandOrRenewSession: throttledExpandOrRenewSession,\n        expandSession,\n        getSession: () => sessionCache,\n        renewObservable,\n        expireObservable,\n        sessionStateUpdateObservable,\n        restartSession: startSession,\n        expire: () => {\n            cancelExpandOrRenewSession();\n            expireSession(sessionCache);\n            synchronizeSession(getExpiredSessionState(sessionCache, configuration));\n        },\n        stop: () => {\n            clearInterval(watchSessionTimeoutId);\n        },\n        updateSessionState,\n    };\n}\n//# sourceMappingURL=sessionStore.js.map","import { timeStampNow } from '../../tools/utils/timeUtils';\nimport { normalizeUrl } from '../../tools/utils/urlPolyfill';\nimport { generateUUID } from '../../tools/utils/stringUtils';\nimport { INTAKE_SITE_US1, INTAKE_SITE_FED_STAGING, PCI_INTAKE_HOST_US1 } from './intakeSites';\nexport function createEndpointBuilder(initConfiguration, trackType, configurationTags) {\n    const buildUrlWithParameters = createEndpointUrlWithParametersBuilder(initConfiguration, trackType);\n    return {\n        build(api, payload) {\n            const parameters = buildEndpointParameters(initConfiguration, trackType, configurationTags, api, payload);\n            return buildUrlWithParameters(parameters);\n        },\n        urlPrefix: buildUrlWithParameters(''),\n        trackType,\n    };\n}\n/**\n * Create a function used to build a full endpoint url from provided parameters. The goal of this\n * function is to pre-compute some parts of the URL to avoid re-computing everything on every\n * request, as only parameters are changing.\n */\nfunction createEndpointUrlWithParametersBuilder(initConfiguration, trackType) {\n    const path = `/api/v2/${trackType}`;\n    const proxy = initConfiguration.proxy;\n    if (typeof proxy === 'string') {\n        const normalizedProxyUrl = normalizeUrl(proxy);\n        return (parameters) => `${normalizedProxyUrl}?ddforward=${encodeURIComponent(`${path}?${parameters}`)}`;\n    }\n    if (typeof proxy === 'function') {\n        return (parameters) => proxy({ path, parameters });\n    }\n    const host = buildEndpointHost(trackType, initConfiguration);\n    return (parameters) => `https://${host}${path}?${parameters}`;\n}\nfunction buildEndpointHost(trackType, initConfiguration) {\n    const { site = INTAKE_SITE_US1, internalAnalyticsSubdomain } = initConfiguration;\n    if (trackType === 'logs' && initConfiguration.usePciIntake && site === INTAKE_SITE_US1) {\n        return PCI_INTAKE_HOST_US1;\n    }\n    if (internalAnalyticsSubdomain && site === INTAKE_SITE_US1) {\n        return `${internalAnalyticsSubdomain}.${INTAKE_SITE_US1}`;\n    }\n    if (site === INTAKE_SITE_FED_STAGING) {\n        return `http-intake.logs.${site}`;\n    }\n    const domainParts = site.split('.');\n    const extension = domainParts.pop();\n    return `browser-intake-${domainParts.join('-')}.${extension}`;\n}\n/**\n * Build parameters to be used for an intake request. Parameters should be re-built for each\n * request, as they change randomly.\n */\nfunction buildEndpointParameters({ clientToken, internalAnalyticsSubdomain }, trackType, configurationTags, api, { retry, encoding }) {\n    const tags = [`sdk_version:${\"6.1.0\"}`, `api:${api}`].concat(configurationTags);\n    if (retry) {\n        tags.push(`retry_count:${retry.count}`, `retry_after:${retry.lastFailureStatus}`);\n    }\n    const parameters = [\n        'ddsource=browser',\n        `ddtags=${encodeURIComponent(tags.join(','))}`,\n        `dd-api-key=${clientToken}`,\n        `dd-evp-origin-version=${encodeURIComponent(\"6.1.0\")}`,\n        'dd-evp-origin=browser',\n        `dd-request-id=${generateUUID()}`,\n    ];\n    if (encoding) {\n        parameters.push(`dd-evp-encoding=${encoding}`);\n    }\n    if (trackType === 'rum') {\n        parameters.push(`batch_time=${timeStampNow()}`);\n    }\n    if (internalAnalyticsSubdomain) {\n        parameters.reverse();\n    }\n    return parameters.join('&');\n}\n//# sourceMappingURL=endpointBuilder.js.map","import { DOCS_ORIGIN, MORE_DETAILS, display } from '../../tools/display';\nexport const TAG_SIZE_LIMIT = 200;\nexport function buildTags(configuration) {\n    const { env, service, version, datacenter } = configuration;\n    const tags = [];\n    if (env) {\n        tags.push(buildTag('env', env));\n    }\n    if (service) {\n        tags.push(buildTag('service', service));\n    }\n    if (version) {\n        tags.push(buildTag('version', version));\n    }\n    if (datacenter) {\n        tags.push(buildTag('datacenter', datacenter));\n    }\n    return tags;\n}\nexport function buildTag(key, rawValue) {\n    // See https://docs.datadoghq.com/getting_started/tagging/#defining-tags for tags syntax. Note\n    // that the backend may not follow the exact same rules, so we only want to display an informal\n    // warning.\n    const valueSizeLimit = TAG_SIZE_LIMIT - key.length - 1;\n    if (rawValue.length > valueSizeLimit || hasForbiddenCharacters(rawValue)) {\n        display.warn(`${key} value doesn't meet tag requirements and will be sanitized. ${MORE_DETAILS} ${DOCS_ORIGIN}/getting_started/tagging/#defining-tags`);\n    }\n    // Let the backend do most of the sanitization, but still make sure multiple tags can't be crafted\n    // by forging a value containing commas.\n    const sanitizedValue = rawValue.replace(/,/g, '_');\n    return `${key}:${sanitizedValue}`;\n}\nfunction hasForbiddenCharacters(rawValue) {\n    // Unicode property escapes is not supported in all browsers, so we use a try/catch.\n    // Todo: Remove the try/catch when dropping support for Chrome 63 and Firefox 67\n    // see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape#browser_compatibility\n    if (!supportUnicodePropertyEscapes()) {\n        return false;\n    }\n    // We use the Unicode property escapes to match any character that is a letter including other languages like Chinese, Japanese, etc.\n    // p{Ll} matches a lowercase letter.\n    // p{Lo} matches a letter that is neither uppercase nor lowercase (ex: Japanese characters).\n    // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape#unicode_property_escapes_vs._character_classes\n    return new RegExp('[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]', 'u').test(rawValue);\n}\nexport function supportUnicodePropertyEscapes() {\n    try {\n        new RegExp('[\\\\p{Ll}]', 'u');\n        return true;\n    }\n    catch (_a) {\n        return false;\n    }\n}\n//# sourceMappingURL=tags.js.map","import { createEndpointBuilder } from './endpointBuilder';\nimport { buildTags } from './tags';\nimport { INTAKE_SITE_US1, INTAKE_URL_PARAMETERS } from './intakeSites';\nexport function computeTransportConfiguration(initConfiguration) {\n    const site = initConfiguration.site || INTAKE_SITE_US1;\n    const tags = buildTags(initConfiguration);\n    const endpointBuilders = computeEndpointBuilders(initConfiguration, tags);\n    const replicaConfiguration = computeReplicaConfiguration(initConfiguration, tags);\n    return {\n        replica: replicaConfiguration,\n        site,\n        ...endpointBuilders,\n    };\n}\nfunction computeEndpointBuilders(initConfiguration, tags) {\n    return {\n        logsEndpointBuilder: createEndpointBuilder(initConfiguration, 'logs', tags),\n        rumEndpointBuilder: createEndpointBuilder(initConfiguration, 'rum', tags),\n        sessionReplayEndpointBuilder: createEndpointBuilder(initConfiguration, 'replay', tags),\n    };\n}\nfunction computeReplicaConfiguration(initConfiguration, tags) {\n    if (!initConfiguration.replica) {\n        return;\n    }\n    const replicaConfiguration = {\n        ...initConfiguration,\n        site: INTAKE_SITE_US1,\n        clientToken: initConfiguration.replica.clientToken,\n    };\n    const replicaEndpointBuilders = {\n        logsEndpointBuilder: createEndpointBuilder(replicaConfiguration, 'logs', tags),\n        rumEndpointBuilder: createEndpointBuilder(replicaConfiguration, 'rum', tags),\n    };\n    return { applicationId: initConfiguration.replica.applicationId, ...replicaEndpointBuilders };\n}\nexport function isIntakeUrl(url) {\n    // check if tags is present in the query string\n    return INTAKE_URL_PARAMETERS.every((param) => url.includes(param));\n}\n//# sourceMappingURL=transportConfiguration.js.map","import { catchUserErrors } from '../../tools/catchUserErrors';\nimport { DOCS_ORIGIN, MORE_DETAILS, display } from '../../tools/display';\nimport { ONE_SECOND } from '../../tools/utils/timeUtils';\nimport { isPercentage } from '../../tools/utils/numberUtils';\nimport { ONE_KIBI_BYTE } from '../../tools/utils/byteUtils';\nimport { objectHasValue } from '../../tools/utils/objectUtils';\nimport { selectSessionStoreStrategyType } from '../session/sessionStore';\nimport { TrackingConsent } from '../trackingConsent';\nimport { computeTransportConfiguration } from './transportConfiguration';\nexport const DefaultPrivacyLevel = {\n    ALLOW: 'allow',\n    MASK: 'mask',\n    MASK_USER_INPUT: 'mask-user-input',\n};\nexport const TraceContextInjection = {\n    ALL: 'all',\n    SAMPLED: 'sampled',\n};\nfunction isString(tag, tagName) {\n    if (tag !== undefined && tag !== null && typeof tag !== 'string') {\n        display.error(`${tagName} must be defined as a string`);\n        return false;\n    }\n    return true;\n}\nfunction isDatadogSite(site) {\n    if (site && typeof site === 'string' && !/(datadog|ddog|datad0g|dd0g)/.test(site)) {\n        display.error(`Site should be a valid Datadog site. ${MORE_DETAILS} ${DOCS_ORIGIN}/getting_started/site/.`);\n        return false;\n    }\n    return true;\n}\nexport function isSampleRate(sampleRate, name) {\n    if (sampleRate !== undefined && !isPercentage(sampleRate)) {\n        display.error(`${name} Sample Rate should be a number between 0 and 100`);\n        return false;\n    }\n    return true;\n}\nexport function validateAndBuildConfiguration(initConfiguration) {\n    var _a, _b, _c, _d, _e, _f;\n    if (!initConfiguration || !initConfiguration.clientToken) {\n        display.error('Client Token is not configured, we will not send any data.');\n        return;\n    }\n    if (!isDatadogSite(initConfiguration.site) ||\n        !isSampleRate(initConfiguration.sessionSampleRate, 'Session') ||\n        !isSampleRate(initConfiguration.telemetrySampleRate, 'Telemetry') ||\n        !isSampleRate(initConfiguration.telemetryConfigurationSampleRate, 'Telemetry Configuration') ||\n        !isSampleRate(initConfiguration.telemetryUsageSampleRate, 'Telemetry Usage') ||\n        !isString(initConfiguration.version, 'Version') ||\n        !isString(initConfiguration.env, 'Env') ||\n        !isString(initConfiguration.service, 'Service')) {\n        return;\n    }\n    if (initConfiguration.trackingConsent !== undefined &&\n        !objectHasValue(TrackingConsent, initConfiguration.trackingConsent)) {\n        display.error('Tracking Consent should be either \"granted\" or \"not-granted\"');\n        return;\n    }\n    return {\n        beforeSend: initConfiguration.beforeSend && catchUserErrors(initConfiguration.beforeSend, 'beforeSend threw an error:'),\n        sessionStoreStrategyType: selectSessionStoreStrategyType(initConfiguration),\n        sessionSampleRate: (_a = initConfiguration.sessionSampleRate) !== null && _a !== void 0 ? _a : 100,\n        telemetrySampleRate: (_b = initConfiguration.telemetrySampleRate) !== null && _b !== void 0 ? _b : 20,\n        telemetryConfigurationSampleRate: (_c = initConfiguration.telemetryConfigurationSampleRate) !== null && _c !== void 0 ? _c : 5,\n        telemetryUsageSampleRate: (_d = initConfiguration.telemetryUsageSampleRate) !== null && _d !== void 0 ? _d : 5,\n        service: initConfiguration.service || undefined,\n        silentMultipleInit: !!initConfiguration.silentMultipleInit,\n        allowUntrustedEvents: !!initConfiguration.allowUntrustedEvents,\n        trackingConsent: (_e = initConfiguration.trackingConsent) !== null && _e !== void 0 ? _e : TrackingConsent.GRANTED,\n        trackAnonymousUser: (_f = initConfiguration.trackAnonymousUser) !== null && _f !== void 0 ? _f : true,\n        storeContextsAcrossPages: !!initConfiguration.storeContextsAcrossPages,\n        /**\n         * beacon payload max queue size implementation is 64kb\n         * ensure that we leave room for logs, rum and potential other users\n         */\n        batchBytesLimit: 16 * ONE_KIBI_BYTE,\n        eventRateLimiterThreshold: 3000,\n        maxTelemetryEventsPerPage: 15,\n        /**\n         * flush automatically, aim to be lower than ALB connection timeout\n         * to maximize connection reuse.\n         */\n        flushTimeout: (30 * ONE_SECOND),\n        /**\n         * Logs intake limit\n         */\n        batchMessagesLimit: 50,\n        messageBytesLimit: 256 * ONE_KIBI_BYTE,\n        ...computeTransportConfiguration(initConfiguration),\n    };\n}\nexport function serializeConfiguration(initConfiguration) {\n    return {\n        session_sample_rate: initConfiguration.sessionSampleRate,\n        telemetry_sample_rate: initConfiguration.telemetrySampleRate,\n        telemetry_configuration_sample_rate: initConfiguration.telemetryConfigurationSampleRate,\n        telemetry_usage_sample_rate: initConfiguration.telemetryUsageSampleRate,\n        use_before_send: !!initConfiguration.beforeSend,\n        use_partitioned_cross_site_session_cookie: initConfiguration.usePartitionedCrossSiteSessionCookie,\n        use_secure_session_cookie: initConfiguration.useSecureSessionCookie,\n        use_proxy: !!initConfiguration.proxy,\n        silent_multiple_init: initConfiguration.silentMultipleInit,\n        track_session_across_subdomains: initConfiguration.trackSessionAcrossSubdomains,\n        track_anonymous_user: initConfiguration.trackAnonymousUser,\n        session_persistence: initConfiguration.sessionPersistence,\n        allow_fallback_to_local_storage: !!initConfiguration.allowFallbackToLocalStorage,\n        store_contexts_across_pages: !!initConfiguration.storeContextsAcrossPages,\n        allow_untrusted_events: !!initConfiguration.allowUntrustedEvents,\n        tracking_consent: initConfiguration.trackingConsent,\n    };\n}\n//# sourceMappingURL=configuration.js.map","import { display } from './display';\nimport { getType } from './utils/typeUtils';\nexport function isMatchOption(item) {\n    const itemType = getType(item);\n    return itemType === 'string' || itemType === 'function' || item instanceof RegExp;\n}\n/**\n * Returns true if value can be matched by at least one of the provided MatchOptions.\n * When comparing strings, setting useStartsWith to true will compare the value with the start of\n * the option, instead of requiring an exact match.\n */\nexport function matchList(list, value, useStartsWith = false) {\n    return list.some((item) => {\n        try {\n            if (typeof item === 'function') {\n                return item(value);\n            }\n            else if (item instanceof RegExp) {\n                return item.test(value);\n            }\n            else if (typeof item === 'string') {\n                return useStartsWith ? value.startsWith(item) : item === value;\n            }\n        }\n        catch (e) {\n            display.error(e);\n        }\n        return false;\n    });\n}\n//# sourceMappingURL=matchOption.js.map","export function getCrypto() {\n    // TODO: remove msCrypto when IE11 support is dropped\n    return window.crypto || window.msCrypto;\n}\n//# sourceMappingURL=crypto.js.map","import { ExperimentalFeature, isExperimentalFeatureEnabled } from '@datadog/browser-core';\nimport { getCrypto } from '../../browser/crypto';\nexport function createTraceIdentifier() {\n    return createIdentifier(64);\n}\nexport function createSpanIdentifier() {\n    return createIdentifier(63);\n}\nlet createIdentifierImplementationCache;\nexport function clearIdentifierImplementationCache() {\n    createIdentifierImplementationCache = undefined;\n}\nfunction createIdentifier(bits) {\n    if (!createIdentifierImplementationCache) {\n        createIdentifierImplementationCache =\n            isExperimentalFeatureEnabled(ExperimentalFeature.CONSISTENT_TRACE_SAMPLING) && areBigIntIdentifiersSupported()\n                ? createIdentifierUsingBigInt\n                : createIdentifierUsingUint32Array;\n    }\n    return createIdentifierImplementationCache(bits);\n}\nexport function areBigIntIdentifiersSupported() {\n    try {\n        crypto.getRandomValues(new BigUint64Array(1));\n        return true;\n    }\n    catch (_a) {\n        return false;\n    }\n}\nfunction createIdentifierUsingBigInt(bits) {\n    let id = crypto.getRandomValues(new BigUint64Array(1))[0];\n    if (bits === 63) {\n        // eslint-disable-next-line no-bitwise\n        id >>= BigInt('1');\n    }\n    return id;\n}\n// TODO: remove this when all browser we support have BigInt support\nfunction createIdentifierUsingUint32Array(bits) {\n    const buffer = getCrypto().getRandomValues(new Uint32Array(2));\n    if (bits === 63) {\n        // eslint-disable-next-line no-bitwise\n        buffer[buffer.length - 1] >>>= 1; // force 63-bit\n    }\n    return {\n        toString(radix = 10) {\n            let high = buffer[1];\n            let low = buffer[0];\n            let str = '';\n            do {\n                const mod = (high % radix) * 4294967296 + low;\n                high = Math.floor(high / radix);\n                low = Math.floor(mod / radix);\n                str = (mod % radix).toString(radix) + str;\n            } while (high || low);\n            return str;\n        },\n    };\n}\nexport function toPaddedHexadecimalString(id) {\n    const traceId = id.toString(16);\n    // TODO: replace with String.prototype.padStart when we drop IE11 support\n    return Array(17 - traceId.length).join('0') + traceId;\n}\n//# sourceMappingURL=identifier.js.map","import { objectEntries, shallowClone, getType, isMatchOption, matchList, TraceContextInjection, } from '@datadog/browser-core';\nimport { getCrypto } from '../../browser/crypto';\nimport { createSpanIdentifier, createTraceIdentifier, toPaddedHexadecimalString } from './identifier';\nimport { isTraceSampled } from './sampler';\nexport function isTracingOption(item) {\n    const expectedItem = item;\n    return (getType(expectedItem) === 'object' &&\n        isMatchOption(expectedItem.match) &&\n        Array.isArray(expectedItem.propagatorTypes));\n}\n/**\n * Clear tracing information to avoid incomplete traces. Ideally, we should do it when the\n * request did not reach the server, but the browser does not expose this. So, we clear tracing\n * information if the request ended with status 0 without being aborted by the application.\n *\n * Reasoning:\n *\n * * Applications are usually aborting requests after a bit of time, for example when the user is\n * typing (autocompletion) or navigating away (in a SPA). With a performant device and good\n * network conditions, the request is likely to reach the server before being canceled.\n *\n * * Requests aborted otherwise (ex: lack of internet, CORS issue, blocked by a privacy extension)\n * are likely to finish quickly and without reaching the server.\n *\n * Of course, it might not be the case every time, but it should limit having incomplete traces a\n * bit.\n * */\nexport function clearTracingIfNeeded(context) {\n    if (context.status === 0 && !context.isAborted) {\n        context.traceId = undefined;\n        context.spanId = undefined;\n        context.traceSampled = undefined;\n    }\n}\nexport function startTracer(configuration, sessionManager) {\n    return {\n        clearTracingIfNeeded,\n        traceFetch: (context) => injectHeadersIfTracingAllowed(configuration, context, sessionManager, (tracingHeaders) => {\n            var _a;\n            if (context.input instanceof Request && !((_a = context.init) === null || _a === void 0 ? void 0 : _a.headers)) {\n                context.input = new Request(context.input);\n                Object.keys(tracingHeaders).forEach((key) => {\n                    ;\n                    context.input.headers.append(key, tracingHeaders[key]);\n                });\n            }\n            else {\n                context.init = shallowClone(context.init);\n                const headers = [];\n                if (context.init.headers instanceof Headers) {\n                    context.init.headers.forEach((value, key) => {\n                        headers.push([key, value]);\n                    });\n                }\n                else if (Array.isArray(context.init.headers)) {\n                    context.init.headers.forEach((header) => {\n                        headers.push(header);\n                    });\n                }\n                else if (context.init.headers) {\n                    Object.keys(context.init.headers).forEach((key) => {\n                        headers.push([key, context.init.headers[key]]);\n                    });\n                }\n                context.init.headers = headers.concat(objectEntries(tracingHeaders));\n            }\n        }),\n        traceXhr: (context, xhr) => injectHeadersIfTracingAllowed(configuration, context, sessionManager, (tracingHeaders) => {\n            Object.keys(tracingHeaders).forEach((name) => {\n                xhr.setRequestHeader(name, tracingHeaders[name]);\n            });\n        }),\n    };\n}\nfunction injectHeadersIfTracingAllowed(configuration, context, sessionManager, inject) {\n    if (!isTracingSupported() || !sessionManager.findTrackedSession()) {\n        return;\n    }\n    const tracingOption = configuration.allowedTracingUrls.find((tracingOption) => matchList([tracingOption.match], context.url, true));\n    if (!tracingOption) {\n        return;\n    }\n    const traceId = createTraceIdentifier();\n    context.traceSampled = isTraceSampled(traceId, configuration.traceSampleRate);\n    const shouldInjectHeaders = context.traceSampled || configuration.traceContextInjection === TraceContextInjection.ALL;\n    if (!shouldInjectHeaders) {\n        return;\n    }\n    context.traceId = traceId;\n    context.spanId = createSpanIdentifier();\n    inject(makeTracingHeaders(context.traceId, context.spanId, context.traceSampled, tracingOption.propagatorTypes));\n}\nexport function isTracingSupported() {\n    return getCrypto() !== undefined;\n}\n/**\n * When trace is not sampled, set priority to '0' instead of not adding the tracing headers\n * to prepare the implementation for sampling delegation.\n */\nfunction makeTracingHeaders(traceId, spanId, traceSampled, propagatorTypes) {\n    const tracingHeaders = {};\n    propagatorTypes.forEach((propagatorType) => {\n        switch (propagatorType) {\n            case 'datadog': {\n                Object.assign(tracingHeaders, {\n                    'x-datadog-origin': 'rum',\n                    'x-datadog-parent-id': spanId.toString(),\n                    'x-datadog-sampling-priority': traceSampled ? '1' : '0',\n                    'x-datadog-trace-id': traceId.toString(),\n                });\n                break;\n            }\n            // https://www.w3.org/TR/trace-context/\n            case 'tracecontext': {\n                Object.assign(tracingHeaders, {\n                    traceparent: `00-0000000000000000${toPaddedHexadecimalString(traceId)}-${toPaddedHexadecimalString(spanId)}-0${traceSampled ? '1' : '0'}`,\n                    tracestate: `dd=s:${traceSampled ? '1' : '0'};o:rum`,\n                });\n                break;\n            }\n            // https://github.com/openzipkin/b3-propagation\n            case 'b3': {\n                Object.assign(tracingHeaders, {\n                    b3: `${toPaddedHexadecimalString(traceId)}-${toPaddedHexadecimalString(spanId)}-${traceSampled ? '1' : '0'}`,\n                });\n                break;\n            }\n            case 'b3multi': {\n                Object.assign(tracingHeaders, {\n                    'X-B3-TraceId': toPaddedHexadecimalString(traceId),\n                    'X-B3-SpanId': toPaddedHexadecimalString(spanId),\n                    'X-B3-Sampled': traceSampled ? '1' : '0',\n                });\n                break;\n            }\n        }\n    });\n    return tracingHeaders;\n}\n//# sourceMappingURL=tracer.js.map","import { performDraw } from '@datadog/browser-core';\nexport function isTraceSampled(identifier, sampleRate) {\n    // Shortcuts for common cases. This is not strictly necessary, but it makes the code faster for\n    // customers willing to ingest all traces.\n    if (sampleRate === 100) {\n        return true;\n    }\n    if (sampleRate === 0) {\n        return false;\n    }\n    // For simplicity, we don't use consistent sampling for browser that don't support BigInt\n    // TODO: remove this when all browser we support have BigInt support\n    if (typeof identifier !== 'bigint') {\n        return performDraw(sampleRate);\n    }\n    // Offer consistent sampling for the same trace id across different environments. The rule is:\n    //\n    //   (identifier * knuthFactor) % 2^64 < sampleRate * 2^64\n    //\n    // Because JavaScript numbers are 64-bit floats, we can't represent 64-bit integers, and the\n    // modulo would be incorrect. Thus, we are using BigInts here.\n    //\n    // Implementation in other languages:\n    // * Go     https://github.com/DataDog/dd-trace-go/blob/ec6fbb1f2d517b7b8e69961052adf7136f3af773/ddtrace/tracer/sampler.go#L86-L91\n    // * Python https://github.com/DataDog/dd-trace-py/blob/0cee2f066fb6e79aa15947c1514c0f406dea47c5/ddtrace/sampling_rule.py#L197\n    // * Ruby   https://github.com/DataDog/dd-trace-rb/blob/1a6e255cdcb7e7e22235ea5955f90f6dfa91045d/lib/datadog/tracing/sampling/rate_sampler.rb#L42\n    // * C++    https://github.com/DataDog/dd-trace-cpp/blob/159629edc438ae45f2bb318eb7bd51abd05e94b5/src/datadog/trace_sampler.cpp#L58\n    // * Java   https://github.com/DataDog/dd-trace-java/blob/896dd6b380533216e0bdee59614606c8272d313e/dd-trace-core/src/main/java/datadog/trace/common/sampling/DeterministicSampler.java#L48\n    //\n    // Note: All implementations have slight variations. Some of them use '<=' instead of '<', and\n    // use `sampleRate * 2^64 - 1` instead of `sampleRate * 2^64`. The following implementation\n    // should adhere to the spec and is a bit simpler than using a 2^64-1 limit as there are less\n    // BigInt arithmetic to write. In practice this does not matter, as we are using floating point\n    // numbers in the end, and Number(2n**64n-1n) === Number(2n**64n).\n    const knuthFactor = BigInt('1111111111111111111');\n    const twoPow64 = BigInt('0x10000000000000000'); // 2n ** 64n\n    const hash = (identifier * knuthFactor) % twoPow64;\n    return Number(hash) <= (sampleRate / 100) * Number(twoPow64);\n}\n//# sourceMappingURL=sampler.js.map","import { getType, isMatchOption, serializeConfiguration, DefaultPrivacyLevel, TraceContextInjection, display, objectHasValue, validateAndBuildConfiguration, isSampleRate, isNumber, } from '@datadog/browser-core';\nimport { isTracingOption } from '../tracing/tracer';\nexport const DEFAULT_PROPAGATOR_TYPES = ['tracecontext', 'datadog'];\nexport function validateAndBuildRumConfiguration(initConfiguration) {\n    var _a, _b, _c, _d, _e, _f;\n    if (initConfiguration.trackFeatureFlagsForEvents !== undefined &&\n        !Array.isArray(initConfiguration.trackFeatureFlagsForEvents)) {\n        display.warn('trackFeatureFlagsForEvents should be an array');\n    }\n    if (!initConfiguration.applicationId) {\n        display.error('Application ID is not configured, no RUM data will be collected.');\n        return;\n    }\n    if (!isSampleRate(initConfiguration.sessionReplaySampleRate, 'Session Replay') ||\n        !isSampleRate(initConfiguration.traceSampleRate, 'Trace')) {\n        return;\n    }\n    if (initConfiguration.excludedActivityUrls !== undefined && !Array.isArray(initConfiguration.excludedActivityUrls)) {\n        display.error('Excluded Activity Urls should be an array');\n        return;\n    }\n    const allowedTracingUrls = validateAndBuildTracingOptions(initConfiguration);\n    if (!allowedTracingUrls) {\n        return;\n    }\n    const baseConfiguration = validateAndBuildConfiguration(initConfiguration);\n    if (!baseConfiguration) {\n        return;\n    }\n    const sessionReplaySampleRate = (_a = initConfiguration.sessionReplaySampleRate) !== null && _a !== void 0 ? _a : 0;\n    return {\n        applicationId: initConfiguration.applicationId,\n        version: initConfiguration.version || undefined,\n        actionNameAttribute: initConfiguration.actionNameAttribute,\n        sessionReplaySampleRate,\n        startSessionReplayRecordingManually: initConfiguration.startSessionReplayRecordingManually !== undefined\n            ? !!initConfiguration.startSessionReplayRecordingManually\n            : sessionReplaySampleRate === 0,\n        traceSampleRate: (_b = initConfiguration.traceSampleRate) !== null && _b !== void 0 ? _b : 100,\n        rulePsr: isNumber(initConfiguration.traceSampleRate) ? initConfiguration.traceSampleRate / 100 : undefined,\n        allowedTracingUrls,\n        excludedActivityUrls: (_c = initConfiguration.excludedActivityUrls) !== null && _c !== void 0 ? _c : [],\n        workerUrl: initConfiguration.workerUrl,\n        compressIntakeRequests: !!initConfiguration.compressIntakeRequests,\n        trackUserInteractions: !!((_d = initConfiguration.trackUserInteractions) !== null && _d !== void 0 ? _d : true),\n        trackViewsManually: !!initConfiguration.trackViewsManually,\n        trackResources: !!((_e = initConfiguration.trackResources) !== null && _e !== void 0 ? _e : true),\n        trackLongTasks: !!((_f = initConfiguration.trackLongTasks) !== null && _f !== void 0 ? _f : true),\n        subdomain: initConfiguration.subdomain,\n        defaultPrivacyLevel: objectHasValue(DefaultPrivacyLevel, initConfiguration.defaultPrivacyLevel)\n            ? initConfiguration.defaultPrivacyLevel\n            : DefaultPrivacyLevel.MASK,\n        enablePrivacyForActionName: !!initConfiguration.enablePrivacyForActionName,\n        customerDataTelemetrySampleRate: 1,\n        traceContextInjection: objectHasValue(TraceContextInjection, initConfiguration.traceContextInjection)\n            ? initConfiguration.traceContextInjection\n            : TraceContextInjection.SAMPLED,\n        plugins: initConfiguration.plugins || [],\n        trackFeatureFlagsForEvents: initConfiguration.trackFeatureFlagsForEvents || [],\n        ...baseConfiguration,\n    };\n}\n/**\n * Validates allowedTracingUrls and converts match options to tracing options\n */\nfunction validateAndBuildTracingOptions(initConfiguration) {\n    if (initConfiguration.allowedTracingUrls === undefined) {\n        return [];\n    }\n    if (!Array.isArray(initConfiguration.allowedTracingUrls)) {\n        display.error('Allowed Tracing URLs should be an array');\n        return;\n    }\n    if (initConfiguration.allowedTracingUrls.length !== 0 && initConfiguration.service === undefined) {\n        display.error('Service needs to be configured when tracing is enabled');\n        return;\n    }\n    // Convert from (MatchOption | TracingOption) to TracingOption, remove unknown properties\n    const tracingOptions = [];\n    initConfiguration.allowedTracingUrls.forEach((option) => {\n        if (isMatchOption(option)) {\n            tracingOptions.push({ match: option, propagatorTypes: DEFAULT_PROPAGATOR_TYPES });\n        }\n        else if (isTracingOption(option)) {\n            tracingOptions.push(option);\n        }\n        else {\n            display.warn('Allowed Tracing Urls parameters should be a string, RegExp, function, or an object. Ignoring parameter', option);\n        }\n    });\n    return tracingOptions;\n}\n/**\n * Combines the selected tracing propagators from the different options in allowedTracingUrls\n */\nfunction getSelectedTracingPropagators(configuration) {\n    const usedTracingPropagators = new Set();\n    if (Array.isArray(configuration.allowedTracingUrls) && configuration.allowedTracingUrls.length > 0) {\n        configuration.allowedTracingUrls.forEach((option) => {\n            if (isMatchOption(option)) {\n                DEFAULT_PROPAGATOR_TYPES.forEach((propagatorType) => usedTracingPropagators.add(propagatorType));\n            }\n            else if (getType(option) === 'object' && Array.isArray(option.propagatorTypes)) {\n                // Ensure we have an array, as we cannot rely on types yet (configuration is provided by users)\n                option.propagatorTypes.forEach((propagatorType) => usedTracingPropagators.add(propagatorType));\n            }\n        });\n    }\n    return Array.from(usedTracingPropagators);\n}\nexport function serializeRumConfiguration(configuration) {\n    var _a;\n    const baseSerializedConfiguration = serializeConfiguration(configuration);\n    return {\n        session_replay_sample_rate: configuration.sessionReplaySampleRate,\n        start_session_replay_recording_manually: configuration.startSessionReplayRecordingManually,\n        trace_sample_rate: configuration.traceSampleRate,\n        trace_context_injection: configuration.traceContextInjection,\n        action_name_attribute: configuration.actionNameAttribute,\n        use_allowed_tracing_urls: Array.isArray(configuration.allowedTracingUrls) && configuration.allowedTracingUrls.length > 0,\n        selected_tracing_propagators: getSelectedTracingPropagators(configuration),\n        default_privacy_level: configuration.defaultPrivacyLevel,\n        enable_privacy_for_action_name: configuration.enablePrivacyForActionName,\n        use_excluded_activity_urls: Array.isArray(configuration.excludedActivityUrls) && configuration.excludedActivityUrls.length > 0,\n        use_worker_url: !!configuration.workerUrl,\n        compress_intake_requests: configuration.compressIntakeRequests,\n        track_views_manually: configuration.trackViewsManually,\n        track_user_interactions: configuration.trackUserInteractions,\n        track_resources: configuration.trackResources,\n        track_long_task: configuration.trackLongTasks,\n        plugins: (_a = configuration.plugins) === null || _a === void 0 ? void 0 : _a.map((plugin) => {\n            var _a;\n            return ({\n                name: plugin.name,\n                ...(_a = plugin.getConfigurationTelemetry) === null || _a === void 0 ? void 0 : _a.call(plugin),\n            });\n        }),\n        track_feature_flags_for_events: configuration.trackFeatureFlagsForEvents,\n        ...baseSerializedConfiguration,\n    };\n}\n//# sourceMappingURL=configuration.js.map","import { display, addEventListener } from '@datadog/browser-core';\nexport const REMOTE_CONFIGURATION_URL = 'https://d3uc069fcn7uxw.cloudfront.net/configuration';\nexport function fetchAndApplyRemoteConfiguration(initConfiguration, callback) {\n    fetchRemoteConfiguration(initConfiguration, (remoteInitConfiguration) => {\n        callback(applyRemoteConfiguration(initConfiguration, remoteInitConfiguration));\n    });\n}\nexport function applyRemoteConfiguration(initConfiguration, remoteInitConfiguration) {\n    return { ...initConfiguration, ...remoteInitConfiguration };\n}\nexport function fetchRemoteConfiguration(configuration, callback) {\n    const xhr = new XMLHttpRequest();\n    addEventListener(configuration, xhr, 'load', function () {\n        if (xhr.status === 200) {\n            callback(JSON.parse(xhr.responseText));\n        }\n        else {\n            displayRemoteConfigurationFetchingError();\n        }\n    });\n    addEventListener(configuration, xhr, 'error', function () {\n        displayRemoteConfigurationFetchingError();\n    });\n    xhr.open('GET', `${REMOTE_CONFIGURATION_URL}/${encodeURIComponent(configuration.remoteConfigurationId)}.json`);\n    xhr.send();\n}\nfunction displayRemoteConfigurationFetchingError() {\n    display.error('Error fetching the remote configuration.');\n}\n//# sourceMappingURL=remoteConfiguration.js.map","import { createBoundedBuffer, display, canUseEventBridge, displayAlreadyInitializedError, willSyntheticsInjectRum, noop, timeStampNow, clocksNow, getEventBridge, ExperimentalFeature, isExperimentalFeatureEnabled, initFeatureFlags, addTelemetryConfiguration, initFetchObservable, } from '@datadog/browser-core';\nimport { validateAndBuildRumConfiguration, } from '../domain/configuration';\nimport { startDurationVital, stopDurationVital } from '../domain/vital/vitalCollection';\nimport { fetchAndApplyRemoteConfiguration, serializeRumConfiguration } from '../domain/configuration';\nimport { callPluginsMethod } from '../domain/plugins';\nexport function createPreStartStrategy({ ignoreInitIfSyntheticsWillInjectRum, startDeflateWorker }, getCommonContext, trackingConsentState, customVitalsState, doStartRum) {\n    const bufferApiCalls = createBoundedBuffer();\n    let firstStartViewCall;\n    let deflateWorker;\n    let cachedInitConfiguration;\n    let cachedConfiguration;\n    const trackingConsentStateSubscription = trackingConsentState.observable.subscribe(tryStartRum);\n    const emptyContext = {};\n    function tryStartRum() {\n        if (!cachedInitConfiguration || !cachedConfiguration || !trackingConsentState.isGranted()) {\n            return;\n        }\n        trackingConsentStateSubscription.unsubscribe();\n        let initialViewOptions;\n        if (cachedConfiguration.trackViewsManually) {\n            if (!firstStartViewCall) {\n                return;\n            }\n            // An initial view is always created when starting RUM.\n            // When tracking views automatically, any startView call before RUM start creates an extra\n            // view.\n            // When tracking views manually, we use the ViewOptions from the first startView call as the\n            // initial view options, and we remove the actual startView call so we don't create an extra\n            // view.\n            bufferApiCalls.remove(firstStartViewCall.callback);\n            initialViewOptions = firstStartViewCall.options;\n        }\n        const startRumResult = doStartRum(cachedConfiguration, deflateWorker, initialViewOptions);\n        bufferApiCalls.drain(startRumResult);\n    }\n    function doInit(initConfiguration) {\n        const eventBridgeAvailable = canUseEventBridge();\n        if (eventBridgeAvailable) {\n            initConfiguration = overrideInitConfigurationForBridge(initConfiguration);\n        }\n        // Update the exposed initConfiguration to reflect the bridge and remote configuration overrides\n        cachedInitConfiguration = initConfiguration;\n        addTelemetryConfiguration(serializeRumConfiguration(initConfiguration));\n        if (cachedConfiguration) {\n            displayAlreadyInitializedError('DD_RUM', initConfiguration);\n            return;\n        }\n        const configuration = validateAndBuildRumConfiguration(initConfiguration);\n        if (!configuration) {\n            return;\n        }\n        if (!eventBridgeAvailable && !configuration.sessionStoreStrategyType) {\n            display.warn('No storage available for session. We will not send any data.');\n            return;\n        }\n        if (configuration.compressIntakeRequests && !eventBridgeAvailable && startDeflateWorker) {\n            deflateWorker = startDeflateWorker(configuration, 'Datadog RUM', \n            // Worker initialization can fail asynchronously, especially in Firefox where even CSP\n            // issues are reported asynchronously. For now, the SDK will continue its execution even if\n            // data won't be sent to Datadog. We could improve this behavior in the future.\n            noop);\n            if (!deflateWorker) {\n                // `startDeflateWorker` should have logged an error message explaining the issue\n                return;\n            }\n        }\n        cachedConfiguration = configuration;\n        // Instrumuent fetch to track network requests\n        // This is needed in case the consent is not granted and some cutsomer\n        // library (Apollo Client) is storing uninstrumented fetch to be used later\n        // The subscrption is needed so that the instrumentation process is completed\n        initFetchObservable().subscribe(noop);\n        trackingConsentState.tryToInit(configuration.trackingConsent);\n        tryStartRum();\n    }\n    const addDurationVital = (vital) => {\n        bufferApiCalls.add((startRumResult) => startRumResult.addDurationVital(vital));\n    };\n    const strategy = {\n        init(initConfiguration, publicApi) {\n            if (!initConfiguration) {\n                display.error('Missing configuration');\n                return;\n            }\n            // Set the experimental feature flags as early as possible, so we can use them in most places\n            initFeatureFlags(initConfiguration.enableExperimentalFeatures);\n            // Expose the initial configuration regardless of initialization success.\n            cachedInitConfiguration = initConfiguration;\n            // If we are in a Synthetics test configured to automatically inject a RUM instance, we want\n            // to completely discard the customer application RUM instance by ignoring their init() call.\n            // But, we should not ignore the init() call from the Synthetics-injected RUM instance, so the\n            // internal `ignoreInitIfSyntheticsWillInjectRum` option is here to bypass this condition.\n            if (ignoreInitIfSyntheticsWillInjectRum && willSyntheticsInjectRum()) {\n                return;\n            }\n            callPluginsMethod(initConfiguration.plugins, 'onInit', { initConfiguration, publicApi });\n            if (initConfiguration.remoteConfigurationId &&\n                isExperimentalFeatureEnabled(ExperimentalFeature.REMOTE_CONFIGURATION)) {\n                fetchAndApplyRemoteConfiguration(initConfiguration, doInit);\n            }\n            else {\n                doInit(initConfiguration);\n            }\n        },\n        get initConfiguration() {\n            return cachedInitConfiguration;\n        },\n        getInternalContext: noop,\n        stopSession: noop,\n        addTiming(name, time = timeStampNow()) {\n            bufferApiCalls.add((startRumResult) => startRumResult.addTiming(name, time));\n        },\n        startView(options, startClocks = clocksNow()) {\n            const callback = (startRumResult) => {\n                startRumResult.startView(options, startClocks);\n            };\n            bufferApiCalls.add(callback);\n            if (!firstStartViewCall) {\n                firstStartViewCall = { options, callback };\n                tryStartRum();\n            }\n        },\n        setViewName(name) {\n            bufferApiCalls.add((startRumResult) => startRumResult.setViewName(name));\n        },\n        setViewContext(context) {\n            bufferApiCalls.add((startRumResult) => startRumResult.setViewContext(context));\n        },\n        setViewContextProperty(key, value) {\n            bufferApiCalls.add((startRumResult) => startRumResult.setViewContextProperty(key, value));\n        },\n        getViewContext: () => emptyContext,\n        addAction(action, commonContext = getCommonContext()) {\n            bufferApiCalls.add((startRumResult) => startRumResult.addAction(action, commonContext));\n        },\n        addError(providedError, commonContext = getCommonContext()) {\n            bufferApiCalls.add((startRumResult) => startRumResult.addError(providedError, commonContext));\n        },\n        addFeatureFlagEvaluation(key, value) {\n            bufferApiCalls.add((startRumResult) => startRumResult.addFeatureFlagEvaluation(key, value));\n        },\n        startDurationVital(name, options) {\n            return startDurationVital(customVitalsState, name, options);\n        },\n        stopDurationVital(name, options) {\n            stopDurationVital(addDurationVital, customVitalsState, name, options);\n        },\n        addDurationVital,\n    };\n    return strategy;\n}\nfunction overrideInitConfigurationForBridge(initConfiguration) {\n    var _a, _b;\n    return {\n        ...initConfiguration,\n        applicationId: '00000000-aaaa-0000-aaaa-000000000000',\n        clientToken: 'empty',\n        sessionSampleRate: 100,\n        defaultPrivacyLevel: (_a = initConfiguration.defaultPrivacyLevel) !== null && _a !== void 0 ? _a : (_b = getEventBridge()) === null || _b === void 0 ? void 0 : _b.getPrivacyLevel(),\n    };\n}\n//# sourceMappingURL=preStartRum.js.map","import { addTelemetryUsage, createContextManager, deepClone, makePublicApi, monitor, clocksNow, callMonitored, createHandlingStack, checkUser, sanitizeUser, sanitize, createIdentityEncoder, createCustomerDataTrackerManager, storeContextManager, displayAlreadyInitializedError, createTrackingConsentState, timeStampToClocks, } from '@datadog/browser-core';\nimport { buildCommonContext } from '../domain/contexts/commonContext';\nimport { createCustomVitalsState } from '../domain/vital/vitalCollection';\nimport { callPluginsMethod } from '../domain/plugins';\nimport { createPreStartStrategy } from './preStartRum';\nconst RUM_STORAGE_KEY = 'rum';\nexport function makeRumPublicApi(startRumImpl, recorderApi, options = {}) {\n    const customerDataTrackerManager = createCustomerDataTrackerManager(0 /* CustomerDataCompressionStatus.Unknown */);\n    const globalContextManager = createContextManager(customerDataTrackerManager.getOrCreateTracker(2 /* CustomerDataType.GlobalContext */));\n    const userContextManager = createContextManager(customerDataTrackerManager.getOrCreateTracker(1 /* CustomerDataType.User */));\n    const trackingConsentState = createTrackingConsentState();\n    const customVitalsState = createCustomVitalsState();\n    function getCommonContext() {\n        return buildCommonContext(globalContextManager, userContextManager, recorderApi);\n    }\n    let strategy = createPreStartStrategy(options, getCommonContext, trackingConsentState, customVitalsState, (configuration, deflateWorker, initialViewOptions) => {\n        if (configuration.storeContextsAcrossPages) {\n            storeContextManager(configuration, globalContextManager, RUM_STORAGE_KEY, 2 /* CustomerDataType.GlobalContext */);\n            storeContextManager(configuration, userContextManager, RUM_STORAGE_KEY, 1 /* CustomerDataType.User */);\n        }\n        customerDataTrackerManager.setCompressionStatus(deflateWorker ? 1 /* CustomerDataCompressionStatus.Enabled */ : 2 /* CustomerDataCompressionStatus.Disabled */);\n        const startRumResult = startRumImpl(configuration, recorderApi, customerDataTrackerManager, getCommonContext, initialViewOptions, deflateWorker && options.createDeflateEncoder\n            ? (streamId) => options.createDeflateEncoder(configuration, deflateWorker, streamId)\n            : createIdentityEncoder, trackingConsentState, customVitalsState);\n        recorderApi.onRumStart(startRumResult.lifeCycle, configuration, startRumResult.session, startRumResult.viewHistory, deflateWorker);\n        strategy = createPostStartStrategy(strategy, startRumResult);\n        callPluginsMethod(configuration.plugins, 'onRumStart', { strategy });\n        return startRumResult;\n    });\n    const startView = monitor((options) => {\n        const sanitizedOptions = typeof options === 'object' ? options : { name: options };\n        if (sanitizedOptions.context) {\n            customerDataTrackerManager.getOrCreateTracker(3 /* CustomerDataType.View */).updateCustomerData(sanitizedOptions.context);\n        }\n        strategy.startView(sanitizedOptions);\n        addTelemetryUsage({ feature: 'start-view' });\n    });\n    const rumPublicApi = makePublicApi({\n        init: monitor((initConfiguration) => {\n            strategy.init(initConfiguration, rumPublicApi);\n        }),\n        setTrackingConsent: monitor((trackingConsent) => {\n            trackingConsentState.update(trackingConsent);\n            addTelemetryUsage({ feature: 'set-tracking-consent', tracking_consent: trackingConsent });\n        }),\n        setViewName: monitor((name) => {\n            strategy.setViewName(name);\n        }),\n        setViewContext: monitor((context) => {\n            strategy.setViewContext(context);\n        }),\n        setViewContextProperty: monitor((key, value) => {\n            strategy.setViewContextProperty(key, value);\n        }),\n        getViewContext: monitor(() => strategy.getViewContext()),\n        setGlobalContext: monitor((context) => {\n            globalContextManager.setContext(context);\n            addTelemetryUsage({ feature: 'set-global-context' });\n        }),\n        getGlobalContext: monitor(() => globalContextManager.getContext()),\n        setGlobalContextProperty: monitor((key, value) => {\n            globalContextManager.setContextProperty(key, value);\n            addTelemetryUsage({ feature: 'set-global-context' });\n        }),\n        removeGlobalContextProperty: monitor((key) => globalContextManager.removeContextProperty(key)),\n        clearGlobalContext: monitor(() => globalContextManager.clearContext()),\n        getInternalContext: monitor((startTime) => strategy.getInternalContext(startTime)),\n        getInitConfiguration: monitor(() => deepClone(strategy.initConfiguration)),\n        addAction: (name, context) => {\n            const handlingStack = createHandlingStack();\n            callMonitored(() => {\n                strategy.addAction({\n                    name: sanitize(name),\n                    context: sanitize(context),\n                    startClocks: clocksNow(),\n                    type: \"custom\" /* ActionType.CUSTOM */,\n                    handlingStack,\n                });\n                addTelemetryUsage({ feature: 'add-action' });\n            });\n        },\n        addError: (error, context) => {\n            const handlingStack = createHandlingStack();\n            callMonitored(() => {\n                strategy.addError({\n                    error, // Do not sanitize error here, it is needed unserialized by computeRawError()\n                    handlingStack,\n                    context: sanitize(context),\n                    startClocks: clocksNow(),\n                });\n                addTelemetryUsage({ feature: 'add-error' });\n            });\n        },\n        addTiming: monitor((name, time) => {\n            // TODO: next major decide to drop relative time support or update its behaviour\n            strategy.addTiming(sanitize(name), time);\n        }),\n        setUser: monitor((newUser) => {\n            if (checkUser(newUser)) {\n                userContextManager.setContext(sanitizeUser(newUser));\n            }\n            addTelemetryUsage({ feature: 'set-user' });\n        }),\n        getUser: monitor(() => userContextManager.getContext()),\n        setUserProperty: monitor((key, property) => {\n            const sanitizedProperty = sanitizeUser({ [key]: property })[key];\n            userContextManager.setContextProperty(key, sanitizedProperty);\n            addTelemetryUsage({ feature: 'set-user' });\n        }),\n        removeUserProperty: monitor((key) => userContextManager.removeContextProperty(key)),\n        clearUser: monitor(() => userContextManager.clearContext()),\n        startView,\n        stopSession: monitor(() => {\n            strategy.stopSession();\n            addTelemetryUsage({ feature: 'stop-session' });\n        }),\n        addFeatureFlagEvaluation: monitor((key, value) => {\n            strategy.addFeatureFlagEvaluation(sanitize(key), sanitize(value));\n            addTelemetryUsage({ feature: 'add-feature-flag-evaluation' });\n        }),\n        getSessionReplayLink: monitor(() => recorderApi.getSessionReplayLink()),\n        startSessionReplayRecording: monitor((options) => {\n            recorderApi.start(options);\n            addTelemetryUsage({ feature: 'start-session-replay-recording', force: options && options.force });\n        }),\n        stopSessionReplayRecording: monitor(() => recorderApi.stop()),\n        addDurationVital: monitor((name, options) => {\n            addTelemetryUsage({ feature: 'add-duration-vital' });\n            strategy.addDurationVital({\n                name: sanitize(name),\n                type: \"duration\" /* VitalType.DURATION */,\n                startClocks: timeStampToClocks(options.startTime),\n                duration: options.duration,\n                context: sanitize(options && options.context),\n                description: sanitize(options && options.description),\n            });\n        }),\n        startDurationVital: monitor((name, options) => {\n            addTelemetryUsage({ feature: 'start-duration-vital' });\n            return strategy.startDurationVital(sanitize(name), {\n                context: sanitize(options && options.context),\n                description: sanitize(options && options.description),\n            });\n        }),\n        stopDurationVital: monitor((nameOrRef, options) => {\n            addTelemetryUsage({ feature: 'stop-duration-vital' });\n            strategy.stopDurationVital(typeof nameOrRef === 'string' ? sanitize(nameOrRef) : nameOrRef, {\n                context: sanitize(options && options.context),\n                description: sanitize(options && options.description),\n            });\n        }),\n    });\n    return rumPublicApi;\n}\nfunction createPostStartStrategy(preStartStrategy, startRumResult) {\n    return {\n        init: (initConfiguration) => {\n            displayAlreadyInitializedError('DD_RUM', initConfiguration);\n        },\n        initConfiguration: preStartStrategy.initConfiguration,\n        ...startRumResult,\n    };\n}\n//# sourceMappingURL=rumPublicApi.js.map","export function buildCommonContext(globalContextManager, userContextManager, recorderApi) {\n    return {\n        context: globalContextManager.getContext(),\n        user: userContextManager.getContext(),\n        hasReplay: recorderApi.isRecording() ? true : undefined,\n    };\n}\n//# sourceMappingURL=commonContext.js.map","import { monitor, noop, Observable, getZoneJsOriginalValue } from '@datadog/browser-core';\nexport function createDOMMutationObservable() {\n    const MutationObserver = getMutationObserverConstructor();\n    return new Observable((observable) => {\n        if (!MutationObserver) {\n            return;\n        }\n        const observer = new MutationObserver(monitor(() => observable.notify()));\n        observer.observe(document, {\n            attributes: true,\n            characterData: true,\n            childList: true,\n            subtree: true,\n        });\n        return () => observer.disconnect();\n    });\n}\nexport function getMutationObserverConstructor() {\n    let constructor;\n    const browserWindow = window;\n    // Angular uses Zone.js to provide a context persisting across async tasks.  Zone.js replaces the\n    // global MutationObserver constructor with a patched version to support the context propagation.\n    // There is an ongoing issue[1][2] with this setup when using a MutationObserver within a Angular\n    // component: on some occasions, the callback is being called in an infinite loop, causing the\n    // page to freeze (even if the callback is completely empty).\n    //\n    // To work around this issue, we try to get the original MutationObserver constructor stored by\n    // Zone.js.\n    //\n    // [1] https://github.com/angular/angular/issues/26948\n    // [2] https://github.com/angular/angular/issues/31712\n    if (browserWindow.Zone) {\n        // Zone.js 0.8.6+ is storing original class constructors into the browser 'window' object[3].\n        //\n        // [3] https://github.com/angular/angular/blob/6375fa79875c0fe7b815efc45940a6e6f5c9c9eb/packages/zone.js/lib/common/utils.ts#L288\n        constructor = getZoneJsOriginalValue(browserWindow, 'MutationObserver');\n        if (browserWindow.MutationObserver && constructor === browserWindow.MutationObserver) {\n            // Anterior Zone.js versions (used in Angular 2) does not expose the original MutationObserver\n            // in the 'window' object. Luckily, the patched MutationObserver class is storing an original\n            // instance in its properties[4]. Let's get the original MutationObserver constructor from\n            // there.\n            //\n            // [4] https://github.com/angular/zone.js/blob/v0.8.5/lib/common/utils.ts#L412\n            const patchedInstance = new browserWindow.MutationObserver(noop);\n            const originalInstance = getZoneJsOriginalValue(patchedInstance, 'originalInstance');\n            constructor = originalInstance && originalInstance.constructor;\n        }\n    }\n    if (!constructor) {\n        constructor = browserWindow.MutationObserver;\n    }\n    return constructor;\n}\n//# sourceMappingURL=domMutationObservable.js.map","import { setTimeout } from '../../tools/timer';\nimport { clocksNow, ONE_MINUTE } from '../../tools/utils/timeUtils';\nimport { ErrorSource } from '../error/error.types';\nexport function createEventRateLimiter(eventType, limit, onLimitReached) {\n    let eventCount = 0;\n    let allowNextEvent = false;\n    return {\n        isLimitReached() {\n            if (eventCount === 0) {\n                setTimeout(() => {\n                    eventCount = 0;\n                }, ONE_MINUTE);\n            }\n            eventCount += 1;\n            if (eventCount <= limit || allowNextEvent) {\n                allowNextEvent = false;\n                return false;\n            }\n            if (eventCount === limit + 1) {\n                allowNextEvent = true;\n                try {\n                    onLimitReached({\n                        message: `Reached max number of ${eventType}s by minute: ${limit}`,\n                        source: ErrorSource.AGENT,\n                        startClocks: clocksNow(),\n                    });\n                }\n                finally {\n                    allowNextEvent = false;\n                }\n            }\n            return true;\n        },\n    };\n}\n//# sourceMappingURL=createEventRateLimiter.js.map","import { getSyntheticsResultId, getSyntheticsTestId, willSyntheticsInjectRum } from '@datadog/browser-core';\nexport function getSyntheticsContext() {\n    const testId = getSyntheticsTestId();\n    const resultId = getSyntheticsResultId();\n    if (testId && resultId) {\n        return {\n            test_id: testId,\n            result_id: resultId,\n            injected: willSyntheticsInjectRum(),\n        };\n    }\n}\n//# sourceMappingURL=syntheticsContext.js.map","import { sanitize, deepClone, getType, objectEntries } from '@datadog/browser-core';\n/**\n * Current limitation:\n * - field path do not support array, 'a.b.c' only\n */\nexport function limitModification(object, modifiableFieldPaths, modifier) {\n    const clone = deepClone(object);\n    const result = modifier(clone);\n    objectEntries(modifiableFieldPaths).forEach(([fieldPath, fieldType]) => {\n        const newValue = get(clone, fieldPath);\n        const newType = getType(newValue);\n        if (newType === fieldType) {\n            set(object, fieldPath, sanitize(newValue));\n        }\n        else if (fieldType === 'object' && (newType === 'undefined' || newType === 'null')) {\n            set(object, fieldPath, {});\n        }\n    });\n    return result;\n}\nfunction get(object, path) {\n    let current = object;\n    for (const field of path.split('.')) {\n        if (!isValidObjectContaining(current, field)) {\n            return;\n        }\n        current = current[field];\n    }\n    return current;\n}\nfunction set(object, path, value) {\n    let current = object;\n    const fields = path.split('.');\n    for (let i = 0; i < fields.length; i += 1) {\n        const field = fields[i];\n        if (!isValidObject(current)) {\n            return;\n        }\n        if (i !== fields.length - 1) {\n            current = current[field];\n        }\n        else {\n            current[field] = value;\n        }\n    }\n}\nfunction isValidObject(object) {\n    return getType(object) === 'object';\n}\nfunction isValidObjectContaining(object, field) {\n    return isValidObject(object) && Object.prototype.hasOwnProperty.call(object, field);\n}\n//# sourceMappingURL=limitModification.js.map","import { combine, isEmptyObject, timeStampNow, currentDrift, display, createEventRateLimiter, canUseEventBridge, round, isExperimentalFeatureEnabled, ExperimentalFeature, getConnectivity, } from '@datadog/browser-core';\nimport { getSyntheticsContext } from './contexts/syntheticsContext';\nimport { limitModification } from './limitModification';\nconst VIEW_MODIFIABLE_FIELD_PATHS = {\n    'view.name': 'string',\n    'view.url': 'string',\n    'view.referrer': 'string',\n};\nconst USER_CUSTOMIZABLE_FIELD_PATHS = {\n    context: 'object',\n};\nconst ROOT_MODIFIABLE_FIELD_PATHS = {\n    service: 'string',\n    version: 'string',\n};\nlet modifiableFieldPathsByEvent;\nexport function startRumAssembly(configuration, lifeCycle, sessionManager, viewHistory, urlContexts, actionContexts, displayContext, ciVisibilityContext, featureFlagContexts, getCommonContext, reportError) {\n    modifiableFieldPathsByEvent = {\n        [\"view\" /* RumEventType.VIEW */]: { ...USER_CUSTOMIZABLE_FIELD_PATHS, ...VIEW_MODIFIABLE_FIELD_PATHS },\n        [\"error\" /* RumEventType.ERROR */]: {\n            'error.message': 'string',\n            'error.stack': 'string',\n            'error.resource.url': 'string',\n            'error.fingerprint': 'string',\n            ...USER_CUSTOMIZABLE_FIELD_PATHS,\n            ...VIEW_MODIFIABLE_FIELD_PATHS,\n            ...ROOT_MODIFIABLE_FIELD_PATHS,\n        },\n        [\"resource\" /* RumEventType.RESOURCE */]: {\n            'resource.url': 'string',\n            ...(isExperimentalFeatureEnabled(ExperimentalFeature.WRITABLE_RESOURCE_GRAPHQL)\n                ? { 'resource.graphql': 'object' }\n                : {}),\n            ...USER_CUSTOMIZABLE_FIELD_PATHS,\n            ...VIEW_MODIFIABLE_FIELD_PATHS,\n            ...ROOT_MODIFIABLE_FIELD_PATHS,\n        },\n        [\"action\" /* RumEventType.ACTION */]: {\n            'action.target.name': 'string',\n            ...USER_CUSTOMIZABLE_FIELD_PATHS,\n            ...VIEW_MODIFIABLE_FIELD_PATHS,\n            ...ROOT_MODIFIABLE_FIELD_PATHS,\n        },\n        [\"long_task\" /* RumEventType.LONG_TASK */]: {\n            ...USER_CUSTOMIZABLE_FIELD_PATHS,\n            ...VIEW_MODIFIABLE_FIELD_PATHS,\n        },\n        [\"vital\" /* RumEventType.VITAL */]: {\n            ...USER_CUSTOMIZABLE_FIELD_PATHS,\n            ...VIEW_MODIFIABLE_FIELD_PATHS,\n        },\n    };\n    const eventRateLimiters = {\n        [\"error\" /* RumEventType.ERROR */]: createEventRateLimiter(\"error\" /* RumEventType.ERROR */, configuration.eventRateLimiterThreshold, reportError),\n        [\"action\" /* RumEventType.ACTION */]: createEventRateLimiter(\"action\" /* RumEventType.ACTION */, configuration.eventRateLimiterThreshold, reportError),\n        [\"vital\" /* RumEventType.VITAL */]: createEventRateLimiter(\"vital\" /* RumEventType.VITAL */, configuration.eventRateLimiterThreshold, reportError),\n    };\n    const syntheticsContext = getSyntheticsContext();\n    lifeCycle.subscribe(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, ({ startTime, rawRumEvent, domainContext, savedCommonContext, customerContext }) => {\n        const viewHistoryEntry = viewHistory.findView(startTime);\n        const urlContext = urlContexts.findUrl(startTime);\n        const session = sessionManager.findTrackedSession(startTime);\n        if (session && viewHistoryEntry && urlContext) {\n            const commonContext = savedCommonContext || getCommonContext();\n            const actionId = actionContexts.findActionId(startTime);\n            const rumContext = {\n                _dd: {\n                    format_version: 2,\n                    drift: currentDrift(),\n                    configuration: {\n                        session_sample_rate: round(configuration.sessionSampleRate, 3),\n                        session_replay_sample_rate: round(configuration.sessionReplaySampleRate, 3),\n                    },\n                    browser_sdk_version: canUseEventBridge() ? \"6.1.0\" : undefined,\n                },\n                application: {\n                    id: configuration.applicationId,\n                },\n                date: timeStampNow(),\n                service: viewHistoryEntry.service || configuration.service,\n                version: viewHistoryEntry.version || configuration.version,\n                source: 'browser',\n                session: {\n                    id: session.id,\n                    type: syntheticsContext\n                        ? \"synthetics\" /* SessionType.SYNTHETICS */\n                        : ciVisibilityContext.get()\n                            ? \"ci_test\" /* SessionType.CI_TEST */\n                            : \"user\" /* SessionType.USER */,\n                },\n                view: {\n                    id: viewHistoryEntry.id,\n                    name: viewHistoryEntry.name,\n                    url: urlContext.url,\n                    referrer: urlContext.referrer,\n                },\n                feature_flags: findFeatureFlagsContext(rawRumEvent, startTime, configuration.trackFeatureFlagsForEvents, featureFlagContexts),\n                action: needToAssembleWithAction(rawRumEvent) && actionId ? { id: actionId } : undefined,\n                synthetics: syntheticsContext,\n                ci_test: ciVisibilityContext.get(),\n                display: displayContext.get(),\n                connectivity: getConnectivity(),\n            };\n            const serverRumEvent = combine(rumContext, rawRumEvent);\n            serverRumEvent.context = combine(commonContext.context, viewHistoryEntry.context, customerContext);\n            if (!('has_replay' in serverRumEvent.session)) {\n                ;\n                serverRumEvent.session.has_replay = commonContext.hasReplay;\n            }\n            if (serverRumEvent.type === 'view') {\n                ;\n                serverRumEvent.session.sampled_for_replay =\n                    session.sessionReplay === 1 /* SessionReplayState.SAMPLED */;\n            }\n            if (session.anonymousId && !commonContext.user.anonymous_id && !!configuration.trackAnonymousUser) {\n                commonContext.user.anonymous_id = session.anonymousId;\n            }\n            if (!isEmptyObject(commonContext.user)) {\n                ;\n                serverRumEvent.usr = commonContext.user;\n            }\n            if (shouldSend(serverRumEvent, configuration.beforeSend, domainContext, eventRateLimiters)) {\n                if (isEmptyObject(serverRumEvent.context)) {\n                    delete serverRumEvent.context;\n                }\n                lifeCycle.notify(12 /* LifeCycleEventType.RUM_EVENT_COLLECTED */, serverRumEvent);\n            }\n        }\n    });\n}\nfunction shouldSend(event, beforeSend, domainContext, eventRateLimiters) {\n    var _a;\n    if (beforeSend) {\n        const result = limitModification(event, modifiableFieldPathsByEvent[event.type], (event) => beforeSend(event, domainContext));\n        if (result === false && event.type !== \"view\" /* RumEventType.VIEW */) {\n            return false;\n        }\n        if (result === false) {\n            display.warn(\"Can't dismiss view events using beforeSend!\");\n        }\n    }\n    const rateLimitReached = (_a = eventRateLimiters[event.type]) === null || _a === void 0 ? void 0 : _a.isLimitReached();\n    return !rateLimitReached;\n}\nfunction needToAssembleWithAction(event) {\n    return [\"error\" /* RumEventType.ERROR */, \"resource\" /* RumEventType.RESOURCE */, \"long_task\" /* RumEventType.LONG_TASK */].indexOf(event.type) !== -1;\n}\nfunction findFeatureFlagsContext(rawRumEvent, eventStartTime, trackFeatureFlagsForEvents, featureFlagContexts) {\n    const isTrackingEnforced = rawRumEvent.type === \"view\" /* RumEventType.VIEW */ || rawRumEvent.type === \"error\" /* RumEventType.ERROR */;\n    const isListedInConfig = trackFeatureFlagsForEvents.includes(rawRumEvent.type);\n    if (isTrackingEnforced || isListedInConfig) {\n        const featureFlagContext = featureFlagContexts.findFeatureFlagEvaluations(eventStartTime);\n        if (featureFlagContext && !isEmptyObject(featureFlagContext)) {\n            return featureFlagContext;\n        }\n    }\n}\n//# sourceMappingURL=assembly.js.map","import { AbstractLifeCycle } from '@datadog/browser-core';\nexport const LifeCycle = (AbstractLifeCycle);\n//# sourceMappingURL=lifeCycle.js.map","// eslint-disable-next-line no-restricted-syntax\nexport class AbstractLifeCycle {\n    constructor() {\n        this.callbacks = {};\n    }\n    notify(eventType, data) {\n        const eventCallbacks = this.callbacks[eventType];\n        if (eventCallbacks) {\n            eventCallbacks.forEach((callback) => callback(data));\n        }\n    }\n    subscribe(eventType, callback) {\n        if (!this.callbacks[eventType]) {\n            this.callbacks[eventType] = [];\n        }\n        this.callbacks[eventType].push(callback);\n        return {\n            unsubscribe: () => {\n                this.callbacks[eventType] = this.callbacks[eventType].filter((other) => callback !== other);\n            },\n        };\n    }\n}\n//# sourceMappingURL=abstractLifeCycle.js.map","import { setInterval, clearInterval } from './timer';\nimport { removeItem } from './utils/arrayUtils';\nimport { addDuration, relativeNow, ONE_MINUTE } from './utils/timeUtils';\nconst END_OF_TIMES = Infinity;\nexport const CLEAR_OLD_VALUES_INTERVAL = ONE_MINUTE;\nexport function createValueHistory({ expireDelay, maxEntries, }) {\n    let entries = [];\n    const clearOldValuesInterval = setInterval(() => clearOldValues(), CLEAR_OLD_VALUES_INTERVAL);\n    function clearOldValues() {\n        const oldTimeThreshold = relativeNow() - expireDelay;\n        while (entries.length > 0 && entries[entries.length - 1].endTime < oldTimeThreshold) {\n            entries.pop();\n        }\n    }\n    /**\n     * Add a value to the history associated with a start time. Returns a reference to this newly\n     * added entry that can be removed or closed.\n     */\n    function add(value, startTime) {\n        const entry = {\n            value,\n            startTime,\n            endTime: END_OF_TIMES,\n            remove: () => {\n                removeItem(entries, entry);\n            },\n            close: (endTime) => {\n                entry.endTime = endTime;\n            },\n        };\n        if (maxEntries && entries.length >= maxEntries) {\n            entries.pop();\n        }\n        entries.unshift(entry);\n        return entry;\n    }\n    /**\n     * Return the latest value that was active during `startTime`, or the currently active value\n     * if no `startTime` is provided. This method assumes that entries are not overlapping.\n     *\n     * If `option.returnInactive` is true, returns the value at `startTime` (active or not).\n     */\n    function find(startTime = END_OF_TIMES, options = { returnInactive: false }) {\n        for (const entry of entries) {\n            if (entry.startTime <= startTime) {\n                if (options.returnInactive || startTime <= entry.endTime) {\n                    return entry.value;\n                }\n                break;\n            }\n        }\n    }\n    /**\n     * Helper function to close the currently active value, if any. This method assumes that entries\n     * are not overlapping.\n     */\n    function closeActive(endTime) {\n        const latestEntry = entries[0];\n        if (latestEntry && latestEntry.endTime === END_OF_TIMES) {\n            latestEntry.close(endTime);\n        }\n    }\n    /**\n     * Return all values with an active period overlapping with the duration,\n     * or all values that were active during `startTime` if no duration is provided,\n     * or all currently active values if no `startTime` is provided.\n     */\n    function findAll(startTime = END_OF_TIMES, duration = 0) {\n        const endTime = addDuration(startTime, duration);\n        return entries\n            .filter((entry) => entry.startTime <= endTime && startTime <= entry.endTime)\n            .map((entry) => entry.value);\n    }\n    /**\n     * Remove all entries from this collection.\n     */\n    function reset() {\n        entries = [];\n    }\n    /**\n     * Stop internal garbage collection of past entries.\n     */\n    function stop() {\n        clearInterval(clearOldValuesInterval);\n    }\n    return { add, find, closeActive, findAll, reset, stop };\n}\n//# sourceMappingURL=valueHistory.js.map","import { SESSION_TIME_OUT_DELAY, createValueHistory } from '@datadog/browser-core';\nexport const VIEW_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY;\nexport function startViewHistory(lifeCycle) {\n    const viewValueHistory = createValueHistory({ expireDelay: VIEW_CONTEXT_TIME_OUT_DELAY });\n    lifeCycle.subscribe(1 /* LifeCycleEventType.BEFORE_VIEW_CREATED */, (view) => {\n        viewValueHistory.add(buildViewHistoryEntry(view), view.startClocks.relative);\n    });\n    lifeCycle.subscribe(5 /* LifeCycleEventType.AFTER_VIEW_ENDED */, ({ endClocks }) => {\n        viewValueHistory.closeActive(endClocks.relative);\n    });\n    lifeCycle.subscribe(3 /* LifeCycleEventType.VIEW_UPDATED */, (viewUpdate) => {\n        const currentView = viewValueHistory.find(viewUpdate.startClocks.relative);\n        if (currentView && viewUpdate.name) {\n            currentView.name = viewUpdate.name;\n        }\n        if (currentView && viewUpdate.context) {\n            currentView.context = viewUpdate.context;\n        }\n    });\n    lifeCycle.subscribe(9 /* LifeCycleEventType.SESSION_RENEWED */, () => {\n        viewValueHistory.reset();\n    });\n    function buildViewHistoryEntry(view) {\n        return {\n            service: view.service,\n            version: view.version,\n            context: view.context,\n            id: view.id,\n            name: view.name,\n            startClocks: view.startClocks,\n        };\n    }\n    return {\n        findView: (startTime) => viewValueHistory.find(startTime),\n        stop: () => {\n            viewValueHistory.stop();\n        },\n    };\n}\n//# sourceMappingURL=viewHistory.js.map","import { instrumentMethod } from '../tools/instrumentMethod';\nimport { Observable } from '../tools/observable';\nimport { elapsed, clocksNow, timeStampNow } from '../tools/utils/timeUtils';\nimport { normalizeUrl } from '../tools/utils/urlPolyfill';\nimport { shallowClone } from '../tools/utils/objectUtils';\nimport { addEventListener } from './addEventListener';\nlet xhrObservable;\nconst xhrContexts = new WeakMap();\nexport function initXhrObservable(configuration) {\n    if (!xhrObservable) {\n        xhrObservable = createXhrObservable(configuration);\n    }\n    return xhrObservable;\n}\nfunction createXhrObservable(configuration) {\n    return new Observable((observable) => {\n        const { stop: stopInstrumentingStart } = instrumentMethod(XMLHttpRequest.prototype, 'open', openXhr);\n        const { stop: stopInstrumentingSend } = instrumentMethod(XMLHttpRequest.prototype, 'send', (call) => {\n            sendXhr(call, configuration, observable);\n        }, { computeHandlingStack: true });\n        const { stop: stopInstrumentingAbort } = instrumentMethod(XMLHttpRequest.prototype, 'abort', abortXhr);\n        return () => {\n            stopInstrumentingStart();\n            stopInstrumentingSend();\n            stopInstrumentingAbort();\n        };\n    });\n}\nfunction openXhr({ target: xhr, parameters: [method, url] }) {\n    xhrContexts.set(xhr, {\n        state: 'open',\n        method: String(method).toUpperCase(),\n        url: normalizeUrl(String(url)),\n    });\n}\nfunction sendXhr({ target: xhr, handlingStack }, configuration, observable) {\n    const context = xhrContexts.get(xhr);\n    if (!context) {\n        return;\n    }\n    const startContext = context;\n    startContext.state = 'start';\n    startContext.startClocks = clocksNow();\n    startContext.isAborted = false;\n    startContext.xhr = xhr;\n    startContext.handlingStack = handlingStack;\n    let hasBeenReported = false;\n    const { stop: stopInstrumentingOnReadyStateChange } = instrumentMethod(xhr, 'onreadystatechange', () => {\n        if (xhr.readyState === XMLHttpRequest.DONE) {\n            // Try to report the XHR as soon as possible, because the XHR may be mutated by the\n            // application during a future event. For example, Angular is calling .abort() on\n            // completed requests during an onreadystatechange event, so the status becomes '0'\n            // before the request is collected.\n            onEnd();\n        }\n    });\n    const onEnd = () => {\n        unsubscribeLoadEndListener();\n        stopInstrumentingOnReadyStateChange();\n        if (hasBeenReported) {\n            return;\n        }\n        hasBeenReported = true;\n        const completeContext = context;\n        completeContext.state = 'complete';\n        completeContext.duration = elapsed(startContext.startClocks.timeStamp, timeStampNow());\n        completeContext.status = xhr.status;\n        observable.notify(shallowClone(completeContext));\n    };\n    const { stop: unsubscribeLoadEndListener } = addEventListener(configuration, xhr, 'loadend', onEnd);\n    observable.notify(startContext);\n}\nfunction abortXhr({ target: xhr }) {\n    const context = xhrContexts.get(xhr);\n    if (context) {\n        context.isAborted = true;\n    }\n}\n//# sourceMappingURL=xhrObservable.js.map","import { addTelemetryDebug, elapsed, getPathName, isValidUrl, toServerDuration, isIntakeUrl, } from '@datadog/browser-core';\nexport const FAKE_INITIAL_DOCUMENT = 'initial_document';\nconst RESOURCE_TYPES = [\n    [\"document\" /* ResourceType.DOCUMENT */, (initiatorType) => FAKE_INITIAL_DOCUMENT === initiatorType],\n    [\"xhr\" /* ResourceType.XHR */, (initiatorType) => 'xmlhttprequest' === initiatorType],\n    [\"fetch\" /* ResourceType.FETCH */, (initiatorType) => 'fetch' === initiatorType],\n    [\"beacon\" /* ResourceType.BEACON */, (initiatorType) => 'beacon' === initiatorType],\n    [\"css\" /* ResourceType.CSS */, (_, path) => /\\.css$/i.test(path)],\n    [\"js\" /* ResourceType.JS */, (_, path) => /\\.js$/i.test(path)],\n    [\n        \"image\" /* ResourceType.IMAGE */,\n        (initiatorType, path) => ['image', 'img', 'icon'].includes(initiatorType) || /\\.(gif|jpg|jpeg|tiff|png|svg|ico)$/i.exec(path) !== null,\n    ],\n    [\"font\" /* ResourceType.FONT */, (_, path) => /\\.(woff|eot|woff2|ttf)$/i.exec(path) !== null],\n    [\n        \"media\" /* ResourceType.MEDIA */,\n        (initiatorType, path) => ['audio', 'video'].includes(initiatorType) || /\\.(mp3|mp4)$/i.exec(path) !== null,\n    ],\n];\nexport function computeResourceEntryType(entry) {\n    const url = entry.name;\n    if (!isValidUrl(url)) {\n        addTelemetryDebug(`Failed to construct URL for \"${entry.name}\"`);\n        return \"other\" /* ResourceType.OTHER */;\n    }\n    const path = getPathName(url);\n    for (const [type, isType] of RESOURCE_TYPES) {\n        if (isType(entry.initiatorType, path)) {\n            return type;\n        }\n    }\n    return \"other\" /* ResourceType.OTHER */;\n}\nfunction areInOrder(...numbers) {\n    for (let i = 1; i < numbers.length; i += 1) {\n        if (numbers[i - 1] > numbers[i]) {\n            return false;\n        }\n    }\n    return true;\n}\nexport function isResourceEntryRequestType(entry) {\n    return entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch';\n}\nexport function computeResourceEntryDuration(entry) {\n    const { duration, startTime, responseEnd } = entry;\n    // Safari duration is always 0 on timings blocked by cross origin policies.\n    if (duration === 0 && startTime < responseEnd) {\n        return toServerDuration(elapsed(startTime, responseEnd));\n    }\n    return toServerDuration(duration);\n}\nexport function computeResourceEntryDetails(entry) {\n    if (!hasValidResourceEntryTimings(entry)) {\n        return undefined;\n    }\n    const { startTime, fetchStart, workerStart, redirectStart, redirectEnd, domainLookupStart, domainLookupEnd, connectStart, secureConnectionStart, connectEnd, requestStart, responseStart, responseEnd, } = entry;\n    const details = {\n        download: formatTiming(startTime, responseStart, responseEnd),\n        first_byte: formatTiming(startTime, requestStart, responseStart),\n    };\n    // Make sure a worker processing time is recorded\n    if (0 < workerStart && workerStart < fetchStart) {\n        details.worker = formatTiming(startTime, workerStart, fetchStart);\n    }\n    // Make sure a connection occurred\n    if (fetchStart < connectEnd) {\n        details.connect = formatTiming(startTime, connectStart, connectEnd);\n        // Make sure a secure connection occurred\n        if (connectStart <= secureConnectionStart && secureConnectionStart <= connectEnd) {\n            details.ssl = formatTiming(startTime, secureConnectionStart, connectEnd);\n        }\n    }\n    // Make sure a domain lookup occurred\n    if (fetchStart < domainLookupEnd) {\n        details.dns = formatTiming(startTime, domainLookupStart, domainLookupEnd);\n    }\n    // Make sure a redirection occurred\n    if (startTime < redirectEnd) {\n        details.redirect = formatTiming(startTime, redirectStart, redirectEnd);\n    }\n    return details;\n}\n/**\n * Entries with negative duration are unexpected and should be dismissed. The intake will ignore RUM\n * Resource events with negative durations anyway.\n * Since Chromium 128, more entries have unexpected negative durations, see\n * https://issues.chromium.org/issues/363031537\n */\nexport function hasValidResourceEntryDuration(entry) {\n    return entry.duration >= 0;\n}\nexport function hasValidResourceEntryTimings(entry) {\n    // Ensure timings are in the right order. On top of filtering out potential invalid\n    // RumPerformanceResourceTiming, it will ignore entries from requests where timings cannot be\n    // collected, for example cross origin requests without a \"Timing-Allow-Origin\" header allowing\n    // it.\n    const areCommonTimingsInOrder = areInOrder(entry.startTime, entry.fetchStart, entry.domainLookupStart, entry.domainLookupEnd, entry.connectStart, entry.connectEnd, entry.requestStart, entry.responseStart, entry.responseEnd);\n    const areRedirectionTimingsInOrder = hasRedirection(entry)\n        ? areInOrder(entry.startTime, entry.redirectStart, entry.redirectEnd, entry.fetchStart)\n        : true;\n    return areCommonTimingsInOrder && areRedirectionTimingsInOrder;\n}\nfunction hasRedirection(entry) {\n    return entry.redirectEnd > entry.startTime;\n}\nfunction formatTiming(origin, start, end) {\n    if (origin <= start && start <= end) {\n        return {\n            duration: toServerDuration(elapsed(start, end)),\n            start: toServerDuration(elapsed(origin, start)),\n        };\n    }\n}\n/**\n * The 'nextHopProtocol' is an empty string for cross-origin resources without CORS headers,\n * meaning the protocol is unknown, and we shouldn't report it.\n * https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/nextHopProtocol#cross-origin_resources\n */\nexport function computeResourceEntryProtocol(entry) {\n    return entry.nextHopProtocol === '' ? undefined : entry.nextHopProtocol;\n}\n/**\n * Handles the 'deliveryType' property to distinguish between supported values ('cache', 'navigational-prefetch'),\n * undefined (unsupported in some browsers), and other cases ('other' for unknown or unrecognized values).\n * see: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/deliveryType\n */\nexport function computeResourceEntryDeliveryType(entry) {\n    return entry.deliveryType === '' ? 'other' : entry.deliveryType;\n}\nexport function computeResourceEntrySize(entry) {\n    // Make sure a request actually occurred\n    if (entry.startTime < entry.responseStart) {\n        const { encodedBodySize, decodedBodySize, transferSize } = entry;\n        return {\n            size: decodedBodySize,\n            encoded_body_size: encodedBodySize,\n            decoded_body_size: decodedBodySize,\n            transfer_size: transferSize,\n        };\n    }\n    return {\n        size: undefined,\n        encoded_body_size: undefined,\n        decoded_body_size: undefined,\n        transfer_size: undefined,\n    };\n}\nexport function isAllowedRequestUrl(url) {\n    return url && !isIntakeUrl(url);\n}\nconst DATA_URL_REGEX = /data:(.+)?(;base64)?,/g;\nexport const MAX_ATTRIBUTE_VALUE_CHAR_LENGTH = 24000;\nexport function isLongDataUrl(url) {\n    if (url.length <= MAX_ATTRIBUTE_VALUE_CHAR_LENGTH) {\n        return false;\n    }\n    else if (url.substring(0, 5) === 'data:') {\n        // Avoid String.match RangeError: Maximum call stack size exceeded\n        url = url.substring(0, MAX_ATTRIBUTE_VALUE_CHAR_LENGTH);\n        return true;\n    }\n    return false;\n}\nexport function sanitizeDataUrl(url) {\n    return `${url.match(DATA_URL_REGEX)[0]}[...]`;\n}\n//# sourceMappingURL=resourceUtils.js.map","import { initFetchObservable, initXhrObservable, readBytesFromStream, elapsed, timeStampNow, tryToClone, } from '@datadog/browser-core';\nimport { isAllowedRequestUrl } from './resource/resourceUtils';\nimport { startTracer } from './tracing/tracer';\nlet nextRequestIndex = 1;\nexport function startRequestCollection(lifeCycle, configuration, sessionManager) {\n    const tracer = startTracer(configuration, sessionManager);\n    trackXhr(lifeCycle, configuration, tracer);\n    trackFetch(lifeCycle, tracer);\n}\nexport function trackXhr(lifeCycle, configuration, tracer) {\n    const subscription = initXhrObservable(configuration).subscribe((rawContext) => {\n        const context = rawContext;\n        if (!isAllowedRequestUrl(context.url)) {\n            return;\n        }\n        switch (context.state) {\n            case 'start':\n                tracer.traceXhr(context, context.xhr);\n                context.requestIndex = getNextRequestIndex();\n                lifeCycle.notify(6 /* LifeCycleEventType.REQUEST_STARTED */, {\n                    requestIndex: context.requestIndex,\n                    url: context.url,\n                });\n                break;\n            case 'complete':\n                tracer.clearTracingIfNeeded(context);\n                lifeCycle.notify(7 /* LifeCycleEventType.REQUEST_COMPLETED */, {\n                    duration: context.duration,\n                    method: context.method,\n                    requestIndex: context.requestIndex,\n                    spanId: context.spanId,\n                    startClocks: context.startClocks,\n                    status: context.status,\n                    traceId: context.traceId,\n                    traceSampled: context.traceSampled,\n                    type: \"xhr\" /* RequestType.XHR */,\n                    url: context.url,\n                    xhr: context.xhr,\n                    isAborted: context.isAborted,\n                    handlingStack: context.handlingStack,\n                });\n                break;\n        }\n    });\n    return { stop: () => subscription.unsubscribe() };\n}\nexport function trackFetch(lifeCycle, tracer) {\n    const subscription = initFetchObservable().subscribe((rawContext) => {\n        const context = rawContext;\n        if (!isAllowedRequestUrl(context.url)) {\n            return;\n        }\n        switch (context.state) {\n            case 'start':\n                tracer.traceFetch(context);\n                context.requestIndex = getNextRequestIndex();\n                lifeCycle.notify(6 /* LifeCycleEventType.REQUEST_STARTED */, {\n                    requestIndex: context.requestIndex,\n                    url: context.url,\n                });\n                break;\n            case 'resolve':\n                waitForResponseToComplete(context, (duration) => {\n                    tracer.clearTracingIfNeeded(context);\n                    lifeCycle.notify(7 /* LifeCycleEventType.REQUEST_COMPLETED */, {\n                        duration,\n                        method: context.method,\n                        requestIndex: context.requestIndex,\n                        responseType: context.responseType,\n                        spanId: context.spanId,\n                        startClocks: context.startClocks,\n                        status: context.status,\n                        traceId: context.traceId,\n                        traceSampled: context.traceSampled,\n                        type: \"fetch\" /* RequestType.FETCH */,\n                        url: context.url,\n                        response: context.response,\n                        init: context.init,\n                        input: context.input,\n                        isAborted: context.isAborted,\n                        handlingStack: context.handlingStack,\n                    });\n                });\n                break;\n        }\n    });\n    return { stop: () => subscription.unsubscribe() };\n}\nfunction getNextRequestIndex() {\n    const result = nextRequestIndex;\n    nextRequestIndex += 1;\n    return result;\n}\nfunction waitForResponseToComplete(context, callback) {\n    const clonedResponse = context.response && tryToClone(context.response);\n    if (!clonedResponse || !clonedResponse.body) {\n        // do not try to wait for the response if the clone failed, fetch error or null body\n        callback(elapsed(context.startClocks.timeStamp, timeStampNow()));\n    }\n    else {\n        readBytesFromStream(clonedResponse.body, () => {\n            callback(elapsed(context.startClocks.timeStamp, timeStampNow()));\n        }, {\n            bytesLimit: Number.POSITIVE_INFINITY,\n            collectStreamBody: false,\n        });\n    }\n}\n//# sourceMappingURL=requestCollection.js.map","import { monitor } from './monitor';\nimport { noop } from './utils/functionUtils';\n/**\n * Read bytes from a ReadableStream until at least `limit` bytes have been read (or until the end of\n * the stream). The callback is invoked with the at most `limit` bytes, and indicates that the limit\n * has been exceeded if more bytes were available.\n */\nexport function readBytesFromStream(stream, callback, options) {\n    const reader = stream.getReader();\n    const chunks = [];\n    let readBytesCount = 0;\n    readMore();\n    function readMore() {\n        reader.read().then(monitor((result) => {\n            if (result.done) {\n                onDone();\n                return;\n            }\n            if (options.collectStreamBody) {\n                chunks.push(result.value);\n            }\n            readBytesCount += result.value.length;\n            if (readBytesCount > options.bytesLimit) {\n                onDone();\n            }\n            else {\n                readMore();\n            }\n        }), monitor((error) => callback(error)));\n    }\n    function onDone() {\n        reader.cancel().catch(\n        // we don't care if cancel fails, but we still need to catch the error to avoid reporting it\n        // as an unhandled rejection\n        noop);\n        let bytes;\n        let limitExceeded;\n        if (options.collectStreamBody) {\n            let completeBuffer;\n            if (chunks.length === 1) {\n                // optimization: if the response is small enough to fit in a single buffer (provided by the browser), just\n                // use it directly.\n                completeBuffer = chunks[0];\n            }\n            else {\n                // else, we need to copy buffers into a larger buffer to concatenate them.\n                completeBuffer = new Uint8Array(readBytesCount);\n                let offset = 0;\n                chunks.forEach((chunk) => {\n                    completeBuffer.set(chunk, offset);\n                    offset += chunk.length;\n                });\n            }\n            bytes = completeBuffer.slice(0, options.bytesLimit);\n            limitExceeded = completeBuffer.length > options.bytesLimit;\n        }\n        callback(undefined, bytes, limitExceeded);\n    }\n}\n//# sourceMappingURL=readBytesFromStream.js.map","import { isNumber } from '@datadog/browser-core';\nexport function discardNegativeDuration(duration) {\n    return isNumber(duration) && duration < 0 ? undefined : duration;\n}\n//# sourceMappingURL=discardNegativeDuration.js.map","import { noop } from '@datadog/browser-core';\nexport function trackEventCounts({ lifeCycle, isChildEvent, onChange: callback = noop, }) {\n    const eventCounts = {\n        errorCount: 0,\n        longTaskCount: 0,\n        resourceCount: 0,\n        actionCount: 0,\n        frustrationCount: 0,\n    };\n    const subscription = lifeCycle.subscribe(12 /* LifeCycleEventType.RUM_EVENT_COLLECTED */, (event) => {\n        var _a;\n        if (event.type === 'view' || event.type === 'vital' || !isChildEvent(event)) {\n            return;\n        }\n        switch (event.type) {\n            case \"error\" /* RumEventType.ERROR */:\n                eventCounts.errorCount += 1;\n                callback();\n                break;\n            case \"action\" /* RumEventType.ACTION */:\n                eventCounts.actionCount += 1;\n                if (event.action.frustration) {\n                    eventCounts.frustrationCount += event.action.frustration.type.length;\n                }\n                callback();\n                break;\n            case \"long_task\" /* RumEventType.LONG_TASK */:\n                eventCounts.longTaskCount += 1;\n                callback();\n                break;\n            case \"resource\" /* RumEventType.RESOURCE */:\n                if (!((_a = event._dd) === null || _a === void 0 ? void 0 : _a.discarded)) {\n                    eventCounts.resourceCount += 1;\n                    callback();\n                }\n                break;\n        }\n    });\n    return {\n        stop: () => {\n            subscription.unsubscribe();\n        },\n        eventCounts,\n    };\n}\n//# sourceMappingURL=trackEventCounts.js.map","import { addEventListeners, dateNow, relativeNow } from '@datadog/browser-core';\n/**\n * first-input timing entry polyfill based on\n * https://github.com/GoogleChrome/web-vitals/blob/master/src/lib/polyfills/firstInputPolyfill.ts\n */\nexport function retrieveFirstInputTiming(configuration, callback) {\n    const startTimeStamp = dateNow();\n    let timingSent = false;\n    const { stop: removeEventListeners } = addEventListeners(configuration, window, [\"click\" /* DOM_EVENT.CLICK */, \"mousedown\" /* DOM_EVENT.MOUSE_DOWN */, \"keydown\" /* DOM_EVENT.KEY_DOWN */, \"touchstart\" /* DOM_EVENT.TOUCH_START */, \"pointerdown\" /* DOM_EVENT.POINTER_DOWN */], (evt) => {\n        // Only count cancelable events, which should trigger behavior important to the user.\n        if (!evt.cancelable) {\n            return;\n        }\n        // This timing will be used to compute the \"first Input delay\", which is the delta between\n        // when the system received the event (e.g. evt.timeStamp) and when it could run the callback\n        // (e.g. performance.now()).\n        const timing = {\n            entryType: 'first-input',\n            processingStart: relativeNow(),\n            processingEnd: relativeNow(),\n            startTime: evt.timeStamp,\n            duration: 0, // arbitrary value to avoid nullable duration and simplify INP logic\n            name: '',\n            cancelable: false,\n            target: null,\n            toJSON: () => ({}),\n        };\n        if (evt.type === \"pointerdown\" /* DOM_EVENT.POINTER_DOWN */) {\n            sendTimingIfPointerIsNotCancelled(configuration, timing);\n        }\n        else {\n            sendTiming(timing);\n        }\n    }, { passive: true, capture: true });\n    return { stop: removeEventListeners };\n    /**\n     * Pointer events are a special case, because they can trigger main or compositor thread behavior.\n     * We differentiate these cases based on whether or not we see a pointercancel event, which are\n     * fired when we scroll. If we're scrolling we don't need to report input delay since FID excludes\n     * scrolling and pinch/zooming.\n     */\n    function sendTimingIfPointerIsNotCancelled(configuration, timing) {\n        addEventListeners(configuration, window, [\"pointerup\" /* DOM_EVENT.POINTER_UP */, \"pointercancel\" /* DOM_EVENT.POINTER_CANCEL */], (event) => {\n            if (event.type === \"pointerup\" /* DOM_EVENT.POINTER_UP */) {\n                sendTiming(timing);\n            }\n        }, { once: true });\n    }\n    function sendTiming(timing) {\n        if (!timingSent) {\n            timingSent = true;\n            removeEventListeners();\n            // In some cases the recorded delay is clearly wrong, e.g. it's negative or it's larger than\n            // the time between now and when the page was loaded.\n            // - https://github.com/GoogleChromeLabs/first-input-delay/issues/4\n            // - https://github.com/GoogleChromeLabs/first-input-delay/issues/6\n            // - https://github.com/GoogleChromeLabs/first-input-delay/issues/7\n            const delay = timing.processingStart - timing.startTime;\n            if (delay >= 0 && delay < dateNow() - startTimeStamp) {\n                callback(timing);\n            }\n        }\n    }\n}\n//# sourceMappingURL=firstInputPolyfill.js.map","import { addEventListener, Observable, setTimeout, clearTimeout, monitor } from '@datadog/browser-core';\nimport { hasValidResourceEntryDuration, isAllowedRequestUrl } from '../domain/resource/resourceUtils';\nimport { retrieveFirstInputTiming } from './firstInputPolyfill';\n// We want to use a real enum (i.e. not a const enum) here, to be able to check whether an arbitrary\n// string is an expected performance entry\n// eslint-disable-next-line no-restricted-syntax\nexport var RumPerformanceEntryType;\n(function (RumPerformanceEntryType) {\n    RumPerformanceEntryType[\"EVENT\"] = \"event\";\n    RumPerformanceEntryType[\"FIRST_INPUT\"] = \"first-input\";\n    RumPerformanceEntryType[\"LARGEST_CONTENTFUL_PAINT\"] = \"largest-contentful-paint\";\n    RumPerformanceEntryType[\"LAYOUT_SHIFT\"] = \"layout-shift\";\n    RumPerformanceEntryType[\"LONG_TASK\"] = \"longtask\";\n    RumPerformanceEntryType[\"LONG_ANIMATION_FRAME\"] = \"long-animation-frame\";\n    RumPerformanceEntryType[\"NAVIGATION\"] = \"navigation\";\n    RumPerformanceEntryType[\"PAINT\"] = \"paint\";\n    RumPerformanceEntryType[\"RESOURCE\"] = \"resource\";\n})(RumPerformanceEntryType || (RumPerformanceEntryType = {}));\nexport function createPerformanceObservable(configuration, options) {\n    return new Observable((observable) => {\n        if (!window.PerformanceObserver) {\n            return;\n        }\n        const handlePerformanceEntries = (entries) => {\n            const rumPerformanceEntries = filterRumPerformanceEntries(entries);\n            if (rumPerformanceEntries.length > 0) {\n                observable.notify(rumPerformanceEntries);\n            }\n        };\n        let timeoutId;\n        let isObserverInitializing = true;\n        const observer = new PerformanceObserver(monitor((entries) => {\n            // In Safari the performance observer callback is synchronous.\n            // Because the buffered performance entry list can be quite large we delay the computation to prevent the SDK from blocking the main thread on init\n            if (isObserverInitializing) {\n                timeoutId = setTimeout(() => handlePerformanceEntries(entries.getEntries()));\n            }\n            else {\n                handlePerformanceEntries(entries.getEntries());\n            }\n        }));\n        try {\n            observer.observe(options);\n        }\n        catch (_a) {\n            // Some old browser versions (<= chrome 74 ) don't support the PerformanceObserver type and buffered options\n            // In these cases, fallback to getEntriesByType and PerformanceObserver with entryTypes\n            // TODO: remove this fallback in the next major version\n            const fallbackSupportedEntryTypes = [\n                RumPerformanceEntryType.RESOURCE,\n                RumPerformanceEntryType.NAVIGATION,\n                RumPerformanceEntryType.LONG_TASK,\n                RumPerformanceEntryType.PAINT,\n            ];\n            if (fallbackSupportedEntryTypes.includes(options.type)) {\n                if (options.buffered) {\n                    timeoutId = setTimeout(() => handlePerformanceEntries(performance.getEntriesByType(options.type)));\n                }\n                try {\n                    observer.observe({ entryTypes: [options.type] });\n                }\n                catch (_b) {\n                    // Old versions of Safari are throwing \"entryTypes contained only unsupported types\"\n                    // errors when observing only unsupported entry types.\n                    //\n                    // We could use `supportPerformanceTimingEvent` to make sure we don't invoke\n                    // `observer.observe` with an unsupported entry type, but Safari 11 and 12 don't support\n                    // `Performance.supportedEntryTypes`, so doing so would lose support for these versions\n                    // even if they do support the entry type.\n                    return;\n                }\n            }\n        }\n        isObserverInitializing = false;\n        manageResourceTimingBufferFull(configuration);\n        let stopFirstInputTiming;\n        if (!supportPerformanceTimingEvent(RumPerformanceEntryType.FIRST_INPUT) &&\n            options.type === RumPerformanceEntryType.FIRST_INPUT) {\n            ;\n            ({ stop: stopFirstInputTiming } = retrieveFirstInputTiming(configuration, (timing) => {\n                handlePerformanceEntries([timing]);\n            }));\n        }\n        return () => {\n            observer.disconnect();\n            if (stopFirstInputTiming) {\n                stopFirstInputTiming();\n            }\n            clearTimeout(timeoutId);\n        };\n    });\n}\nlet resourceTimingBufferFullListener;\nfunction manageResourceTimingBufferFull(configuration) {\n    if (!resourceTimingBufferFullListener && supportPerformanceObject() && 'addEventListener' in performance) {\n        // https://bugzilla.mozilla.org/show_bug.cgi?id=1559377\n        resourceTimingBufferFullListener = addEventListener(configuration, performance, 'resourcetimingbufferfull', () => {\n            performance.clearResourceTimings();\n        });\n    }\n    return () => {\n        resourceTimingBufferFullListener === null || resourceTimingBufferFullListener === void 0 ? void 0 : resourceTimingBufferFullListener.stop();\n    };\n}\nfunction supportPerformanceObject() {\n    return window.performance !== undefined && 'getEntries' in performance;\n}\nexport function supportPerformanceTimingEvent(entryType) {\n    return (window.PerformanceObserver &&\n        PerformanceObserver.supportedEntryTypes !== undefined &&\n        PerformanceObserver.supportedEntryTypes.includes(entryType));\n}\nfunction filterRumPerformanceEntries(entries) {\n    return entries.filter((entry) => !isForbiddenResource(entry));\n}\nfunction isForbiddenResource(entry) {\n    return (entry.entryType === RumPerformanceEntryType.RESOURCE &&\n        (!isAllowedRequestUrl(entry.name) || !hasValidResourceEntryDuration(entry)));\n}\n//# sourceMappingURL=performanceObservable.js.map","import { matchList, monitor, Observable, timeStampNow, setTimeout, clearTimeout } from '@datadog/browser-core';\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../browser/performanceObservable';\n// Delay to wait for a page activity to validate the tracking process\nexport const PAGE_ACTIVITY_VALIDATION_DELAY = 100;\n// Delay to wait after a page activity to end the tracking process\nexport const PAGE_ACTIVITY_END_DELAY = 100;\n/**\n * Wait for the page activity end\n *\n * Detection lifecycle:\n * ```\n *                        Wait page activity end\n *              .-------------------'--------------------.\n *              v                                        v\n *     [Wait for a page activity ]          [Wait for a maximum duration]\n *     [timeout: VALIDATION_DELAY]          [  timeout: maxDuration     ]\n *          /                  \\                           |\n *         v                    v                          |\n *  [No page activity]   [Page activity]                   |\n *         |                   |,----------------------.   |\n *         v                   v                       |   |\n *     (Discard)     [Wait for a page activity]        |   |\n *                   [   timeout: END_DELAY   ]        |   |\n *                       /                \\            |   |\n *                      v                  v           |   |\n *             [No page activity]    [Page activity]   |   |\n *                      |                 |            |   |\n *                      |                 '------------'   |\n *                      '-----------. ,--------------------'\n *                                   v\n *                                 (End)\n * ```\n *\n * Note: by assuming that maxDuration is greater than VALIDATION_DELAY, we are sure that if the\n * process is still alive after maxDuration, it has been validated.\n */\nexport function waitPageActivityEnd(lifeCycle, domMutationObservable, windowOpenObservable, configuration, pageActivityEndCallback, maxDuration) {\n    const pageActivityObservable = createPageActivityObservable(lifeCycle, domMutationObservable, windowOpenObservable, configuration);\n    return doWaitPageActivityEnd(pageActivityObservable, pageActivityEndCallback, maxDuration);\n}\nexport function doWaitPageActivityEnd(pageActivityObservable, pageActivityEndCallback, maxDuration) {\n    let pageActivityEndTimeoutId;\n    let hasCompleted = false;\n    const validationTimeoutId = setTimeout(monitor(() => complete({ hadActivity: false })), PAGE_ACTIVITY_VALIDATION_DELAY);\n    const maxDurationTimeoutId = maxDuration !== undefined\n        ? setTimeout(monitor(() => complete({ hadActivity: true, end: timeStampNow() })), maxDuration)\n        : undefined;\n    const pageActivitySubscription = pageActivityObservable.subscribe(({ isBusy }) => {\n        clearTimeout(validationTimeoutId);\n        clearTimeout(pageActivityEndTimeoutId);\n        const lastChangeTime = timeStampNow();\n        if (!isBusy) {\n            pageActivityEndTimeoutId = setTimeout(monitor(() => complete({ hadActivity: true, end: lastChangeTime })), PAGE_ACTIVITY_END_DELAY);\n        }\n    });\n    const stop = () => {\n        hasCompleted = true;\n        clearTimeout(validationTimeoutId);\n        clearTimeout(pageActivityEndTimeoutId);\n        clearTimeout(maxDurationTimeoutId);\n        pageActivitySubscription.unsubscribe();\n    };\n    function complete(event) {\n        if (hasCompleted) {\n            return;\n        }\n        stop();\n        pageActivityEndCallback(event);\n    }\n    return { stop };\n}\nexport function createPageActivityObservable(lifeCycle, domMutationObservable, windowOpenObservable, configuration) {\n    return new Observable((observable) => {\n        const subscriptions = [];\n        let firstRequestIndex;\n        let pendingRequestsCount = 0;\n        subscriptions.push(domMutationObservable.subscribe(notifyPageActivity), windowOpenObservable.subscribe(notifyPageActivity), createPerformanceObservable(configuration, { type: RumPerformanceEntryType.RESOURCE }).subscribe((entries) => {\n            if (entries.some((entry) => !isExcludedUrl(configuration, entry.name))) {\n                notifyPageActivity();\n            }\n        }), lifeCycle.subscribe(6 /* LifeCycleEventType.REQUEST_STARTED */, (startEvent) => {\n            if (isExcludedUrl(configuration, startEvent.url)) {\n                return;\n            }\n            if (firstRequestIndex === undefined) {\n                firstRequestIndex = startEvent.requestIndex;\n            }\n            pendingRequestsCount += 1;\n            notifyPageActivity();\n        }), lifeCycle.subscribe(7 /* LifeCycleEventType.REQUEST_COMPLETED */, (request) => {\n            if (isExcludedUrl(configuration, request.url) ||\n                firstRequestIndex === undefined ||\n                // If the request started before the tracking start, ignore it\n                request.requestIndex < firstRequestIndex) {\n                return;\n            }\n            pendingRequestsCount -= 1;\n            notifyPageActivity();\n        }));\n        return () => {\n            subscriptions.forEach((s) => s.unsubscribe());\n        };\n        function notifyPageActivity() {\n            observable.notify({ isBusy: pendingRequestsCount > 0 });\n        }\n    });\n}\nfunction isExcludedUrl(configuration, requestUrl) {\n    return matchList(configuration.excludedActivityUrls, requestUrl);\n}\n//# sourceMappingURL=waitPageActivityEnd.js.map","export function isTextNode(node) {\n    return node.nodeType === Node.TEXT_NODE;\n}\nexport function isCommentNode(node) {\n    return node.nodeType === Node.COMMENT_NODE;\n}\nexport function isElementNode(node) {\n    return node.nodeType === Node.ELEMENT_NODE;\n}\nexport function isNodeShadowHost(node) {\n    return isElementNode(node) && Boolean(node.shadowRoot);\n}\nexport function isNodeShadowRoot(node) {\n    const shadowRoot = node;\n    return !!shadowRoot.host && shadowRoot.nodeType === Node.DOCUMENT_FRAGMENT_NODE && isElementNode(shadowRoot.host);\n}\nexport function hasChildNodes(node) {\n    return node.childNodes.length > 0 || isNodeShadowHost(node);\n}\nexport function forEachChildNodes(node, callback) {\n    let child = node.firstChild;\n    while (child) {\n        callback(child);\n        child = child.nextSibling;\n    }\n    if (isNodeShadowHost(node)) {\n        callback(node.shadowRoot);\n    }\n}\n/**\n * Return `host` in case if the current node is a shadow root otherwise will return the `parentNode`\n */\nexport function getParentNode(node) {\n    return isNodeShadowRoot(node) ? node.host : node.parentNode;\n}\n//# sourceMappingURL=htmlDomUtils.js.map","import { DefaultPrivacyLevel } from '@datadog/browser-core';\nimport { isElementNode, getParentNode, isTextNode } from '../browser/htmlDomUtils';\nexport const NodePrivacyLevel = {\n    IGNORE: 'ignore',\n    HIDDEN: 'hidden',\n    ALLOW: DefaultPrivacyLevel.ALLOW,\n    MASK: DefaultPrivacyLevel.MASK,\n    MASK_USER_INPUT: DefaultPrivacyLevel.MASK_USER_INPUT,\n};\nexport const PRIVACY_ATTR_NAME = 'data-dd-privacy';\n// Privacy Attrs\nexport const PRIVACY_ATTR_VALUE_ALLOW = 'allow';\nexport const PRIVACY_ATTR_VALUE_MASK = 'mask';\nexport const PRIVACY_ATTR_VALUE_MASK_USER_INPUT = 'mask-user-input';\nexport const PRIVACY_ATTR_VALUE_HIDDEN = 'hidden';\n// Privacy Classes - not all customers can set plain HTML attributes, so support classes too\nexport const PRIVACY_CLASS_PREFIX = 'dd-privacy-';\n// Private Replacement Templates\nexport const CENSORED_STRING_MARK = '***';\nexport const CENSORED_IMG_MARK = 'data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';\nexport const FORM_PRIVATE_TAG_NAMES = {\n    INPUT: true,\n    OUTPUT: true,\n    TEXTAREA: true,\n    SELECT: true,\n    OPTION: true,\n    DATALIST: true,\n    OPTGROUP: true,\n};\nconst TEXT_MASKING_CHAR = 'x';\n/**\n * Get node privacy level by iterating over its ancestors. When the direct parent privacy level is\n * know, it is best to use something like:\n *\n * derivePrivacyLevelGivenParent(getNodeSelfPrivacyLevel(node), parentNodePrivacyLevel)\n */\nexport function getNodePrivacyLevel(node, defaultPrivacyLevel, cache) {\n    if (cache && cache.has(node)) {\n        return cache.get(node);\n    }\n    const parentNode = getParentNode(node);\n    const parentNodePrivacyLevel = parentNode\n        ? getNodePrivacyLevel(parentNode, defaultPrivacyLevel, cache)\n        : defaultPrivacyLevel;\n    const selfNodePrivacyLevel = getNodeSelfPrivacyLevel(node);\n    const nodePrivacyLevel = reducePrivacyLevel(selfNodePrivacyLevel, parentNodePrivacyLevel);\n    if (cache) {\n        cache.set(node, nodePrivacyLevel);\n    }\n    return nodePrivacyLevel;\n}\n/**\n * Reduces the next privacy level based on self + parent privacy levels\n */\nexport function reducePrivacyLevel(childPrivacyLevel, parentNodePrivacyLevel) {\n    switch (parentNodePrivacyLevel) {\n        // These values cannot be overridden\n        case NodePrivacyLevel.HIDDEN:\n        case NodePrivacyLevel.IGNORE:\n            return parentNodePrivacyLevel;\n    }\n    switch (childPrivacyLevel) {\n        case NodePrivacyLevel.ALLOW:\n        case NodePrivacyLevel.MASK:\n        case NodePrivacyLevel.MASK_USER_INPUT:\n        case NodePrivacyLevel.HIDDEN:\n        case NodePrivacyLevel.IGNORE:\n            return childPrivacyLevel;\n        default:\n            return parentNodePrivacyLevel;\n    }\n}\n/**\n * Determines the node's own privacy level without checking for ancestors.\n */\nexport function getNodeSelfPrivacyLevel(node) {\n    // Only Element types can have a privacy level set\n    if (!isElementNode(node)) {\n        return;\n    }\n    // Overrules for replay purpose\n    if (node.tagName === 'BASE') {\n        return NodePrivacyLevel.ALLOW;\n    }\n    // Overrules to enforce end-user protection\n    if (node.tagName === 'INPUT') {\n        const inputElement = node;\n        if (inputElement.type === 'password' || inputElement.type === 'email' || inputElement.type === 'tel') {\n            return NodePrivacyLevel.MASK;\n        }\n        if (inputElement.type === 'hidden') {\n            return NodePrivacyLevel.MASK;\n        }\n        const autocomplete = inputElement.getAttribute('autocomplete');\n        // Handle input[autocomplete=cc-number/cc-csc/cc-exp/cc-exp-month/cc-exp-year/new-password/current-password]\n        if (autocomplete && (autocomplete.startsWith('cc-') || autocomplete.endsWith('-password'))) {\n            return NodePrivacyLevel.MASK;\n        }\n    }\n    // Check HTML privacy attributes and classes\n    if (node.matches(getPrivacySelector(NodePrivacyLevel.HIDDEN))) {\n        return NodePrivacyLevel.HIDDEN;\n    }\n    if (node.matches(getPrivacySelector(NodePrivacyLevel.MASK))) {\n        return NodePrivacyLevel.MASK;\n    }\n    if (node.matches(getPrivacySelector(NodePrivacyLevel.MASK_USER_INPUT))) {\n        return NodePrivacyLevel.MASK_USER_INPUT;\n    }\n    if (node.matches(getPrivacySelector(NodePrivacyLevel.ALLOW))) {\n        return NodePrivacyLevel.ALLOW;\n    }\n    if (shouldIgnoreElement(node)) {\n        return NodePrivacyLevel.IGNORE;\n    }\n}\n/**\n * Helper aiming to unify `mask` and `mask-user-input` privacy levels:\n *\n * In the `mask` case, it is trivial: we should mask the element.\n *\n * In the `mask-user-input` case, we should mask the element only if it is a \"form\" element or the\n * direct parent is a form element for text nodes).\n *\n * Other `shouldMaskNode` cases are edge cases that should not matter too much (ex: should we mask a\n * node if it is ignored or hidden? it doesn't matter since it won't be serialized).\n */\nexport function shouldMaskNode(node, privacyLevel) {\n    switch (privacyLevel) {\n        case NodePrivacyLevel.MASK:\n        case NodePrivacyLevel.HIDDEN:\n        case NodePrivacyLevel.IGNORE:\n            return true;\n        case NodePrivacyLevel.MASK_USER_INPUT:\n            return isTextNode(node) ? isFormElement(node.parentNode) : isFormElement(node);\n        default:\n            return false;\n    }\n}\nfunction isFormElement(node) {\n    if (!node || node.nodeType !== node.ELEMENT_NODE) {\n        return false;\n    }\n    const element = node;\n    if (element.tagName === 'INPUT') {\n        switch (element.type) {\n            case 'button':\n            case 'color':\n            case 'reset':\n            case 'submit':\n                return false;\n        }\n    }\n    return !!FORM_PRIVATE_TAG_NAMES[element.tagName];\n}\n/**\n * Text censoring non-destructively maintains whitespace characters in order to preserve text shape\n * during replay.\n */\nexport const censorText = (text) => text.replace(/\\S/g, TEXT_MASKING_CHAR);\nexport function getTextContent(textNode, ignoreWhiteSpace, parentNodePrivacyLevel) {\n    var _a;\n    // The parent node may not be a html element which has a tagName attribute.\n    // So just let it be undefined which is ok in this use case.\n    const parentTagName = (_a = textNode.parentElement) === null || _a === void 0 ? void 0 : _a.tagName;\n    let textContent = textNode.textContent || '';\n    if (ignoreWhiteSpace && !textContent.trim()) {\n        return;\n    }\n    const nodePrivacyLevel = parentNodePrivacyLevel;\n    const isScript = parentTagName === 'SCRIPT';\n    if (isScript) {\n        // For perf reasons, we don't record script (heuristic)\n        textContent = CENSORED_STRING_MARK;\n    }\n    else if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n        // Should never occur, but just in case, we set to CENSORED_MARK.\n        textContent = CENSORED_STRING_MARK;\n    }\n    else if (shouldMaskNode(textNode, nodePrivacyLevel)) {\n        if (\n        // Scrambling the child list breaks text nodes for DATALIST/SELECT/OPTGROUP\n        parentTagName === 'DATALIST' ||\n            parentTagName === 'SELECT' ||\n            parentTagName === 'OPTGROUP') {\n            if (!textContent.trim()) {\n                return;\n            }\n        }\n        else if (parentTagName === 'OPTION') {\n            // <Option> has low entropy in charset + text length, so use `CENSORED_STRING_MARK` when masked\n            textContent = CENSORED_STRING_MARK;\n        }\n        else {\n            textContent = censorText(textContent);\n        }\n    }\n    return textContent;\n}\n/**\n * TODO: Preserve CSS element order, and record the presence of the tag, just don't render\n * We don't need this logic on the recorder side.\n * For security related meta's, customer can mask themmanually given they\n * are easy to identify in the HEAD tag.\n */\nexport function shouldIgnoreElement(element) {\n    if (element.nodeName === 'SCRIPT') {\n        return true;\n    }\n    if (element.nodeName === 'LINK') {\n        const relAttribute = getLowerCaseAttribute('rel');\n        return (\n        // Link as script - Ignore only when rel=preload, modulepreload or prefetch\n        (/preload|prefetch/i.test(relAttribute) && getLowerCaseAttribute('as') === 'script') ||\n            // Favicons\n            relAttribute === 'shortcut icon' ||\n            relAttribute === 'icon');\n    }\n    if (element.nodeName === 'META') {\n        const nameAttribute = getLowerCaseAttribute('name');\n        const relAttribute = getLowerCaseAttribute('rel');\n        const propertyAttribute = getLowerCaseAttribute('property');\n        return (\n        // Favicons\n        /^msapplication-tile(image|color)$/.test(nameAttribute) ||\n            nameAttribute === 'application-name' ||\n            relAttribute === 'icon' ||\n            relAttribute === 'apple-touch-icon' ||\n            relAttribute === 'shortcut icon' ||\n            // Description\n            nameAttribute === 'keywords' ||\n            nameAttribute === 'description' ||\n            // Social\n            /^(og|twitter|fb):/.test(propertyAttribute) ||\n            /^(og|twitter):/.test(nameAttribute) ||\n            nameAttribute === 'pinterest' ||\n            // Robots\n            nameAttribute === 'robots' ||\n            nameAttribute === 'googlebot' ||\n            nameAttribute === 'bingbot' ||\n            // Http headers. Ex: X-UA-Compatible, Content-Type, Content-Language, cache-control,\n            // X-Translated-By\n            element.hasAttribute('http-equiv') ||\n            // Authorship\n            nameAttribute === 'author' ||\n            nameAttribute === 'generator' ||\n            nameAttribute === 'framework' ||\n            nameAttribute === 'publisher' ||\n            nameAttribute === 'progid' ||\n            /^article:/.test(propertyAttribute) ||\n            /^product:/.test(propertyAttribute) ||\n            // Verification\n            nameAttribute === 'google-site-verification' ||\n            nameAttribute === 'yandex-verification' ||\n            nameAttribute === 'csrf-token' ||\n            nameAttribute === 'p:domain_verify' ||\n            nameAttribute === 'verify-v1' ||\n            nameAttribute === 'verification' ||\n            nameAttribute === 'shopify-checkout-api-token');\n    }\n    function getLowerCaseAttribute(name) {\n        return (element.getAttribute(name) || '').toLowerCase();\n    }\n    return false;\n}\nexport function getPrivacySelector(privacyLevel) {\n    return `[${PRIVACY_ATTR_NAME}=\"${privacyLevel}\"], .${PRIVACY_CLASS_PREFIX}${privacyLevel}`;\n}\n//# sourceMappingURL=privacy.js.map","import { safeTruncate } from '@datadog/browser-core';\nimport { NodePrivacyLevel, getPrivacySelector } from '../privacy';\n/**\n * Get the action name from the attribute 'data-dd-action-name' on the element or any of its parent.\n * It can also be retrieved from a user defined attribute.\n */\nexport const DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE = 'data-dd-action-name';\nexport const ACTION_NAME_PLACEHOLDER = 'Masked Element';\nexport function getActionNameFromElement(element, { enablePrivacyForActionName, actionNameAttribute: userProgrammaticAttribute }, nodePrivacyLevel) {\n    // Proceed to get the action name in two steps:\n    // * first, get the name programmatically, explicitly defined by the user.\n    // * then, if privacy is set to mask, return a placeholder for the undefined.\n    // * if privacy is not set to mask, use strategies that are known to return good results.\n    //   Those strategies will be used on the element and a few parents, but it's likely that they won't succeed at all.\n    // * if no name is found this way, use strategies returning less accurate names as a fallback.\n    //   Those are much likely to succeed.\n    const defaultActionName = getActionNameFromElementProgrammatically(element, DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE) ||\n        (userProgrammaticAttribute && getActionNameFromElementProgrammatically(element, userProgrammaticAttribute));\n    if (defaultActionName) {\n        return { name: defaultActionName, nameSource: \"custom_attribute\" /* ActionNameSource.CUSTOM_ATTRIBUTE */ };\n    }\n    else if (nodePrivacyLevel === NodePrivacyLevel.MASK) {\n        return { name: ACTION_NAME_PLACEHOLDER, nameSource: \"mask_placeholder\" /* ActionNameSource.MASK_PLACEHOLDER */ };\n    }\n    return (getActionNameFromElementForStrategies(element, userProgrammaticAttribute, priorityStrategies, enablePrivacyForActionName) ||\n        getActionNameFromElementForStrategies(element, userProgrammaticAttribute, fallbackStrategies, enablePrivacyForActionName) || { name: '', nameSource: \"blank\" /* ActionNameSource.BLANK */ });\n}\nfunction getActionNameFromElementProgrammatically(targetElement, programmaticAttribute) {\n    // We don't use getActionNameFromElementForStrategies here, because we want to consider all parents,\n    // without limit. It is up to the user to declare a relevant naming strategy.\n    const elementWithAttribute = targetElement.closest(`[${programmaticAttribute}]`);\n    if (!elementWithAttribute) {\n        return;\n    }\n    const name = elementWithAttribute.getAttribute(programmaticAttribute);\n    return truncate(normalizeWhitespace(name.trim()));\n}\nconst priorityStrategies = [\n    // associated LABEL text\n    (element, userProgrammaticAttribute) => {\n        if ('labels' in element && element.labels && element.labels.length > 0) {\n            return getActionNameFromTextualContent(element.labels[0], userProgrammaticAttribute);\n        }\n    },\n    // INPUT button (and associated) value\n    (element) => {\n        if (element.nodeName === 'INPUT') {\n            const input = element;\n            const type = input.getAttribute('type');\n            if (type === 'button' || type === 'submit' || type === 'reset') {\n                return { name: input.value, nameSource: \"text_content\" /* ActionNameSource.TEXT_CONTENT */ };\n            }\n        }\n    },\n    // BUTTON, LABEL or button-like element text\n    (element, userProgrammaticAttribute, privacyEnabledActionName) => {\n        if (element.nodeName === 'BUTTON' || element.nodeName === 'LABEL' || element.getAttribute('role') === 'button') {\n            return getActionNameFromTextualContent(element, userProgrammaticAttribute, privacyEnabledActionName);\n        }\n    },\n    (element) => getActionNameFromStandardAttribute(element, 'aria-label'),\n    // associated element text designated by the aria-labelledby attribute\n    (element, userProgrammaticAttribute, privacyEnabledActionName) => {\n        const labelledByAttribute = element.getAttribute('aria-labelledby');\n        if (labelledByAttribute) {\n            return {\n                name: labelledByAttribute\n                    .split(/\\s+/)\n                    .map((id) => getElementById(element, id))\n                    .filter((label) => Boolean(label))\n                    .map((element) => getTextualContent(element, userProgrammaticAttribute, privacyEnabledActionName))\n                    .join(' '),\n                nameSource: \"text_content\" /* ActionNameSource.TEXT_CONTENT */,\n            };\n        }\n    },\n    (element) => getActionNameFromStandardAttribute(element, 'alt'),\n    (element) => getActionNameFromStandardAttribute(element, 'name'),\n    (element) => getActionNameFromStandardAttribute(element, 'title'),\n    (element) => getActionNameFromStandardAttribute(element, 'placeholder'),\n    // SELECT first OPTION text\n    (element, userProgrammaticAttribute) => {\n        if ('options' in element && element.options.length > 0) {\n            return getActionNameFromTextualContent(element.options[0], userProgrammaticAttribute);\n        }\n    },\n];\nconst fallbackStrategies = [\n    (element, userProgrammaticAttribute, privacyEnabledActionName) => getActionNameFromTextualContent(element, userProgrammaticAttribute, privacyEnabledActionName),\n];\n/**\n * Iterates over the target element and its parent, using the strategies list to get an action name.\n * Each strategies are applied on each element, stopping as soon as a non-empty value is returned.\n */\nconst MAX_PARENTS_TO_CONSIDER = 10;\nfunction getActionNameFromElementForStrategies(targetElement, userProgrammaticAttribute, strategies, privacyEnabledActionName) {\n    let element = targetElement;\n    let recursionCounter = 0;\n    while (recursionCounter <= MAX_PARENTS_TO_CONSIDER &&\n        element &&\n        element.nodeName !== 'BODY' &&\n        element.nodeName !== 'HTML' &&\n        element.nodeName !== 'HEAD') {\n        for (const strategy of strategies) {\n            const actionName = strategy(element, userProgrammaticAttribute, privacyEnabledActionName);\n            if (actionName) {\n                const { name, nameSource } = actionName;\n                const trimmedName = name && name.trim();\n                if (trimmedName) {\n                    return { name: truncate(normalizeWhitespace(trimmedName)), nameSource };\n                }\n            }\n        }\n        // Consider a FORM as a contextual limit to get the action name.  This is experimental and may\n        // be reconsidered in the future.\n        if (element.nodeName === 'FORM') {\n            break;\n        }\n        element = element.parentElement;\n        recursionCounter += 1;\n    }\n}\nfunction normalizeWhitespace(s) {\n    return s.replace(/\\s+/g, ' ');\n}\nfunction truncate(s) {\n    return s.length > 100 ? `${safeTruncate(s, 100)} [...]` : s;\n}\nfunction getElementById(refElement, id) {\n    // Use the element ownerDocument here, because tests are executed in an iframe, so\n    // document.getElementById won't work.\n    return refElement.ownerDocument ? refElement.ownerDocument.getElementById(id) : null;\n}\nfunction getActionNameFromStandardAttribute(element, attribute) {\n    return {\n        name: element.getAttribute(attribute) || '',\n        nameSource: \"standard_attribute\" /* ActionNameSource.STANDARD_ATTRIBUTE */,\n    };\n}\nfunction getActionNameFromTextualContent(element, userProgrammaticAttribute, privacyEnabledActionName) {\n    return {\n        name: getTextualContent(element, userProgrammaticAttribute, privacyEnabledActionName) || '',\n        nameSource: \"text_content\" /* ActionNameSource.TEXT_CONTENT */,\n    };\n}\nfunction getTextualContent(element, userProgrammaticAttribute, privacyEnabledActionName) {\n    if (element.isContentEditable) {\n        return;\n    }\n    if ('innerText' in element) {\n        let text = element.innerText;\n        const removeTextFromElements = (query) => {\n            const list = element.querySelectorAll(query);\n            for (let index = 0; index < list.length; index += 1) {\n                const element = list[index];\n                if ('innerText' in element) {\n                    const textToReplace = element.innerText;\n                    if (textToReplace && textToReplace.trim().length > 0) {\n                        text = text.replace(textToReplace, '');\n                    }\n                }\n            }\n        };\n        // remove the text of elements with programmatic attribute value\n        removeTextFromElements(`[${DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE}]`);\n        if (userProgrammaticAttribute) {\n            removeTextFromElements(`[${userProgrammaticAttribute}]`);\n        }\n        if (privacyEnabledActionName) {\n            // remove the text of elements with privacy override\n            removeTextFromElements(`${getPrivacySelector(NodePrivacyLevel.HIDDEN)}, ${getPrivacySelector(NodePrivacyLevel.MASK)}`);\n        }\n        return text;\n    }\n    return element.textContent;\n}\n//# sourceMappingURL=getActionNameFromElement.js.map","import { DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE } from './action/getActionNameFromElement';\n/**\n * Stable attributes are attributes that are commonly used to identify parts of a UI (ex:\n * component). Those attribute values should not be generated randomly (hardcoded most of the time)\n * and stay the same across deploys. They are not necessarily unique across the document.\n */\nexport const STABLE_ATTRIBUTES = [\n    DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE,\n    // Common test attributes (list provided by google recorder)\n    'data-testid',\n    'data-test',\n    'data-qa',\n    'data-cy',\n    'data-test-id',\n    'data-qa-id',\n    'data-testing',\n    // FullStory decorator attributes:\n    'data-component',\n    'data-element',\n    'data-source-file',\n];\n// Selectors to use if they target a single element on the whole document. Those selectors are\n// considered as \"stable\" and uniquely identify an element regardless of the page state. If we find\n// one, we should consider the selector \"complete\" and stop iterating over ancestors.\nconst GLOBALLY_UNIQUE_SELECTOR_GETTERS = [getStableAttributeSelector, getIDSelector];\n// Selectors to use if they target a single element among an element descendants. Those selectors\n// are more brittle than \"globally unique\" selectors and should be combined with ancestor selectors\n// to improve specificity.\nconst UNIQUE_AMONG_CHILDREN_SELECTOR_GETTERS = [\n    getStableAttributeSelector,\n    getClassSelector,\n    getTagNameSelector,\n];\nexport function getSelectorFromElement(targetElement, actionNameAttribute) {\n    if (!isConnected(targetElement)) {\n        // We cannot compute a selector for a detached element, as we don't have access to all of its\n        // parents, and we cannot determine if it's unique in the document.\n        return;\n    }\n    let targetElementSelector;\n    let currentElement = targetElement;\n    while (currentElement && currentElement.nodeName !== 'HTML') {\n        const globallyUniqueSelector = findSelector(currentElement, GLOBALLY_UNIQUE_SELECTOR_GETTERS, isSelectorUniqueGlobally, actionNameAttribute, targetElementSelector);\n        if (globallyUniqueSelector) {\n            return globallyUniqueSelector;\n        }\n        const uniqueSelectorAmongChildren = findSelector(currentElement, UNIQUE_AMONG_CHILDREN_SELECTOR_GETTERS, isSelectorUniqueAmongSiblings, actionNameAttribute, targetElementSelector);\n        targetElementSelector =\n            uniqueSelectorAmongChildren || combineSelector(getPositionSelector(currentElement), targetElementSelector);\n        currentElement = currentElement.parentElement;\n    }\n    return targetElementSelector;\n}\nfunction isGeneratedValue(value) {\n    // To compute the \"URL path group\", the backend replaces every URL path parts as a question mark\n    // if it thinks the part is an identifier. The condition it uses is to checks whether a digit is\n    // present.\n    //\n    // Here, we use the same strategy: if the value contains a digit, we consider it generated. This\n    // strategy might be a bit naive and fail in some cases, but there are many fallbacks to generate\n    // CSS selectors so it should be fine most of the time.\n    return /[0-9]/.test(value);\n}\nfunction getIDSelector(element) {\n    if (element.id && !isGeneratedValue(element.id)) {\n        return `#${CSS.escape(element.id)}`;\n    }\n}\nfunction getClassSelector(element) {\n    if (element.tagName === 'BODY') {\n        return;\n    }\n    const classList = element.classList;\n    for (let i = 0; i < classList.length; i += 1) {\n        const className = classList[i];\n        if (isGeneratedValue(className)) {\n            continue;\n        }\n        return `${CSS.escape(element.tagName)}.${CSS.escape(className)}`;\n    }\n}\nfunction getTagNameSelector(element) {\n    return CSS.escape(element.tagName);\n}\nfunction getStableAttributeSelector(element, actionNameAttribute) {\n    if (actionNameAttribute) {\n        const selector = getAttributeSelector(actionNameAttribute);\n        if (selector) {\n            return selector;\n        }\n    }\n    for (const attributeName of STABLE_ATTRIBUTES) {\n        const selector = getAttributeSelector(attributeName);\n        if (selector) {\n            return selector;\n        }\n    }\n    function getAttributeSelector(attributeName) {\n        if (element.hasAttribute(attributeName)) {\n            return `${CSS.escape(element.tagName)}[${attributeName}=\"${CSS.escape(element.getAttribute(attributeName))}\"]`;\n        }\n    }\n}\nfunction getPositionSelector(element) {\n    let sibling = element.parentElement.firstElementChild;\n    let elementIndex = 1;\n    while (sibling && sibling !== element) {\n        if (sibling.tagName === element.tagName) {\n            elementIndex += 1;\n        }\n        sibling = sibling.nextElementSibling;\n    }\n    return `${CSS.escape(element.tagName)}:nth-of-type(${elementIndex})`;\n}\nfunction findSelector(element, selectorGetters, predicate, actionNameAttribute, childSelector) {\n    for (const selectorGetter of selectorGetters) {\n        const elementSelector = selectorGetter(element, actionNameAttribute);\n        if (!elementSelector) {\n            continue;\n        }\n        if (predicate(element, elementSelector, childSelector)) {\n            return combineSelector(elementSelector, childSelector);\n        }\n    }\n}\n/**\n * Check whether the selector is unique among the whole document.\n */\nfunction isSelectorUniqueGlobally(element, elementSelector, childSelector) {\n    return element.ownerDocument.querySelectorAll(combineSelector(elementSelector, childSelector)).length === 1;\n}\n/**\n * Check whether the selector is unique among the element siblings. In other words, it returns true\n * if \"ELEMENT_PARENT > CHILD_SELECTOR\" returns a single element.\n *\n * @param {Element} currentElement - the element being considered while iterating over the target\n * element ancestors.\n *\n * @param {string} currentElementSelector - a selector that matches the current element. That\n * selector is not a composed selector (i.e. it might be a single tag name, class name...).\n *\n * @param {string|undefined} childSelector - child selector is a selector that targets a descendant\n * of the current element. When undefined, the current element is the target element.\n *\n * # Scope selector usage\n *\n * When composed together, the final selector will be joined with `>` operators to make sure we\n * target direct descendants at each level. In this function, we'll use `querySelector` to check if\n * a selector matches descendants of the current element. But by default, the query selector match\n * elements at any level. Example:\n *\n * ```html\n * <main>\n *   <div>\n *     <span></span>\n *   </div>\n *   <marquee>\n *     <div>\n *       <span></span>\n *     </div>\n *   </marquee>\n * </main>\n * ```\n *\n * `sibling.querySelector('DIV > SPAN')` will match both span elements, so we would consider the\n * selector to be not unique, even if it is unique when we'll compose it with the parent with a `>`\n * operator (`MAIN > DIV > SPAN`).\n *\n * To avoid this, we can use the `:scope` selector to make sure the selector starts from the current\n * sibling (i.e. `sibling.querySelector('DIV:scope > SPAN')` will only match the first span).\n *\n * The result will be less accurate on browsers that don't support :scope (i. e. IE): it will check\n * for any element matching the selector contained in the parent (in other words,\n * \"ELEMENT_PARENT CHILD_SELECTOR\" returns a single element), regardless of whether the selector is\n * a direct descendant of the element parent. This should not impact results too much: if it\n * inaccurately returns false, we'll just fall back to another strategy.\n *\n * [1]: https://developer.mozilla.org/fr/docs/Web/CSS/:scope\n *\n * # Performance considerations\n *\n * We compute selectors in performance-critical operations (ex: during a click), so we need to make\n * sure the function is as fast as possible. We observed that naively using `querySelectorAll` to\n * check if the selector matches more than 1 element is quite expensive, so we want to avoid it.\n *\n * Because we are iterating the DOM upward and we use that function at every level, we know the\n * child selector is already unique among the current element children, so we don't need to check\n * for the current element subtree.\n *\n * Instead, we can focus on the current element siblings. If we find a single element matching the\n * selector within a sibling, we know that it's not unique. This allows us to use `querySelector`\n * (or `matches`, when the current element is the target element) instead of `querySelectorAll`.\n */\nexport function isSelectorUniqueAmongSiblings(currentElement, currentElementSelector, childSelector) {\n    let isSiblingMatching;\n    if (childSelector === undefined) {\n        // If the child selector is undefined (meaning `currentElement` is the target element, not one\n        // of its ancestor), we need to use `matches` to check if the sibling is matching the selector,\n        // as `querySelector` only returns a descendant of the element.\n        isSiblingMatching = (sibling) => sibling.matches(currentElementSelector);\n    }\n    else {\n        const scopedSelector = supportScopeSelector()\n            ? combineSelector(`${currentElementSelector}:scope`, childSelector)\n            : combineSelector(currentElementSelector, childSelector);\n        isSiblingMatching = (sibling) => sibling.querySelector(scopedSelector) !== null;\n    }\n    const parent = currentElement.parentElement;\n    let sibling = parent.firstElementChild;\n    while (sibling) {\n        if (sibling !== currentElement && isSiblingMatching(sibling)) {\n            return false;\n        }\n        sibling = sibling.nextElementSibling;\n    }\n    return true;\n}\nfunction combineSelector(parent, child) {\n    return child ? `${parent}>${child}` : parent;\n}\nlet supportScopeSelectorCache;\nexport function supportScopeSelector() {\n    if (supportScopeSelectorCache === undefined) {\n        try {\n            document.querySelector(':scope');\n            supportScopeSelectorCache = true;\n        }\n        catch (_a) {\n            supportScopeSelectorCache = false;\n        }\n    }\n    return supportScopeSelectorCache;\n}\n/**\n * Polyfill-utility for the `isConnected` property not supported in Edge <=18\n */\nfunction isConnected(element) {\n    if ('isConnected' in\n        // cast is to make sure `element` is not inferred as `never` after the check\n        element) {\n        return element.isConnected;\n    }\n    return element.ownerDocument.documentElement.contains(element);\n}\n//# sourceMappingURL=getSelectorFromElement.js.map","import { ONE_SECOND, clearTimeout, setTimeout } from '@datadog/browser-core';\nexport const MAX_DURATION_BETWEEN_CLICKS = ONE_SECOND;\nexport const MAX_DISTANCE_BETWEEN_CLICKS = 100;\nexport function createClickChain(firstClick, onFinalize) {\n    const bufferedClicks = [];\n    let status = 0 /* ClickChainStatus.WaitingForMoreClicks */;\n    let maxDurationBetweenClicksTimeoutId;\n    appendClick(firstClick);\n    function appendClick(click) {\n        click.stopObservable.subscribe(tryFinalize);\n        bufferedClicks.push(click);\n        clearTimeout(maxDurationBetweenClicksTimeoutId);\n        maxDurationBetweenClicksTimeoutId = setTimeout(dontAcceptMoreClick, MAX_DURATION_BETWEEN_CLICKS);\n    }\n    function tryFinalize() {\n        if (status === 1 /* ClickChainStatus.WaitingForClicksToStop */ && bufferedClicks.every((click) => click.isStopped())) {\n            status = 2 /* ClickChainStatus.Finalized */;\n            onFinalize(bufferedClicks);\n        }\n    }\n    function dontAcceptMoreClick() {\n        clearTimeout(maxDurationBetweenClicksTimeoutId);\n        if (status === 0 /* ClickChainStatus.WaitingForMoreClicks */) {\n            status = 1 /* ClickChainStatus.WaitingForClicksToStop */;\n            tryFinalize();\n        }\n    }\n    return {\n        tryAppend: (click) => {\n            if (status !== 0 /* ClickChainStatus.WaitingForMoreClicks */) {\n                return false;\n            }\n            if (bufferedClicks.length > 0 &&\n                !areEventsSimilar(bufferedClicks[bufferedClicks.length - 1].event, click.event)) {\n                dontAcceptMoreClick();\n                return false;\n            }\n            appendClick(click);\n            return true;\n        },\n        stop: () => {\n            dontAcceptMoreClick();\n        },\n    };\n}\n/**\n * Checks whether two events are similar by comparing their target, position and timestamp\n */\nfunction areEventsSimilar(first, second) {\n    return (first.target === second.target &&\n        mouseEventDistance(first, second) <= MAX_DISTANCE_BETWEEN_CLICKS &&\n        first.timeStamp - second.timeStamp <= MAX_DURATION_BETWEEN_CLICKS);\n}\nfunction mouseEventDistance(origin, other) {\n    return Math.sqrt(Math.pow(origin.clientX - other.clientX, 2) + Math.pow(origin.clientY - other.clientY, 2));\n}\n//# sourceMappingURL=clickChain.js.map","import { addEventListener } from '@datadog/browser-core';\nexport function listenActionEvents(configuration, { onPointerDown, onPointerUp }) {\n    let selectionEmptyAtPointerDown;\n    let userActivity = {\n        selection: false,\n        input: false,\n        scroll: false,\n    };\n    let clickContext;\n    const listeners = [\n        addEventListener(configuration, window, \"pointerdown\" /* DOM_EVENT.POINTER_DOWN */, (event) => {\n            if (isValidPointerEvent(event)) {\n                selectionEmptyAtPointerDown = isSelectionEmpty();\n                userActivity = {\n                    selection: false,\n                    input: false,\n                    scroll: false,\n                };\n                clickContext = onPointerDown(event);\n            }\n        }, { capture: true }),\n        addEventListener(configuration, window, \"selectionchange\" /* DOM_EVENT.SELECTION_CHANGE */, () => {\n            if (!selectionEmptyAtPointerDown || !isSelectionEmpty()) {\n                userActivity.selection = true;\n            }\n        }, { capture: true }),\n        addEventListener(configuration, window, \"scroll\" /* DOM_EVENT.SCROLL */, () => {\n            userActivity.scroll = true;\n        }, { capture: true, passive: true }),\n        addEventListener(configuration, window, \"pointerup\" /* DOM_EVENT.POINTER_UP */, (event) => {\n            if (isValidPointerEvent(event) && clickContext) {\n                // Use a scoped variable to make sure the value is not changed by other clicks\n                const localUserActivity = userActivity;\n                onPointerUp(clickContext, event, () => localUserActivity);\n                clickContext = undefined;\n            }\n        }, { capture: true }),\n        addEventListener(configuration, window, \"input\" /* DOM_EVENT.INPUT */, () => {\n            userActivity.input = true;\n        }, { capture: true }),\n    ];\n    return {\n        stop: () => {\n            listeners.forEach((listener) => listener.stop());\n        },\n    };\n}\nfunction isSelectionEmpty() {\n    const selection = window.getSelection();\n    return !selection || selection.isCollapsed;\n}\nfunction isValidPointerEvent(event) {\n    return (event.target instanceof Element &&\n        // Only consider 'primary' pointer events for now. Multi-touch support could be implemented in\n        // the future.\n        event.isPrimary !== false);\n}\n//# sourceMappingURL=listenActionEvents.js.map","import { ONE_SECOND } from '@datadog/browser-core';\nconst MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE = 3;\nexport function computeFrustration(clicks, rageClick) {\n    if (isRage(clicks)) {\n        rageClick.addFrustration(\"rage_click\" /* FrustrationType.RAGE_CLICK */);\n        if (clicks.some(isDead)) {\n            rageClick.addFrustration(\"dead_click\" /* FrustrationType.DEAD_CLICK */);\n        }\n        if (rageClick.hasError) {\n            rageClick.addFrustration(\"error_click\" /* FrustrationType.ERROR_CLICK */);\n        }\n        return { isRage: true };\n    }\n    const hasSelectionChanged = clicks.some((click) => click.getUserActivity().selection);\n    clicks.forEach((click) => {\n        if (click.hasError) {\n            click.addFrustration(\"error_click\" /* FrustrationType.ERROR_CLICK */);\n        }\n        if (isDead(click) &&\n            // Avoid considering clicks part of a double-click or triple-click selections as dead clicks\n            !hasSelectionChanged) {\n            click.addFrustration(\"dead_click\" /* FrustrationType.DEAD_CLICK */);\n        }\n    });\n    return { isRage: false };\n}\nexport function isRage(clicks) {\n    if (clicks.some((click) => click.getUserActivity().selection || click.getUserActivity().scroll)) {\n        return false;\n    }\n    for (let i = 0; i < clicks.length - (MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE - 1); i += 1) {\n        if (clicks[i + MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE - 1].event.timeStamp - clicks[i].event.timeStamp <=\n            ONE_SECOND) {\n            return true;\n        }\n    }\n    return false;\n}\nconst DEAD_CLICK_EXCLUDE_SELECTOR = \n// inputs that don't trigger a meaningful event like \"input\" when clicked, including textual\n// inputs (using a negative selector is shorter here)\n'input:not([type=\"checkbox\"]):not([type=\"radio\"]):not([type=\"button\"]):not([type=\"submit\"]):not([type=\"reset\"]):not([type=\"range\"]),' +\n    'textarea,' +\n    'select,' +\n    // contenteditable and their descendants don't always trigger meaningful changes when manipulated\n    '[contenteditable],' +\n    '[contenteditable] *,' +\n    // canvas, as there is no good way to detect activity occurring on them\n    'canvas,' +\n    // links that are interactive (have an href attribute) or any of their descendants, as they can\n    // open a new tab or navigate to a hash without triggering a meaningful event\n    'a[href],' +\n    'a[href] *';\nexport function isDead(click) {\n    if (click.hasPageActivity || click.getUserActivity().input || click.getUserActivity().scroll) {\n        return false;\n    }\n    return !click.event.target.matches(DEAD_CLICK_EXCLUDE_SELECTOR);\n}\n//# sourceMappingURL=computeFrustration.js.map","import { elapsed, ONE_SECOND, relativeNow } from '@datadog/browser-core';\n// Maximum duration for click actions\nexport const CLICK_ACTION_MAX_DURATION = 10 * ONE_SECOND;\nexport const interactionSelectorCache = new Map();\nexport function getInteractionSelector(relativeTimestamp) {\n    const selector = interactionSelectorCache.get(relativeTimestamp);\n    interactionSelectorCache.delete(relativeTimestamp);\n    return selector;\n}\nexport function updateInteractionSelector(relativeTimestamp, selector) {\n    interactionSelectorCache.set(relativeTimestamp, selector);\n    interactionSelectorCache.forEach((_, relativeTimestamp) => {\n        if (elapsed(relativeTimestamp, relativeNow()) > CLICK_ACTION_MAX_DURATION) {\n            interactionSelectorCache.delete(relativeTimestamp);\n        }\n    });\n}\n//# sourceMappingURL=interactionSelectorCache.js.map","import { timeStampNow, Observable, getRelativeTime, ONE_MINUTE, generateUUID, clocksNow, elapsed, createValueHistory, } from '@datadog/browser-core';\nimport { trackEventCounts } from '../trackEventCounts';\nimport { PAGE_ACTIVITY_VALIDATION_DELAY, waitPageActivityEnd } from '../waitPageActivityEnd';\nimport { getSelectorFromElement } from '../getSelectorFromElement';\nimport { getNodePrivacyLevel, NodePrivacyLevel } from '../privacy';\nimport { createClickChain } from './clickChain';\nimport { getActionNameFromElement } from './getActionNameFromElement';\nimport { listenActionEvents } from './listenActionEvents';\nimport { computeFrustration } from './computeFrustration';\nimport { CLICK_ACTION_MAX_DURATION, updateInteractionSelector } from './interactionSelectorCache';\nexport const ACTION_CONTEXT_TIME_OUT_DELAY = 5 * ONE_MINUTE; // arbitrary\nexport function trackClickActions(lifeCycle, domMutationObservable, windowOpenObservable, configuration) {\n    const history = createValueHistory({ expireDelay: ACTION_CONTEXT_TIME_OUT_DELAY });\n    const stopObservable = new Observable();\n    let currentClickChain;\n    lifeCycle.subscribe(9 /* LifeCycleEventType.SESSION_RENEWED */, () => {\n        history.reset();\n    });\n    lifeCycle.subscribe(4 /* LifeCycleEventType.VIEW_ENDED */, stopClickChain);\n    const { stop: stopActionEventsListener } = listenActionEvents(configuration, {\n        onPointerDown: (pointerDownEvent) => processPointerDown(configuration, lifeCycle, domMutationObservable, pointerDownEvent, windowOpenObservable),\n        onPointerUp: ({ clickActionBase, hadActivityOnPointerDown }, startEvent, getUserActivity) => {\n            startClickAction(configuration, lifeCycle, domMutationObservable, windowOpenObservable, history, stopObservable, appendClickToClickChain, clickActionBase, startEvent, getUserActivity, hadActivityOnPointerDown);\n        },\n    });\n    const actionContexts = {\n        findActionId: (startTime) => history.findAll(startTime),\n    };\n    return {\n        stop: () => {\n            stopClickChain();\n            stopObservable.notify();\n            stopActionEventsListener();\n        },\n        actionContexts,\n    };\n    function appendClickToClickChain(click) {\n        if (!currentClickChain || !currentClickChain.tryAppend(click)) {\n            const rageClick = click.clone();\n            currentClickChain = createClickChain(click, (clicks) => {\n                finalizeClicks(clicks, rageClick);\n            });\n        }\n    }\n    function stopClickChain() {\n        if (currentClickChain) {\n            currentClickChain.stop();\n        }\n    }\n}\nfunction processPointerDown(configuration, lifeCycle, domMutationObservable, pointerDownEvent, windowOpenObservable) {\n    const nodePrivacyLevel = configuration.enablePrivacyForActionName\n        ? getNodePrivacyLevel(pointerDownEvent.target, configuration.defaultPrivacyLevel)\n        : NodePrivacyLevel.ALLOW;\n    if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n        return undefined;\n    }\n    const clickActionBase = computeClickActionBase(pointerDownEvent, nodePrivacyLevel, configuration);\n    let hadActivityOnPointerDown = false;\n    waitPageActivityEnd(lifeCycle, domMutationObservable, windowOpenObservable, configuration, (pageActivityEndEvent) => {\n        hadActivityOnPointerDown = pageActivityEndEvent.hadActivity;\n    }, \n    // We don't care about the activity duration, we just want to know whether an activity did happen\n    // within the \"validation delay\" or not. Limit the duration so the callback is called sooner.\n    PAGE_ACTIVITY_VALIDATION_DELAY);\n    return { clickActionBase, hadActivityOnPointerDown: () => hadActivityOnPointerDown };\n}\nfunction startClickAction(configuration, lifeCycle, domMutationObservable, windowOpenObservable, history, stopObservable, appendClickToClickChain, clickActionBase, startEvent, getUserActivity, hadActivityOnPointerDown) {\n    var _a;\n    const click = newClick(lifeCycle, history, getUserActivity, clickActionBase, startEvent);\n    appendClickToClickChain(click);\n    const selector = (_a = clickActionBase === null || clickActionBase === void 0 ? void 0 : clickActionBase.target) === null || _a === void 0 ? void 0 : _a.selector;\n    if (selector) {\n        updateInteractionSelector(startEvent.timeStamp, selector);\n    }\n    const { stop: stopWaitPageActivityEnd } = waitPageActivityEnd(lifeCycle, domMutationObservable, windowOpenObservable, configuration, (pageActivityEndEvent) => {\n        if (pageActivityEndEvent.hadActivity && pageActivityEndEvent.end < click.startClocks.timeStamp) {\n            // If the clock is looking weird, just discard the click\n            click.discard();\n        }\n        else {\n            if (pageActivityEndEvent.hadActivity) {\n                click.stop(pageActivityEndEvent.end);\n            }\n            else if (hadActivityOnPointerDown()) {\n                click.stop(\n                // using the click start as activity end, so the click will have some activity but its\n                // duration will be 0 (as the activity started before the click start)\n                click.startClocks.timeStamp);\n            }\n            else {\n                click.stop();\n            }\n        }\n    }, CLICK_ACTION_MAX_DURATION);\n    const viewEndedSubscription = lifeCycle.subscribe(4 /* LifeCycleEventType.VIEW_ENDED */, ({ endClocks }) => {\n        click.stop(endClocks.timeStamp);\n    });\n    const stopSubscription = stopObservable.subscribe(() => {\n        click.stop();\n    });\n    click.stopObservable.subscribe(() => {\n        viewEndedSubscription.unsubscribe();\n        stopWaitPageActivityEnd();\n        stopSubscription.unsubscribe();\n    });\n}\nfunction computeClickActionBase(event, nodePrivacyLevel, configuration) {\n    const rect = event.target.getBoundingClientRect();\n    const selector = getSelectorFromElement(event.target, configuration.actionNameAttribute);\n    if (selector) {\n        updateInteractionSelector(event.timeStamp, selector);\n    }\n    const actionName = getActionNameFromElement(event.target, configuration, nodePrivacyLevel);\n    return {\n        type: \"click\" /* ActionType.CLICK */,\n        target: {\n            width: Math.round(rect.width),\n            height: Math.round(rect.height),\n            selector,\n        },\n        position: {\n            // Use clientX and Y because for SVG element offsetX and Y are relatives to the <svg> element\n            x: Math.round(event.clientX - rect.left),\n            y: Math.round(event.clientY - rect.top),\n        },\n        name: actionName.name,\n        nameSource: actionName.nameSource,\n    };\n}\nfunction newClick(lifeCycle, history, getUserActivity, clickActionBase, startEvent) {\n    const id = generateUUID();\n    const startClocks = clocksNow();\n    const historyEntry = history.add(id, startClocks.relative);\n    const eventCountsSubscription = trackEventCounts({\n        lifeCycle,\n        isChildEvent: (event) => event.action !== undefined &&\n            (Array.isArray(event.action.id) ? event.action.id.includes(id) : event.action.id === id),\n    });\n    let status = 0 /* ClickStatus.ONGOING */;\n    let activityEndTime;\n    const frustrationTypes = [];\n    const stopObservable = new Observable();\n    function stop(newActivityEndTime) {\n        if (status !== 0 /* ClickStatus.ONGOING */) {\n            return;\n        }\n        activityEndTime = newActivityEndTime;\n        status = 1 /* ClickStatus.STOPPED */;\n        if (activityEndTime) {\n            historyEntry.close(getRelativeTime(activityEndTime));\n        }\n        else {\n            historyEntry.remove();\n        }\n        eventCountsSubscription.stop();\n        stopObservable.notify();\n    }\n    return {\n        event: startEvent,\n        stop,\n        stopObservable,\n        get hasError() {\n            return eventCountsSubscription.eventCounts.errorCount > 0;\n        },\n        get hasPageActivity() {\n            return activityEndTime !== undefined;\n        },\n        getUserActivity,\n        addFrustration: (frustrationType) => {\n            frustrationTypes.push(frustrationType);\n        },\n        startClocks,\n        isStopped: () => status === 1 /* ClickStatus.STOPPED */ || status === 2 /* ClickStatus.FINALIZED */,\n        clone: () => newClick(lifeCycle, history, getUserActivity, clickActionBase, startEvent),\n        validate: (domEvents) => {\n            stop();\n            if (status !== 1 /* ClickStatus.STOPPED */) {\n                return;\n            }\n            const { resourceCount, errorCount, longTaskCount } = eventCountsSubscription.eventCounts;\n            const clickAction = {\n                duration: activityEndTime && elapsed(startClocks.timeStamp, activityEndTime),\n                startClocks,\n                id,\n                frustrationTypes,\n                counts: {\n                    resourceCount,\n                    errorCount,\n                    longTaskCount,\n                },\n                events: domEvents !== null && domEvents !== void 0 ? domEvents : [startEvent],\n                event: startEvent,\n                ...clickActionBase,\n            };\n            lifeCycle.notify(0 /* LifeCycleEventType.AUTO_ACTION_COMPLETED */, clickAction);\n            status = 2 /* ClickStatus.FINALIZED */;\n        },\n        discard: () => {\n            stop();\n            status = 2 /* ClickStatus.FINALIZED */;\n        },\n    };\n}\nexport function finalizeClicks(clicks, rageClick) {\n    const { isRage } = computeFrustration(clicks, rageClick);\n    if (isRage) {\n        clicks.forEach((click) => click.discard());\n        rageClick.stop(timeStampNow());\n        rageClick.validate(clicks.map((click) => click.event));\n    }\n    else {\n        rageClick.discard();\n        clicks.forEach((click) => click.validate());\n    }\n}\n//# sourceMappingURL=trackClickActions.js.map","import { noop, combine, toServerDuration, generateUUID, ExperimentalFeature, isExperimentalFeatureEnabled, } from '@datadog/browser-core';\nimport { discardNegativeDuration } from '../discardNegativeDuration';\nimport { trackClickActions } from './trackClickActions';\nexport function startActionCollection(lifeCycle, domMutationObservable, windowOpenObservable, configuration, pageStateHistory) {\n    lifeCycle.subscribe(0 /* LifeCycleEventType.AUTO_ACTION_COMPLETED */, (action) => lifeCycle.notify(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, processAction(action, pageStateHistory)));\n    let actionContexts = { findActionId: noop };\n    let stop = noop;\n    if (configuration.trackUserInteractions) {\n        ;\n        ({ actionContexts, stop } = trackClickActions(lifeCycle, domMutationObservable, windowOpenObservable, configuration));\n    }\n    return {\n        addAction: (action, savedCommonContext) => {\n            lifeCycle.notify(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, {\n                savedCommonContext,\n                ...processAction(action, pageStateHistory),\n            });\n        },\n        actionContexts,\n        stop,\n    };\n}\nfunction processAction(action, pageStateHistory) {\n    const autoActionProperties = isAutoAction(action)\n        ? {\n            action: {\n                id: action.id,\n                loading_time: discardNegativeDuration(toServerDuration(action.duration)),\n                frustration: {\n                    type: action.frustrationTypes,\n                },\n                error: {\n                    count: action.counts.errorCount,\n                },\n                long_task: {\n                    count: action.counts.longTaskCount,\n                },\n                resource: {\n                    count: action.counts.resourceCount,\n                },\n            },\n            _dd: {\n                action: {\n                    target: action.target,\n                    position: action.position,\n                    name_source: isExperimentalFeatureEnabled(ExperimentalFeature.ACTION_NAME_MASKING)\n                        ? action.nameSource\n                        : undefined,\n                },\n            },\n        }\n        : undefined;\n    const customerContext = !isAutoAction(action) ? action.context : undefined;\n    const actionEvent = combine({\n        action: {\n            id: generateUUID(),\n            target: {\n                name: action.name,\n            },\n            type: action.type,\n        },\n        date: action.startClocks.timeStamp,\n        type: \"action\" /* RumEventType.ACTION */,\n        view: { in_foreground: pageStateHistory.wasInPageStateAt(\"active\" /* PageState.ACTIVE */, action.startClocks.relative) },\n    }, autoActionProperties);\n    const domainContext = isAutoAction(action) ? { events: action.events } : {};\n    if (!isAutoAction(action) && action.handlingStack) {\n        domainContext.handlingStack = action.handlingStack;\n    }\n    return {\n        customerContext,\n        rawRumEvent: actionEvent,\n        startTime: action.startClocks.relative,\n        domainContext,\n    };\n}\nfunction isAutoAction(action) {\n    return action.type !== \"custom\" /* ActionType.CUSTOM */;\n}\n//# sourceMappingURL=actionCollection.js.map","import { instrumentMethod } from '../../tools/instrumentMethod';\nimport { clocksNow } from '../../tools/utils/timeUtils';\nimport { computeStackTrace, computeStackTraceFromOnErrorMessage } from '../../tools/stackTrace/computeStackTrace';\nimport { computeRawError, isError } from './error';\nimport { ErrorSource } from './error.types';\nexport function trackRuntimeError(errorObservable) {\n    const handleRuntimeError = (stackTrace, originalError) => {\n        const rawError = computeRawError({\n            stackTrace,\n            originalError,\n            startClocks: clocksNow(),\n            nonErrorPrefix: \"Uncaught\" /* NonErrorPrefix.UNCAUGHT */,\n            source: ErrorSource.SOURCE,\n            handling: \"unhandled\" /* ErrorHandling.UNHANDLED */,\n        });\n        errorObservable.notify(rawError);\n    };\n    const { stop: stopInstrumentingOnError } = instrumentOnError(handleRuntimeError);\n    const { stop: stopInstrumentingOnUnhandledRejection } = instrumentUnhandledRejection(handleRuntimeError);\n    return {\n        stop: () => {\n            stopInstrumentingOnError();\n            stopInstrumentingOnUnhandledRejection();\n        },\n    };\n}\nexport function instrumentOnError(callback) {\n    return instrumentMethod(window, 'onerror', ({ parameters: [messageObj, url, line, column, errorObj] }) => {\n        let stackTrace;\n        if (isError(errorObj)) {\n            stackTrace = computeStackTrace(errorObj);\n        }\n        else {\n            stackTrace = computeStackTraceFromOnErrorMessage(messageObj, url, line, column);\n        }\n        callback(stackTrace, errorObj !== null && errorObj !== void 0 ? errorObj : messageObj);\n    });\n}\nexport function instrumentUnhandledRejection(callback) {\n    return instrumentMethod(window, 'onunhandledrejection', ({ parameters: [e] }) => {\n        const reason = e.reason || 'Empty reason';\n        const stack = computeStackTrace(reason);\n        callback(stack, reason);\n    });\n}\n//# sourceMappingURL=trackRuntimeError.js.map","import { flattenErrorCauses, isError, tryToGetFingerprint } from '../error/error';\nimport { mergeObservables, Observable } from '../../tools/observable';\nimport { ConsoleApiName, globalConsole } from '../../tools/display';\nimport { callMonitored } from '../../tools/monitor';\nimport { sanitize } from '../../tools/serialisation/sanitize';\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify';\nimport { ErrorSource } from '../error/error.types';\nimport { computeStackTrace } from '../../tools/stackTrace/computeStackTrace';\nimport { createHandlingStack, toStackTraceString, formatErrorMessage } from '../../tools/stackTrace/handlingStack';\nimport { clocksNow } from '../../tools/utils/timeUtils';\nlet consoleObservablesByApi = {};\nexport function initConsoleObservable(apis) {\n    const consoleObservables = apis.map((api) => {\n        if (!consoleObservablesByApi[api]) {\n            consoleObservablesByApi[api] = createConsoleObservable(api); // we are sure that the observable created for this api will yield the expected ConsoleLog type\n        }\n        return consoleObservablesByApi[api];\n    });\n    return mergeObservables(...consoleObservables);\n}\nexport function resetConsoleObservable() {\n    consoleObservablesByApi = {};\n}\nfunction createConsoleObservable(api) {\n    return new Observable((observable) => {\n        const originalConsoleApi = globalConsole[api];\n        globalConsole[api] = (...params) => {\n            originalConsoleApi.apply(console, params);\n            const handlingStack = createHandlingStack();\n            callMonitored(() => {\n                observable.notify(buildConsoleLog(params, api, handlingStack));\n            });\n        };\n        return () => {\n            globalConsole[api] = originalConsoleApi;\n        };\n    });\n}\nfunction buildConsoleLog(params, api, handlingStack) {\n    const message = params.map((param) => formatConsoleParameters(param)).join(' ');\n    let error;\n    if (api === ConsoleApiName.error) {\n        const firstErrorParam = params.find(isError);\n        error = {\n            stack: firstErrorParam ? toStackTraceString(computeStackTrace(firstErrorParam)) : undefined,\n            fingerprint: tryToGetFingerprint(firstErrorParam),\n            causes: firstErrorParam ? flattenErrorCauses(firstErrorParam, 'console') : undefined,\n            startClocks: clocksNow(),\n            message,\n            source: ErrorSource.CONSOLE,\n            handling: \"handled\" /* ErrorHandling.HANDLED */,\n            handlingStack,\n        };\n    }\n    return {\n        api,\n        message,\n        error,\n        handlingStack,\n    };\n}\nfunction formatConsoleParameters(param) {\n    if (typeof param === 'string') {\n        return sanitize(param);\n    }\n    if (isError(param)) {\n        return formatErrorMessage(computeStackTrace(param));\n    }\n    return jsonStringify(sanitize(param), undefined, 2);\n}\n//# sourceMappingURL=consoleObservable.js.map","import { toStackTraceString } from '../../tools/stackTrace/handlingStack';\nimport { monitor } from '../../tools/monitor';\nimport { mergeObservables, Observable } from '../../tools/observable';\nimport { addEventListener } from '../../browser/addEventListener';\nimport { safeTruncate } from '../../tools/utils/stringUtils';\nimport { ErrorSource } from '../error/error.types';\nimport { clocksNow } from '../../tools/utils/timeUtils';\nexport const RawReportType = {\n    intervention: 'intervention',\n    deprecation: 'deprecation',\n    cspViolation: 'csp_violation',\n};\nexport function initReportObservable(configuration, apis) {\n    const observables = [];\n    if (apis.includes(RawReportType.cspViolation)) {\n        observables.push(createCspViolationReportObservable(configuration));\n    }\n    const reportTypes = apis.filter((api) => api !== RawReportType.cspViolation);\n    if (reportTypes.length) {\n        observables.push(createReportObservable(reportTypes));\n    }\n    return mergeObservables(...observables);\n}\nfunction createReportObservable(reportTypes) {\n    return new Observable((observable) => {\n        if (!window.ReportingObserver) {\n            return;\n        }\n        const handleReports = monitor((reports, _) => reports.forEach((report) => observable.notify(buildRawReportErrorFromReport(report))));\n        const observer = new window.ReportingObserver(handleReports, {\n            types: reportTypes,\n            buffered: true,\n        });\n        observer.observe();\n        return () => {\n            observer.disconnect();\n        };\n    });\n}\nfunction createCspViolationReportObservable(configuration) {\n    return new Observable((observable) => {\n        const { stop } = addEventListener(configuration, document, \"securitypolicyviolation\" /* DOM_EVENT.SECURITY_POLICY_VIOLATION */, (event) => {\n            observable.notify(buildRawReportErrorFromCspViolation(event));\n        });\n        return stop;\n    });\n}\nfunction buildRawReportErrorFromReport(report) {\n    const { type, body } = report;\n    return buildRawReportError({\n        type: body.id,\n        message: `${type}: ${body.message}`,\n        originalError: report,\n        stack: buildStack(body.id, body.message, body.sourceFile, body.lineNumber, body.columnNumber),\n    });\n}\nfunction buildRawReportErrorFromCspViolation(event) {\n    const message = `'${event.blockedURI}' blocked by '${event.effectiveDirective}' directive`;\n    return buildRawReportError({\n        type: event.effectiveDirective,\n        message: `${RawReportType.cspViolation}: ${message}`,\n        originalError: event,\n        csp: {\n            disposition: event.disposition,\n        },\n        stack: buildStack(event.effectiveDirective, event.originalPolicy\n            ? `${message} of the policy \"${safeTruncate(event.originalPolicy, 100, '...')}\"`\n            : 'no policy', event.sourceFile, event.lineNumber, event.columnNumber),\n    });\n}\nfunction buildRawReportError(partial) {\n    return {\n        startClocks: clocksNow(),\n        source: ErrorSource.REPORT,\n        handling: \"unhandled\" /* ErrorHandling.UNHANDLED */,\n        ...partial,\n    };\n}\nfunction buildStack(name, message, sourceFile, lineNumber, columnNumber) {\n    return sourceFile\n        ? toStackTraceString({\n            name,\n            message,\n            stack: [\n                {\n                    func: '?',\n                    url: sourceFile,\n                    line: lineNumber !== null && lineNumber !== void 0 ? lineNumber : undefined,\n                    column: columnNumber !== null && columnNumber !== void 0 ? columnNumber : undefined,\n                },\n            ],\n        })\n        : undefined;\n}\n//# sourceMappingURL=reportObservable.js.map","import { ErrorSource, generateUUID, computeRawError, computeStackTrace, Observable, trackRuntimeError, isError, } from '@datadog/browser-core';\nimport { trackConsoleError } from './trackConsoleError';\nimport { trackReportError } from './trackReportError';\nexport function startErrorCollection(lifeCycle, configuration, pageStateHistory) {\n    const errorObservable = new Observable();\n    trackConsoleError(errorObservable);\n    trackRuntimeError(errorObservable);\n    trackReportError(configuration, errorObservable);\n    errorObservable.subscribe((error) => lifeCycle.notify(13 /* LifeCycleEventType.RAW_ERROR_COLLECTED */, { error }));\n    return doStartErrorCollection(lifeCycle, pageStateHistory);\n}\nexport function doStartErrorCollection(lifeCycle, pageStateHistory) {\n    lifeCycle.subscribe(13 /* LifeCycleEventType.RAW_ERROR_COLLECTED */, ({ error, customerContext, savedCommonContext }) => {\n        lifeCycle.notify(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, {\n            customerContext,\n            savedCommonContext,\n            ...processError(error, pageStateHistory),\n        });\n    });\n    return {\n        addError: ({ error, handlingStack, componentStack, startClocks, context: customerContext }, savedCommonContext) => {\n            const stackTrace = isError(error) ? computeStackTrace(error) : undefined;\n            const rawError = computeRawError({\n                stackTrace,\n                originalError: error,\n                handlingStack,\n                componentStack,\n                startClocks,\n                nonErrorPrefix: \"Provided\" /* NonErrorPrefix.PROVIDED */,\n                source: ErrorSource.CUSTOM,\n                handling: \"handled\" /* ErrorHandling.HANDLED */,\n            });\n            lifeCycle.notify(13 /* LifeCycleEventType.RAW_ERROR_COLLECTED */, {\n                customerContext,\n                savedCommonContext,\n                error: rawError,\n            });\n        },\n    };\n}\nfunction processError(error, pageStateHistory) {\n    const rawRumEvent = {\n        date: error.startClocks.timeStamp,\n        error: {\n            id: generateUUID(),\n            message: error.message,\n            source: error.source,\n            stack: error.stack,\n            handling_stack: error.handlingStack,\n            component_stack: error.componentStack,\n            type: error.type,\n            handling: error.handling,\n            causes: error.causes,\n            source_type: 'browser',\n            fingerprint: error.fingerprint,\n            csp: error.csp,\n        },\n        type: \"error\" /* RumEventType.ERROR */,\n        view: { in_foreground: pageStateHistory.wasInPageStateAt(\"active\" /* PageState.ACTIVE */, error.startClocks.relative) },\n    };\n    const domainContext = {\n        error: error.originalError,\n        handlingStack: error.handlingStack,\n    };\n    return {\n        rawRumEvent,\n        startTime: error.startClocks.relative,\n        domainContext,\n    };\n}\n//# sourceMappingURL=errorCollection.js.map","import { initConsoleObservable, ConsoleApiName } from '@datadog/browser-core';\nexport function trackConsoleError(errorObservable) {\n    const subscription = initConsoleObservable([ConsoleApiName.error]).subscribe((consoleLog) => errorObservable.notify(consoleLog.error));\n    return {\n        stop: () => {\n            subscription.unsubscribe();\n        },\n    };\n}\n//# sourceMappingURL=trackConsoleError.js.map","import { initReportObservable, RawReportType } from '@datadog/browser-core';\nexport function trackReportError(configuration, errorObservable) {\n    const subscription = initReportObservable(configuration, [\n        RawReportType.cspViolation,\n        RawReportType.intervention,\n    ]).subscribe((rawError) => errorObservable.notify(rawError));\n    return {\n        stop: () => {\n            subscription.unsubscribe();\n        },\n    };\n}\n//# sourceMappingURL=trackReportError.js.map","import { ONE_SECOND } from './utils/timeUtils';\nimport { requestIdleCallback } from './requestIdleCallback';\n/**\n * Maximum delay before starting to execute tasks in the queue. We don't want to wait too long\n * before running tasks, as it might hurt reliability (ex: if the user navigates away, we might lose\n * the opportunity to send some data). We also don't want to run tasks too often, as it might hurt\n * performance.\n */\nconst IDLE_CALLBACK_TIMEOUT = ONE_SECOND;\n/**\n * Maximum amount of time allocated to running tasks when a timeout (`IDLE_CALLBACK_TIMEOUT`) is\n * reached. We should not run tasks for too long as it will hurt performance, but we should still\n * run some tasks to avoid postponing them forever.\n *\n * Rational: Running tasks for 30ms every second (IDLE_CALLBACK_TIMEOUT) should be acceptable.\n */\nexport const MAX_EXECUTION_TIME_ON_TIMEOUT = 30;\nexport function createTaskQueue() {\n    const pendingTasks = [];\n    function run(deadline) {\n        let executionTimeRemaining;\n        if (deadline.didTimeout) {\n            const start = performance.now();\n            executionTimeRemaining = () => MAX_EXECUTION_TIME_ON_TIMEOUT - (performance.now() - start);\n        }\n        else {\n            executionTimeRemaining = deadline.timeRemaining.bind(deadline);\n        }\n        while (executionTimeRemaining() > 0 && pendingTasks.length) {\n            pendingTasks.shift()();\n        }\n        if (pendingTasks.length) {\n            scheduleNextRun();\n        }\n    }\n    function scheduleNextRun() {\n        requestIdleCallback(run, { timeout: IDLE_CALLBACK_TIMEOUT });\n    }\n    return {\n        push(task) {\n            if (pendingTasks.push(task) === 1) {\n                scheduleNextRun();\n            }\n        },\n    };\n}\n//# sourceMappingURL=taskQueue.js.map","import { addDuration } from '@datadog/browser-core';\nimport { hasValidResourceEntryDuration, hasValidResourceEntryTimings } from './resourceUtils';\nconst alreadyMatchedEntries = new WeakSet();\n/**\n * Look for corresponding timing in resource timing buffer\n *\n * Observations:\n * - Timing (start, end) are nested inside the request (start, end)\n * - Some timing can be not exactly nested, being off by < 1 ms\n *\n * Strategy:\n * - from valid nested entries (with 1 ms error margin)\n * - filter out timing that were already matched to a request\n * - then, if a single timing match, return the timing\n * - otherwise we can't decide, return undefined\n */\nexport function matchRequestResourceEntry(request) {\n    if (!performance || !('getEntriesByName' in performance)) {\n        return;\n    }\n    const sameNameEntries = performance.getEntriesByName(request.url, 'resource');\n    if (!sameNameEntries.length || !('toJSON' in sameNameEntries[0])) {\n        return;\n    }\n    const candidates = sameNameEntries\n        .filter((entry) => !alreadyMatchedEntries.has(entry))\n        .filter((entry) => hasValidResourceEntryDuration(entry) && hasValidResourceEntryTimings(entry))\n        .filter((entry) => isBetween(entry, request.startClocks.relative, endTime({ startTime: request.startClocks.relative, duration: request.duration })));\n    if (candidates.length === 1) {\n        alreadyMatchedEntries.add(candidates[0]);\n        return candidates[0].toJSON();\n    }\n    return;\n}\nfunction endTime(timing) {\n    return addDuration(timing.startTime, timing.duration);\n}\nfunction isBetween(timing, start, end) {\n    const errorMargin = 1;\n    return timing.startTime >= start - errorMargin && endTime(timing) <= addDuration(end, errorMargin);\n}\n//# sourceMappingURL=matchRequestResourceEntry.js.map","import { dateNow, findCommaSeparatedValue, ONE_MINUTE } from '@datadog/browser-core';\nimport { isCommentNode, isTextNode } from '../../browser/htmlDomUtils';\nexport const INITIAL_DOCUMENT_OUTDATED_TRACE_ID_THRESHOLD = 2 * ONE_MINUTE;\nexport function getDocumentTraceId(document) {\n    const data = getDocumentTraceDataFromMeta(document) || getDocumentTraceDataFromComment(document);\n    if (!data || data.traceTime <= dateNow() - INITIAL_DOCUMENT_OUTDATED_TRACE_ID_THRESHOLD) {\n        return undefined;\n    }\n    return data.traceId;\n}\nexport function getDocumentTraceDataFromMeta(document) {\n    const traceIdMeta = document.querySelector('meta[name=dd-trace-id]');\n    const traceTimeMeta = document.querySelector('meta[name=dd-trace-time]');\n    return createDocumentTraceData(traceIdMeta && traceIdMeta.content, traceTimeMeta && traceTimeMeta.content);\n}\nexport function getDocumentTraceDataFromComment(document) {\n    const comment = findTraceComment(document);\n    if (!comment) {\n        return undefined;\n    }\n    return createDocumentTraceData(findCommaSeparatedValue(comment, 'trace-id'), findCommaSeparatedValue(comment, 'trace-time'));\n}\nexport function createDocumentTraceData(traceId, rawTraceTime) {\n    const traceTime = rawTraceTime && Number(rawTraceTime);\n    if (!traceId || !traceTime) {\n        return undefined;\n    }\n    return {\n        traceId,\n        traceTime,\n    };\n}\nexport function findTraceComment(document) {\n    // 1. Try to find the comment as a direct child of the document\n    // Note: TSLint advises to use a 'for of', but TS doesn't allow to use 'for of' if the iterated\n    // value is not an array or string (here, a NodeList).\n    for (let i = 0; i < document.childNodes.length; i += 1) {\n        const comment = getTraceCommentFromNode(document.childNodes[i]);\n        if (comment) {\n            return comment;\n        }\n    }\n    // 2. If the comment is placed after the </html> tag, but have some space or new lines before or\n    // after, the DOM parser will lift it (and the surrounding text) at the end of the <body> tag.\n    // Try to look for the comment at the end of the <body> by by iterating over its child nodes in\n    // reverse order, stopping if we come across a non-text node.\n    if (document.body) {\n        for (let i = document.body.childNodes.length - 1; i >= 0; i -= 1) {\n            const node = document.body.childNodes[i];\n            const comment = getTraceCommentFromNode(node);\n            if (comment) {\n                return comment;\n            }\n            if (!isTextNode(node)) {\n                break;\n            }\n        }\n    }\n}\nfunction getTraceCommentFromNode(node) {\n    if (node && isCommentNode(node)) {\n        const match = /^\\s*DATADOG;(.*?)\\s*$/.exec(node.data);\n        if (match) {\n            return match[1];\n        }\n    }\n}\n//# sourceMappingURL=getDocumentTraceId.js.map","import { getRelativeTime, isNumber } from '@datadog/browser-core';\nimport { RumPerformanceEntryType, supportPerformanceTimingEvent, } from './performanceObservable';\nexport function getNavigationEntry() {\n    if (supportPerformanceTimingEvent(RumPerformanceEntryType.NAVIGATION)) {\n        const navigationEntry = performance.getEntriesByType(RumPerformanceEntryType.NAVIGATION)[0];\n        if (navigationEntry) {\n            return navigationEntry;\n        }\n    }\n    const timings = computeTimingsFromDeprecatedPerformanceTiming();\n    const entry = {\n        entryType: RumPerformanceEntryType.NAVIGATION,\n        initiatorType: 'navigation',\n        name: window.location.href,\n        startTime: 0,\n        duration: timings.responseEnd,\n        decodedBodySize: 0,\n        encodedBodySize: 0,\n        transferSize: 0,\n        workerStart: 0,\n        toJSON: () => ({ ...entry, toJSON: undefined }),\n        ...timings,\n    };\n    return entry;\n}\nexport function computeTimingsFromDeprecatedPerformanceTiming() {\n    const result = {};\n    const timing = performance.timing;\n    for (const key in timing) {\n        if (isNumber(timing[key])) {\n            const numberKey = key;\n            const timingElement = timing[numberKey];\n            result[numberKey] = timingElement === 0 ? 0 : getRelativeTime(timingElement);\n        }\n    }\n    return result;\n}\n//# sourceMappingURL=performanceUtils.js.map","import { runOnReadyState } from '@datadog/browser-core';\nimport { RumPerformanceEntryType } from '../../browser/performanceObservable';\nimport { getDocumentTraceId } from '../tracing/getDocumentTraceId';\nimport { getNavigationEntry } from '../../browser/performanceUtils';\nimport { FAKE_INITIAL_DOCUMENT } from './resourceUtils';\nexport function retrieveInitialDocumentResourceTiming(configuration, callback) {\n    runOnReadyState(configuration, 'interactive', () => {\n        const entry = Object.assign(getNavigationEntry().toJSON(), {\n            entryType: RumPerformanceEntryType.RESOURCE,\n            initiatorType: FAKE_INITIAL_DOCUMENT,\n            traceId: getDocumentTraceId(document),\n            toJSON: () => ({ ...entry, toJSON: undefined }),\n        });\n        callback(entry);\n    });\n}\n//# sourceMappingURL=retrieveInitialDocumentResourceTiming.js.map","import { combine, generateUUID, toServerDuration, relativeToClocks, createTaskQueue, } from '@datadog/browser-core';\nimport { RumPerformanceEntryType, createPerformanceObservable, } from '../../browser/performanceObservable';\nimport { createSpanIdentifier } from '../tracing/identifier';\nimport { matchRequestResourceEntry } from './matchRequestResourceEntry';\nimport { computeResourceEntryDetails, computeResourceEntryDuration, computeResourceEntryType, computeResourceEntrySize, computeResourceEntryProtocol, computeResourceEntryDeliveryType, isResourceEntryRequestType, isLongDataUrl, sanitizeDataUrl, } from './resourceUtils';\nimport { retrieveInitialDocumentResourceTiming } from './retrieveInitialDocumentResourceTiming';\nexport function startResourceCollection(lifeCycle, configuration, pageStateHistory, taskQueue = createTaskQueue(), retrieveInitialDocumentResourceTimingImpl = retrieveInitialDocumentResourceTiming) {\n    lifeCycle.subscribe(7 /* LifeCycleEventType.REQUEST_COMPLETED */, (request) => {\n        handleResource(() => processRequest(request, configuration, pageStateHistory));\n    });\n    const performanceResourceSubscription = createPerformanceObservable(configuration, {\n        type: RumPerformanceEntryType.RESOURCE,\n        buffered: true,\n    }).subscribe((entries) => {\n        for (const entry of entries) {\n            if (!isResourceEntryRequestType(entry)) {\n                handleResource(() => processResourceEntry(entry, configuration));\n            }\n        }\n    });\n    retrieveInitialDocumentResourceTimingImpl(configuration, (timing) => {\n        handleResource(() => processResourceEntry(timing, configuration));\n    });\n    function handleResource(computeRawEvent) {\n        taskQueue.push(() => {\n            const rawEvent = computeRawEvent();\n            if (rawEvent) {\n                lifeCycle.notify(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, rawEvent);\n            }\n        });\n    }\n    return {\n        stop: () => {\n            performanceResourceSubscription.unsubscribe();\n        },\n    };\n}\nfunction processRequest(request, configuration, pageStateHistory) {\n    const matchingTiming = matchRequestResourceEntry(request);\n    const startClocks = matchingTiming ? relativeToClocks(matchingTiming.startTime) : request.startClocks;\n    const tracingInfo = computeRequestTracingInfo(request, configuration);\n    if (!configuration.trackResources && !tracingInfo) {\n        return;\n    }\n    const type = request.type === \"xhr\" /* RequestType.XHR */ ? \"xhr\" /* ResourceType.XHR */ : \"fetch\" /* ResourceType.FETCH */;\n    const correspondingTimingOverrides = matchingTiming ? computeResourceEntryMetrics(matchingTiming) : undefined;\n    const duration = computeRequestDuration(pageStateHistory, startClocks, request.duration);\n    const resourceEvent = combine({\n        date: startClocks.timeStamp,\n        resource: {\n            id: generateUUID(),\n            type,\n            duration,\n            method: request.method,\n            status_code: request.status,\n            protocol: matchingTiming && computeResourceEntryProtocol(matchingTiming),\n            url: isLongDataUrl(request.url) ? sanitizeDataUrl(request.url) : request.url,\n            delivery_type: matchingTiming && computeResourceEntryDeliveryType(matchingTiming),\n        },\n        type: \"resource\" /* RumEventType.RESOURCE */,\n        _dd: {\n            discarded: !configuration.trackResources,\n        },\n    }, tracingInfo, correspondingTimingOverrides);\n    return {\n        startTime: startClocks.relative,\n        rawRumEvent: resourceEvent,\n        domainContext: {\n            performanceEntry: matchingTiming,\n            xhr: request.xhr,\n            response: request.response,\n            requestInput: request.input,\n            requestInit: request.init,\n            error: request.error,\n            isAborted: request.isAborted,\n            handlingStack: request.handlingStack,\n        },\n    };\n}\nfunction processResourceEntry(entry, configuration) {\n    const startClocks = relativeToClocks(entry.startTime);\n    const tracingInfo = computeResourceEntryTracingInfo(entry, configuration);\n    if (!configuration.trackResources && !tracingInfo) {\n        return;\n    }\n    const type = computeResourceEntryType(entry);\n    const entryMetrics = computeResourceEntryMetrics(entry);\n    const resourceEvent = combine({\n        date: startClocks.timeStamp,\n        resource: {\n            id: generateUUID(),\n            type,\n            url: entry.name,\n            status_code: discardZeroStatus(entry.responseStatus),\n            protocol: computeResourceEntryProtocol(entry),\n            delivery_type: computeResourceEntryDeliveryType(entry),\n        },\n        type: \"resource\" /* RumEventType.RESOURCE */,\n        _dd: {\n            discarded: !configuration.trackResources,\n        },\n    }, tracingInfo, entryMetrics);\n    return {\n        startTime: startClocks.relative,\n        rawRumEvent: resourceEvent,\n        domainContext: {\n            performanceEntry: entry,\n        },\n    };\n}\nfunction computeResourceEntryMetrics(entry) {\n    const { renderBlockingStatus } = entry;\n    return {\n        resource: {\n            duration: computeResourceEntryDuration(entry),\n            render_blocking_status: renderBlockingStatus,\n            ...computeResourceEntrySize(entry),\n            ...computeResourceEntryDetails(entry),\n        },\n    };\n}\nfunction computeRequestTracingInfo(request, configuration) {\n    const hasBeenTraced = request.traceSampled && request.traceId && request.spanId;\n    if (!hasBeenTraced) {\n        return undefined;\n    }\n    return {\n        _dd: {\n            span_id: request.spanId.toString(),\n            trace_id: request.traceId.toString(),\n            rule_psr: configuration.rulePsr,\n        },\n    };\n}\nfunction computeResourceEntryTracingInfo(entry, configuration) {\n    const hasBeenTraced = entry.traceId;\n    if (!hasBeenTraced) {\n        return undefined;\n    }\n    return {\n        _dd: {\n            trace_id: entry.traceId,\n            span_id: createSpanIdentifier().toString(),\n            rule_psr: configuration.rulePsr,\n        },\n    };\n}\nfunction computeRequestDuration(pageStateHistory, startClocks, duration) {\n    return !pageStateHistory.wasInPageStateDuringPeriod(\"frozen\" /* PageState.FROZEN */, startClocks.relative, duration)\n        ? toServerDuration(duration)\n        : undefined;\n}\n/**\n * The status is 0 for cross-origin resources without CORS headers, so the status is meaningless, and we shouldn't report it\n * https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/responseStatus#cross-origin_response_status_codes\n */\nfunction discardZeroStatus(statusCode) {\n    return statusCode === 0 ? undefined : statusCode;\n}\n//# sourceMappingURL=resourceCollection.js.map","import { ONE_MINUTE } from '@datadog/browser-core';\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../../../browser/performanceObservable';\n// Discard FCP timings above a certain delay to avoid incorrect data\n// It happens in some cases like sleep mode or some browser implementations\nexport const FCP_MAXIMUM_DELAY = 10 * ONE_MINUTE;\nexport function trackFirstContentfulPaint(configuration, firstHidden, callback) {\n    const performanceSubscription = createPerformanceObservable(configuration, {\n        type: RumPerformanceEntryType.PAINT,\n        buffered: true,\n    }).subscribe((entries) => {\n        const fcpEntry = entries.find((entry) => entry.name === 'first-contentful-paint' &&\n            entry.startTime < firstHidden.timeStamp &&\n            entry.startTime < FCP_MAXIMUM_DELAY);\n        if (fcpEntry) {\n            callback(fcpEntry.startTime);\n        }\n    });\n    return {\n        stop: performanceSubscription.unsubscribe,\n    };\n}\n//# sourceMappingURL=trackFirstContentfulPaint.js.map","import { setTimeout, relativeNow, runOnReadyState, clearTimeout } from '@datadog/browser-core';\nimport { getNavigationEntry } from '../../../browser/performanceUtils';\nexport function trackNavigationTimings(configuration, callback, getNavigationEntryImpl = getNavigationEntry) {\n    return waitAfterLoadEvent(configuration, () => {\n        const entry = getNavigationEntryImpl();\n        if (!isIncompleteNavigation(entry)) {\n            callback(processNavigationEntry(entry));\n        }\n    });\n}\nfunction processNavigationEntry(entry) {\n    return {\n        domComplete: entry.domComplete,\n        domContentLoaded: entry.domContentLoadedEventEnd,\n        domInteractive: entry.domInteractive,\n        loadEvent: entry.loadEventEnd,\n        // In some cases the value reported is negative or is larger\n        // than the current page time. Ignore these cases:\n        // https://github.com/GoogleChrome/web-vitals/issues/137\n        // https://github.com/GoogleChrome/web-vitals/issues/162\n        firstByte: entry.responseStart >= 0 && entry.responseStart <= relativeNow() ? entry.responseStart : undefined,\n    };\n}\nfunction isIncompleteNavigation(entry) {\n    return entry.loadEventEnd <= 0;\n}\nfunction waitAfterLoadEvent(configuration, callback) {\n    let timeoutId;\n    const { stop: stopOnReadyState } = runOnReadyState(configuration, 'complete', () => {\n        // Invoke the callback a bit after the actual load event, so the \"loadEventEnd\" timing is accurate\n        timeoutId = setTimeout(() => callback());\n    });\n    return {\n        stop: () => {\n            stopOnReadyState();\n            clearTimeout(timeoutId);\n        },\n    };\n}\n//# sourceMappingURL=trackNavigationTimings.js.map","import { ONE_MINUTE, addEventListeners, findLast } from '@datadog/browser-core';\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../../../browser/performanceObservable';\nimport { getSelectorFromElement } from '../../getSelectorFromElement';\n// Discard LCP timings above a certain delay to avoid incorrect data\n// It happens in some cases like sleep mode or some browser implementations\nexport const LCP_MAXIMUM_DELAY = 10 * ONE_MINUTE;\n/**\n * Track the largest contentful paint (LCP) occurring during the initial View.  This can yield\n * multiple values, only the most recent one should be used.\n * Documentation: https://web.dev/lcp/\n * Reference implementation: https://github.com/GoogleChrome/web-vitals/blob/master/src/onLCP.ts\n */\nexport function trackLargestContentfulPaint(configuration, firstHidden, eventTarget, callback) {\n    // Ignore entries that come after the first user interaction. According to the documentation, the\n    // browser should not send largest-contentful-paint entries after a user interact with the page,\n    // but the web-vitals reference implementation uses this as a safeguard.\n    let firstInteractionTimestamp = Infinity;\n    const { stop: stopEventListener } = addEventListeners(configuration, eventTarget, [\"pointerdown\" /* DOM_EVENT.POINTER_DOWN */, \"keydown\" /* DOM_EVENT.KEY_DOWN */], (event) => {\n        firstInteractionTimestamp = event.timeStamp;\n    }, { capture: true, once: true });\n    let biggestLcpSize = 0;\n    const performanceLcpSubscription = createPerformanceObservable(configuration, {\n        type: RumPerformanceEntryType.LARGEST_CONTENTFUL_PAINT,\n        buffered: true,\n    }).subscribe((entries) => {\n        const lcpEntry = findLast(entries, (entry) => entry.entryType === RumPerformanceEntryType.LARGEST_CONTENTFUL_PAINT &&\n            entry.startTime < firstInteractionTimestamp &&\n            entry.startTime < firstHidden.timeStamp &&\n            entry.startTime < LCP_MAXIMUM_DELAY &&\n            // Ensure to get the LCP entry with the biggest size, see\n            // https://bugs.chromium.org/p/chromium/issues/detail?id=1516655\n            entry.size > biggestLcpSize);\n        if (lcpEntry) {\n            let lcpTargetSelector;\n            if (lcpEntry.element) {\n                lcpTargetSelector = getSelectorFromElement(lcpEntry.element, configuration.actionNameAttribute);\n            }\n            callback({\n                value: lcpEntry.startTime,\n                targetSelector: lcpTargetSelector,\n            });\n            biggestLcpSize = lcpEntry.size;\n        }\n    });\n    return {\n        stop: () => {\n            stopEventListener();\n            performanceLcpSubscription.unsubscribe();\n        },\n    };\n}\n//# sourceMappingURL=trackLargestContentfulPaint.js.map","import { addEventListeners } from '@datadog/browser-core';\nexport function trackFirstHidden(configuration, eventTarget = window) {\n    let timeStamp;\n    let stopListeners;\n    if (document.visibilityState === 'hidden') {\n        timeStamp = 0;\n    }\n    else {\n        timeStamp = Infinity;\n        ({ stop: stopListeners } = addEventListeners(configuration, eventTarget, [\"pagehide\" /* DOM_EVENT.PAGE_HIDE */, \"visibilitychange\" /* DOM_EVENT.VISIBILITY_CHANGE */], (event) => {\n            if (event.type === \"pagehide\" /* DOM_EVENT.PAGE_HIDE */ || document.visibilityState === 'hidden') {\n                timeStamp = event.timeStamp;\n                stopListeners();\n            }\n        }, { capture: true }));\n    }\n    return {\n        get timeStamp() {\n            return timeStamp;\n        },\n        stop() {\n            stopListeners === null || stopListeners === void 0 ? void 0 : stopListeners();\n        },\n    };\n}\n//# sourceMappingURL=trackFirstHidden.js.map","import { trackFirstContentfulPaint } from './trackFirstContentfulPaint';\nimport { trackFirstInput } from './trackFirstInput';\nimport { trackNavigationTimings } from './trackNavigationTimings';\nimport { trackLargestContentfulPaint } from './trackLargestContentfulPaint';\nimport { trackFirstHidden } from './trackFirstHidden';\nexport function trackInitialViewMetrics(configuration, setLoadEvent, scheduleViewUpdate) {\n    const initialViewMetrics = {};\n    const { stop: stopNavigationTracking } = trackNavigationTimings(configuration, (navigationTimings) => {\n        setLoadEvent(navigationTimings.loadEvent);\n        initialViewMetrics.navigationTimings = navigationTimings;\n        scheduleViewUpdate();\n    });\n    const firstHidden = trackFirstHidden(configuration);\n    const { stop: stopFCPTracking } = trackFirstContentfulPaint(configuration, firstHidden, (firstContentfulPaint) => {\n        initialViewMetrics.firstContentfulPaint = firstContentfulPaint;\n        scheduleViewUpdate();\n    });\n    const { stop: stopLCPTracking } = trackLargestContentfulPaint(configuration, firstHidden, window, (largestContentfulPaint) => {\n        initialViewMetrics.largestContentfulPaint = largestContentfulPaint;\n        scheduleViewUpdate();\n    });\n    const { stop: stopFIDTracking } = trackFirstInput(configuration, firstHidden, (firstInput) => {\n        initialViewMetrics.firstInput = firstInput;\n        scheduleViewUpdate();\n    });\n    function stop() {\n        stopNavigationTracking();\n        stopFCPTracking();\n        stopLCPTracking();\n        stopFIDTracking();\n        firstHidden.stop();\n    }\n    return {\n        stop,\n        initialViewMetrics,\n    };\n}\n//# sourceMappingURL=trackInitialViewMetrics.js.map","import { elapsed } from '@datadog/browser-core';\nimport { isElementNode } from '../../../browser/htmlDomUtils';\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../../../browser/performanceObservable';\nimport { getSelectorFromElement } from '../../getSelectorFromElement';\n/**\n * Track the first input occurring during the initial View to return:\n * - First Input Delay\n * - First Input Time\n * Callback is called at most one time.\n * Documentation: https://web.dev/fid/\n * Reference implementation: https://github.com/GoogleChrome/web-vitals/blob/master/src/getFID.ts\n */\nexport function trackFirstInput(configuration, firstHidden, callback) {\n    const performanceFirstInputSubscription = createPerformanceObservable(configuration, {\n        type: RumPerformanceEntryType.FIRST_INPUT,\n        buffered: true,\n    }).subscribe((entries) => {\n        const firstInputEntry = entries.find((entry) => entry.startTime < firstHidden.timeStamp);\n        if (firstInputEntry) {\n            const firstInputDelay = elapsed(firstInputEntry.startTime, firstInputEntry.processingStart);\n            let firstInputTargetSelector;\n            if (firstInputEntry.target && isElementNode(firstInputEntry.target)) {\n                firstInputTargetSelector = getSelectorFromElement(firstInputEntry.target, configuration.actionNameAttribute);\n            }\n            callback({\n                // Ensure firstInputDelay to be positive, see\n                // https://bugs.chromium.org/p/chromium/issues/detail?id=1185815\n                delay: firstInputDelay >= 0 ? firstInputDelay : 0,\n                time: firstInputEntry.startTime,\n                targetSelector: firstInputTargetSelector,\n            });\n        }\n    });\n    return {\n        stop: () => {\n            performanceFirstInputSubscription.unsubscribe();\n        },\n    };\n}\n//# sourceMappingURL=trackFirstInput.js.map","import { round, ONE_SECOND, noop, elapsed } from '@datadog/browser-core';\nimport { isElementNode } from '../../../browser/htmlDomUtils';\nimport { supportPerformanceTimingEvent, RumPerformanceEntryType, createPerformanceObservable, } from '../../../browser/performanceObservable';\nimport { getSelectorFromElement } from '../../getSelectorFromElement';\n/**\n * Track the cumulative layout shifts (CLS).\n * Layout shifts are grouped into session windows.\n * The minimum gap between session windows is 1 second.\n * The maximum duration of a session window is 5 second.\n * The session window layout shift value is the sum of layout shifts inside it.\n * The CLS value is the max of session windows values.\n *\n * This yields a new value whenever the CLS value is updated (a higher session window value is computed).\n *\n * See isLayoutShiftSupported to check for browser support.\n *\n * Documentation:\n * https://web.dev/cls/\n * https://web.dev/evolving-cls/\n * Reference implementation: https://github.com/GoogleChrome/web-vitals/blob/master/src/getCLS.ts\n */\nexport function trackCumulativeLayoutShift(configuration, viewStart, callback) {\n    if (!isLayoutShiftSupported()) {\n        return {\n            stop: noop,\n        };\n    }\n    let maxClsValue = 0;\n    let biggestShift;\n    // if no layout shift happen the value should be reported as 0\n    callback({\n        value: 0,\n    });\n    const window = slidingSessionWindow();\n    const performanceSubscription = createPerformanceObservable(configuration, {\n        type: RumPerformanceEntryType.LAYOUT_SHIFT,\n        buffered: true,\n    }).subscribe((entries) => {\n        var _a;\n        for (const entry of entries) {\n            if (entry.hadRecentInput || entry.startTime < viewStart) {\n                continue;\n            }\n            const { cumulatedValue, isMaxValue } = window.update(entry);\n            if (isMaxValue) {\n                const attribution = getFirstElementAttribution(entry.sources);\n                biggestShift = {\n                    target: (attribution === null || attribution === void 0 ? void 0 : attribution.node) ? new WeakRef(attribution.node) : undefined,\n                    time: elapsed(viewStart, entry.startTime),\n                    previousRect: attribution === null || attribution === void 0 ? void 0 : attribution.previousRect,\n                    currentRect: attribution === null || attribution === void 0 ? void 0 : attribution.currentRect,\n                };\n            }\n            if (cumulatedValue > maxClsValue) {\n                maxClsValue = cumulatedValue;\n                const target = (_a = biggestShift === null || biggestShift === void 0 ? void 0 : biggestShift.target) === null || _a === void 0 ? void 0 : _a.deref();\n                callback({\n                    value: round(maxClsValue, 4),\n                    targetSelector: target && getSelectorFromElement(target, configuration.actionNameAttribute),\n                    time: biggestShift === null || biggestShift === void 0 ? void 0 : biggestShift.time,\n                    previousRect: (biggestShift === null || biggestShift === void 0 ? void 0 : biggestShift.previousRect) ? asRumRect(biggestShift.previousRect) : undefined,\n                    currentRect: (biggestShift === null || biggestShift === void 0 ? void 0 : biggestShift.currentRect) ? asRumRect(biggestShift.currentRect) : undefined,\n                });\n            }\n        }\n    });\n    return {\n        stop: () => {\n            performanceSubscription.unsubscribe();\n        },\n    };\n}\nfunction getFirstElementAttribution(sources) {\n    return sources.find((source) => !!source.node && isElementNode(source.node));\n}\nfunction asRumRect({ x, y, width, height }) {\n    return { x, y, width, height };\n}\nexport const MAX_WINDOW_DURATION = 5 * ONE_SECOND;\nconst MAX_UPDATE_GAP = ONE_SECOND;\nfunction slidingSessionWindow() {\n    let cumulatedValue = 0;\n    let startTime;\n    let endTime;\n    let maxValue = 0;\n    return {\n        update: (entry) => {\n            const shouldCreateNewWindow = startTime === undefined ||\n                entry.startTime - endTime >= MAX_UPDATE_GAP ||\n                entry.startTime - startTime >= MAX_WINDOW_DURATION;\n            let isMaxValue;\n            if (shouldCreateNewWindow) {\n                startTime = endTime = entry.startTime;\n                maxValue = cumulatedValue = entry.value;\n                isMaxValue = true;\n            }\n            else {\n                cumulatedValue += entry.value;\n                endTime = entry.startTime;\n                isMaxValue = entry.value > maxValue;\n                if (isMaxValue) {\n                    maxValue = entry.value;\n                }\n            }\n            return {\n                cumulatedValue,\n                isMaxValue,\n            };\n        },\n    };\n}\n/**\n * Check whether `layout-shift` is supported by the browser.\n */\nexport function isLayoutShiftSupported() {\n    return supportPerformanceTimingEvent(RumPerformanceEntryType.LAYOUT_SHIFT) && 'WeakRef' in window;\n}\n//# sourceMappingURL=trackCumulativeLayoutShift.js.map","/**\n * performance.interactionCount polyfill\n *\n * The interactionCount is an integer which counts the total number of distinct user interactions,\n * for which there was a unique interactionId.\n *\n * The interactionCount polyfill is an estimate based on a convention specific to Chrome. Cf: https://github.com/GoogleChrome/web-vitals/pull/213\n * This is currently not an issue as the polyfill is only used for INP which is currently only supported on Chrome.\n * Hopefully when/if other browsers will support INP, they will also implement performance.interactionCount at the same time, so we won't need that polyfill.\n *\n * Reference implementation: https://github.com/GoogleChrome/web-vitals/blob/main/src/lib/polyfills/interactionCountPolyfill.ts\n */\nimport { monitor } from '@datadog/browser-core';\nlet observer;\nlet interactionCountEstimate = 0;\nlet minKnownInteractionId = Infinity;\nlet maxKnownInteractionId = 0;\nexport function initInteractionCountPolyfill() {\n    if ('interactionCount' in performance || observer) {\n        return;\n    }\n    observer = new window.PerformanceObserver(monitor((entries) => {\n        entries.getEntries().forEach((e) => {\n            const entry = e;\n            if (entry.interactionId) {\n                minKnownInteractionId = Math.min(minKnownInteractionId, entry.interactionId);\n                maxKnownInteractionId = Math.max(maxKnownInteractionId, entry.interactionId);\n                interactionCountEstimate = (maxKnownInteractionId - minKnownInteractionId) / 7 + 1;\n            }\n        });\n    }));\n    observer.observe({ type: 'event', buffered: true, durationThreshold: 0 });\n}\n/**\n * Returns the `interactionCount` value using the native API (if available)\n * or the polyfill estimate in this module.\n */\nexport const getInteractionCount = () => observer ? interactionCountEstimate : window.performance.interactionCount || 0;\n//# sourceMappingURL=interactionCountPolyfill.js.map","import { elapsed, noop, ONE_MINUTE } from '@datadog/browser-core';\nimport { createPerformanceObservable, RumPerformanceEntryType, supportPerformanceTimingEvent, } from '../../../browser/performanceObservable';\nimport { getSelectorFromElement } from '../../getSelectorFromElement';\nimport { isElementNode } from '../../../browser/htmlDomUtils';\nimport { getInteractionSelector } from '../../action/interactionSelectorCache';\nimport { getInteractionCount, initInteractionCountPolyfill } from './interactionCountPolyfill';\n// Arbitrary value to prevent unnecessary memory usage on views with lots of interactions.\nconst MAX_INTERACTION_ENTRIES = 10;\n// Arbitrary value to cap INP outliers\nexport const MAX_INP_VALUE = (1 * ONE_MINUTE);\n/**\n * Track the interaction to next paint (INP).\n * To avoid outliers, return the p98 worst interaction of the view.\n * Documentation: https://web.dev/inp/\n * Reference implementation: https://github.com/GoogleChrome/web-vitals/blob/main/src/onINP.ts\n */\nexport function trackInteractionToNextPaint(configuration, viewStart, viewLoadingType) {\n    if (!isInteractionToNextPaintSupported()) {\n        return {\n            getInteractionToNextPaint: () => undefined,\n            setViewEnd: noop,\n            stop: noop,\n        };\n    }\n    const { getViewInteractionCount, stopViewInteractionCount } = trackViewInteractionCount(viewLoadingType);\n    let viewEnd = Infinity;\n    const longestInteractions = trackLongestInteractions(getViewInteractionCount);\n    let interactionToNextPaint = -1;\n    let interactionToNextPaintTargetSelector;\n    let interactionToNextPaintStartTime;\n    function handleEntries(entries) {\n        for (const entry of entries) {\n            if (entry.interactionId &&\n                // Check the entry start time is inside the view bounds because some view interactions can be reported after the view end (if long duration).\n                entry.startTime >= viewStart &&\n                entry.startTime <= viewEnd) {\n                longestInteractions.process(entry);\n            }\n        }\n        const newInteraction = longestInteractions.estimateP98Interaction();\n        if (newInteraction && newInteraction.duration !== interactionToNextPaint) {\n            interactionToNextPaint = newInteraction.duration;\n            interactionToNextPaintStartTime = elapsed(viewStart, newInteraction.startTime);\n            interactionToNextPaintTargetSelector = getInteractionSelector(newInteraction.startTime);\n            if (!interactionToNextPaintTargetSelector && newInteraction.target && isElementNode(newInteraction.target)) {\n                interactionToNextPaintTargetSelector = getSelectorFromElement(newInteraction.target, configuration.actionNameAttribute);\n            }\n        }\n    }\n    const firstInputSubscription = createPerformanceObservable(configuration, {\n        type: RumPerformanceEntryType.FIRST_INPUT,\n        buffered: true,\n    }).subscribe(handleEntries);\n    const eventSubscription = createPerformanceObservable(configuration, {\n        type: RumPerformanceEntryType.EVENT,\n        // durationThreshold only impact PerformanceEventTiming entries used for INP computation which requires a threshold at 40 (default is 104ms)\n        // cf: https://github.com/GoogleChrome/web-vitals/blob/3806160ffbc93c3c4abf210a167b81228172b31c/src/onINP.ts#L202-L210\n        durationThreshold: 40,\n        buffered: true,\n    }).subscribe(handleEntries);\n    return {\n        getInteractionToNextPaint: () => {\n            // If no INP duration where captured because of the performanceObserver 40ms threshold\n            // but the view interaction count > 0 then report 0\n            if (interactionToNextPaint >= 0) {\n                return {\n                    value: Math.min(interactionToNextPaint, MAX_INP_VALUE),\n                    targetSelector: interactionToNextPaintTargetSelector,\n                    time: interactionToNextPaintStartTime,\n                };\n            }\n            else if (getViewInteractionCount()) {\n                return {\n                    value: 0,\n                };\n            }\n        },\n        setViewEnd: (viewEndTime) => {\n            viewEnd = viewEndTime;\n            stopViewInteractionCount();\n        },\n        stop: () => {\n            eventSubscription.unsubscribe();\n            firstInputSubscription.unsubscribe();\n        },\n    };\n}\nfunction trackLongestInteractions(getViewInteractionCount) {\n    const longestInteractions = [];\n    function sortAndTrimLongestInteractions() {\n        longestInteractions.sort((a, b) => b.duration - a.duration).splice(MAX_INTERACTION_ENTRIES);\n    }\n    return {\n        /**\n         * Process the performance entry:\n         * - if its duration is long enough, add the performance entry to the list of worst interactions\n         * - if an entry with the same interaction id exists and its duration is lower than the new one, then replace it in the list of worst interactions\n         */\n        process(entry) {\n            const interactionIndex = longestInteractions.findIndex((interaction) => entry.interactionId === interaction.interactionId);\n            const minLongestInteraction = longestInteractions[longestInteractions.length - 1];\n            if (interactionIndex !== -1) {\n                if (entry.duration > longestInteractions[interactionIndex].duration) {\n                    longestInteractions[interactionIndex] = entry;\n                    sortAndTrimLongestInteractions();\n                }\n            }\n            else if (longestInteractions.length < MAX_INTERACTION_ENTRIES ||\n                entry.duration > minLongestInteraction.duration) {\n                longestInteractions.push(entry);\n                sortAndTrimLongestInteractions();\n            }\n        },\n        /**\n         * Compute the p98 longest interaction.\n         * For better performance the computation is based on 10 longest interactions and the interaction count of the current view.\n         */\n        estimateP98Interaction() {\n            const interactionIndex = Math.min(longestInteractions.length - 1, Math.floor(getViewInteractionCount() / 50));\n            return longestInteractions[interactionIndex];\n        },\n    };\n}\nexport function trackViewInteractionCount(viewLoadingType) {\n    initInteractionCountPolyfill();\n    const previousInteractionCount = viewLoadingType === \"initial_load\" /* ViewLoadingType.INITIAL_LOAD */ ? 0 : getInteractionCount();\n    let state = { stopped: false };\n    function computeViewInteractionCount() {\n        return getInteractionCount() - previousInteractionCount;\n    }\n    return {\n        getViewInteractionCount: () => {\n            if (state.stopped) {\n                return state.interactionCount;\n            }\n            return computeViewInteractionCount();\n        },\n        stopViewInteractionCount: () => {\n            state = { stopped: true, interactionCount: computeViewInteractionCount() };\n        },\n    };\n}\nexport function isInteractionToNextPaintSupported() {\n    return (supportPerformanceTimingEvent(RumPerformanceEntryType.EVENT) &&\n        window.PerformanceEventTiming &&\n        'interactionId' in PerformanceEventTiming.prototype);\n}\n//# sourceMappingURL=trackInteractionToNextPaint.js.map","export function getScrollX() {\n    let scrollX;\n    const visual = window.visualViewport;\n    if (visual) {\n        scrollX = visual.pageLeft - visual.offsetLeft;\n    }\n    else if (window.scrollX !== undefined) {\n        scrollX = window.scrollX;\n    }\n    else {\n        scrollX = window.pageXOffset || 0;\n    }\n    return Math.round(scrollX);\n}\nexport function getScrollY() {\n    let scrollY;\n    const visual = window.visualViewport;\n    if (visual) {\n        scrollY = visual.pageTop - visual.offsetTop;\n    }\n    else if (window.scrollY !== undefined) {\n        scrollY = window.scrollY;\n    }\n    else {\n        scrollY = window.pageYOffset || 0;\n    }\n    return Math.round(scrollY);\n}\n//# sourceMappingURL=scroll.js.map","import { Observable, throttle, addEventListener } from '@datadog/browser-core';\nlet viewportObservable;\nexport function initViewportObservable(configuration) {\n    if (!viewportObservable) {\n        viewportObservable = createViewportObservable(configuration);\n    }\n    return viewportObservable;\n}\nexport function createViewportObservable(configuration) {\n    return new Observable((observable) => {\n        const { throttled: updateDimension } = throttle(() => {\n            observable.notify(getViewportDimension());\n        }, 200);\n        return addEventListener(configuration, window, \"resize\" /* DOM_EVENT.RESIZE */, updateDimension, { capture: true, passive: true })\n            .stop;\n    });\n}\n// excludes the width and height of any rendered classic scrollbar that is fixed to the visual viewport\nexport function getViewportDimension() {\n    const visual = window.visualViewport;\n    if (visual) {\n        return {\n            width: Number(visual.width * visual.scale),\n            height: Number(visual.height * visual.scale),\n        };\n    }\n    return {\n        width: Number(window.innerWidth || 0),\n        height: Number(window.innerHeight || 0),\n    };\n}\n//# sourceMappingURL=viewportObservable.js.map","import { Observable, ONE_SECOND, elapsed, relativeNow, throttle, addEventListener, monitor, } from '@datadog/browser-core';\nimport { getScrollY } from '../../../browser/scroll';\nimport { getViewportDimension } from '../../../browser/viewportObservable';\n/** Arbitrary scroll throttle duration */\nexport const THROTTLE_SCROLL_DURATION = ONE_SECOND;\nexport function trackScrollMetrics(configuration, viewStart, callback, scrollValues = createScrollValuesObservable(configuration)) {\n    let maxScrollDepth = 0;\n    let maxScrollHeight = 0;\n    let maxScrollHeightTime = 0;\n    const subscription = scrollValues.subscribe(({ scrollDepth, scrollTop, scrollHeight }) => {\n        let shouldUpdate = false;\n        if (scrollDepth > maxScrollDepth) {\n            maxScrollDepth = scrollDepth;\n            shouldUpdate = true;\n        }\n        if (scrollHeight > maxScrollHeight) {\n            maxScrollHeight = scrollHeight;\n            const now = relativeNow();\n            maxScrollHeightTime = elapsed(viewStart.relative, now);\n            shouldUpdate = true;\n        }\n        if (shouldUpdate) {\n            callback({\n                maxDepth: Math.min(maxScrollDepth, maxScrollHeight),\n                maxDepthScrollTop: scrollTop,\n                maxScrollHeight,\n                maxScrollHeightTime,\n            });\n        }\n    });\n    return {\n        stop: () => subscription.unsubscribe(),\n    };\n}\nexport function computeScrollValues() {\n    const scrollTop = getScrollY();\n    const { height } = getViewportDimension();\n    const scrollHeight = Math.round((document.scrollingElement || document.documentElement).scrollHeight);\n    const scrollDepth = Math.round(height + scrollTop);\n    return {\n        scrollHeight,\n        scrollDepth,\n        scrollTop,\n    };\n}\nexport function createScrollValuesObservable(configuration, throttleDuration = THROTTLE_SCROLL_DURATION) {\n    return new Observable((observable) => {\n        function notify() {\n            observable.notify(computeScrollValues());\n        }\n        if (window.ResizeObserver) {\n            const throttledNotify = throttle(notify, throttleDuration, {\n                leading: false,\n                trailing: true,\n            });\n            const observerTarget = document.scrollingElement || document.documentElement;\n            const resizeObserver = new ResizeObserver(monitor(throttledNotify.throttled));\n            if (observerTarget) {\n                resizeObserver.observe(observerTarget);\n            }\n            const eventListener = addEventListener(configuration, window, \"scroll\" /* DOM_EVENT.SCROLL */, throttledNotify.throttled, {\n                passive: true,\n            });\n            return () => {\n                throttledNotify.cancel();\n                resizeObserver.disconnect();\n                eventListener.stop();\n            };\n        }\n    });\n}\n//# sourceMappingURL=trackScrollMetrics.js.map","import { trackCumulativeLayoutShift } from './trackCumulativeLayoutShift';\nimport { trackInteractionToNextPaint } from './trackInteractionToNextPaint';\nimport { trackLoadingTime } from './trackLoadingTime';\nimport { trackScrollMetrics } from './trackScrollMetrics';\nexport function trackCommonViewMetrics(lifeCycle, domMutationObservable, windowOpenObservable, configuration, scheduleViewUpdate, loadingType, viewStart) {\n    const commonViewMetrics = {};\n    const { stop: stopLoadingTimeTracking, setLoadEvent } = trackLoadingTime(lifeCycle, domMutationObservable, windowOpenObservable, configuration, loadingType, viewStart, (newLoadingTime) => {\n        commonViewMetrics.loadingTime = newLoadingTime;\n        scheduleViewUpdate();\n    });\n    const { stop: stopScrollMetricsTracking } = trackScrollMetrics(configuration, viewStart, (newScrollMetrics) => {\n        commonViewMetrics.scroll = newScrollMetrics;\n    });\n    const { stop: stopCLSTracking } = trackCumulativeLayoutShift(configuration, viewStart.relative, (cumulativeLayoutShift) => {\n        commonViewMetrics.cumulativeLayoutShift = cumulativeLayoutShift;\n        scheduleViewUpdate();\n    });\n    const { stop: stopINPTracking, getInteractionToNextPaint, setViewEnd, } = trackInteractionToNextPaint(configuration, viewStart.relative, loadingType);\n    return {\n        stop: () => {\n            stopLoadingTimeTracking();\n            stopCLSTracking();\n            stopScrollMetricsTracking();\n        },\n        stopINPTracking,\n        setLoadEvent,\n        setViewEnd,\n        getCommonViewMetrics: () => {\n            commonViewMetrics.interactionToNextPaint = getInteractionToNextPaint();\n            return commonViewMetrics;\n        },\n    };\n}\n//# sourceMappingURL=trackCommonViewMetrics.js.map","import { elapsed } from '@datadog/browser-core';\nimport { waitPageActivityEnd } from '../../waitPageActivityEnd';\nimport { trackFirstHidden } from './trackFirstHidden';\nexport function trackLoadingTime(lifeCycle, domMutationObservable, windowOpenObservable, configuration, loadType, viewStart, callback) {\n    let isWaitingForLoadEvent = loadType === \"initial_load\" /* ViewLoadingType.INITIAL_LOAD */;\n    let isWaitingForActivityLoadingTime = true;\n    const loadingTimeCandidates = [];\n    const firstHidden = trackFirstHidden(configuration);\n    function invokeCallbackIfAllCandidatesAreReceived() {\n        if (!isWaitingForActivityLoadingTime && !isWaitingForLoadEvent && loadingTimeCandidates.length > 0) {\n            const loadingTime = Math.max(...loadingTimeCandidates);\n            if (loadingTime < firstHidden.timeStamp) {\n                callback(loadingTime);\n            }\n        }\n    }\n    const { stop } = waitPageActivityEnd(lifeCycle, domMutationObservable, windowOpenObservable, configuration, (event) => {\n        if (isWaitingForActivityLoadingTime) {\n            isWaitingForActivityLoadingTime = false;\n            if (event.hadActivity) {\n                loadingTimeCandidates.push(elapsed(viewStart.timeStamp, event.end));\n            }\n            invokeCallbackIfAllCandidatesAreReceived();\n        }\n    });\n    return {\n        stop: () => {\n            stop();\n            firstHidden.stop();\n        },\n        setLoadEvent: (loadEvent) => {\n            if (isWaitingForLoadEvent) {\n                isWaitingForLoadEvent = false;\n                loadingTimeCandidates.push(loadEvent);\n                invokeCallbackIfAllCandidatesAreReceived();\n            }\n        },\n    };\n}\n//# sourceMappingURL=trackLoadingTime.js.map","import { noop, PageExitReason, shallowClone, elapsed, generateUUID, ONE_MINUTE, throttle, clocksNow, clocksOrigin, timeStampNow, display, looksLikeRelativeTime, setInterval, clearInterval, setTimeout, Observable, createContextManager, } from '@datadog/browser-core';\nimport { trackViewEventCounts } from './trackViewEventCounts';\nimport { trackInitialViewMetrics } from './viewMetrics/trackInitialViewMetrics';\nimport { trackCommonViewMetrics } from './viewMetrics/trackCommonViewMetrics';\nexport const THROTTLE_VIEW_UPDATE_PERIOD = 3000;\nexport const SESSION_KEEP_ALIVE_INTERVAL = 5 * ONE_MINUTE;\n// Some events or metrics can be captured after the end of the view. To avoid missing those;\n// an arbitrary delay is added for stopping their tracking after the view ends.\n//\n// Ideally, we would not stop and keep tracking events or metrics until the end of the session.\n// But this might have a small performance impact if there are many many views.\n// So let's have a fairly short delay improving the situation in most cases and avoid impacting performances too much.\nexport const KEEP_TRACKING_AFTER_VIEW_DELAY = 5 * ONE_MINUTE;\nexport function trackViews(location, lifeCycle, domMutationObservable, windowOpenObservable, configuration, locationChangeObservable, areViewsTrackedAutomatically, initialViewOptions) {\n    const activeViews = new Set();\n    let currentView = startNewView(\"initial_load\" /* ViewLoadingType.INITIAL_LOAD */, clocksOrigin(), initialViewOptions);\n    startViewLifeCycle();\n    let locationChangeSubscription;\n    if (areViewsTrackedAutomatically) {\n        locationChangeSubscription = renewViewOnLocationChange(locationChangeObservable);\n    }\n    function startNewView(loadingType, startClocks, viewOptions) {\n        const newlyCreatedView = newView(lifeCycle, domMutationObservable, windowOpenObservable, configuration, location, loadingType, startClocks, viewOptions);\n        activeViews.add(newlyCreatedView);\n        newlyCreatedView.stopObservable.subscribe(() => {\n            activeViews.delete(newlyCreatedView);\n        });\n        return newlyCreatedView;\n    }\n    function startViewLifeCycle() {\n        lifeCycle.subscribe(9 /* LifeCycleEventType.SESSION_RENEWED */, () => {\n            // Renew view on session renewal\n            currentView = startNewView(\"route_change\" /* ViewLoadingType.ROUTE_CHANGE */, undefined, {\n                name: currentView.name,\n                service: currentView.service,\n                version: currentView.version,\n                context: currentView.contextManager.getContext(),\n            });\n        });\n        lifeCycle.subscribe(8 /* LifeCycleEventType.SESSION_EXPIRED */, () => {\n            currentView.end({ sessionIsActive: false });\n        });\n        // End the current view on page unload\n        lifeCycle.subscribe(10 /* LifeCycleEventType.PAGE_EXITED */, (pageExitEvent) => {\n            if (pageExitEvent.reason === PageExitReason.UNLOADING) {\n                currentView.end();\n            }\n        });\n    }\n    function renewViewOnLocationChange(locationChangeObservable) {\n        return locationChangeObservable.subscribe(({ oldLocation, newLocation }) => {\n            if (areDifferentLocation(oldLocation, newLocation)) {\n                currentView.end();\n                currentView = startNewView(\"route_change\" /* ViewLoadingType.ROUTE_CHANGE */);\n            }\n        });\n    }\n    return {\n        addTiming: (name, time = timeStampNow()) => {\n            currentView.addTiming(name, time);\n        },\n        startView: (options, startClocks) => {\n            currentView.end({ endClocks: startClocks });\n            currentView = startNewView(\"route_change\" /* ViewLoadingType.ROUTE_CHANGE */, startClocks, options);\n        },\n        setViewContext: (context) => {\n            currentView.contextManager.setContext(context);\n        },\n        setViewContextProperty: (key, value) => {\n            currentView.contextManager.setContextProperty(key, value);\n        },\n        setViewName: (name) => {\n            currentView.setViewName(name);\n        },\n        getViewContext: () => currentView.contextManager.getContext(),\n        stop: () => {\n            if (locationChangeSubscription) {\n                locationChangeSubscription.unsubscribe();\n            }\n            currentView.end();\n            activeViews.forEach((view) => view.stop());\n        },\n    };\n}\nfunction newView(lifeCycle, domMutationObservable, windowOpenObservable, configuration, initialLocation, loadingType, startClocks = clocksNow(), viewOptions) {\n    // Setup initial values\n    const id = generateUUID();\n    const stopObservable = new Observable();\n    const customTimings = {};\n    let documentVersion = 0;\n    let endClocks;\n    const location = shallowClone(initialLocation);\n    const contextManager = createContextManager();\n    let sessionIsActive = true;\n    let name;\n    let service;\n    let version;\n    let context;\n    if (viewOptions) {\n        name = viewOptions.name;\n        service = viewOptions.service || undefined;\n        version = viewOptions.version || undefined;\n        if (viewOptions.context) {\n            context = viewOptions.context;\n            // use ContextManager to update the context so we always sanitize it\n            contextManager.setContext(context);\n        }\n    }\n    const viewCreatedEvent = {\n        id,\n        name,\n        startClocks,\n        service,\n        version,\n        context,\n    };\n    lifeCycle.notify(1 /* LifeCycleEventType.BEFORE_VIEW_CREATED */, viewCreatedEvent);\n    lifeCycle.notify(2 /* LifeCycleEventType.VIEW_CREATED */, viewCreatedEvent);\n    // Update the view every time the measures are changing\n    const { throttled: scheduleViewUpdate, cancel: cancelScheduleViewUpdate } = throttle(triggerViewUpdate, THROTTLE_VIEW_UPDATE_PERIOD, {\n        leading: false,\n    });\n    const { setLoadEvent, setViewEnd, stop: stopCommonViewMetricsTracking, stopINPTracking, getCommonViewMetrics, } = trackCommonViewMetrics(lifeCycle, domMutationObservable, windowOpenObservable, configuration, scheduleViewUpdate, loadingType, startClocks);\n    const { stop: stopInitialViewMetricsTracking, initialViewMetrics } = loadingType === \"initial_load\" /* ViewLoadingType.INITIAL_LOAD */\n        ? trackInitialViewMetrics(configuration, setLoadEvent, scheduleViewUpdate)\n        : { stop: noop, initialViewMetrics: {} };\n    const { stop: stopEventCountsTracking, eventCounts } = trackViewEventCounts(lifeCycle, id, scheduleViewUpdate);\n    // Session keep alive\n    const keepAliveIntervalId = setInterval(triggerViewUpdate, SESSION_KEEP_ALIVE_INTERVAL);\n    // Initial view update\n    triggerViewUpdate();\n    contextManager.changeObservable.subscribe(triggerViewUpdate);\n    function triggerViewUpdate() {\n        cancelScheduleViewUpdate();\n        documentVersion += 1;\n        const currentEnd = endClocks === undefined ? timeStampNow() : endClocks.timeStamp;\n        lifeCycle.notify(3 /* LifeCycleEventType.VIEW_UPDATED */, {\n            customTimings,\n            documentVersion,\n            id,\n            name,\n            service,\n            version,\n            context: contextManager.getContext(),\n            loadingType,\n            location,\n            startClocks,\n            commonViewMetrics: getCommonViewMetrics(),\n            initialViewMetrics,\n            duration: elapsed(startClocks.timeStamp, currentEnd),\n            isActive: endClocks === undefined,\n            sessionIsActive,\n            eventCounts,\n        });\n    }\n    return {\n        get name() {\n            return name;\n        },\n        service,\n        version,\n        contextManager,\n        stopObservable,\n        end(options = {}) {\n            var _a, _b;\n            if (endClocks) {\n                // view already ended\n                return;\n            }\n            endClocks = (_a = options.endClocks) !== null && _a !== void 0 ? _a : clocksNow();\n            sessionIsActive = (_b = options.sessionIsActive) !== null && _b !== void 0 ? _b : true;\n            lifeCycle.notify(4 /* LifeCycleEventType.VIEW_ENDED */, { endClocks });\n            lifeCycle.notify(5 /* LifeCycleEventType.AFTER_VIEW_ENDED */, { endClocks });\n            clearInterval(keepAliveIntervalId);\n            setViewEnd(endClocks.relative);\n            stopCommonViewMetricsTracking();\n            triggerViewUpdate();\n            setTimeout(() => {\n                this.stop();\n            }, KEEP_TRACKING_AFTER_VIEW_DELAY);\n        },\n        stop() {\n            stopInitialViewMetricsTracking();\n            stopEventCountsTracking();\n            stopINPTracking();\n            stopObservable.notify();\n        },\n        addTiming(name, time) {\n            if (endClocks) {\n                return;\n            }\n            const relativeTime = looksLikeRelativeTime(time) ? time : elapsed(startClocks.timeStamp, time);\n            customTimings[sanitizeTiming(name)] = relativeTime;\n            scheduleViewUpdate();\n        },\n        setViewName(updatedName) {\n            name = updatedName;\n            triggerViewUpdate();\n        },\n    };\n}\n/**\n * Timing name is used as facet path that must contain only letters, digits, or the characters - _ . @ $\n */\nfunction sanitizeTiming(name) {\n    const sanitized = name.replace(/[^a-zA-Z0-9-_.@$]/g, '_');\n    if (sanitized !== name) {\n        display.warn(`Invalid timing name: ${name}, sanitized to: ${sanitized}`);\n    }\n    return sanitized;\n}\nfunction areDifferentLocation(currentLocation, otherLocation) {\n    return (currentLocation.pathname !== otherLocation.pathname ||\n        (!isHashAnAnchor(otherLocation.hash) &&\n            getPathFromHash(otherLocation.hash) !== getPathFromHash(currentLocation.hash)));\n}\nfunction isHashAnAnchor(hash) {\n    const correspondingId = hash.substring(1);\n    // check if the correspondingId is empty because on Firefox an empty string passed to getElementById() prints a consol warning\n    return correspondingId !== '' && !!document.getElementById(correspondingId);\n}\nfunction getPathFromHash(hash) {\n    const index = hash.indexOf('?');\n    return index < 0 ? hash : hash.slice(0, index);\n}\n//# sourceMappingURL=trackViews.js.map","import { trackEventCounts } from '../trackEventCounts';\nexport function trackViewEventCounts(lifeCycle, viewId, onChange) {\n    const { stop, eventCounts } = trackEventCounts({\n        lifeCycle,\n        isChildEvent: (event) => event.view.id === viewId,\n        onChange,\n    });\n    return {\n        stop,\n        eventCounts,\n    };\n}\n//# sourceMappingURL=trackViewEventCounts.js.map","import { isEmptyObject, mapValues, toServerDuration } from '@datadog/browser-core';\nimport { discardNegativeDuration } from '../discardNegativeDuration';\nimport { trackViews } from './trackViews';\nexport function startViewCollection(lifeCycle, configuration, location, domMutationObservable, pageOpenObserable, locationChangeObservable, pageStateHistory, recorderApi, initialViewOptions) {\n    lifeCycle.subscribe(3 /* LifeCycleEventType.VIEW_UPDATED */, (view) => lifeCycle.notify(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, processViewUpdate(view, configuration, recorderApi, pageStateHistory)));\n    return trackViews(location, lifeCycle, domMutationObservable, pageOpenObserable, configuration, locationChangeObservable, !configuration.trackViewsManually, initialViewOptions);\n}\nfunction processViewUpdate(view, configuration, recorderApi, pageStateHistory) {\n    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;\n    const replayStats = recorderApi.getReplayStats(view.id);\n    const pageStates = pageStateHistory.findAll(view.startClocks.relative, view.duration);\n    const viewEvent = {\n        _dd: {\n            document_version: view.documentVersion,\n            replay_stats: replayStats,\n            page_states: pageStates,\n            configuration: {\n                start_session_replay_recording_manually: configuration.startSessionReplayRecordingManually,\n            },\n        },\n        date: view.startClocks.timeStamp,\n        type: \"view\" /* RumEventType.VIEW */,\n        view: {\n            action: {\n                count: view.eventCounts.actionCount,\n            },\n            frustration: {\n                count: view.eventCounts.frustrationCount,\n            },\n            cumulative_layout_shift: (_a = view.commonViewMetrics.cumulativeLayoutShift) === null || _a === void 0 ? void 0 : _a.value,\n            cumulative_layout_shift_time: toServerDuration((_b = view.commonViewMetrics.cumulativeLayoutShift) === null || _b === void 0 ? void 0 : _b.time),\n            cumulative_layout_shift_target_selector: (_c = view.commonViewMetrics.cumulativeLayoutShift) === null || _c === void 0 ? void 0 : _c.targetSelector,\n            first_byte: toServerDuration((_d = view.initialViewMetrics.navigationTimings) === null || _d === void 0 ? void 0 : _d.firstByte),\n            dom_complete: toServerDuration((_e = view.initialViewMetrics.navigationTimings) === null || _e === void 0 ? void 0 : _e.domComplete),\n            dom_content_loaded: toServerDuration((_f = view.initialViewMetrics.navigationTimings) === null || _f === void 0 ? void 0 : _f.domContentLoaded),\n            dom_interactive: toServerDuration((_g = view.initialViewMetrics.navigationTimings) === null || _g === void 0 ? void 0 : _g.domInteractive),\n            error: {\n                count: view.eventCounts.errorCount,\n            },\n            first_contentful_paint: toServerDuration(view.initialViewMetrics.firstContentfulPaint),\n            first_input_delay: toServerDuration((_h = view.initialViewMetrics.firstInput) === null || _h === void 0 ? void 0 : _h.delay),\n            first_input_time: toServerDuration((_j = view.initialViewMetrics.firstInput) === null || _j === void 0 ? void 0 : _j.time),\n            first_input_target_selector: (_k = view.initialViewMetrics.firstInput) === null || _k === void 0 ? void 0 : _k.targetSelector,\n            interaction_to_next_paint: toServerDuration((_l = view.commonViewMetrics.interactionToNextPaint) === null || _l === void 0 ? void 0 : _l.value),\n            interaction_to_next_paint_time: toServerDuration((_m = view.commonViewMetrics.interactionToNextPaint) === null || _m === void 0 ? void 0 : _m.time),\n            interaction_to_next_paint_target_selector: (_o = view.commonViewMetrics.interactionToNextPaint) === null || _o === void 0 ? void 0 : _o.targetSelector,\n            is_active: view.isActive,\n            name: view.name,\n            largest_contentful_paint: toServerDuration((_p = view.initialViewMetrics.largestContentfulPaint) === null || _p === void 0 ? void 0 : _p.value),\n            largest_contentful_paint_target_selector: (_q = view.initialViewMetrics.largestContentfulPaint) === null || _q === void 0 ? void 0 : _q.targetSelector,\n            load_event: toServerDuration((_r = view.initialViewMetrics.navigationTimings) === null || _r === void 0 ? void 0 : _r.loadEvent),\n            loading_time: discardNegativeDuration(toServerDuration(view.commonViewMetrics.loadingTime)),\n            loading_type: view.loadingType,\n            long_task: {\n                count: view.eventCounts.longTaskCount,\n            },\n            performance: computeViewPerformanceData(view.commonViewMetrics, view.initialViewMetrics),\n            resource: {\n                count: view.eventCounts.resourceCount,\n            },\n            time_spent: toServerDuration(view.duration),\n        },\n        display: view.commonViewMetrics.scroll\n            ? {\n                scroll: {\n                    max_depth: view.commonViewMetrics.scroll.maxDepth,\n                    max_depth_scroll_top: view.commonViewMetrics.scroll.maxDepthScrollTop,\n                    max_scroll_height: view.commonViewMetrics.scroll.maxScrollHeight,\n                    max_scroll_height_time: toServerDuration(view.commonViewMetrics.scroll.maxScrollHeightTime),\n                },\n            }\n            : undefined,\n        session: {\n            has_replay: replayStats ? true : undefined,\n            is_active: view.sessionIsActive ? undefined : false,\n        },\n        privacy: {\n            replay_level: configuration.defaultPrivacyLevel,\n        },\n    };\n    if (!isEmptyObject(view.customTimings)) {\n        viewEvent.view.custom_timings = mapValues(view.customTimings, toServerDuration);\n    }\n    return {\n        rawRumEvent: viewEvent,\n        startTime: view.startClocks.relative,\n        domainContext: {\n            location: view.location,\n        },\n    };\n}\nfunction computeViewPerformanceData({ cumulativeLayoutShift, interactionToNextPaint }, { firstContentfulPaint, firstInput, largestContentfulPaint }) {\n    return {\n        cls: cumulativeLayoutShift && {\n            score: cumulativeLayoutShift.value,\n            timestamp: toServerDuration(cumulativeLayoutShift.time),\n            target_selector: cumulativeLayoutShift.targetSelector,\n            previous_rect: cumulativeLayoutShift.previousRect,\n            current_rect: cumulativeLayoutShift.currentRect,\n        },\n        fcp: firstContentfulPaint && { timestamp: toServerDuration(firstContentfulPaint) },\n        fid: firstInput && {\n            duration: toServerDuration(firstInput.delay),\n            timestamp: toServerDuration(firstInput.time),\n            target_selector: firstInput.targetSelector,\n        },\n        inp: interactionToNextPaint && {\n            duration: toServerDuration(interactionToNextPaint.value),\n            timestamp: toServerDuration(interactionToNextPaint.time),\n            target_selector: interactionToNextPaint.targetSelector,\n        },\n        lcp: largestContentfulPaint && {\n            timestamp: toServerDuration(largestContentfulPaint.value),\n            target_selector: largestContentfulPaint.targetSelector,\n        },\n    };\n}\n//# sourceMappingURL=viewCollection.js.map","import { Observable } from '../../tools/observable';\nimport { createValueHistory } from '../../tools/valueHistory';\nimport { relativeNow, clocksOrigin, ONE_MINUTE } from '../../tools/utils/timeUtils';\nimport { addEventListener, addEventListeners } from '../../browser/addEventListener';\nimport { clearInterval, setInterval } from '../../tools/timer';\nimport { SESSION_TIME_OUT_DELAY } from './sessionConstants';\nimport { startSessionStore } from './sessionStore';\nexport const VISIBILITY_CHECK_DELAY = ONE_MINUTE;\nconst SESSION_CONTEXT_TIMEOUT_DELAY = SESSION_TIME_OUT_DELAY;\nlet stopCallbacks = [];\nexport function startSessionManager(configuration, productKey, computeSessionState, trackingConsentState) {\n    const renewObservable = new Observable();\n    const expireObservable = new Observable();\n    // TODO - Improve configuration type and remove assertion\n    const sessionStore = startSessionStore(configuration.sessionStoreStrategyType, configuration, productKey, computeSessionState);\n    stopCallbacks.push(() => sessionStore.stop());\n    const sessionContextHistory = createValueHistory({\n        expireDelay: SESSION_CONTEXT_TIMEOUT_DELAY,\n    });\n    stopCallbacks.push(() => sessionContextHistory.stop());\n    sessionStore.renewObservable.subscribe(() => {\n        sessionContextHistory.add(buildSessionContext(), relativeNow());\n        renewObservable.notify();\n    });\n    sessionStore.expireObservable.subscribe(() => {\n        expireObservable.notify();\n        sessionContextHistory.closeActive(relativeNow());\n    });\n    // We expand/renew session unconditionally as tracking consent is always granted when the session\n    // manager is started.\n    sessionStore.expandOrRenewSession();\n    sessionContextHistory.add(buildSessionContext(), clocksOrigin().relative);\n    trackingConsentState.observable.subscribe(() => {\n        if (trackingConsentState.isGranted()) {\n            sessionStore.expandOrRenewSession();\n        }\n        else {\n            sessionStore.expire();\n        }\n    });\n    trackActivity(configuration, () => {\n        if (trackingConsentState.isGranted()) {\n            sessionStore.expandOrRenewSession();\n        }\n    });\n    trackVisibility(configuration, () => sessionStore.expandSession());\n    trackResume(configuration, () => sessionStore.restartSession());\n    function buildSessionContext() {\n        return {\n            id: sessionStore.getSession().id,\n            trackingType: sessionStore.getSession()[productKey],\n            isReplayForced: !!sessionStore.getSession().forcedReplay,\n            anonymousId: sessionStore.getSession().anonymousId,\n        };\n    }\n    return {\n        findSession: (startTime, options) => sessionContextHistory.find(startTime, options),\n        renewObservable,\n        expireObservable,\n        sessionStateUpdateObservable: sessionStore.sessionStateUpdateObservable,\n        expire: sessionStore.expire,\n        updateSessionState: sessionStore.updateSessionState,\n    };\n}\nexport function stopSessionManager() {\n    stopCallbacks.forEach((e) => e());\n    stopCallbacks = [];\n}\nfunction trackActivity(configuration, expandOrRenewSession) {\n    const { stop } = addEventListeners(configuration, window, [\"click\" /* DOM_EVENT.CLICK */, \"touchstart\" /* DOM_EVENT.TOUCH_START */, \"keydown\" /* DOM_EVENT.KEY_DOWN */, \"scroll\" /* DOM_EVENT.SCROLL */], expandOrRenewSession, { capture: true, passive: true });\n    stopCallbacks.push(stop);\n}\nfunction trackVisibility(configuration, expandSession) {\n    const expandSessionWhenVisible = () => {\n        if (document.visibilityState === 'visible') {\n            expandSession();\n        }\n    };\n    const { stop } = addEventListener(configuration, document, \"visibilitychange\" /* DOM_EVENT.VISIBILITY_CHANGE */, expandSessionWhenVisible);\n    stopCallbacks.push(stop);\n    const visibilityCheckInterval = setInterval(expandSessionWhenVisible, VISIBILITY_CHECK_DELAY);\n    stopCallbacks.push(() => {\n        clearInterval(visibilityCheckInterval);\n    });\n}\nfunction trackResume(configuration, cb) {\n    const { stop } = addEventListener(configuration, window, \"resume\" /* DOM_EVENT.RESUME */, cb, { capture: true });\n    stopCallbacks.push(stop);\n}\n//# sourceMappingURL=sessionManager.js.map","import { Observable, bridgeSupports, noop, performDraw, startSessionManager, } from '@datadog/browser-core';\nexport const RUM_SESSION_KEY = 'rum';\nexport function startRumSessionManager(configuration, lifeCycle, trackingConsentState) {\n    const sessionManager = startSessionManager(configuration, RUM_SESSION_KEY, (rawTrackingType) => computeSessionState(configuration, rawTrackingType), trackingConsentState);\n    sessionManager.expireObservable.subscribe(() => {\n        lifeCycle.notify(8 /* LifeCycleEventType.SESSION_EXPIRED */);\n    });\n    sessionManager.renewObservable.subscribe(() => {\n        lifeCycle.notify(9 /* LifeCycleEventType.SESSION_RENEWED */);\n    });\n    sessionManager.sessionStateUpdateObservable.subscribe(({ previousState, newState }) => {\n        if (!previousState.forcedReplay && newState.forcedReplay) {\n            const sessionEntity = sessionManager.findSession();\n            if (sessionEntity) {\n                sessionEntity.isReplayForced = true;\n            }\n        }\n    });\n    return {\n        findTrackedSession: (startTime) => {\n            const session = sessionManager.findSession(startTime);\n            if (!session || !isTypeTracked(session.trackingType)) {\n                return;\n            }\n            return {\n                id: session.id,\n                sessionReplay: session.trackingType === \"1\" /* RumTrackingType.TRACKED_WITH_SESSION_REPLAY */\n                    ? 1 /* SessionReplayState.SAMPLED */\n                    : session.isReplayForced\n                        ? 2 /* SessionReplayState.FORCED */\n                        : 0 /* SessionReplayState.OFF */,\n                anonymousId: session.anonymousId,\n            };\n        },\n        expire: sessionManager.expire,\n        expireObservable: sessionManager.expireObservable,\n        setForcedReplay: () => sessionManager.updateSessionState({ forcedReplay: '1' }),\n    };\n}\n/**\n * Start a tracked replay session stub\n */\nexport function startRumSessionManagerStub() {\n    const session = {\n        id: '00000000-aaaa-0000-aaaa-000000000000',\n        sessionReplay: bridgeSupports(\"records\" /* BridgeCapability.RECORDS */) ? 1 /* SessionReplayState.SAMPLED */ : 0 /* SessionReplayState.OFF */,\n    };\n    return {\n        findTrackedSession: () => session,\n        expire: noop,\n        expireObservable: new Observable(),\n        setForcedReplay: noop,\n    };\n}\nfunction computeSessionState(configuration, rawTrackingType) {\n    let trackingType;\n    if (hasValidRumSession(rawTrackingType)) {\n        trackingType = rawTrackingType;\n    }\n    else if (!performDraw(configuration.sessionSampleRate)) {\n        trackingType = \"0\" /* RumTrackingType.NOT_TRACKED */;\n    }\n    else if (!performDraw(configuration.sessionReplaySampleRate)) {\n        trackingType = \"2\" /* RumTrackingType.TRACKED_WITHOUT_SESSION_REPLAY */;\n    }\n    else {\n        trackingType = \"1\" /* RumTrackingType.TRACKED_WITH_SESSION_REPLAY */;\n    }\n    return {\n        trackingType,\n        isTracked: isTypeTracked(trackingType),\n    };\n}\nfunction hasValidRumSession(trackingType) {\n    return (trackingType === \"0\" /* RumTrackingType.NOT_TRACKED */ ||\n        trackingType === \"1\" /* RumTrackingType.TRACKED_WITH_SESSION_REPLAY */ ||\n        trackingType === \"2\" /* RumTrackingType.TRACKED_WITHOUT_SESSION_REPLAY */);\n}\nfunction isTypeTracked(rumSessionType) {\n    return (rumSessionType === \"2\" /* RumTrackingType.TRACKED_WITHOUT_SESSION_REPLAY */ ||\n        rumSessionType === \"1\" /* RumTrackingType.TRACKED_WITH_SESSION_REPLAY */);\n}\n//# sourceMappingURL=rumSessionManager.js.map","import { DOCS_TROUBLESHOOTING, MORE_DETAILS, display } from '../tools/display';\nimport { objectValues } from '../tools/utils/polyfills';\nimport { isPageExitReason } from '../browser/pageExitObservable';\nimport { jsonStringify } from '../tools/serialisation/jsonStringify';\nimport { computeBytesCount } from '../tools/utils/byteUtils';\nexport function createBatch({ encoder, request, flushController, messageBytesLimit, }) {\n    let upsertBuffer = {};\n    const flushSubscription = flushController.flushObservable.subscribe((event) => flush(event));\n    function push(serializedMessage, estimatedMessageBytesCount, key) {\n        flushController.notifyBeforeAddMessage(estimatedMessageBytesCount);\n        if (key !== undefined) {\n            upsertBuffer[key] = serializedMessage;\n            flushController.notifyAfterAddMessage();\n        }\n        else {\n            encoder.write(encoder.isEmpty ? serializedMessage : `\\n${serializedMessage}`, (realMessageBytesCount) => {\n                flushController.notifyAfterAddMessage(realMessageBytesCount - estimatedMessageBytesCount);\n            });\n        }\n    }\n    function hasMessageFor(key) {\n        return key !== undefined && upsertBuffer[key] !== undefined;\n    }\n    function remove(key) {\n        const removedMessage = upsertBuffer[key];\n        delete upsertBuffer[key];\n        const messageBytesCount = encoder.estimateEncodedBytesCount(removedMessage);\n        flushController.notifyAfterRemoveMessage(messageBytesCount);\n    }\n    function addOrUpdate(message, key) {\n        const serializedMessage = jsonStringify(message);\n        const estimatedMessageBytesCount = encoder.estimateEncodedBytesCount(serializedMessage);\n        if (estimatedMessageBytesCount >= messageBytesLimit) {\n            display.warn(`Discarded a message whose size was bigger than the maximum allowed size ${messageBytesLimit}KB. ${MORE_DETAILS} ${DOCS_TROUBLESHOOTING}/#technical-limitations`);\n            return;\n        }\n        if (hasMessageFor(key)) {\n            remove(key);\n        }\n        push(serializedMessage, estimatedMessageBytesCount, key);\n    }\n    function flush(event) {\n        const upsertMessages = objectValues(upsertBuffer).join('\\n');\n        upsertBuffer = {};\n        const isPageExit = isPageExitReason(event.reason);\n        const send = isPageExit ? request.sendOnExit : request.send;\n        if (isPageExit &&\n            // Note: checking that the encoder is async is not strictly needed, but it's an optimization:\n            // if the encoder is async we need to send two requests in some cases (one for encoded data\n            // and the other for non-encoded data). But if it's not async, we don't have to worry about\n            // it and always send a single request.\n            encoder.isAsync) {\n            const encoderResult = encoder.finishSync();\n            // Send encoded messages\n            if (encoderResult.outputBytesCount) {\n                send(formatPayloadFromEncoder(encoderResult));\n            }\n            // Send messages that are not yet encoded at this point\n            const pendingMessages = [encoderResult.pendingData, upsertMessages].filter(Boolean).join('\\n');\n            if (pendingMessages) {\n                send({\n                    data: pendingMessages,\n                    bytesCount: computeBytesCount(pendingMessages),\n                });\n            }\n        }\n        else {\n            if (upsertMessages) {\n                encoder.write(encoder.isEmpty ? upsertMessages : `\\n${upsertMessages}`);\n            }\n            encoder.finish((encoderResult) => {\n                send(formatPayloadFromEncoder(encoderResult));\n            });\n        }\n    }\n    return {\n        flushController,\n        add: addOrUpdate,\n        upsert: addOrUpdate,\n        stop: flushSubscription.unsubscribe,\n    };\n}\nfunction formatPayloadFromEncoder(encoderResult) {\n    let data;\n    if (typeof encoderResult.output === 'string') {\n        data = encoderResult.output;\n    }\n    else {\n        data = new Blob([encoderResult.output], {\n            // This will set the 'Content-Type: text/plain' header. Reasoning:\n            // * The intake rejects the request if there is no content type.\n            // * The browser will issue CORS preflight requests if we set it to 'application/json', which\n            // could induce higher intake load (and maybe has other impacts).\n            // * Also it's not quite JSON, since we are concatenating multiple JSON objects separated by\n            // new lines.\n            type: 'text/plain',\n        });\n    }\n    return {\n        data,\n        bytesCount: encoderResult.outputBytesCount,\n        encoding: encoderResult.encoding,\n    };\n}\n//# sourceMappingURL=batch.js.map","import { Observable } from '../tools/observable';\nimport { clearTimeout, setTimeout } from '../tools/timer';\n/**\n * Returns a \"flush controller\", responsible of notifying when flushing a pool of pending data needs\n * to happen. The implementation is designed to support both synchronous and asynchronous usages,\n * but relies on invariants described in each method documentation to keep a coherent state.\n */\nexport function createFlushController({ messagesLimit, bytesLimit, durationLimit, pageExitObservable, sessionExpireObservable, }) {\n    const pageExitSubscription = pageExitObservable.subscribe((event) => flush(event.reason));\n    const sessionExpireSubscription = sessionExpireObservable.subscribe(() => flush('session_expire'));\n    const flushObservable = new Observable(() => () => {\n        pageExitSubscription.unsubscribe();\n        sessionExpireSubscription.unsubscribe();\n    });\n    let currentBytesCount = 0;\n    let currentMessagesCount = 0;\n    function flush(flushReason) {\n        if (currentMessagesCount === 0) {\n            return;\n        }\n        const messagesCount = currentMessagesCount;\n        const bytesCount = currentBytesCount;\n        currentMessagesCount = 0;\n        currentBytesCount = 0;\n        cancelDurationLimitTimeout();\n        flushObservable.notify({\n            reason: flushReason,\n            messagesCount,\n            bytesCount,\n        });\n    }\n    let durationLimitTimeoutId;\n    function scheduleDurationLimitTimeout() {\n        if (durationLimitTimeoutId === undefined) {\n            durationLimitTimeoutId = setTimeout(() => {\n                flush('duration_limit');\n            }, durationLimit);\n        }\n    }\n    function cancelDurationLimitTimeout() {\n        clearTimeout(durationLimitTimeoutId);\n        durationLimitTimeoutId = undefined;\n    }\n    return {\n        flushObservable,\n        get messagesCount() {\n            return currentMessagesCount;\n        },\n        /**\n         * Notifies that a message will be added to a pool of pending messages waiting to be flushed.\n         *\n         * This function needs to be called synchronously, right before adding the message, so no flush\n         * event can happen after `notifyBeforeAddMessage` and before adding the message.\n         *\n         * @param estimatedMessageBytesCount: an estimation of the message bytes count once it is\n         * actually added.\n         */\n        notifyBeforeAddMessage(estimatedMessageBytesCount) {\n            if (currentBytesCount + estimatedMessageBytesCount >= bytesLimit) {\n                flush('bytes_limit');\n            }\n            // Consider the message to be added now rather than in `notifyAfterAddMessage`, because if no\n            // message was added yet and `notifyAfterAddMessage` is called asynchronously, we still want\n            // to notify when a flush is needed (for example on page exit).\n            currentMessagesCount += 1;\n            currentBytesCount += estimatedMessageBytesCount;\n            scheduleDurationLimitTimeout();\n        },\n        /**\n         * Notifies that a message *was* added to a pool of pending messages waiting to be flushed.\n         *\n         * This function can be called asynchronously after the message was added, but in this case it\n         * should not be called if a flush event occurred in between.\n         *\n         * @param messageBytesCountDiff: the difference between the estimated message bytes count and\n         * its actual bytes count once added to the pool.\n         */\n        notifyAfterAddMessage(messageBytesCountDiff = 0) {\n            currentBytesCount += messageBytesCountDiff;\n            if (currentMessagesCount >= messagesLimit) {\n                flush('messages_limit');\n            }\n            else if (currentBytesCount >= bytesLimit) {\n                flush('bytes_limit');\n            }\n        },\n        /**\n         * Notifies that a message was removed from a pool of pending messages waiting to be flushed.\n         *\n         * This function needs to be called synchronously, right after removing the message, so no flush\n         * event can happen after removing the message and before `notifyAfterRemoveMessage`.\n         *\n         * @param messageBytesCount: the message bytes count that was added to the pool. Should\n         * correspond to the sum of bytes counts passed to `notifyBeforeAddMessage` and\n         * `notifyAfterAddMessage`.\n         */\n        notifyAfterRemoveMessage(messageBytesCount) {\n            currentBytesCount -= messageBytesCount;\n            currentMessagesCount -= 1;\n            if (currentMessagesCount === 0) {\n                cancelDurationLimitTimeout();\n            }\n        },\n    };\n}\n//# sourceMappingURL=flushController.js.map","import { combine, isTelemetryReplicationAllowed, startBatchWithReplica, } from '@datadog/browser-core';\nexport function startRumBatch(configuration, lifeCycle, telemetryEventObservable, reportError, pageExitObservable, sessionExpireObservable, createEncoder) {\n    const replica = configuration.replica;\n    const batch = startBatchWithReplica(configuration, {\n        endpoint: configuration.rumEndpointBuilder,\n        encoder: createEncoder(2 /* DeflateEncoderStreamId.RUM */),\n    }, replica && {\n        endpoint: replica.rumEndpointBuilder,\n        transformMessage: (message) => combine(message, { application: { id: replica.applicationId } }),\n        encoder: createEncoder(3 /* DeflateEncoderStreamId.RUM_REPLICA */),\n    }, reportError, pageExitObservable, sessionExpireObservable);\n    lifeCycle.subscribe(12 /* LifeCycleEventType.RUM_EVENT_COLLECTED */, (serverRumEvent) => {\n        if (serverRumEvent.type === \"view\" /* RumEventType.VIEW */) {\n            batch.upsert(serverRumEvent, serverRumEvent.view.id);\n        }\n        else {\n            batch.add(serverRumEvent);\n        }\n    });\n    telemetryEventObservable.subscribe((event) => batch.add(event, isTelemetryReplicationAllowed(configuration)));\n    return batch;\n}\n//# sourceMappingURL=startRumBatch.js.map","import { createBatch } from './batch';\nimport { createHttpRequest } from './httpRequest';\nimport { createFlushController } from './flushController';\nexport function startBatchWithReplica(configuration, primary, replica, reportError, pageExitObservable, sessionExpireObservable, batchFactoryImp = createBatch) {\n    const primaryBatch = createBatchFromConfig(configuration, primary);\n    const replicaBatch = replica && createBatchFromConfig(configuration, replica);\n    function createBatchFromConfig(configuration, { endpoint, encoder }) {\n        return batchFactoryImp({\n            encoder,\n            request: createHttpRequest(endpoint, configuration.batchBytesLimit, reportError),\n            flushController: createFlushController({\n                messagesLimit: configuration.batchMessagesLimit,\n                bytesLimit: configuration.batchBytesLimit,\n                durationLimit: configuration.flushTimeout,\n                pageExitObservable,\n                sessionExpireObservable,\n            }),\n            messageBytesLimit: configuration.messageBytesLimit,\n        });\n    }\n    return {\n        flushObservable: primaryBatch.flushController.flushObservable,\n        add(message, replicated = true) {\n            primaryBatch.add(message);\n            if (replicaBatch && replicated) {\n                replicaBatch.add(replica.transformMessage ? replica.transformMessage(message) : message);\n            }\n        },\n        upsert: (message, key) => {\n            primaryBatch.upsert(message, key);\n            if (replicaBatch) {\n                replicaBatch.upsert(replica.transformMessage ? replica.transformMessage(message) : message, key);\n            }\n        },\n        stop: () => {\n            primaryBatch.stop();\n            if (replicaBatch) {\n                replicaBatch.stop();\n            }\n        },\n    };\n}\n//# sourceMappingURL=startBatchWithReplica.js.map","import { SESSION_TIME_OUT_DELAY, relativeNow, createValueHistory } from '@datadog/browser-core';\n/**\n * We want to attach to an event:\n * - the url corresponding to its start\n * - the referrer corresponding to the previous view url (or document referrer for initial view)\n */\nexport const URL_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY;\nexport function startUrlContexts(lifeCycle, locationChangeObservable, location) {\n    const urlContextHistory = createValueHistory({ expireDelay: URL_CONTEXT_TIME_OUT_DELAY });\n    let previousViewUrl;\n    lifeCycle.subscribe(1 /* LifeCycleEventType.BEFORE_VIEW_CREATED */, ({ startClocks }) => {\n        const viewUrl = location.href;\n        urlContextHistory.add(buildUrlContext({\n            url: viewUrl,\n            referrer: !previousViewUrl ? document.referrer : previousViewUrl,\n        }), startClocks.relative);\n        previousViewUrl = viewUrl;\n    });\n    lifeCycle.subscribe(5 /* LifeCycleEventType.AFTER_VIEW_ENDED */, ({ endClocks }) => {\n        urlContextHistory.closeActive(endClocks.relative);\n    });\n    const locationChangeSubscription = locationChangeObservable.subscribe(({ newLocation }) => {\n        const current = urlContextHistory.find();\n        if (current) {\n            const changeTime = relativeNow();\n            urlContextHistory.closeActive(changeTime);\n            urlContextHistory.add(buildUrlContext({\n                url: newLocation.href,\n                referrer: current.referrer,\n            }), changeTime);\n        }\n    });\n    function buildUrlContext({ url, referrer }) {\n        return {\n            url,\n            referrer,\n        };\n    }\n    return {\n        findUrl: (startTime) => urlContextHistory.find(startTime),\n        stop: () => {\n            locationChangeSubscription.unsubscribe();\n            urlContextHistory.stop();\n        },\n    };\n}\n//# sourceMappingURL=urlContexts.js.map","import { addEventListener, instrumentMethod, Observable, shallowClone } from '@datadog/browser-core';\nexport function createLocationChangeObservable(configuration, location) {\n    let currentLocation = shallowClone(location);\n    return new Observable((observable) => {\n        const { stop: stopHistoryTracking } = trackHistory(configuration, onLocationChange);\n        const { stop: stopHashTracking } = trackHash(configuration, onLocationChange);\n        function onLocationChange() {\n            if (currentLocation.href === location.href) {\n                return;\n            }\n            const newLocation = shallowClone(location);\n            observable.notify({\n                newLocation,\n                oldLocation: currentLocation,\n            });\n            currentLocation = newLocation;\n        }\n        return () => {\n            stopHistoryTracking();\n            stopHashTracking();\n        };\n    });\n}\nfunction trackHistory(configuration, onHistoryChange) {\n    const { stop: stopInstrumentingPushState } = instrumentMethod(getHistoryInstrumentationTarget('pushState'), 'pushState', ({ onPostCall }) => {\n        onPostCall(onHistoryChange);\n    });\n    const { stop: stopInstrumentingReplaceState } = instrumentMethod(getHistoryInstrumentationTarget('replaceState'), 'replaceState', ({ onPostCall }) => {\n        onPostCall(onHistoryChange);\n    });\n    const { stop: removeListener } = addEventListener(configuration, window, \"popstate\" /* DOM_EVENT.POP_STATE */, onHistoryChange);\n    return {\n        stop: () => {\n            stopInstrumentingPushState();\n            stopInstrumentingReplaceState();\n            removeListener();\n        },\n    };\n}\nfunction trackHash(configuration, onHashChange) {\n    return addEventListener(configuration, window, \"hashchange\" /* DOM_EVENT.HASH_CHANGE */, onHashChange);\n}\nfunction getHistoryInstrumentationTarget(methodName) {\n    // Ideally we should always instument the method on the prototype, however some frameworks (e.g [Next.js](https://github.com/vercel/next.js/blob/d3f5532065f3e3bb84fb54bd2dfd1a16d0f03a21/packages/next/src/client/components/app-router.tsx#L429))\n    // are wrapping the instance method. In that case we should also wrap the instance method.\n    return Object.prototype.hasOwnProperty.call(history, methodName) ? history : History.prototype;\n}\n//# sourceMappingURL=locationChangeObservable.js.map","import { SESSION_TIME_OUT_DELAY, createValueHistory } from '@datadog/browser-core';\nexport const FEATURE_FLAG_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY;\nexport const BYTES_COMPUTATION_THROTTLING_DELAY = 200;\n/**\n * Start feature flag contexts\n *\n * Feature flag contexts follow the life of views.\n * A new context is added when a view is created and ended when the view is ended\n *\n * Note: we choose not to add a new context at each evaluation to save memory\n */\nexport function startFeatureFlagContexts(lifeCycle, customerDataTracker) {\n    const featureFlagContexts = createValueHistory({\n        expireDelay: FEATURE_FLAG_CONTEXT_TIME_OUT_DELAY,\n    });\n    lifeCycle.subscribe(1 /* LifeCycleEventType.BEFORE_VIEW_CREATED */, ({ startClocks }) => {\n        featureFlagContexts.add({}, startClocks.relative);\n        customerDataTracker.resetCustomerData();\n    });\n    lifeCycle.subscribe(5 /* LifeCycleEventType.AFTER_VIEW_ENDED */, ({ endClocks }) => {\n        featureFlagContexts.closeActive(endClocks.relative);\n    });\n    return {\n        findFeatureFlagEvaluations: (startTime) => featureFlagContexts.find(startTime),\n        addFeatureFlagEvaluation: (key, value) => {\n            const currentContext = featureFlagContexts.find();\n            if (currentContext) {\n                currentContext[key] = value;\n                customerDataTracker.updateCustomerData(currentContext);\n            }\n        },\n        stop: () => customerDataTracker.stop(),\n    };\n}\n//# sourceMappingURL=featureFlagContext.js.map","import { performDraw, ONE_SECOND, addTelemetryDebug, setInterval } from '@datadog/browser-core';\nexport const MEASURES_PERIOD_DURATION = 10 * ONE_SECOND;\nlet currentPeriodMeasures;\nlet currentBatchMeasures;\nlet batchHasRumEvent;\nexport function startCustomerDataTelemetry(configuration, telemetry, lifeCycle, customerDataTrackerManager, batchFlushObservable) {\n    const customerDataTelemetryEnabled = telemetry.enabled && performDraw(configuration.customerDataTelemetrySampleRate);\n    if (!customerDataTelemetryEnabled) {\n        return;\n    }\n    initCurrentPeriodMeasures();\n    initCurrentBatchMeasures();\n    // We measure the data of every view updates even if there could only be one per batch due to the upsert\n    // It means that contexts bytes count sums can be higher than it really is\n    lifeCycle.subscribe(12 /* LifeCycleEventType.RUM_EVENT_COLLECTED */, (event) => {\n        batchHasRumEvent = true;\n        updateMeasure(currentBatchMeasures.globalContextBytes, customerDataTrackerManager.getOrCreateTracker(2 /* CustomerDataType.GlobalContext */).getBytesCount());\n        updateMeasure(currentBatchMeasures.userContextBytes, customerDataTrackerManager.getOrCreateTracker(1 /* CustomerDataType.User */).getBytesCount());\n        updateMeasure(currentBatchMeasures.featureFlagBytes, [\"view\" /* RumEventType.VIEW */, \"error\" /* RumEventType.ERROR */].includes(event.type)\n            ? customerDataTrackerManager.getOrCreateTracker(0 /* CustomerDataType.FeatureFlag */).getBytesCount()\n            : 0);\n    });\n    batchFlushObservable.subscribe(({ bytesCount, messagesCount }) => {\n        // Don't measure batch that only contains telemetry events to avoid batch sending loop\n        // It could happen because after each batch we are adding a customer data measures telemetry event to the next one\n        if (!batchHasRumEvent) {\n            return;\n        }\n        currentPeriodMeasures.batchCount += 1;\n        updateMeasure(currentPeriodMeasures.batchBytesCount, bytesCount);\n        updateMeasure(currentPeriodMeasures.batchMessagesCount, messagesCount);\n        mergeMeasure(currentPeriodMeasures.globalContextBytes, currentBatchMeasures.globalContextBytes);\n        mergeMeasure(currentPeriodMeasures.userContextBytes, currentBatchMeasures.userContextBytes);\n        mergeMeasure(currentPeriodMeasures.featureFlagBytes, currentBatchMeasures.featureFlagBytes);\n        initCurrentBatchMeasures();\n    });\n    setInterval(sendCurrentPeriodMeasures, MEASURES_PERIOD_DURATION);\n}\nfunction sendCurrentPeriodMeasures() {\n    if (currentPeriodMeasures.batchCount === 0) {\n        return;\n    }\n    addTelemetryDebug('Customer data measures', currentPeriodMeasures);\n    initCurrentPeriodMeasures();\n}\nfunction createMeasure() {\n    return { min: Infinity, max: 0, sum: 0 };\n}\nfunction updateMeasure(measure, value) {\n    measure.sum += value;\n    measure.min = Math.min(measure.min, value);\n    measure.max = Math.max(measure.max, value);\n}\nfunction mergeMeasure(target, source) {\n    target.sum += source.sum;\n    target.min = Math.min(target.min, source.min);\n    target.max = Math.max(target.max, source.max);\n}\nfunction initCurrentPeriodMeasures() {\n    currentPeriodMeasures = {\n        batchCount: 0,\n        batchBytesCount: createMeasure(),\n        batchMessagesCount: createMeasure(),\n        globalContextBytes: createMeasure(),\n        userContextBytes: createMeasure(),\n        featureFlagBytes: createMeasure(),\n    };\n}\nfunction initCurrentBatchMeasures() {\n    batchHasRumEvent = false;\n    currentBatchMeasures = {\n        globalContextBytes: createMeasure(),\n        userContextBytes: createMeasure(),\n        featureFlagBytes: createMeasure(),\n    };\n}\n//# sourceMappingURL=startCustomerDataTelemetry.js.map","import { elapsed, createValueHistory, SESSION_TIME_OUT_DELAY, toServerDuration, addEventListeners, relativeNow, } from '@datadog/browser-core';\n// Arbitrary value to cap number of element for memory consumption in the browser\nexport const MAX_PAGE_STATE_ENTRIES = 4000;\n// Arbitrary value to cap number of element for backend & to save bandwidth\nexport const MAX_PAGE_STATE_ENTRIES_SELECTABLE = 500;\nexport const PAGE_STATE_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY;\nexport function startPageStateHistory(configuration, maxPageStateEntriesSelectable = MAX_PAGE_STATE_ENTRIES_SELECTABLE) {\n    const pageStateEntryHistory = createValueHistory({\n        expireDelay: PAGE_STATE_CONTEXT_TIME_OUT_DELAY,\n        maxEntries: MAX_PAGE_STATE_ENTRIES,\n    });\n    let currentPageState;\n    addPageState(getPageState(), relativeNow());\n    const { stop: stopEventListeners } = addEventListeners(configuration, window, [\n        \"pageshow\" /* DOM_EVENT.PAGE_SHOW */,\n        \"focus\" /* DOM_EVENT.FOCUS */,\n        \"blur\" /* DOM_EVENT.BLUR */,\n        \"visibilitychange\" /* DOM_EVENT.VISIBILITY_CHANGE */,\n        \"resume\" /* DOM_EVENT.RESUME */,\n        \"freeze\" /* DOM_EVENT.FREEZE */,\n        \"pagehide\" /* DOM_EVENT.PAGE_HIDE */,\n    ], (event) => {\n        addPageState(computePageState(event), event.timeStamp);\n    }, { capture: true });\n    function addPageState(nextPageState, startTime = relativeNow()) {\n        if (nextPageState === currentPageState) {\n            return;\n        }\n        currentPageState = nextPageState;\n        pageStateEntryHistory.closeActive(startTime);\n        pageStateEntryHistory.add({ state: currentPageState, startTime }, startTime);\n    }\n    const pageStateHistory = {\n        findAll: (eventStartTime, duration) => {\n            const pageStateEntries = pageStateEntryHistory.findAll(eventStartTime, duration);\n            if (pageStateEntries.length === 0) {\n                return;\n            }\n            const pageStateServerEntries = [];\n            // limit the number of entries to return\n            const limit = Math.max(0, pageStateEntries.length - maxPageStateEntriesSelectable);\n            // loop page state entries backward to return the selected ones in desc order\n            for (let index = pageStateEntries.length - 1; index >= limit; index--) {\n                const pageState = pageStateEntries[index];\n                // compute the start time relative to the event start time (ex: to be relative to the view start time)\n                const relativeStartTime = elapsed(eventStartTime, pageState.startTime);\n                pageStateServerEntries.push({\n                    state: pageState.state,\n                    start: toServerDuration(relativeStartTime),\n                });\n            }\n            return pageStateServerEntries;\n        },\n        wasInPageStateAt: (state, startTime) => pageStateHistory.wasInPageStateDuringPeriod(state, startTime, 0),\n        wasInPageStateDuringPeriod: (state, startTime, duration) => pageStateEntryHistory.findAll(startTime, duration).some((pageState) => pageState.state === state),\n        addPageState,\n        stop: () => {\n            stopEventListeners();\n            pageStateEntryHistory.stop();\n        },\n    };\n    return pageStateHistory;\n}\nfunction computePageState(event) {\n    if (event.type === \"freeze\" /* DOM_EVENT.FREEZE */) {\n        return \"frozen\" /* PageState.FROZEN */;\n    }\n    else if (event.type === \"pagehide\" /* DOM_EVENT.PAGE_HIDE */) {\n        return event.persisted ? \"frozen\" /* PageState.FROZEN */ : \"terminated\" /* PageState.TERMINATED */;\n    }\n    return getPageState();\n}\nfunction getPageState() {\n    if (document.visibilityState === 'hidden') {\n        return \"hidden\" /* PageState.HIDDEN */;\n    }\n    if (document.hasFocus()) {\n        return \"active\" /* PageState.ACTIVE */;\n    }\n    return \"passive\" /* PageState.PASSIVE */;\n}\n//# sourceMappingURL=pageStateHistory.js.map","import { setInterval, clearInterval, Observable, addEventListener, ONE_SECOND, findCommaSeparatedValue, } from '@datadog/browser-core';\nexport function createCookieObservable(configuration, cookieName) {\n    const detectCookieChangeStrategy = window.cookieStore\n        ? listenToCookieStoreChange(configuration)\n        : watchCookieFallback;\n    return new Observable((observable) => detectCookieChangeStrategy(cookieName, (event) => observable.notify(event)));\n}\nfunction listenToCookieStoreChange(configuration) {\n    return (cookieName, callback) => {\n        const listener = addEventListener(configuration, window.cookieStore, \"change\" /* DOM_EVENT.CHANGE */, (event) => {\n            // Based on our experimentation, we're assuming that entries for the same cookie cannot be in both the 'changed' and 'deleted' arrays.\n            // However, due to ambiguity in the specification, we asked for clarification: https://github.com/WICG/cookie-store/issues/226\n            const changeEvent = event.changed.find((event) => event.name === cookieName) ||\n                event.deleted.find((event) => event.name === cookieName);\n            if (changeEvent) {\n                callback(changeEvent.value);\n            }\n        });\n        return listener.stop;\n    };\n}\nexport const WATCH_COOKIE_INTERVAL_DELAY = ONE_SECOND;\nfunction watchCookieFallback(cookieName, callback) {\n    const previousCookieValue = findCommaSeparatedValue(document.cookie, cookieName);\n    const watchCookieIntervalId = setInterval(() => {\n        const cookieValue = findCommaSeparatedValue(document.cookie, cookieName);\n        if (cookieValue !== previousCookieValue) {\n            callback(cookieValue);\n        }\n    }, WATCH_COOKIE_INTERVAL_DELAY);\n    return () => {\n        clearInterval(watchCookieIntervalId);\n    };\n}\n//# sourceMappingURL=cookieObservable.js.map","import { getInitCookie } from '@datadog/browser-core';\nimport { createCookieObservable } from '../../browser/cookieObservable';\nexport const CI_VISIBILITY_TEST_ID_COOKIE_NAME = 'datadog-ci-visibility-test-execution-id';\nexport function startCiVisibilityContext(configuration, cookieObservable = createCookieObservable(configuration, CI_VISIBILITY_TEST_ID_COOKIE_NAME)) {\n    var _a;\n    let testExecutionId = getInitCookie(CI_VISIBILITY_TEST_ID_COOKIE_NAME) || ((_a = window.Cypress) === null || _a === void 0 ? void 0 : _a.env('traceId'));\n    const cookieObservableSubscription = cookieObservable.subscribe((value) => {\n        testExecutionId = value;\n    });\n    return {\n        get: () => {\n            if (typeof testExecutionId === 'string') {\n                return {\n                    test_execution_id: testExecutionId,\n                };\n            }\n        },\n        stop: () => cookieObservableSubscription.unsubscribe(),\n    };\n}\n//# sourceMappingURL=ciVisibilityContext.js.map","import { sendToExtension, createPageExitObservable, startTelemetry, canUseEventBridge, getEventBridge, addTelemetryDebug, drainPreStartTelemetry, } from '@datadog/browser-core';\nimport { createDOMMutationObservable } from '../browser/domMutationObservable';\nimport { createWindowOpenObservable } from '../browser/windowOpenObservable';\nimport { startRumAssembly } from '../domain/assembly';\nimport { startInternalContext } from '../domain/contexts/internalContext';\nimport { LifeCycle } from '../domain/lifeCycle';\nimport { startViewHistory } from '../domain/contexts/viewHistory';\nimport { startRequestCollection } from '../domain/requestCollection';\nimport { startActionCollection } from '../domain/action/actionCollection';\nimport { startErrorCollection } from '../domain/error/errorCollection';\nimport { startResourceCollection } from '../domain/resource/resourceCollection';\nimport { startViewCollection } from '../domain/view/viewCollection';\nimport { startRumSessionManager, startRumSessionManagerStub } from '../domain/rumSessionManager';\nimport { startRumBatch } from '../transport/startRumBatch';\nimport { startRumEventBridge } from '../transport/startRumEventBridge';\nimport { startUrlContexts } from '../domain/contexts/urlContexts';\nimport { createLocationChangeObservable } from '../browser/locationChangeObservable';\nimport { startFeatureFlagContexts } from '../domain/contexts/featureFlagContext';\nimport { startCustomerDataTelemetry } from '../domain/startCustomerDataTelemetry';\nimport { startPageStateHistory } from '../domain/contexts/pageStateHistory';\nimport { startDisplayContext } from '../domain/contexts/displayContext';\nimport { startVitalCollection } from '../domain/vital/vitalCollection';\nimport { startCiVisibilityContext } from '../domain/contexts/ciVisibilityContext';\nimport { startLongAnimationFrameCollection } from '../domain/longAnimationFrame/longAnimationFrameCollection';\nimport { RumPerformanceEntryType } from '../browser/performanceObservable';\nimport { startLongTaskCollection } from '../domain/longTask/longTaskCollection';\nexport function startRum(configuration, recorderApi, customerDataTrackerManager, getCommonContext, initialViewOptions, createEncoder, \n// `startRum` and its subcomponents assume tracking consent is granted initially and starts\n// collecting logs unconditionally. As such, `startRum` should be called with a\n// `trackingConsentState` set to \"granted\".\ntrackingConsentState, customVitalsState) {\n    var _a;\n    const cleanupTasks = [];\n    const lifeCycle = new LifeCycle();\n    lifeCycle.subscribe(12 /* LifeCycleEventType.RUM_EVENT_COLLECTED */, (event) => sendToExtension('rum', event));\n    const telemetry = startRumTelemetry(configuration);\n    telemetry.setContextProvider(() => {\n        var _a, _b;\n        return ({\n            application: {\n                id: configuration.applicationId,\n            },\n            session: {\n                id: (_a = session.findTrackedSession()) === null || _a === void 0 ? void 0 : _a.id,\n            },\n            view: {\n                id: (_b = viewHistory.findView()) === null || _b === void 0 ? void 0 : _b.id,\n            },\n            action: {\n                id: actionContexts.findActionId(),\n            },\n        });\n    });\n    const reportError = (error) => {\n        lifeCycle.notify(13 /* LifeCycleEventType.RAW_ERROR_COLLECTED */, { error });\n        addTelemetryDebug('Error reported to customer', { 'error.message': error.message });\n    };\n    const featureFlagContexts = startFeatureFlagContexts(lifeCycle, customerDataTrackerManager.getOrCreateTracker(0 /* CustomerDataType.FeatureFlag */));\n    const pageExitObservable = createPageExitObservable(configuration);\n    const pageExitSubscription = pageExitObservable.subscribe((event) => {\n        lifeCycle.notify(10 /* LifeCycleEventType.PAGE_EXITED */, event);\n    });\n    cleanupTasks.push(() => pageExitSubscription.unsubscribe());\n    const session = !canUseEventBridge()\n        ? startRumSessionManager(configuration, lifeCycle, trackingConsentState)\n        : startRumSessionManagerStub();\n    if (!canUseEventBridge()) {\n        const batch = startRumBatch(configuration, lifeCycle, telemetry.observable, reportError, pageExitObservable, session.expireObservable, createEncoder);\n        cleanupTasks.push(() => batch.stop());\n        startCustomerDataTelemetry(configuration, telemetry, lifeCycle, customerDataTrackerManager, batch.flushObservable);\n    }\n    else {\n        startRumEventBridge(lifeCycle);\n    }\n    const domMutationObservable = createDOMMutationObservable();\n    const locationChangeObservable = createLocationChangeObservable(configuration, location);\n    const pageStateHistory = startPageStateHistory(configuration);\n    const { observable: windowOpenObservable, stop: stopWindowOpen } = createWindowOpenObservable();\n    cleanupTasks.push(stopWindowOpen);\n    const { viewHistory, urlContexts, actionContexts, addAction, stop: stopRumEventCollection, } = startRumEventCollection(lifeCycle, configuration, location, session, pageStateHistory, locationChangeObservable, domMutationObservable, featureFlagContexts, windowOpenObservable, getCommonContext, reportError);\n    cleanupTasks.push(stopRumEventCollection);\n    drainPreStartTelemetry();\n    const { addTiming, startView, setViewName, setViewContext, setViewContextProperty, getViewContext, stop: stopViewCollection, } = startViewCollection(lifeCycle, configuration, location, domMutationObservable, windowOpenObservable, locationChangeObservable, pageStateHistory, recorderApi, initialViewOptions);\n    cleanupTasks.push(stopViewCollection);\n    const { stop: stopResourceCollection } = startResourceCollection(lifeCycle, configuration, pageStateHistory);\n    cleanupTasks.push(stopResourceCollection);\n    if (configuration.trackLongTasks) {\n        if ((_a = PerformanceObserver.supportedEntryTypes) === null || _a === void 0 ? void 0 : _a.includes(RumPerformanceEntryType.LONG_ANIMATION_FRAME)) {\n            const { stop: stopLongAnimationFrameCollection } = startLongAnimationFrameCollection(lifeCycle, configuration);\n            cleanupTasks.push(stopLongAnimationFrameCollection);\n        }\n        else {\n            startLongTaskCollection(lifeCycle, configuration);\n        }\n    }\n    const { addError } = startErrorCollection(lifeCycle, configuration, pageStateHistory);\n    startRequestCollection(lifeCycle, configuration, session);\n    const vitalCollection = startVitalCollection(lifeCycle, pageStateHistory, customVitalsState);\n    const internalContext = startInternalContext(configuration.applicationId, session, viewHistory, actionContexts, urlContexts);\n    return {\n        addAction,\n        addError,\n        addTiming,\n        addFeatureFlagEvaluation: featureFlagContexts.addFeatureFlagEvaluation,\n        startView,\n        setViewContext,\n        setViewContextProperty,\n        getViewContext,\n        setViewName,\n        lifeCycle,\n        viewHistory,\n        session,\n        stopSession: () => session.expire(),\n        getInternalContext: internalContext.get,\n        startDurationVital: vitalCollection.startDurationVital,\n        stopDurationVital: vitalCollection.stopDurationVital,\n        addDurationVital: vitalCollection.addDurationVital,\n        stop: () => {\n            cleanupTasks.forEach((task) => task());\n        },\n    };\n}\nfunction startRumTelemetry(configuration) {\n    const telemetry = startTelemetry(\"browser-rum-sdk\" /* TelemetryService.RUM */, configuration);\n    if (canUseEventBridge()) {\n        const bridge = getEventBridge();\n        telemetry.observable.subscribe((event) => bridge.send('internal_telemetry', event));\n    }\n    return telemetry;\n}\nexport function startRumEventCollection(lifeCycle, configuration, location, sessionManager, pageStateHistory, locationChangeObservable, domMutationObservable, featureFlagContexts, windowOpenObservable, getCommonContext, reportError) {\n    const viewHistory = startViewHistory(lifeCycle);\n    const urlContexts = startUrlContexts(lifeCycle, locationChangeObservable, location);\n    const actionCollection = startActionCollection(lifeCycle, domMutationObservable, windowOpenObservable, configuration, pageStateHistory);\n    const displayContext = startDisplayContext(configuration);\n    const ciVisibilityContext = startCiVisibilityContext(configuration);\n    startRumAssembly(configuration, lifeCycle, sessionManager, viewHistory, urlContexts, actionCollection.actionContexts, displayContext, ciVisibilityContext, featureFlagContexts, getCommonContext, reportError);\n    return {\n        viewHistory,\n        pageStateHistory,\n        urlContexts,\n        addAction: actionCollection.addAction,\n        actionContexts: actionCollection.actionContexts,\n        stop: () => {\n            actionCollection.stop();\n            ciVisibilityContext.stop();\n            displayContext.stop();\n            urlContexts.stop();\n            viewHistory.stop();\n            pageStateHistory.stop();\n        },\n    };\n}\n//# sourceMappingURL=startRum.js.map","import { getEventBridge } from '@datadog/browser-core';\nexport function startRumEventBridge(lifeCycle) {\n    const bridge = getEventBridge();\n    lifeCycle.subscribe(12 /* LifeCycleEventType.RUM_EVENT_COLLECTED */, (serverRumEvent) => {\n        bridge.send('rum', serverRumEvent);\n    });\n}\n//# sourceMappingURL=startRumEventBridge.js.map","import { instrumentMethod, Observable } from '@datadog/browser-core';\nexport function createWindowOpenObservable() {\n    const observable = new Observable();\n    const { stop } = instrumentMethod(window, 'open', () => observable.notify());\n    return { observable, stop };\n}\n//# sourceMappingURL=windowOpenObservable.js.map","import { monitor } from '@datadog/browser-core';\nimport { getViewportDimension, initViewportObservable } from '../../browser/viewportObservable';\nexport function startDisplayContext(configuration) {\n    let viewport;\n    // Use requestAnimationFrame to delay the calculation of viewport dimensions until after SDK initialization, preventing long tasks.\n    const animationFrameId = requestAnimationFrame(monitor(() => {\n        viewport = getViewportDimension();\n    }));\n    const unsubscribeViewport = initViewportObservable(configuration).subscribe((viewportDimension) => {\n        viewport = viewportDimension;\n    }).unsubscribe;\n    return {\n        get: () => (viewport ? { viewport } : undefined),\n        stop: () => {\n            unsubscribeViewport();\n            if (animationFrameId) {\n                cancelAnimationFrame(animationFrameId);\n            }\n        },\n    };\n}\n//# sourceMappingURL=displayContext.js.map","import { toServerDuration, relativeToClocks, generateUUID } from '@datadog/browser-core';\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../../browser/performanceObservable';\nexport function startLongAnimationFrameCollection(lifeCycle, configuration) {\n    const performanceResourceSubscription = createPerformanceObservable(configuration, {\n        type: RumPerformanceEntryType.LONG_ANIMATION_FRAME,\n        buffered: true,\n    }).subscribe((entries) => {\n        for (const entry of entries) {\n            const startClocks = relativeToClocks(entry.startTime);\n            const rawRumEvent = {\n                date: startClocks.timeStamp,\n                long_task: {\n                    id: generateUUID(),\n                    entry_type: \"long-animation-frame\" /* RumLongTaskEntryType.LONG_ANIMATION_FRAME */,\n                    duration: toServerDuration(entry.duration),\n                    blocking_duration: toServerDuration(entry.blockingDuration),\n                    first_ui_event_timestamp: toServerDuration(entry.firstUIEventTimestamp),\n                    render_start: toServerDuration(entry.renderStart),\n                    style_and_layout_start: toServerDuration(entry.styleAndLayoutStart),\n                    start_time: toServerDuration(entry.startTime),\n                    scripts: entry.scripts.map((script) => ({\n                        duration: toServerDuration(script.duration),\n                        pause_duration: toServerDuration(script.pauseDuration),\n                        forced_style_and_layout_duration: toServerDuration(script.forcedStyleAndLayoutDuration),\n                        start_time: toServerDuration(script.startTime),\n                        execution_start: toServerDuration(script.executionStart),\n                        source_url: script.sourceURL,\n                        source_function_name: script.sourceFunctionName,\n                        source_char_position: script.sourceCharPosition,\n                        invoker: script.invoker,\n                        invoker_type: script.invokerType,\n                        window_attribution: script.windowAttribution,\n                    })),\n                },\n                type: \"long_task\" /* RumEventType.LONG_TASK */,\n                _dd: {\n                    discarded: false,\n                },\n            };\n            lifeCycle.notify(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, {\n                rawRumEvent,\n                startTime: startClocks.relative,\n                domainContext: { performanceEntry: entry },\n            });\n        }\n    });\n    return {\n        stop: () => performanceResourceSubscription.unsubscribe(),\n    };\n}\n//# sourceMappingURL=longAnimationFrameCollection.js.map","import { toServerDuration, relativeToClocks, generateUUID } from '@datadog/browser-core';\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../../browser/performanceObservable';\nexport function startLongTaskCollection(lifeCycle, configuration) {\n    const performanceLongTaskSubscription = createPerformanceObservable(configuration, {\n        type: RumPerformanceEntryType.LONG_TASK,\n        buffered: true,\n    }).subscribe((entries) => {\n        for (const entry of entries) {\n            if (entry.entryType !== RumPerformanceEntryType.LONG_TASK) {\n                break;\n            }\n            if (!configuration.trackLongTasks) {\n                break;\n            }\n            const startClocks = relativeToClocks(entry.startTime);\n            const rawRumEvent = {\n                date: startClocks.timeStamp,\n                long_task: {\n                    id: generateUUID(),\n                    entry_type: \"long-task\" /* RumLongTaskEntryType.LONG_TASK */,\n                    duration: toServerDuration(entry.duration),\n                },\n                type: \"long_task\" /* RumEventType.LONG_TASK */,\n                _dd: {\n                    discarded: false,\n                },\n            };\n            lifeCycle.notify(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, {\n                rawRumEvent,\n                startTime: startClocks.relative,\n                domainContext: { performanceEntry: entry },\n            });\n        }\n    });\n    return {\n        stop() {\n            performanceLongTaskSubscription.unsubscribe();\n        },\n    };\n}\n//# sourceMappingURL=longTaskCollection.js.map","/**\n * Internal context keep returning v1 format\n * to not break compatibility with logs data format\n */\nexport function startInternalContext(applicationId, sessionManager, viewHistory, actionContexts, urlContexts) {\n    return {\n        get: (startTime) => {\n            const viewContext = viewHistory.findView(startTime);\n            const urlContext = urlContexts.findUrl(startTime);\n            const session = sessionManager.findTrackedSession(startTime);\n            if (session && viewContext && urlContext) {\n                const actionId = actionContexts.findActionId(startTime);\n                return {\n                    application_id: applicationId,\n                    session_id: session.id,\n                    user_action: actionId ? { id: actionId } : undefined,\n                    view: { id: viewContext.id, name: viewContext.name, referrer: urlContext.referrer, url: urlContext.url },\n                };\n            }\n        },\n    };\n}\n//# sourceMappingURL=internalContext.js.map","import { INTAKE_SITE_STAGING, INTAKE_SITE_US1, INTAKE_SITE_EU1 } from '@datadog/browser-core';\nexport function getSessionReplayUrl(configuration, { session, viewContext, errorType, }) {\n    const sessionId = session ? session.id : 'no-session-id';\n    const parameters = [];\n    if (errorType !== undefined) {\n        parameters.push(`error-type=${errorType}`);\n    }\n    if (viewContext) {\n        parameters.push(`seed=${viewContext.id}`);\n        parameters.push(`from=${viewContext.startClocks.timeStamp}`);\n    }\n    const origin = getDatadogSiteUrl(configuration);\n    const path = `/rum/replay/sessions/${sessionId}`;\n    return `${origin}${path}?${parameters.join('&')}`;\n}\nexport function getDatadogSiteUrl(rumConfiguration) {\n    const site = rumConfiguration.site;\n    const subdomain = rumConfiguration.subdomain || getSiteDefaultSubdomain(rumConfiguration);\n    return `https://${subdomain ? `${subdomain}.` : ''}${site}`;\n}\nfunction getSiteDefaultSubdomain(configuration) {\n    switch (configuration.site) {\n        case INTAKE_SITE_US1:\n        case INTAKE_SITE_EU1:\n            return 'app';\n        case INTAKE_SITE_STAGING:\n            return 'dd';\n        default:\n            return undefined;\n    }\n}\n//# sourceMappingURL=getSessionReplayUrl.js.map","import { buildUrl } from '@datadog/browser-core';\nimport { getParentNode, isNodeShadowRoot, CENSORED_STRING_MARK, shouldMaskNode } from '@datadog/browser-rum-core';\nconst serializedNodeIds = new WeakMap();\nexport function hasSerializedNode(node) {\n    return serializedNodeIds.has(node);\n}\nexport function nodeAndAncestorsHaveSerializedNode(node) {\n    let current = node;\n    while (current) {\n        if (!hasSerializedNode(current) && !isNodeShadowRoot(current)) {\n            return false;\n        }\n        current = getParentNode(current);\n    }\n    return true;\n}\nexport function getSerializedNodeId(node) {\n    return serializedNodeIds.get(node);\n}\nexport function setSerializedNodeId(node, serializeNodeId) {\n    serializedNodeIds.set(node, serializeNodeId);\n}\n/**\n * Get the element \"value\" to be serialized as an attribute or an input update record. It respects\n * the input privacy mode of the element.\n * PERFROMANCE OPTIMIZATION: Assumes that privacy level `HIDDEN` is never encountered because of earlier checks.\n */\nexport function getElementInputValue(element, nodePrivacyLevel) {\n    /*\n     BROWSER SPEC NOTE: <input>, <select>\n     For some <input> elements, the `value` is an exceptional property/attribute that has the\n     value synced between el.value and el.getAttribute()\n     input[type=button,checkbox,hidden,image,radio,reset,submit]\n     */\n    const tagName = element.tagName;\n    const value = element.value;\n    if (shouldMaskNode(element, nodePrivacyLevel)) {\n        const type = element.type;\n        if (tagName === 'INPUT' && (type === 'button' || type === 'submit' || type === 'reset')) {\n            // Overrule `MASK` privacy level for button-like element values, as they are used during replay\n            // to display their label. They can still be hidden via the \"hidden\" privacy attribute or class name.\n            return value;\n        }\n        else if (!value || tagName === 'OPTION') {\n            // <Option> value provides no benefit\n            return;\n        }\n        return CENSORED_STRING_MARK;\n    }\n    if (tagName === 'OPTION' || tagName === 'SELECT') {\n        return element.value;\n    }\n    if (tagName !== 'INPUT' && tagName !== 'TEXTAREA') {\n        return;\n    }\n    return value;\n}\nexport const URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")([^\"]*)\"|([^)]*))\\)/gm;\nexport const ABSOLUTE_URL = /^[A-Za-z]+:|^\\/\\//;\nexport const DATA_URI = /^data:.*,/i;\nexport function switchToAbsoluteUrl(cssText, cssHref) {\n    return cssText.replace(URL_IN_CSS_REF, (matchingSubstring, singleQuote, urlWrappedInSingleQuotes, doubleQuote, urlWrappedInDoubleQuotes, urlNotWrappedInQuotes) => {\n        const url = urlWrappedInSingleQuotes || urlWrappedInDoubleQuotes || urlNotWrappedInQuotes;\n        if (!cssHref || !url || ABSOLUTE_URL.test(url) || DATA_URI.test(url)) {\n            return matchingSubstring;\n        }\n        const quote = singleQuote || doubleQuote || '';\n        return `url(${quote}${makeUrlAbsolute(url, cssHref)}${quote})`;\n    });\n}\nexport function makeUrlAbsolute(url, baseUrl) {\n    try {\n        return buildUrl(url, baseUrl).href;\n    }\n    catch (_a) {\n        return url;\n    }\n}\nconst TAG_NAME_REGEX = /[^a-z1-6-_]/;\nexport function getValidTagName(tagName) {\n    const processedTagName = tagName.toLowerCase().trim();\n    if (TAG_NAME_REGEX.test(processedTagName)) {\n        // if the tag name is odd and we cannot extract\n        // anything from the string, then we return a\n        // generic div\n        return 'div';\n    }\n    return processedTagName;\n}\nexport function censoredImageForSize(width, height) {\n    return `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${width}' height='${height}' style='background-color:silver'%3E%3C/svg%3E`;\n}\n//# sourceMappingURL=serializationUtils.js.map","export const RecordType = {\n    FullSnapshot: 2,\n    IncrementalSnapshot: 3,\n    Meta: 4,\n    Focus: 6,\n    ViewEnd: 7,\n    VisualViewport: 8,\n    FrustrationRecord: 9,\n};\nexport const NodeType = {\n    Document: 0,\n    DocumentType: 1,\n    Element: 2,\n    Text: 3,\n    CDATA: 4,\n    DocumentFragment: 11,\n};\nexport const IncrementalSource = {\n    Mutation: 0,\n    MouseMove: 1,\n    MouseInteraction: 2,\n    Scroll: 3,\n    ViewportResize: 4,\n    Input: 5,\n    TouchMove: 6,\n    MediaInteraction: 7,\n    StyleSheetRule: 8,\n    // CanvasMutation : 9,\n    // Font : 10,\n};\nexport const MouseInteractionType = {\n    MouseUp: 0,\n    MouseDown: 1,\n    Click: 2,\n    ContextMenu: 3,\n    DblClick: 4,\n    Focus: 5,\n    Blur: 6,\n    TouchStart: 7,\n    TouchEnd: 9,\n};\nexport const MediaInteractionType = {\n    Play: 0,\n    Pause: 1,\n};\n//# sourceMappingURL=sessionReplayConstants.js.map","export function serializeStyleSheets(cssStyleSheets) {\n    if (cssStyleSheets === undefined || cssStyleSheets.length === 0) {\n        return undefined;\n    }\n    return cssStyleSheets.map((cssStyleSheet) => {\n        const rules = cssStyleSheet.cssRules || cssStyleSheet.rules;\n        const cssRules = Array.from(rules, (cssRule) => cssRule.cssText);\n        const styleSheet = {\n            cssRules,\n            disabled: cssStyleSheet.disabled || undefined,\n            media: cssStyleSheet.media.length > 0 ? Array.from(cssStyleSheet.media) : undefined,\n        };\n        return styleSheet;\n    });\n}\n//# sourceMappingURL=serializeStyleSheets.js.map","import { NodePrivacyLevel, PRIVACY_ATTR_NAME, CENSORED_STRING_MARK, CENSORED_IMG_MARK, STABLE_ATTRIBUTES, isLongDataUrl, sanitizeDataUrl, } from '@datadog/browser-rum-core';\nimport { censoredImageForSize } from './serializationUtils';\nexport function serializeAttribute(element, nodePrivacyLevel, attributeName, configuration) {\n    if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n        // dup condition for direct access case\n        return null;\n    }\n    const attributeValue = element.getAttribute(attributeName);\n    if (nodePrivacyLevel === NodePrivacyLevel.MASK &&\n        attributeName !== PRIVACY_ATTR_NAME &&\n        !STABLE_ATTRIBUTES.includes(attributeName) &&\n        attributeName !== configuration.actionNameAttribute) {\n        const tagName = element.tagName;\n        switch (attributeName) {\n            // Mask Attribute text content\n            case 'title':\n            case 'alt':\n            case 'placeholder':\n                return CENSORED_STRING_MARK;\n        }\n        // mask image URLs\n        if (tagName === 'IMG' && (attributeName === 'src' || attributeName === 'srcset')) {\n            // generate image with similar dimension than the original to have the same rendering behaviour\n            const image = element;\n            if (image.naturalWidth > 0) {\n                return censoredImageForSize(image.naturalWidth, image.naturalHeight);\n            }\n            const { width, height } = element.getBoundingClientRect();\n            if (width > 0 || height > 0) {\n                return censoredImageForSize(width, height);\n            }\n            // if we can't get the image size, fallback to the censored image\n            return CENSORED_IMG_MARK;\n        }\n        // mask source URLs\n        if (tagName === 'SOURCE' && (attributeName === 'src' || attributeName === 'srcset')) {\n            return CENSORED_IMG_MARK;\n        }\n        // mask <a> URLs\n        if (tagName === 'A' && attributeName === 'href') {\n            return CENSORED_STRING_MARK;\n        }\n        // mask data-* attributes\n        if (attributeValue && attributeName.startsWith('data-')) {\n            // Exception: it's safe to reveal the `${PRIVACY_ATTR_NAME}` attr\n            return CENSORED_STRING_MARK;\n        }\n        // mask iframe srcdoc\n        if (tagName === 'IFRAME' && attributeName === 'srcdoc') {\n            return CENSORED_STRING_MARK;\n        }\n    }\n    if (!attributeValue || typeof attributeValue !== 'string') {\n        return attributeValue;\n    }\n    // Minimum Fix for customer.\n    if (isLongDataUrl(attributeValue)) {\n        return sanitizeDataUrl(attributeValue);\n    }\n    return attributeValue;\n}\n//# sourceMappingURL=serializeAttribute.js.map","import { NodePrivacyLevel, shouldMaskNode } from '@datadog/browser-rum-core';\nimport { isSafari } from '@datadog/browser-core';\nimport { getElementInputValue, switchToAbsoluteUrl, getValidTagName } from './serializationUtils';\nimport { serializeAttribute } from './serializeAttribute';\nexport function serializeAttributes(element, nodePrivacyLevel, options) {\n    if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n        return {};\n    }\n    const safeAttrs = {};\n    const tagName = getValidTagName(element.tagName);\n    const doc = element.ownerDocument;\n    for (let i = 0; i < element.attributes.length; i += 1) {\n        const attribute = element.attributes.item(i);\n        const attributeName = attribute.name;\n        const attributeValue = serializeAttribute(element, nodePrivacyLevel, attributeName, options.configuration);\n        if (attributeValue !== null) {\n            safeAttrs[attributeName] = attributeValue;\n        }\n    }\n    if (element.value &&\n        (tagName === 'textarea' || tagName === 'select' || tagName === 'option' || tagName === 'input')) {\n        const formValue = getElementInputValue(element, nodePrivacyLevel);\n        if (formValue !== undefined) {\n            safeAttrs.value = formValue;\n        }\n    }\n    /**\n     * <Option> can be selected, which occurs if its `value` matches ancestor `<Select>.value`\n     */\n    if (tagName === 'option' && nodePrivacyLevel === NodePrivacyLevel.ALLOW) {\n        // For privacy=`MASK`, all the values would be the same, so skip.\n        const optionElement = element;\n        if (optionElement.selected) {\n            safeAttrs.selected = optionElement.selected;\n        }\n    }\n    // remote css\n    if (tagName === 'link') {\n        const stylesheet = Array.from(doc.styleSheets).find((s) => s.href === element.href);\n        const cssText = getCssRulesString(stylesheet);\n        if (cssText && stylesheet) {\n            safeAttrs._cssText = cssText;\n        }\n    }\n    // dynamic stylesheet\n    if (tagName === 'style' && element.sheet) {\n        const cssText = getCssRulesString(element.sheet);\n        if (cssText) {\n            safeAttrs._cssText = cssText;\n        }\n    }\n    /**\n     * Forms: input[type=checkbox,radio]\n     * The `checked` property for <input> is a little bit special:\n     * 1. el.checked is a setter that returns if truthy.\n     * 2. getAttribute returns the string value\n     * getAttribute('checked') does not sync with `Element.checked`, so use JS property\n     * NOTE: `checked` property exists on `HTMLInputElement`. For serializer assumptions, we check for type=radio|check.\n     */\n    const inputElement = element;\n    if (tagName === 'input' && (inputElement.type === 'radio' || inputElement.type === 'checkbox')) {\n        if (nodePrivacyLevel === NodePrivacyLevel.ALLOW) {\n            safeAttrs.checked = !!inputElement.checked;\n        }\n        else if (shouldMaskNode(inputElement, nodePrivacyLevel)) {\n            delete safeAttrs.checked;\n        }\n    }\n    /**\n     * Serialize the media playback state\n     */\n    if (tagName === 'audio' || tagName === 'video') {\n        const mediaElement = element;\n        safeAttrs.rr_mediaState = mediaElement.paused ? 'paused' : 'played';\n    }\n    /**\n     * Serialize the scroll state for each element only for full snapshot\n     */\n    let scrollTop;\n    let scrollLeft;\n    const serializationContext = options.serializationContext;\n    switch (serializationContext.status) {\n        case 0 /* SerializationContextStatus.INITIAL_FULL_SNAPSHOT */:\n            scrollTop = Math.round(element.scrollTop);\n            scrollLeft = Math.round(element.scrollLeft);\n            if (scrollTop || scrollLeft) {\n                serializationContext.elementsScrollPositions.set(element, { scrollTop, scrollLeft });\n            }\n            break;\n        case 1 /* SerializationContextStatus.SUBSEQUENT_FULL_SNAPSHOT */:\n            if (serializationContext.elementsScrollPositions.has(element)) {\n                ;\n                ({ scrollTop, scrollLeft } = serializationContext.elementsScrollPositions.get(element));\n            }\n            break;\n    }\n    if (scrollLeft) {\n        safeAttrs.rr_scrollLeft = scrollLeft;\n    }\n    if (scrollTop) {\n        safeAttrs.rr_scrollTop = scrollTop;\n    }\n    return safeAttrs;\n}\nexport function getCssRulesString(cssStyleSheet) {\n    if (!cssStyleSheet) {\n        return null;\n    }\n    let rules;\n    try {\n        rules = cssStyleSheet.rules || cssStyleSheet.cssRules;\n    }\n    catch (_a) {\n        // if css is protected by CORS we cannot access cssRules see: https://www.w3.org/TR/cssom-1/#the-cssstylesheet-interface\n    }\n    if (!rules) {\n        return null;\n    }\n    const styleSheetCssText = Array.from(rules, isSafari() ? getCssRuleStringForSafari : getCssRuleString).join('');\n    return switchToAbsoluteUrl(styleSheetCssText, cssStyleSheet.href);\n}\nfunction getCssRuleStringForSafari(rule) {\n    // Safari does not escape attribute selectors containing : properly\n    // https://bugs.webkit.org/show_bug.cgi?id=184604\n    if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\n        // This regex replaces [foo:bar] by [foo\\\\:bar]\n        const escapeColon = /(\\[[\\w-]+[^\\\\])(:[^\\]]+\\])/g;\n        return rule.cssText.replace(escapeColon, '$1\\\\$2');\n    }\n    return getCssRuleString(rule);\n}\nfunction getCssRuleString(rule) {\n    // If it's an @import rule, try to inline sub-rules recursively with `getCssRulesString`. This\n    // operation can fail if the imported stylesheet is protected by CORS, in which case we fallback\n    // to the @import rule CSS text.\n    return (isCSSImportRule(rule) && getCssRulesString(rule.styleSheet)) || rule.cssText;\n}\nfunction isCSSImportRule(rule) {\n    return 'styleSheet' in rule;\n}\nfunction isCSSStyleRule(rule) {\n    return 'selectorText' in rule;\n}\n//# sourceMappingURL=serializeAttributes.js.map","import { reducePrivacyLevel, getNodeSelfPrivacyLevel, getTextContent, isNodeShadowRoot, hasChildNodes, forEachChildNodes, NodePrivacyLevel, PRIVACY_ATTR_NAME, PRIVACY_ATTR_VALUE_HIDDEN, } from '@datadog/browser-rum-core';\nimport { NodeType } from '../../../types';\nimport { getSerializedNodeId, getValidTagName, setSerializedNodeId } from './serializationUtils';\nimport { serializeStyleSheets } from './serializeStyleSheets';\nimport { serializeAttributes } from './serializeAttributes';\nexport function serializeNodeWithId(node, options) {\n    const serializedNode = serializeNode(node, options);\n    if (!serializedNode) {\n        return null;\n    }\n    // Try to reuse the previous id\n    const id = getSerializedNodeId(node) || generateNextId();\n    const serializedNodeWithId = serializedNode;\n    serializedNodeWithId.id = id;\n    setSerializedNodeId(node, id);\n    if (options.serializedNodeIds) {\n        options.serializedNodeIds.add(id);\n    }\n    return serializedNodeWithId;\n}\nlet _nextId = 1;\nexport function generateNextId() {\n    return _nextId++;\n}\nexport function serializeChildNodes(node, options) {\n    const result = [];\n    forEachChildNodes(node, (childNode) => {\n        const serializedChildNode = serializeNodeWithId(childNode, options);\n        if (serializedChildNode) {\n            result.push(serializedChildNode);\n        }\n    });\n    return result;\n}\nfunction serializeNode(node, options) {\n    switch (node.nodeType) {\n        case node.DOCUMENT_NODE:\n            return serializeDocumentNode(node, options);\n        case node.DOCUMENT_FRAGMENT_NODE:\n            return serializeDocumentFragmentNode(node, options);\n        case node.DOCUMENT_TYPE_NODE:\n            return serializeDocumentTypeNode(node);\n        case node.ELEMENT_NODE:\n            return serializeElementNode(node, options);\n        case node.TEXT_NODE:\n            return serializeTextNode(node, options);\n        case node.CDATA_SECTION_NODE:\n            return serializeCDataNode();\n    }\n}\nexport function serializeDocumentNode(document, options) {\n    return {\n        type: NodeType.Document,\n        childNodes: serializeChildNodes(document, options),\n        adoptedStyleSheets: serializeStyleSheets(document.adoptedStyleSheets),\n    };\n}\nfunction serializeDocumentFragmentNode(element, options) {\n    const isShadowRoot = isNodeShadowRoot(element);\n    if (isShadowRoot) {\n        options.serializationContext.shadowRootsController.addShadowRoot(element);\n    }\n    return {\n        type: NodeType.DocumentFragment,\n        childNodes: serializeChildNodes(element, options),\n        isShadowRoot,\n        adoptedStyleSheets: isShadowRoot ? serializeStyleSheets(element.adoptedStyleSheets) : undefined,\n    };\n}\nfunction serializeDocumentTypeNode(documentType) {\n    return {\n        type: NodeType.DocumentType,\n        name: documentType.name,\n        publicId: documentType.publicId,\n        systemId: documentType.systemId,\n    };\n}\n/**\n * Serializing Element nodes involves capturing:\n * 1. HTML ATTRIBUTES:\n * 2. JS STATE:\n * - scroll offsets\n * - Form fields (input value, checkbox checked, option selection, range)\n * - Canvas state,\n * - Media (video/audio) play mode + currentTime\n * - iframe contents\n * - webcomponents\n * 3. CUSTOM PROPERTIES:\n * - height+width for when `hidden` to cover the element\n * 4. EXCLUDED INTERACTION STATE:\n * - focus (possible, but not worth perf impact)\n * - hover (tracked only via mouse activity)\n * - fullscreen mode\n */\nfunction serializeElementNode(element, options) {\n    const tagName = getValidTagName(element.tagName);\n    const isSVG = isSVGElement(element) || undefined;\n    // For performance reason, we don't use getNodePrivacyLevel directly: we leverage the\n    // parentNodePrivacyLevel option to avoid iterating over all parents\n    const nodePrivacyLevel = reducePrivacyLevel(getNodeSelfPrivacyLevel(element), options.parentNodePrivacyLevel);\n    if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n        const { width, height } = element.getBoundingClientRect();\n        return {\n            type: NodeType.Element,\n            tagName,\n            attributes: {\n                rr_width: `${width}px`,\n                rr_height: `${height}px`,\n                [PRIVACY_ATTR_NAME]: PRIVACY_ATTR_VALUE_HIDDEN,\n            },\n            childNodes: [],\n            isSVG,\n        };\n    }\n    // Ignore Elements like Script and some Link, Metas\n    if (nodePrivacyLevel === NodePrivacyLevel.IGNORE) {\n        return;\n    }\n    const attributes = serializeAttributes(element, nodePrivacyLevel, options);\n    let childNodes = [];\n    if (hasChildNodes(element) &&\n        // Do not serialize style children as the css rules are already in the _cssText attribute\n        tagName !== 'style') {\n        // OBJECT POOLING OPTIMIZATION:\n        // We should not create a new object systematically as it could impact performances. Try to reuse\n        // the same object as much as possible, and clone it only if we need to.\n        let childNodesSerializationOptions;\n        if (options.parentNodePrivacyLevel === nodePrivacyLevel && options.ignoreWhiteSpace === (tagName === 'head')) {\n            childNodesSerializationOptions = options;\n        }\n        else {\n            childNodesSerializationOptions = {\n                ...options,\n                parentNodePrivacyLevel: nodePrivacyLevel,\n                ignoreWhiteSpace: tagName === 'head',\n            };\n        }\n        childNodes = serializeChildNodes(element, childNodesSerializationOptions);\n    }\n    return {\n        type: NodeType.Element,\n        tagName,\n        attributes,\n        childNodes,\n        isSVG,\n    };\n}\nfunction isSVGElement(el) {\n    return el.tagName === 'svg' || el instanceof SVGElement;\n}\n/**\n * Text Nodes are dependant on Element nodes\n * Privacy levels are set on elements so we check the parentElement of a text node\n * for privacy level.\n */\nfunction serializeTextNode(textNode, options) {\n    const textContent = getTextContent(textNode, options.ignoreWhiteSpace || false, options.parentNodePrivacyLevel);\n    if (textContent === undefined) {\n        return;\n    }\n    return {\n        type: NodeType.Text,\n        textContent,\n    };\n}\nfunction serializeCDataNode() {\n    return {\n        type: NodeType.CDATA,\n        textContent: '',\n    };\n}\n//# sourceMappingURL=serializeNode.js.map","import { serializeNodeWithId } from './serializeNode';\nexport function serializeDocument(document, configuration, serializationContext) {\n    // We are sure that Documents are never ignored, so this function never returns null\n    return serializeNodeWithId(document, {\n        serializationContext,\n        parentNodePrivacyLevel: configuration.defaultPrivacyLevel,\n        configuration,\n    });\n}\n//# sourceMappingURL=serializeDocument.js.map","import { isNodeShadowHost } from '@datadog/browser-rum-core';\nexport function isTouchEvent(event) {\n    return Boolean(event.changedTouches);\n}\nexport function getEventTarget(event) {\n    if (event.composed === true && isNodeShadowHost(event.target)) {\n        return event.composedPath()[0];\n    }\n    return event.target;\n}\n//# sourceMappingURL=eventsUtils.js.map","/**\n * Browsers have not standardized various dimension properties. Mobile devices typically report\n * dimensions in reference to the visual viewport, while desktop uses the layout viewport. For example,\n * Mobile Chrome will change innerWidth when a pinch zoom takes place, while Chrome Desktop (mac) will not.\n *\n * With the new Viewport API, we now calculate and normalize dimension properties to the layout viewport.\n * If the VisualViewport API is not supported by a browser, it isn't reasonably possible to detect or normalize\n * which viewport is being measured. Therefore these exported functions will fallback to assuming that the layout\n * viewport is being measured by the browser\n */\n// Scrollbar widths vary across properties on different devices and browsers\nconst TOLERANCE = 25;\n/**\n * Use the Visual Viewport API's properties to measure scrollX/Y in reference to the layout viewport\n * in order to determine if window.scrollX/Y is measuring the layout or visual viewport.\n * This finding corresponds to which viewport mouseEvent.clientX/Y and window.innerWidth/Height measures.\n */\nfunction isVisualViewportFactoredIn(visualViewport) {\n    return (Math.abs(visualViewport.pageTop - visualViewport.offsetTop - window.scrollY) > TOLERANCE ||\n        Math.abs(visualViewport.pageLeft - visualViewport.offsetLeft - window.scrollX) > TOLERANCE);\n}\nexport const convertMouseEventToLayoutCoordinates = (clientX, clientY) => {\n    const visualViewport = window.visualViewport;\n    const normalized = {\n        layoutViewportX: clientX,\n        layoutViewportY: clientY,\n        visualViewportX: clientX,\n        visualViewportY: clientY,\n    };\n    if (!visualViewport) {\n        // On old browsers, we cannot normalize, so fallback to clientX/Y\n        return normalized;\n    }\n    else if (isVisualViewportFactoredIn(visualViewport)) {\n        // Typically Mobile Devices\n        normalized.layoutViewportX = Math.round(clientX + visualViewport.offsetLeft);\n        normalized.layoutViewportY = Math.round(clientY + visualViewport.offsetTop);\n    }\n    else {\n        // Typically Desktop Devices\n        normalized.visualViewportX = Math.round(clientX - visualViewport.offsetLeft);\n        normalized.visualViewportY = Math.round(clientY - visualViewport.offsetTop);\n    }\n    return normalized;\n};\nexport const getVisualViewport = (visualViewport) => ({\n    scale: visualViewport.scale,\n    offsetLeft: visualViewport.offsetLeft,\n    offsetTop: visualViewport.offsetTop,\n    pageLeft: visualViewport.pageLeft,\n    pageTop: visualViewport.pageTop,\n    height: visualViewport.height,\n    width: visualViewport.width,\n});\n//# sourceMappingURL=viewports.js.map","import { timeStampNow } from '@datadog/browser-core';\nimport { RecordType } from '../../types';\nexport function assembleIncrementalSnapshot(source, data) {\n    return {\n        data: {\n            source,\n            ...data,\n        },\n        type: RecordType.IncrementalSnapshot,\n        timestamp: timeStampNow(),\n    };\n}\n//# sourceMappingURL=assembly.js.map","import { addEventListeners, addTelemetryDebug, throttle } from '@datadog/browser-core';\nimport { getSerializedNodeId, hasSerializedNode } from '../serialization';\nimport { IncrementalSource } from '../../../types';\nimport { getEventTarget, isTouchEvent } from '../eventsUtils';\nimport { convertMouseEventToLayoutCoordinates } from '../viewports';\nimport { assembleIncrementalSnapshot } from '../assembly';\nconst MOUSE_MOVE_OBSERVER_THRESHOLD = 50;\nexport function trackMove(configuration, moveCb) {\n    const { throttled: updatePosition, cancel: cancelThrottle } = throttle((event) => {\n        const target = getEventTarget(event);\n        if (hasSerializedNode(target)) {\n            const coordinates = tryToComputeCoordinates(event);\n            if (!coordinates) {\n                return;\n            }\n            const position = {\n                id: getSerializedNodeId(target),\n                timeOffset: 0,\n                x: coordinates.x,\n                y: coordinates.y,\n            };\n            moveCb(assembleIncrementalSnapshot(isTouchEvent(event) ? IncrementalSource.TouchMove : IncrementalSource.MouseMove, { positions: [position] }));\n        }\n    }, MOUSE_MOVE_OBSERVER_THRESHOLD, {\n        trailing: false,\n    });\n    const { stop: removeListener } = addEventListeners(configuration, document, [\"mousemove\" /* DOM_EVENT.MOUSE_MOVE */, \"touchmove\" /* DOM_EVENT.TOUCH_MOVE */], updatePosition, {\n        capture: true,\n        passive: true,\n    });\n    return {\n        stop: () => {\n            removeListener();\n            cancelThrottle();\n        },\n    };\n}\nexport function tryToComputeCoordinates(event) {\n    let { clientX: x, clientY: y } = isTouchEvent(event) ? event.changedTouches[0] : event;\n    if (window.visualViewport) {\n        const { visualViewportX, visualViewportY } = convertMouseEventToLayoutCoordinates(x, y);\n        x = visualViewportX;\n        y = visualViewportY;\n    }\n    if (!Number.isFinite(x) || !Number.isFinite(y)) {\n        if (event.isTrusted) {\n            addTelemetryDebug('mouse/touch event without x/y');\n        }\n        return undefined;\n    }\n    return { x, y };\n}\n//# sourceMappingURL=trackMove.js.map","import { addEventListeners } from '@datadog/browser-core';\nimport { getNodePrivacyLevel, NodePrivacyLevel } from '@datadog/browser-rum-core';\nimport { IncrementalSource, MouseInteractionType } from '../../../types';\nimport { assembleIncrementalSnapshot } from '../assembly';\nimport { getEventTarget } from '../eventsUtils';\nimport { getSerializedNodeId, hasSerializedNode } from '../serialization';\nimport { tryToComputeCoordinates } from './trackMove';\nconst eventTypeToMouseInteraction = {\n    // Listen for pointerup DOM events instead of mouseup for MouseInteraction/MouseUp records. This\n    // allows to reference such records from Frustration records.\n    //\n    // In the context of supporting Mobile Session Replay, we introduced `PointerInteraction` records\n    // used by the Mobile SDKs in place of `MouseInteraction`. In the future, we should replace\n    // `MouseInteraction` by `PointerInteraction` in the Browser SDK so we have an uniform way to\n    // convey such interaction. This would cleanly solve the issue since we would have\n    // `PointerInteraction/Up` records that we could reference from `Frustration` records.\n    [\"pointerup\" /* DOM_EVENT.POINTER_UP */]: MouseInteractionType.MouseUp,\n    [\"mousedown\" /* DOM_EVENT.MOUSE_DOWN */]: MouseInteractionType.MouseDown,\n    [\"click\" /* DOM_EVENT.CLICK */]: MouseInteractionType.Click,\n    [\"contextmenu\" /* DOM_EVENT.CONTEXT_MENU */]: MouseInteractionType.ContextMenu,\n    [\"dblclick\" /* DOM_EVENT.DBL_CLICK */]: MouseInteractionType.DblClick,\n    [\"focus\" /* DOM_EVENT.FOCUS */]: MouseInteractionType.Focus,\n    [\"blur\" /* DOM_EVENT.BLUR */]: MouseInteractionType.Blur,\n    [\"touchstart\" /* DOM_EVENT.TOUCH_START */]: MouseInteractionType.TouchStart,\n    [\"touchend\" /* DOM_EVENT.TOUCH_END */]: MouseInteractionType.TouchEnd,\n};\nexport function trackMouseInteraction(configuration, mouseInteractionCb, recordIds) {\n    const handler = (event) => {\n        const target = getEventTarget(event);\n        if (getNodePrivacyLevel(target, configuration.defaultPrivacyLevel) === NodePrivacyLevel.HIDDEN ||\n            !hasSerializedNode(target)) {\n            return;\n        }\n        const id = getSerializedNodeId(target);\n        const type = eventTypeToMouseInteraction[event.type];\n        let interaction;\n        if (type !== MouseInteractionType.Blur && type !== MouseInteractionType.Focus) {\n            const coordinates = tryToComputeCoordinates(event);\n            if (!coordinates) {\n                return;\n            }\n            interaction = { id, type, x: coordinates.x, y: coordinates.y };\n        }\n        else {\n            interaction = { id, type };\n        }\n        const record = {\n            id: recordIds.getIdForEvent(event),\n            ...assembleIncrementalSnapshot(IncrementalSource.MouseInteraction, interaction),\n        };\n        mouseInteractionCb(record);\n    };\n    return addEventListeners(configuration, document, Object.keys(eventTypeToMouseInteraction), handler, {\n        capture: true,\n        passive: true,\n    });\n}\n//# sourceMappingURL=trackMouseInteraction.js.map","import { throttle, addEventListener } from '@datadog/browser-core';\nimport { getScrollX, getScrollY, getNodePrivacyLevel, NodePrivacyLevel } from '@datadog/browser-rum-core';\nimport { getEventTarget } from '../eventsUtils';\nimport { getSerializedNodeId, hasSerializedNode } from '../serialization';\nimport { IncrementalSource } from '../../../types';\nimport { assembleIncrementalSnapshot } from '../assembly';\nconst SCROLL_OBSERVER_THRESHOLD = 100;\nexport function trackScroll(configuration, scrollCb, elementsScrollPositions, target = document) {\n    const { throttled: updatePosition, cancel: cancelThrottle } = throttle((event) => {\n        const target = getEventTarget(event);\n        if (!target ||\n            getNodePrivacyLevel(target, configuration.defaultPrivacyLevel) === NodePrivacyLevel.HIDDEN ||\n            !hasSerializedNode(target)) {\n            return;\n        }\n        const id = getSerializedNodeId(target);\n        const scrollPositions = target === document\n            ? {\n                scrollTop: getScrollY(),\n                scrollLeft: getScrollX(),\n            }\n            : {\n                scrollTop: Math.round(target.scrollTop),\n                scrollLeft: Math.round(target.scrollLeft),\n            };\n        elementsScrollPositions.set(target, scrollPositions);\n        scrollCb(assembleIncrementalSnapshot(IncrementalSource.Scroll, {\n            id,\n            x: scrollPositions.scrollLeft,\n            y: scrollPositions.scrollTop,\n        }));\n    }, SCROLL_OBSERVER_THRESHOLD);\n    const { stop: removeListener } = addEventListener(configuration, target, \"scroll\" /* DOM_EVENT.SCROLL */, updatePosition, {\n        capture: true,\n        passive: true,\n    });\n    return {\n        stop: () => {\n            removeListener();\n            cancelThrottle();\n        },\n    };\n}\n//# sourceMappingURL=trackScroll.js.map","import { throttle, addEventListeners, timeStampNow, noop } from '@datadog/browser-core';\nimport { initViewportObservable } from '@datadog/browser-rum-core';\nimport { IncrementalSource, RecordType } from '../../../types';\nimport { getVisualViewport } from '../viewports';\nimport { assembleIncrementalSnapshot } from '../assembly';\nconst VISUAL_VIEWPORT_OBSERVER_THRESHOLD = 200;\nexport function trackViewportResize(configuration, viewportResizeCb) {\n    const viewportResizeSubscription = initViewportObservable(configuration).subscribe((data) => {\n        viewportResizeCb(assembleIncrementalSnapshot(IncrementalSource.ViewportResize, data));\n    });\n    return {\n        stop: () => {\n            viewportResizeSubscription.unsubscribe();\n        },\n    };\n}\nexport function trackVisualViewportResize(configuration, visualViewportResizeCb) {\n    const visualViewport = window.visualViewport;\n    if (!visualViewport) {\n        return { stop: noop };\n    }\n    const { throttled: updateDimension, cancel: cancelThrottle } = throttle(() => {\n        visualViewportResizeCb({\n            data: getVisualViewport(visualViewport),\n            type: RecordType.VisualViewport,\n            timestamp: timeStampNow(),\n        });\n    }, VISUAL_VIEWPORT_OBSERVER_THRESHOLD, {\n        trailing: false,\n    });\n    const { stop: removeListener } = addEventListeners(configuration, visualViewport, [\"resize\" /* DOM_EVENT.RESIZE */, \"scroll\" /* DOM_EVENT.SCROLL */], updateDimension, {\n        capture: true,\n        passive: true,\n    });\n    return {\n        stop: () => {\n            removeListener();\n            cancelThrottle();\n        },\n    };\n}\n//# sourceMappingURL=trackViewportResize.js.map","import { addEventListeners } from '@datadog/browser-core';\nimport { NodePrivacyLevel, getNodePrivacyLevel } from '@datadog/browser-rum-core';\nimport { IncrementalSource, MediaInteractionType } from '../../../types';\nimport { getEventTarget } from '../eventsUtils';\nimport { getSerializedNodeId, hasSerializedNode } from '../serialization';\nimport { assembleIncrementalSnapshot } from '../assembly';\nexport function trackMediaInteraction(configuration, mediaInteractionCb) {\n    return addEventListeners(configuration, document, [\"play\" /* DOM_EVENT.PLAY */, \"pause\" /* DOM_EVENT.PAUSE */], (event) => {\n        const target = getEventTarget(event);\n        if (!target ||\n            getNodePrivacyLevel(target, configuration.defaultPrivacyLevel) === NodePrivacyLevel.HIDDEN ||\n            !hasSerializedNode(target)) {\n            return;\n        }\n        mediaInteractionCb(assembleIncrementalSnapshot(IncrementalSource.MediaInteraction, {\n            id: getSerializedNodeId(target),\n            type: event.type === \"play\" /* DOM_EVENT.PLAY */ ? MediaInteractionType.Play : MediaInteractionType.Pause,\n        }));\n    }, {\n        capture: true,\n        passive: true,\n    });\n}\n//# sourceMappingURL=trackMediaInteraction.js.map","import { instrumentMethod } from '@datadog/browser-core';\nimport { IncrementalSource } from '../../../types';\nimport { getSerializedNodeId, hasSerializedNode } from '../serialization';\nimport { assembleIncrementalSnapshot } from '../assembly';\nexport function trackStyleSheet(styleSheetCb) {\n    function checkStyleSheetAndCallback(styleSheet, callback) {\n        if (styleSheet && hasSerializedNode(styleSheet.ownerNode)) {\n            callback(getSerializedNodeId(styleSheet.ownerNode));\n        }\n    }\n    const instrumentationStoppers = [\n        instrumentMethod(CSSStyleSheet.prototype, 'insertRule', ({ target: styleSheet, parameters: [rule, index] }) => {\n            checkStyleSheetAndCallback(styleSheet, (id) => styleSheetCb(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule, {\n                id,\n                adds: [{ rule, index }],\n            })));\n        }),\n        instrumentMethod(CSSStyleSheet.prototype, 'deleteRule', ({ target: styleSheet, parameters: [index] }) => {\n            checkStyleSheetAndCallback(styleSheet, (id) => styleSheetCb(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule, {\n                id,\n                removes: [{ index }],\n            })));\n        }),\n    ];\n    if (typeof CSSGroupingRule !== 'undefined') {\n        instrumentGroupingCSSRuleClass(CSSGroupingRule);\n    }\n    else {\n        instrumentGroupingCSSRuleClass(CSSMediaRule);\n        instrumentGroupingCSSRuleClass(CSSSupportsRule);\n    }\n    function instrumentGroupingCSSRuleClass(cls) {\n        instrumentationStoppers.push(instrumentMethod(cls.prototype, 'insertRule', ({ target: styleSheet, parameters: [rule, index] }) => {\n            checkStyleSheetAndCallback(styleSheet.parentStyleSheet, (id) => {\n                const path = getPathToNestedCSSRule(styleSheet);\n                if (path) {\n                    path.push(index || 0);\n                    styleSheetCb(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule, {\n                        id,\n                        adds: [{ rule, index: path }],\n                    }));\n                }\n            });\n        }), instrumentMethod(cls.prototype, 'deleteRule', ({ target: styleSheet, parameters: [index] }) => {\n            checkStyleSheetAndCallback(styleSheet.parentStyleSheet, (id) => {\n                const path = getPathToNestedCSSRule(styleSheet);\n                if (path) {\n                    path.push(index);\n                    styleSheetCb(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule, {\n                        id,\n                        removes: [{ index: path }],\n                    }));\n                }\n            });\n        }));\n    }\n    return {\n        stop: () => {\n            instrumentationStoppers.forEach((stopper) => stopper.stop());\n        },\n    };\n}\nexport function getPathToNestedCSSRule(rule) {\n    const path = [];\n    let currentRule = rule;\n    while (currentRule.parentRule) {\n        const rules = Array.from(currentRule.parentRule.cssRules);\n        const index = rules.indexOf(currentRule);\n        path.unshift(index);\n        currentRule = currentRule.parentRule;\n    }\n    // A rule may not be attached to a stylesheet\n    if (!currentRule.parentStyleSheet) {\n        return;\n    }\n    const rules = Array.from(currentRule.parentStyleSheet.cssRules);\n    const index = rules.indexOf(currentRule);\n    path.unshift(index);\n    return path;\n}\n//# sourceMappingURL=trackStyleSheet.js.map","import { addEventListeners, timeStampNow } from '@datadog/browser-core';\nimport { RecordType } from '../../../types';\nexport function trackFocus(configuration, focusCb) {\n    return addEventListeners(configuration, window, [\"focus\" /* DOM_EVENT.FOCUS */, \"blur\" /* DOM_EVENT.BLUR */], () => {\n        focusCb({\n            data: { has_focus: document.hasFocus() },\n            type: RecordType.Focus,\n            timestamp: timeStampNow(),\n        });\n    });\n}\n//# sourceMappingURL=trackFocus.js.map","import { RecordType } from '../../../types';\nexport function trackFrustration(lifeCycle, frustrationCb, recordIds) {\n    const frustrationSubscription = lifeCycle.subscribe(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, (data) => {\n        var _a, _b;\n        if (data.rawRumEvent.type === \"action\" /* RumEventType.ACTION */ &&\n            data.rawRumEvent.action.type === \"click\" /* ActionType.CLICK */ &&\n            ((_b = (_a = data.rawRumEvent.action.frustration) === null || _a === void 0 ? void 0 : _a.type) === null || _b === void 0 ? void 0 : _b.length) &&\n            'events' in data.domainContext &&\n            data.domainContext.events &&\n            data.domainContext.events.length) {\n            frustrationCb({\n                timestamp: data.rawRumEvent.date,\n                type: RecordType.FrustrationRecord,\n                data: {\n                    frustrationTypes: data.rawRumEvent.action.frustration.type,\n                    recordIds: data.domainContext.events.map((e) => recordIds.getIdForEvent(e)),\n                },\n            });\n        }\n    });\n    return {\n        stop: () => {\n            frustrationSubscription.unsubscribe();\n        },\n    };\n}\n//# sourceMappingURL=trackFrustration.js.map","import { timeStampNow } from '@datadog/browser-core';\nimport { RecordType } from '../../../types';\nexport function trackViewEnd(lifeCycle, viewEndCb) {\n    const viewEndSubscription = lifeCycle.subscribe(4 /* LifeCycleEventType.VIEW_ENDED */, () => {\n        viewEndCb({\n            timestamp: timeStampNow(),\n            type: RecordType.ViewEnd,\n        });\n    });\n    return {\n        stop: () => {\n            viewEndSubscription.unsubscribe();\n        },\n    };\n}\n//# sourceMappingURL=trackViewEnd.js.map","import { instrumentSetter, addEventListeners, noop } from '@datadog/browser-core';\nimport { NodePrivacyLevel, getNodePrivacyLevel, shouldMaskNode } from '@datadog/browser-rum-core';\nimport { IncrementalSource } from '../../../types';\nimport { getEventTarget } from '../eventsUtils';\nimport { getElementInputValue, getSerializedNodeId, hasSerializedNode } from '../serialization';\nimport { assembleIncrementalSnapshot } from '../assembly';\nexport function trackInput(configuration, inputCb, target = document) {\n    const defaultPrivacyLevel = configuration.defaultPrivacyLevel;\n    const lastInputStateMap = new WeakMap();\n    const isShadowRoot = target !== document;\n    const { stop: stopEventListeners } = addEventListeners(configuration, target, \n    // The 'input' event bubbles across shadow roots, so we don't have to listen for it on shadow\n    // roots since it will be handled by the event listener that we did add to the document. Only\n    // the 'change' event is blocked and needs to be handled on shadow roots.\n    isShadowRoot ? [\"change\" /* DOM_EVENT.CHANGE */] : [\"input\" /* DOM_EVENT.INPUT */, \"change\" /* DOM_EVENT.CHANGE */], (event) => {\n        const target = getEventTarget(event);\n        if (target instanceof HTMLInputElement ||\n            target instanceof HTMLTextAreaElement ||\n            target instanceof HTMLSelectElement) {\n            onElementChange(target);\n        }\n    }, {\n        capture: true,\n        passive: true,\n    });\n    let stopPropertySetterInstrumentation;\n    if (!isShadowRoot) {\n        const instrumentationStoppers = [\n            instrumentSetter(HTMLInputElement.prototype, 'value', onElementChange),\n            instrumentSetter(HTMLInputElement.prototype, 'checked', onElementChange),\n            instrumentSetter(HTMLSelectElement.prototype, 'value', onElementChange),\n            instrumentSetter(HTMLTextAreaElement.prototype, 'value', onElementChange),\n            instrumentSetter(HTMLSelectElement.prototype, 'selectedIndex', onElementChange),\n        ];\n        stopPropertySetterInstrumentation = () => {\n            instrumentationStoppers.forEach((stopper) => stopper.stop());\n        };\n    }\n    else {\n        stopPropertySetterInstrumentation = noop;\n    }\n    return {\n        stop: () => {\n            stopPropertySetterInstrumentation();\n            stopEventListeners();\n        },\n    };\n    function onElementChange(target) {\n        const nodePrivacyLevel = getNodePrivacyLevel(target, defaultPrivacyLevel);\n        if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n            return;\n        }\n        const type = target.type;\n        let inputState;\n        if (type === 'radio' || type === 'checkbox') {\n            if (shouldMaskNode(target, nodePrivacyLevel)) {\n                return;\n            }\n            inputState = { isChecked: target.checked };\n        }\n        else {\n            const value = getElementInputValue(target, nodePrivacyLevel);\n            if (value === undefined) {\n                return;\n            }\n            inputState = { text: value };\n        }\n        // Can be multiple changes on the same node within the same batched mutation observation.\n        cbWithDedup(target, inputState);\n        // If a radio was checked, other radios with the same name attribute will be unchecked.\n        const name = target.name;\n        if (type === 'radio' && name && target.checked) {\n            document.querySelectorAll(`input[type=\"radio\"][name=\"${CSS.escape(name)}\"]`).forEach((el) => {\n                if (el !== target) {\n                    // TODO: Consider the privacy implications for various differing input privacy levels\n                    cbWithDedup(el, { isChecked: false });\n                }\n            });\n        }\n    }\n    /**\n     * There can be multiple changes on the same node within the same batched mutation observation.\n     */\n    function cbWithDedup(target, inputState) {\n        if (!hasSerializedNode(target)) {\n            return;\n        }\n        const lastInputState = lastInputStateMap.get(target);\n        if (!lastInputState ||\n            lastInputState.text !== inputState.text ||\n            lastInputState.isChecked !== inputState.isChecked) {\n            lastInputStateMap.set(target, inputState);\n            inputCb(assembleIncrementalSnapshot(IncrementalSource.Input, {\n                id: getSerializedNodeId(target),\n                ...inputState,\n            }));\n        }\n    }\n}\n//# sourceMappingURL=trackInput.js.map","import { noop, throttle, requestIdleCallback } from '@datadog/browser-core';\n/**\n * Maximum duration to wait before processing mutations. If the browser is idle, mutations will be\n * processed more quickly. If the browser is busy executing small tasks (ex: rendering frames), the\n * mutations will wait MUTATION_PROCESS_MAX_DELAY milliseconds before being processed. If the\n * browser is busy executing a longer task, mutations will be processed after this task.\n */\nconst MUTATION_PROCESS_MAX_DELAY = 100;\n/**\n * Minimum duration to wait before processing mutations. This is used to batch mutations together\n * and be able to deduplicate them to save processing time and bandwidth.\n * 16ms is the duration of a frame at 60fps that ensure fluid UI.\n */\nexport const MUTATION_PROCESS_MIN_DELAY = 16;\nexport function createMutationBatch(processMutationBatch) {\n    let cancelScheduledFlush = noop;\n    let pendingMutations = [];\n    function flush() {\n        cancelScheduledFlush();\n        processMutationBatch(pendingMutations);\n        pendingMutations = [];\n    }\n    const { throttled: throttledFlush, cancel: cancelThrottle } = throttle(flush, MUTATION_PROCESS_MIN_DELAY, {\n        leading: false,\n    });\n    return {\n        addMutations: (mutations) => {\n            if (pendingMutations.length === 0) {\n                cancelScheduledFlush = requestIdleCallback(throttledFlush, { timeout: MUTATION_PROCESS_MAX_DELAY });\n            }\n            pendingMutations.push(...mutations);\n        },\n        flush,\n        stop: () => {\n            cancelScheduledFlush();\n            cancelThrottle();\n        },\n    };\n}\n//# sourceMappingURL=mutationBatch.js.map","import { monitor, noop } from '@datadog/browser-core';\nimport { isNodeShadowHost, getMutationObserverConstructor, getParentNode, forEachChildNodes, getNodePrivacyLevel, getTextContent, NodePrivacyLevel, } from '@datadog/browser-rum-core';\nimport { IncrementalSource } from '../../../types';\nimport { getElementInputValue, getSerializedNodeId, hasSerializedNode, nodeAndAncestorsHaveSerializedNode, serializeNodeWithId, serializeAttribute, } from '../serialization';\nimport { createMutationBatch } from '../mutationBatch';\nimport { assembleIncrementalSnapshot } from '../assembly';\n/**\n * Buffers and aggregate mutations generated by a MutationObserver into MutationPayload\n */\nexport function trackMutation(mutationCallback, configuration, shadowRootsController, target) {\n    const MutationObserver = getMutationObserverConstructor();\n    if (!MutationObserver) {\n        return { stop: noop, flush: noop };\n    }\n    const mutationBatch = createMutationBatch((mutations) => {\n        processMutations(mutations.concat(observer.takeRecords()), mutationCallback, configuration, shadowRootsController);\n    });\n    const observer = new MutationObserver(monitor(mutationBatch.addMutations));\n    observer.observe(target, {\n        attributeOldValue: true,\n        attributes: true,\n        characterData: true,\n        characterDataOldValue: true,\n        childList: true,\n        subtree: true,\n    });\n    return {\n        stop: () => {\n            observer.disconnect();\n            mutationBatch.stop();\n        },\n        flush: () => {\n            mutationBatch.flush();\n        },\n    };\n}\nfunction processMutations(mutations, mutationCallback, configuration, shadowRootsController) {\n    const nodePrivacyLevelCache = new Map();\n    mutations\n        .filter((mutation) => mutation.type === 'childList')\n        .forEach((mutation) => {\n        mutation.removedNodes.forEach((removedNode) => {\n            traverseRemovedShadowDom(removedNode, shadowRootsController.removeShadowRoot);\n        });\n    });\n    // Discard any mutation with a 'target' node that:\n    // * isn't injected in the current document or isn't known/serialized yet: those nodes are likely\n    // part of a mutation occurring in a parent Node\n    // * should be hidden or ignored\n    const filteredMutations = mutations.filter((mutation) => mutation.target.isConnected &&\n        nodeAndAncestorsHaveSerializedNode(mutation.target) &&\n        getNodePrivacyLevel(mutation.target, configuration.defaultPrivacyLevel, nodePrivacyLevelCache) !==\n            NodePrivacyLevel.HIDDEN);\n    const { adds, removes, hasBeenSerialized } = processChildListMutations(filteredMutations.filter((mutation) => mutation.type === 'childList'), configuration, shadowRootsController, nodePrivacyLevelCache);\n    const texts = processCharacterDataMutations(filteredMutations.filter((mutation) => mutation.type === 'characterData' && !hasBeenSerialized(mutation.target)), configuration, nodePrivacyLevelCache);\n    const attributes = processAttributesMutations(filteredMutations.filter((mutation) => mutation.type === 'attributes' && !hasBeenSerialized(mutation.target)), configuration, nodePrivacyLevelCache);\n    if (!texts.length && !attributes.length && !removes.length && !adds.length) {\n        return;\n    }\n    mutationCallback(assembleIncrementalSnapshot(IncrementalSource.Mutation, { adds, removes, texts, attributes }));\n}\nfunction processChildListMutations(mutations, configuration, shadowRootsController, nodePrivacyLevelCache) {\n    // First, we iterate over mutations to collect:\n    //\n    // * nodes that have been added in the document and not removed by a subsequent mutation\n    // * nodes that have been removed from the document but were not added in a previous mutation\n    //\n    // For this second category, we also collect their previous parent (mutation.target) because we'll\n    // need it to emit a 'remove' mutation.\n    //\n    // Those two categories may overlap: if a node moved from a position to another, it is reported as\n    // two mutation records, one with a \"removedNodes\" and the other with \"addedNodes\". In this case,\n    // the node will be in both sets.\n    const addedAndMovedNodes = new Set();\n    const removedNodes = new Map();\n    for (const mutation of mutations) {\n        mutation.addedNodes.forEach((node) => {\n            addedAndMovedNodes.add(node);\n        });\n        mutation.removedNodes.forEach((node) => {\n            if (!addedAndMovedNodes.has(node)) {\n                removedNodes.set(node, mutation.target);\n            }\n            addedAndMovedNodes.delete(node);\n        });\n    }\n    // Then, we sort nodes that are still in the document by topological order, for two reasons:\n    //\n    // * We will serialize each added nodes with their descendants. We don't want to serialize a node\n    // twice, so we need to iterate over the parent nodes first and skip any node that is contained in\n    // a precedent node.\n    //\n    // * To emit \"add\" mutations, we need references to the parent and potential next sibling of each\n    // added node. So we need to iterate over the parent nodes first, and when multiple nodes are\n    // siblings, we want to iterate from last to first. This will ensure that any \"next\" node is\n    // already serialized and have an id.\n    const sortedAddedAndMovedNodes = Array.from(addedAndMovedNodes);\n    sortAddedAndMovedNodes(sortedAddedAndMovedNodes);\n    // Then, we iterate over our sorted node sets to emit mutations. We collect the newly serialized\n    // node ids in a set to be able to skip subsequent related mutations.\n    const serializedNodeIds = new Set();\n    const addedNodeMutations = [];\n    for (const node of sortedAddedAndMovedNodes) {\n        if (hasBeenSerialized(node)) {\n            continue;\n        }\n        const parentNodePrivacyLevel = getNodePrivacyLevel(node.parentNode, configuration.defaultPrivacyLevel, nodePrivacyLevelCache);\n        if (parentNodePrivacyLevel === NodePrivacyLevel.HIDDEN || parentNodePrivacyLevel === NodePrivacyLevel.IGNORE) {\n            continue;\n        }\n        const serializedNode = serializeNodeWithId(node, {\n            serializedNodeIds,\n            parentNodePrivacyLevel,\n            serializationContext: { status: 2 /* SerializationContextStatus.MUTATION */, shadowRootsController },\n            configuration,\n        });\n        if (!serializedNode) {\n            continue;\n        }\n        const parentNode = getParentNode(node);\n        addedNodeMutations.push({\n            nextId: getNextSibling(node),\n            parentId: getSerializedNodeId(parentNode),\n            node: serializedNode,\n        });\n    }\n    // Finally, we emit remove mutations.\n    const removedNodeMutations = [];\n    removedNodes.forEach((parent, node) => {\n        if (hasSerializedNode(node)) {\n            removedNodeMutations.push({\n                parentId: getSerializedNodeId(parent),\n                id: getSerializedNodeId(node),\n            });\n        }\n    });\n    return { adds: addedNodeMutations, removes: removedNodeMutations, hasBeenSerialized };\n    function hasBeenSerialized(node) {\n        return hasSerializedNode(node) && serializedNodeIds.has(getSerializedNodeId(node));\n    }\n    function getNextSibling(node) {\n        let nextSibling = node.nextSibling;\n        while (nextSibling) {\n            if (hasSerializedNode(nextSibling)) {\n                return getSerializedNodeId(nextSibling);\n            }\n            nextSibling = nextSibling.nextSibling;\n        }\n        return null;\n    }\n}\nfunction processCharacterDataMutations(mutations, configuration, nodePrivacyLevelCache) {\n    var _a;\n    const textMutations = [];\n    // Deduplicate mutations based on their target node\n    const handledNodes = new Set();\n    const filteredMutations = mutations.filter((mutation) => {\n        if (handledNodes.has(mutation.target)) {\n            return false;\n        }\n        handledNodes.add(mutation.target);\n        return true;\n    });\n    // Emit mutations\n    for (const mutation of filteredMutations) {\n        const value = mutation.target.textContent;\n        if (value === mutation.oldValue) {\n            continue;\n        }\n        const parentNodePrivacyLevel = getNodePrivacyLevel(getParentNode(mutation.target), configuration.defaultPrivacyLevel, nodePrivacyLevelCache);\n        if (parentNodePrivacyLevel === NodePrivacyLevel.HIDDEN || parentNodePrivacyLevel === NodePrivacyLevel.IGNORE) {\n            continue;\n        }\n        textMutations.push({\n            id: getSerializedNodeId(mutation.target),\n            // TODO: pass a valid \"ignoreWhiteSpace\" argument\n            value: (_a = getTextContent(mutation.target, false, parentNodePrivacyLevel)) !== null && _a !== void 0 ? _a : null,\n        });\n    }\n    return textMutations;\n}\nfunction processAttributesMutations(mutations, configuration, nodePrivacyLevelCache) {\n    const attributeMutations = [];\n    // Deduplicate mutations based on their target node and changed attribute\n    const handledElements = new Map();\n    const filteredMutations = mutations.filter((mutation) => {\n        const handledAttributes = handledElements.get(mutation.target);\n        if (handledAttributes && handledAttributes.has(mutation.attributeName)) {\n            return false;\n        }\n        if (!handledAttributes) {\n            handledElements.set(mutation.target, new Set([mutation.attributeName]));\n        }\n        else {\n            handledAttributes.add(mutation.attributeName);\n        }\n        return true;\n    });\n    // Emit mutations\n    const emittedMutations = new Map();\n    for (const mutation of filteredMutations) {\n        const uncensoredValue = mutation.target.getAttribute(mutation.attributeName);\n        if (uncensoredValue === mutation.oldValue) {\n            continue;\n        }\n        const privacyLevel = getNodePrivacyLevel(mutation.target, configuration.defaultPrivacyLevel, nodePrivacyLevelCache);\n        const attributeValue = serializeAttribute(mutation.target, privacyLevel, mutation.attributeName, configuration);\n        let transformedValue;\n        if (mutation.attributeName === 'value') {\n            const inputValue = getElementInputValue(mutation.target, privacyLevel);\n            if (inputValue === undefined) {\n                continue;\n            }\n            transformedValue = inputValue;\n        }\n        else if (typeof attributeValue === 'string') {\n            transformedValue = attributeValue;\n        }\n        else {\n            transformedValue = null;\n        }\n        let emittedMutation = emittedMutations.get(mutation.target);\n        if (!emittedMutation) {\n            emittedMutation = {\n                id: getSerializedNodeId(mutation.target),\n                attributes: {},\n            };\n            attributeMutations.push(emittedMutation);\n            emittedMutations.set(mutation.target, emittedMutation);\n        }\n        emittedMutation.attributes[mutation.attributeName] = transformedValue;\n    }\n    return attributeMutations;\n}\nexport function sortAddedAndMovedNodes(nodes) {\n    nodes.sort((a, b) => {\n        const position = a.compareDocumentPosition(b);\n        /* eslint-disable no-bitwise */\n        if (position & Node.DOCUMENT_POSITION_CONTAINED_BY) {\n            return -1;\n        }\n        else if (position & Node.DOCUMENT_POSITION_CONTAINS) {\n            return 1;\n        }\n        else if (position & Node.DOCUMENT_POSITION_FOLLOWING) {\n            return 1;\n        }\n        else if (position & Node.DOCUMENT_POSITION_PRECEDING) {\n            return -1;\n        }\n        /* eslint-enable no-bitwise */\n        return 0;\n    });\n}\nfunction traverseRemovedShadowDom(removedNode, shadowDomRemovedCallback) {\n    if (isNodeShadowHost(removedNode)) {\n        shadowDomRemovedCallback(removedNode.shadowRoot);\n    }\n    forEachChildNodes(removedNode, (childNode) => traverseRemovedShadowDom(childNode, shadowDomRemovedCallback));\n}\n//# sourceMappingURL=trackMutation.js.map","import { trackInput, trackMutation, trackScroll } from './trackers';\nexport const initShadowRootsController = (configuration, callback, elementsScrollPositions) => {\n    const controllerByShadowRoot = new Map();\n    const shadowRootsController = {\n        addShadowRoot: (shadowRoot) => {\n            if (controllerByShadowRoot.has(shadowRoot)) {\n                return;\n            }\n            const mutationTracker = trackMutation(callback, configuration, shadowRootsController, shadowRoot);\n            // The change event does not bubble up across the shadow root, we have to listen on the shadow root\n            const inputTracker = trackInput(configuration, callback, shadowRoot);\n            // The scroll event does not bubble up across the shadow root, we have to listen on the shadow root\n            const scrollTracker = trackScroll(configuration, callback, elementsScrollPositions, shadowRoot);\n            controllerByShadowRoot.set(shadowRoot, {\n                flush: () => mutationTracker.flush(),\n                stop: () => {\n                    mutationTracker.stop();\n                    inputTracker.stop();\n                    scrollTracker.stop();\n                },\n            });\n        },\n        removeShadowRoot: (shadowRoot) => {\n            const entry = controllerByShadowRoot.get(shadowRoot);\n            if (!entry) {\n                // unidentified root cause: observed in some cases with shadow DOM added by browser extensions\n                return;\n            }\n            entry.stop();\n            controllerByShadowRoot.delete(shadowRoot);\n        },\n        stop: () => {\n            controllerByShadowRoot.forEach(({ stop }) => stop());\n        },\n        flush: () => {\n            controllerByShadowRoot.forEach(({ flush }) => flush());\n        },\n    };\n    return shadowRootsController;\n};\n//# sourceMappingURL=shadowRootsController.js.map","import { sendToExtension } from '@datadog/browser-core';\nimport * as replayStats from '../replayStats';\nimport { trackFocus, trackFrustration, trackInput, trackMediaInteraction, trackMouseInteraction, trackMove, trackMutation, trackScroll, trackStyleSheet, trackViewEnd, trackViewportResize, trackVisualViewportResize, } from './trackers';\nimport { createElementsScrollPositions } from './elementsScrollPositions';\nimport { initShadowRootsController } from './shadowRootsController';\nimport { startFullSnapshots } from './startFullSnapshots';\nimport { initRecordIds } from './recordIds';\nexport function record(options) {\n    const { emit, configuration, lifeCycle } = options;\n    // runtime checks for user options\n    if (!emit) {\n        throw new Error('emit function is required');\n    }\n    const emitAndComputeStats = (record) => {\n        emit(record);\n        sendToExtension('record', { record });\n        const view = options.viewHistory.findView();\n        replayStats.addRecord(view.id);\n    };\n    const elementsScrollPositions = createElementsScrollPositions();\n    const shadowRootsController = initShadowRootsController(configuration, emitAndComputeStats, elementsScrollPositions);\n    const { stop: stopFullSnapshots } = startFullSnapshots(elementsScrollPositions, shadowRootsController, lifeCycle, configuration, flushMutations, (records) => records.forEach((record) => emitAndComputeStats(record)));\n    function flushMutations() {\n        shadowRootsController.flush();\n        mutationTracker.flush();\n    }\n    const recordIds = initRecordIds();\n    const mutationTracker = trackMutation(emitAndComputeStats, configuration, shadowRootsController, document);\n    const trackers = [\n        mutationTracker,\n        trackMove(configuration, emitAndComputeStats),\n        trackMouseInteraction(configuration, emitAndComputeStats, recordIds),\n        trackScroll(configuration, emitAndComputeStats, elementsScrollPositions, document),\n        trackViewportResize(configuration, emitAndComputeStats),\n        trackInput(configuration, emitAndComputeStats),\n        trackMediaInteraction(configuration, emitAndComputeStats),\n        trackStyleSheet(emitAndComputeStats),\n        trackFocus(configuration, emitAndComputeStats),\n        trackVisualViewportResize(configuration, emitAndComputeStats),\n        trackFrustration(lifeCycle, emitAndComputeStats, recordIds),\n        trackViewEnd(lifeCycle, (viewEndRecord) => {\n            flushMutations();\n            emitAndComputeStats(viewEndRecord);\n        }),\n    ];\n    return {\n        stop: () => {\n            shadowRootsController.stop();\n            trackers.forEach((tracker) => tracker.stop());\n            stopFullSnapshots();\n        },\n        flushMutations,\n        shadowRootsController,\n    };\n}\n//# sourceMappingURL=record.js.map","export function createElementsScrollPositions() {\n    const scrollPositionsByElement = new WeakMap();\n    return {\n        set(element, scrollPositions) {\n            if (element === document && !document.scrollingElement) {\n                // cf https://drafts.csswg.org/cssom-view/#dom-document-scrollingelement,\n                // in some cases scrolling elements can not be defined, we don't support those for now\n                return;\n            }\n            scrollPositionsByElement.set(element === document ? document.scrollingElement : element, scrollPositions);\n        },\n        get(element) {\n            return scrollPositionsByElement.get(element);\n        },\n        has(element) {\n            return scrollPositionsByElement.has(element);\n        },\n    };\n}\n//# sourceMappingURL=elementsScrollPositions.js.map","import { getScrollX, getScrollY, getViewportDimension } from '@datadog/browser-rum-core';\nimport { timeStampNow } from '@datadog/browser-core';\nimport { RecordType } from '../../types';\nimport { serializeDocument } from './serialization';\nimport { getVisualViewport } from './viewports';\nexport function startFullSnapshots(elementsScrollPositions, shadowRootsController, lifeCycle, configuration, flushMutations, fullSnapshotCallback) {\n    const takeFullSnapshot = (timestamp = timeStampNow(), serializationContext = {\n        status: 0 /* SerializationContextStatus.INITIAL_FULL_SNAPSHOT */,\n        elementsScrollPositions,\n        shadowRootsController,\n    }) => {\n        const { width, height } = getViewportDimension();\n        const records = [\n            {\n                data: {\n                    height,\n                    href: window.location.href,\n                    width,\n                },\n                type: RecordType.Meta,\n                timestamp,\n            },\n            {\n                data: {\n                    has_focus: document.hasFocus(),\n                },\n                type: RecordType.Focus,\n                timestamp,\n            },\n            {\n                data: {\n                    node: serializeDocument(document, configuration, serializationContext),\n                    initialOffset: {\n                        left: getScrollX(),\n                        top: getScrollY(),\n                    },\n                },\n                type: RecordType.FullSnapshot,\n                timestamp,\n            },\n        ];\n        if (window.visualViewport) {\n            records.push({\n                data: getVisualViewport(window.visualViewport),\n                type: RecordType.VisualViewport,\n                timestamp,\n            });\n        }\n        return records;\n    };\n    fullSnapshotCallback(takeFullSnapshot());\n    const { unsubscribe } = lifeCycle.subscribe(2 /* LifeCycleEventType.VIEW_CREATED */, (view) => {\n        flushMutations();\n        fullSnapshotCallback(takeFullSnapshot(view.startClocks.timeStamp, {\n            shadowRootsController,\n            status: 1 /* SerializationContextStatus.SUBSEQUENT_FULL_SNAPSHOT */,\n            elementsScrollPositions,\n        }));\n    });\n    return {\n        stop: unsubscribe,\n    };\n}\n//# sourceMappingURL=startFullSnapshots.js.map","export function initRecordIds() {\n    const recordIds = new WeakMap();\n    let nextId = 1;\n    return {\n        getIdForEvent(event) {\n            if (!recordIds.has(event)) {\n                recordIds.set(event, nextId++);\n            }\n            return recordIds.get(event);\n        },\n    };\n}\n//# sourceMappingURL=recordIds.js.map","import { RecordType } from '../../types';\nimport * as replayStats from '../replayStats';\nexport function createSegment({ context, creationReason, encoder, }) {\n    let encodedBytesCount = 0;\n    const viewId = context.view.id;\n    const metadata = {\n        start: Infinity,\n        end: -Infinity,\n        creation_reason: creationReason,\n        records_count: 0,\n        has_full_snapshot: false,\n        index_in_view: replayStats.getSegmentsCount(viewId),\n        source: 'browser',\n        ...context,\n    };\n    replayStats.addSegment(viewId);\n    function addRecord(record, callback) {\n        metadata.start = Math.min(metadata.start, record.timestamp);\n        metadata.end = Math.max(metadata.end, record.timestamp);\n        metadata.records_count += 1;\n        metadata.has_full_snapshot || (metadata.has_full_snapshot = record.type === RecordType.FullSnapshot);\n        const prefix = encoder.isEmpty ? '{\"records\":[' : ',';\n        encoder.write(prefix + JSON.stringify(record), (additionalEncodedBytesCount) => {\n            encodedBytesCount += additionalEncodedBytesCount;\n            callback(encodedBytesCount);\n        });\n    }\n    function flush(callback) {\n        if (encoder.isEmpty) {\n            throw new Error('Empty segment flushed');\n        }\n        encoder.write(`],${JSON.stringify(metadata).slice(1)}\\n`);\n        encoder.finish((encoderResult) => {\n            replayStats.addWroteData(metadata.view.id, encoderResult.rawBytesCount);\n            callback(metadata, encoderResult);\n        });\n    }\n    return { addRecord, flush };\n}\n//# sourceMappingURL=segment.js.map","import { isPageExitReason, ONE_SECOND, clearTimeout, setTimeout } from '@datadog/browser-core';\nimport { buildReplayPayload } from './buildReplayPayload';\nimport { createSegment } from './segment';\nexport const SEGMENT_DURATION_LIMIT = 5 * ONE_SECOND;\n/**\n * beacon payload max queue size implementation is 64kb\n * ensure that we leave room for logs, rum and potential other users\n */\nexport let SEGMENT_BYTES_LIMIT = 60000;\n// Segments are the main data structure for session replays. They contain context information used\n// for indexing or UI needs, and a list of records (RRWeb 'events', renamed to avoid confusing\n// namings). They are stored without any processing from the intake, and fetched one after the\n// other while a session is being replayed. Their encoding (deflate) are carefully crafted to allow\n// concatenating multiple segments together. Segments have a size overhead (metadata), so our goal is to\n// build segments containing as many records as possible while complying with the various flush\n// strategies to guarantee a good replay quality.\n//\n// When the recording starts, a segment is initially created.  The segment is flushed (finalized and\n// sent) based on various events (non-exhaustive list):\n//\n// * the page visibility change or becomes to unload\n// * the segment duration reaches a limit\n// * the encoded segment bytes count reaches a limit\n// * ...\n//\n// A segment cannot be created without its context.  If the RUM session ends and no session id is\n// available when creating a new segment, records will be ignored, until the session is renewed and\n// a new session id is available.\n//\n// Empty segments (segments with no record) aren't useful and should be ignored.\n//\n// To help investigate session replays issues, each segment is created with a \"creation reason\",\n// indicating why the session has been created.\nexport function startSegmentCollection(lifeCycle, configuration, sessionManager, viewHistory, httpRequest, encoder) {\n    return doStartSegmentCollection(lifeCycle, () => computeSegmentContext(configuration.applicationId, sessionManager, viewHistory), httpRequest, encoder);\n}\nexport function doStartSegmentCollection(lifeCycle, getSegmentContext, httpRequest, encoder) {\n    let state = {\n        status: 0 /* SegmentCollectionStatus.WaitingForInitialRecord */,\n        nextSegmentCreationReason: 'init',\n    };\n    const { unsubscribe: unsubscribeViewCreated } = lifeCycle.subscribe(2 /* LifeCycleEventType.VIEW_CREATED */, () => {\n        flushSegment('view_change');\n    });\n    const { unsubscribe: unsubscribePageExited } = lifeCycle.subscribe(10 /* LifeCycleEventType.PAGE_EXITED */, (pageExitEvent) => {\n        flushSegment(pageExitEvent.reason);\n    });\n    function flushSegment(flushReason) {\n        if (state.status === 1 /* SegmentCollectionStatus.SegmentPending */) {\n            state.segment.flush((metadata, encoderResult) => {\n                const payload = buildReplayPayload(encoderResult.output, metadata, encoderResult.rawBytesCount);\n                if (isPageExitReason(flushReason)) {\n                    httpRequest.sendOnExit(payload);\n                }\n                else {\n                    httpRequest.send(payload);\n                }\n            });\n            clearTimeout(state.expirationTimeoutId);\n        }\n        if (flushReason !== 'stop') {\n            state = {\n                status: 0 /* SegmentCollectionStatus.WaitingForInitialRecord */,\n                nextSegmentCreationReason: flushReason,\n            };\n        }\n        else {\n            state = {\n                status: 2 /* SegmentCollectionStatus.Stopped */,\n            };\n        }\n    }\n    return {\n        addRecord: (record) => {\n            if (state.status === 2 /* SegmentCollectionStatus.Stopped */) {\n                return;\n            }\n            if (state.status === 0 /* SegmentCollectionStatus.WaitingForInitialRecord */) {\n                const context = getSegmentContext();\n                if (!context) {\n                    return;\n                }\n                state = {\n                    status: 1 /* SegmentCollectionStatus.SegmentPending */,\n                    segment: createSegment({ encoder, context, creationReason: state.nextSegmentCreationReason }),\n                    expirationTimeoutId: setTimeout(() => {\n                        flushSegment('segment_duration_limit');\n                    }, SEGMENT_DURATION_LIMIT),\n                };\n            }\n            state.segment.addRecord(record, (encodedBytesCount) => {\n                if (encodedBytesCount > SEGMENT_BYTES_LIMIT) {\n                    flushSegment('segment_bytes_limit');\n                }\n            });\n        },\n        stop: () => {\n            flushSegment('stop');\n            unsubscribeViewCreated();\n            unsubscribePageExited();\n        },\n    };\n}\nexport function computeSegmentContext(applicationId, sessionManager, viewHistory) {\n    const session = sessionManager.findTrackedSession();\n    const viewContext = viewHistory.findView();\n    if (!session || !viewContext) {\n        return undefined;\n    }\n    return {\n        application: {\n            id: applicationId,\n        },\n        session: {\n            id: session.id,\n        },\n        view: {\n            id: viewContext.id,\n        },\n    };\n}\nexport function setSegmentBytesLimit(newSegmentBytesLimit = 60000) {\n    SEGMENT_BYTES_LIMIT = newSegmentBytesLimit;\n}\n//# sourceMappingURL=segmentCollection.js.map","export function buildReplayPayload(data, metadata, rawSegmentBytesCount) {\n    const formData = new FormData();\n    formData.append('segment', new Blob([data], {\n        type: 'application/octet-stream',\n    }), `${metadata.session.id}-${metadata.start}`);\n    const metadataAndSegmentSizes = {\n        raw_segment_size: rawSegmentBytesCount,\n        compressed_segment_size: data.byteLength,\n        ...metadata,\n    };\n    const serializedMetadataAndSegmentSizes = JSON.stringify(metadataAndSegmentSizes);\n    formData.append('event', new Blob([serializedMetadataAndSegmentSizes], { type: 'application/json' }));\n    return { data: formData, bytesCount: data.byteLength };\n}\n//# sourceMappingURL=buildReplayPayload.js.map","import { createHttpRequest, addTelemetryDebug, canUseEventBridge } from '@datadog/browser-core';\nimport { record } from '../domain/record';\nimport { startSegmentCollection, SEGMENT_BYTES_LIMIT } from '../domain/segmentCollection';\nimport { startRecordBridge } from '../domain/startRecordBridge';\nexport function startRecording(lifeCycle, configuration, sessionManager, viewHistory, encoder, httpRequest) {\n    const cleanupTasks = [];\n    const reportError = (error) => {\n        lifeCycle.notify(13 /* LifeCycleEventType.RAW_ERROR_COLLECTED */, { error });\n        addTelemetryDebug('Error reported to customer', { 'error.message': error.message });\n    };\n    const replayRequest = httpRequest || createHttpRequest(configuration.sessionReplayEndpointBuilder, SEGMENT_BYTES_LIMIT, reportError);\n    let addRecord;\n    if (!canUseEventBridge()) {\n        const segmentCollection = startSegmentCollection(lifeCycle, configuration, sessionManager, viewHistory, replayRequest, encoder);\n        addRecord = segmentCollection.addRecord;\n        cleanupTasks.push(segmentCollection.stop);\n    }\n    else {\n        ;\n        ({ addRecord } = startRecordBridge(viewHistory));\n    }\n    const { stop: stopRecording } = record({\n        emit: addRecord,\n        configuration,\n        lifeCycle,\n        viewHistory,\n    });\n    cleanupTasks.push(stopRecording);\n    return {\n        stop: () => {\n            cleanupTasks.forEach((task) => task());\n        },\n    };\n}\n//# sourceMappingURL=startRecording.js.map","import { getEventBridge } from '@datadog/browser-core';\nexport function startRecordBridge(viewHistory) {\n    const bridge = getEventBridge();\n    return {\n        addRecord: (record) => {\n            // Get the current active view, not at the time of the record, aligning with the segment logic.\n            // This approach could potentially associate the record to an incorrect view, in case the record date is in the past (e.g. frustration records).\n            // However the risk is minimal. We could address the issue when potential negative impact are identified.\n            const view = viewHistory.findView();\n            bridge.send('record', record, view.id);\n        },\n    };\n}\n//# sourceMappingURL=startRecordBridge.js.map","export const MAX_STATS_HISTORY = 10;\nlet statsPerView;\nexport function getSegmentsCount(viewId) {\n    return getOrCreateReplayStats(viewId).segments_count;\n}\nexport function addSegment(viewId) {\n    getOrCreateReplayStats(viewId).segments_count += 1;\n}\nexport function addRecord(viewId) {\n    getOrCreateReplayStats(viewId).records_count += 1;\n}\nexport function addWroteData(viewId, additionalBytesCount) {\n    getOrCreateReplayStats(viewId).segments_total_raw_size += additionalBytesCount;\n}\nexport function getReplayStats(viewId) {\n    return statsPerView === null || statsPerView === void 0 ? void 0 : statsPerView.get(viewId);\n}\nexport function resetReplayStats() {\n    statsPerView = undefined;\n}\nfunction getOrCreateReplayStats(viewId) {\n    if (!statsPerView) {\n        statsPerView = new Map();\n    }\n    let replayStats;\n    if (statsPerView.has(viewId)) {\n        replayStats = statsPerView.get(viewId);\n    }\n    else {\n        replayStats = {\n            records_count: 0,\n            segments_count: 0,\n            segments_total_raw_size: 0,\n        };\n        statsPerView.set(viewId, replayStats);\n        if (statsPerView.size > MAX_STATS_HISTORY) {\n            deleteOldestStats();\n        }\n    }\n    return replayStats;\n}\nfunction deleteOldestStats() {\n    if (!statsPerView) {\n        return;\n    }\n    const toDelete = statsPerView.keys().next().value;\n    if (toDelete) {\n        statsPerView.delete(toDelete);\n    }\n}\n//# sourceMappingURL=replayStats.js.map","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { addEventListener, addTelemetryDebug, concatBuffers } from '@datadog/browser-core';\nexport function createDeflateEncoder(configuration, worker, streamId) {\n    let rawBytesCount = 0;\n    let compressedData = [];\n    let compressedDataTrailer;\n    let nextWriteActionId = 0;\n    const pendingWriteActions = [];\n    const { stop: removeMessageListener } = addEventListener(configuration, worker, 'message', ({ data: workerResponse }) => {\n        if (workerResponse.type !== 'wrote' || workerResponse.streamId !== streamId) {\n            return;\n        }\n        rawBytesCount += workerResponse.additionalBytesCount;\n        compressedData.push(workerResponse.result);\n        compressedDataTrailer = workerResponse.trailer;\n        const nextPendingAction = pendingWriteActions.shift();\n        if (nextPendingAction && nextPendingAction.id === workerResponse.id) {\n            if (nextPendingAction.writeCallback) {\n                nextPendingAction.writeCallback(workerResponse.result.byteLength);\n            }\n            else if (nextPendingAction.finishCallback) {\n                nextPendingAction.finishCallback();\n            }\n        }\n        else {\n            removeMessageListener();\n            addTelemetryDebug('Worker responses received out of order.');\n        }\n    });\n    function consumeResult() {\n        const output = compressedData.length === 0 ? new Uint8Array(0) : concatBuffers(compressedData.concat(compressedDataTrailer));\n        const result = {\n            rawBytesCount,\n            output,\n            outputBytesCount: output.byteLength,\n            encoding: 'deflate',\n        };\n        rawBytesCount = 0;\n        compressedData = [];\n        return result;\n    }\n    function sendResetIfNeeded() {\n        if (nextWriteActionId > 0) {\n            worker.postMessage({\n                action: 'reset',\n                streamId,\n            });\n            nextWriteActionId = 0;\n        }\n    }\n    return {\n        isAsync: true,\n        get isEmpty() {\n            return nextWriteActionId === 0;\n        },\n        write(data, callback) {\n            worker.postMessage({\n                action: 'write',\n                id: nextWriteActionId,\n                data,\n                streamId,\n            });\n            pendingWriteActions.push({\n                id: nextWriteActionId,\n                writeCallback: callback,\n                data,\n            });\n            nextWriteActionId += 1;\n        },\n        finish(callback) {\n            sendResetIfNeeded();\n            if (!pendingWriteActions.length) {\n                callback(consumeResult());\n            }\n            else {\n                // Make sure we do not call any write callback\n                pendingWriteActions.forEach((pendingWriteAction) => {\n                    delete pendingWriteAction.writeCallback;\n                });\n                // Wait for the last action to finish before calling the finish callback\n                pendingWriteActions[pendingWriteActions.length - 1].finishCallback = () => callback(consumeResult());\n            }\n        },\n        finishSync() {\n            sendResetIfNeeded();\n            const pendingData = pendingWriteActions\n                .map((pendingWriteAction) => {\n                // Make sure we do not call any write or finish callback\n                delete pendingWriteAction.writeCallback;\n                delete pendingWriteAction.finishCallback;\n                return pendingWriteAction.data;\n            })\n                .join('');\n            return { ...consumeResult(), pendingData };\n        },\n        estimateEncodedBytesCount(data) {\n            // This is a rough estimation of the data size once it'll be encoded by deflate. We observed\n            // that if it's the first chunk of data pushed to the stream, the ratio is lower (3-4), but\n            // after that the ratio is greater (10+). We chose 8 here, which (on average) seems to produce\n            // requests of the expected size.\n            return data.length / 8;\n        },\n        stop() {\n            removeMessageListener();\n        },\n    };\n}\n//# sourceMappingURL=deflateEncoder.js.map","import { addTelemetryError, display, addEventListener, setTimeout, ONE_SECOND, DOCS_ORIGIN, } from '@datadog/browser-core';\nexport const INITIALIZATION_TIME_OUT_DELAY = 30 * ONE_SECOND;\nfunction createDeflateWorker(configuration) {\n    return new Worker(configuration.workerUrl || URL.createObjectURL(new Blob([\"(()=>{\\\"use strict\\\";function t(t){const e=t.reduce(((t,e)=>t+e.length),0),a=new Uint8Array(e);let n=0;for(const e of t)a.set(e,n),n+=e.length;return a}function e(t){for(var e=t.length;--e>=0;)t[e]=0}var a=256,n=286,r=30,i=15,s=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),h=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),l=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),_=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o=new Array(576);e(o);var d=new Array(60);e(d);var u=new Array(512);e(u);var f=new Array(256);e(f);var c=new Array(29);e(c);var p,g,w,v=new Array(r);function b(t,e,a,n,r){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=n,this.max_length=r,this.has_stree=t&&t.length}function m(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}e(v);var y=function(t){return t<256?u[t]:u[256+(t>>>7)]},k=function(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},z=function(t,e,a){t.bi_valid>16-a?(t.bi_buf|=e<<t.bi_valid&65535,k(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=a)},x=function(t,e,a){z(t,a[2*e],a[2*e+1])},A=function(t,e){var a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},U=function(t,e,a){var n,r,s=new Array(16),h=0;for(n=1;n<=i;n++)s[n]=h=h+a[n-1]<<1;for(r=0;r<=e;r++){var l=t[2*r+1];0!==l&&(t[2*r]=A(s[l]++,l))}},I=function(t){var e;for(e=0;e<n;e++)t.dyn_ltree[2*e]=0;for(e=0;e<r;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0},B=function(t){t.bi_valid>8?k(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},E=function(t,e,a,n){var r=2*e,i=2*a;return t[r]<t[i]||t[r]===t[i]&&n[e]<=n[a]},S=function(t,e,a){for(var n=t.heap[a],r=a<<1;r<=t.heap_len&&(r<t.heap_len&&E(e,t.heap[r+1],t.heap[r],t.depth)&&r++,!E(e,n,t.heap[r],t.depth));)t.heap[a]=t.heap[r],a=r,r<<=1;t.heap[a]=n},C=function(t,e,n){var r,i,l,_,o=0;if(0!==t.last_lit)do{r=t.pending_buf[t.d_buf+2*o]<<8|t.pending_buf[t.d_buf+2*o+1],i=t.pending_buf[t.l_buf+o],o++,0===r?x(t,i,e):(l=f[i],x(t,l+a+1,e),0!==(_=s[l])&&(i-=c[l],z(t,i,_)),r--,l=y(r),x(t,l,n),0!==(_=h[l])&&(r-=v[l],z(t,r,_)))}while(o<t.last_lit);x(t,256,e)},D=function(t,e){var a,n,r,s=e.dyn_tree,h=e.stat_desc.static_tree,l=e.stat_desc.has_stree,_=e.stat_desc.elems,o=-1;for(t.heap_len=0,t.heap_max=573,a=0;a<_;a++)0!==s[2*a]?(t.heap[++t.heap_len]=o=a,t.depth[a]=0):s[2*a+1]=0;for(;t.heap_len<2;)s[2*(r=t.heap[++t.heap_len]=o<2?++o:0)]=1,t.depth[r]=0,t.opt_len--,l&&(t.static_len-=h[2*r+1]);for(e.max_code=o,a=t.heap_len>>1;a>=1;a--)S(t,s,a);r=_;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],S(t,s,1),n=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=n,s[2*r]=s[2*a]+s[2*n],t.depth[r]=(t.depth[a]>=t.depth[n]?t.depth[a]:t.depth[n])+1,s[2*a+1]=s[2*n+1]=r,t.heap[1]=r++,S(t,s,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],function(t,e){var a,n,r,s,h,l,_=e.dyn_tree,o=e.max_code,d=e.stat_desc.static_tree,u=e.stat_desc.has_stree,f=e.stat_desc.extra_bits,c=e.stat_desc.extra_base,p=e.stat_desc.max_length,g=0;for(s=0;s<=i;s++)t.bl_count[s]=0;for(_[2*t.heap[t.heap_max]+1]=0,a=t.heap_max+1;a<573;a++)(s=_[2*_[2*(n=t.heap[a])+1]+1]+1)>p&&(s=p,g++),_[2*n+1]=s,n>o||(t.bl_count[s]++,h=0,n>=c&&(h=f[n-c]),l=_[2*n],t.opt_len+=l*(s+h),u&&(t.static_len+=l*(d[2*n+1]+h)));if(0!==g){do{for(s=p-1;0===t.bl_count[s];)s--;t.bl_count[s]--,t.bl_count[s+1]+=2,t.bl_count[p]--,g-=2}while(g>0);for(s=p;0!==s;s--)for(n=t.bl_count[s];0!==n;)(r=t.heap[--a])>o||(_[2*r+1]!==s&&(t.opt_len+=(s-_[2*r+1])*_[2*r],_[2*r+1]=s),n--)}}(t,e),U(s,o,t.bl_count)},j=function(t,e,a){var n,r,i=-1,s=e[1],h=0,l=7,_=4;for(0===s&&(l=138,_=3),e[2*(a+1)+1]=65535,n=0;n<=a;n++)r=s,s=e[2*(n+1)+1],++h<l&&r===s||(h<_?t.bl_tree[2*r]+=h:0!==r?(r!==i&&t.bl_tree[2*r]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,i=r,0===s?(l=138,_=3):r===s?(l=6,_=3):(l=7,_=4))},M=function(t,e,a){var n,r,i=-1,s=e[1],h=0,l=7,_=4;for(0===s&&(l=138,_=3),n=0;n<=a;n++)if(r=s,s=e[2*(n+1)+1],!(++h<l&&r===s)){if(h<_)do{x(t,r,t.bl_tree)}while(0!=--h);else 0!==r?(r!==i&&(x(t,r,t.bl_tree),h--),x(t,16,t.bl_tree),z(t,h-3,2)):h<=10?(x(t,17,t.bl_tree),z(t,h-3,3)):(x(t,18,t.bl_tree),z(t,h-11,7));h=0,i=r,0===s?(l=138,_=3):r===s?(l=6,_=3):(l=7,_=4)}},L=!1,T=function(t,e,a,n){z(t,0+(n?1:0),3),function(t,e,a,n){B(t),n&&(k(t,a),k(t,~a)),t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a}(t,e,a,!0)},H=function(t,e,n,r){var i,s,h=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,n=4093624447;for(e=0;e<=31;e++,n>>>=1)if(1&n&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<a;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0}(t)),D(t,t.l_desc),D(t,t.d_desc),h=function(t){var e;for(j(t,t.dyn_ltree,t.l_desc.max_code),j(t,t.dyn_dtree,t.d_desc.max_code),D(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*_[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),i=t.opt_len+3+7>>>3,(s=t.static_len+3+7>>>3)<=i&&(i=s)):i=s=n+5,n+4<=i&&-1!==e?T(t,e,n,r):4===t.strategy||s===i?(z(t,2+(r?1:0),3),C(t,o,d)):(z(t,4+(r?1:0),3),function(t,e,a,n){var r;for(z(t,e-257,5),z(t,a-1,5),z(t,n-4,4),r=0;r<n;r++)z(t,t.bl_tree[2*_[r]+1],3);M(t,t.dyn_ltree,e-1),M(t,t.dyn_dtree,a-1)}(t,t.l_desc.max_code+1,t.d_desc.max_code+1,h+1),C(t,t.dyn_ltree,t.dyn_dtree)),I(t),r&&B(t)},R={_tr_init:function(t){L||(!function(){var t,e,a,_,m,y=new Array(16);for(a=0,_=0;_<28;_++)for(c[_]=a,t=0;t<1<<s[_];t++)f[a++]=_;for(f[a-1]=_,m=0,_=0;_<16;_++)for(v[_]=m,t=0;t<1<<h[_];t++)u[m++]=_;for(m>>=7;_<r;_++)for(v[_]=m<<7,t=0;t<1<<h[_]-7;t++)u[256+m++]=_;for(e=0;e<=i;e++)y[e]=0;for(t=0;t<=143;)o[2*t+1]=8,t++,y[8]++;for(;t<=255;)o[2*t+1]=9,t++,y[9]++;for(;t<=279;)o[2*t+1]=7,t++,y[7]++;for(;t<=287;)o[2*t+1]=8,t++,y[8]++;for(U(o,287,y),t=0;t<r;t++)d[2*t+1]=5,d[2*t]=A(t,5);p=new b(o,s,257,n,i),g=new b(d,h,0,r,i),w=new b(new Array(0),l,0,19,7)}(),L=!0),t.l_desc=new m(t.dyn_ltree,p),t.d_desc=new m(t.dyn_dtree,g),t.bl_desc=new m(t.bl_tree,w),t.bi_buf=0,t.bi_valid=0,I(t)},_tr_stored_block:T,_tr_flush_block:H,_tr_tally:function(t,e,n){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&n,t.last_lit++,0===e?t.dyn_ltree[2*n]++:(t.matches++,e--,t.dyn_ltree[2*(f[n]+a+1)]++,t.dyn_dtree[2*y(e)]++),t.last_lit===t.lit_bufsize-1},_tr_align:function(t){z(t,2,3),x(t,256,o),function(t){16===t.bi_valid?(k(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}(t)}},K=function(t,e,a,n){for(var r=65535&t,i=t>>>16&65535,s=0;0!==a;){a-=s=a>2e3?2e3:a;do{i=i+(r=r+e[n++]|0)|0}while(--s);r%=65521,i%=65521}return r|i<<16},N=new Uint32Array(function(){for(var t,e=[],a=0;a<256;a++){t=a;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e}()),O=function(t,e,a,n){var r=N,i=n+a;t^=-1;for(var s=n;s<i;s++)t=t>>>8^r[255&(t^e[s])];return~t},q={2:\\\"need dictionary\\\",1:\\\"stream end\\\",0:\\\"\\\",\\\"-1\\\":\\\"file error\\\",\\\"-2\\\":\\\"stream error\\\",\\\"-3\\\":\\\"data error\\\",\\\"-4\\\":\\\"insufficient memory\\\",\\\"-5\\\":\\\"buffer error\\\",\\\"-6\\\":\\\"incompatible version\\\"},F=0,G=2,J=3,P=4,Q=0,V=1,W=-1,X=0,Y=8,Z=R._tr_init,$=R._tr_stored_block,tt=R._tr_flush_block,et=R._tr_tally,at=R._tr_align,nt=F,rt=1,it=J,st=P,ht=5,lt=Q,_t=V,ot=-2,dt=-3,ut=-5,ft=W,ct=1,pt=2,gt=3,wt=4,vt=X,bt=2,mt=Y,yt=258,kt=262,zt=103,xt=113,At=666,Ut=function(t,e){return t.msg=q[e],e},It=function(t){return(t<<1)-(t>4?9:0)},Bt=function(t){for(var e=t.length;--e>=0;)t[e]=0},Et=function(t,e,a){return(e<<t.hash_shift^a)&t.hash_mask},St=function(t){var e=t.state,a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},Ct=function(t,e){tt(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,St(t.strm)},Dt=function(t,e){t.pending_buf[t.pending++]=e},jt=function(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},Mt=function(t,e){var a,n,r=t.max_chain_length,i=t.strstart,s=t.prev_length,h=t.nice_match,l=t.strstart>t.w_size-kt?t.strstart-(t.w_size-kt):0,_=t.window,o=t.w_mask,d=t.prev,u=t.strstart+yt,f=_[i+s-1],c=_[i+s];t.prev_length>=t.good_match&&(r>>=2),h>t.lookahead&&(h=t.lookahead);do{if(_[(a=e)+s]===c&&_[a+s-1]===f&&_[a]===_[i]&&_[++a]===_[i+1]){i+=2,a++;do{}while(_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&i<u);if(n=yt-(u-i),i=u-yt,n>s){if(t.match_start=e,s=n,n>=h)break;f=_[i+s-1],c=_[i+s]}}}while((e=d[e&o])>l&&0!=--r);return s<=t.lookahead?s:t.lookahead},Lt=function(t){var e,a,n,r,i,s,h,l,_,o,d=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=d+(d-kt)){t.window.set(t.window.subarray(d,d+d),0),t.match_start-=d,t.strstart-=d,t.block_start-=d,e=a=t.hash_size;do{n=t.head[--e],t.head[e]=n>=d?n-d:0}while(--a);e=a=d;do{n=t.prev[--e],t.prev[e]=n>=d?n-d:0}while(--a);r+=d}if(0===t.strm.avail_in)break;if(s=t.strm,h=t.window,l=t.strstart+t.lookahead,_=r,o=void 0,(o=s.avail_in)>_&&(o=_),a=0===o?0:(s.avail_in-=o,h.set(s.input.subarray(s.next_in,s.next_in+o),l),1===s.state.wrap?s.adler=K(s.adler,h,o,l):2===s.state.wrap&&(s.adler=O(s.adler,h,o,l)),s.next_in+=o,s.total_in+=o,o),t.lookahead+=a,t.lookahead+t.insert>=3)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=Et(t,t.ins_h,t.window[i+1]);t.insert&&(t.ins_h=Et(t,t.ins_h,t.window[i+3-1]),t.prev[i&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=i,i++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<kt&&0!==t.strm.avail_in)},Tt=function(t,e){for(var a,n;;){if(t.lookahead<kt){if(Lt(t),t.lookahead<kt&&e===nt)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=Et(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-kt&&(t.match_length=Mt(t,a)),t.match_length>=3)if(n=et(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=Et(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=Et(t,t.ins_h,t.window[t.strstart+1]);else n=et(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(Ct(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===st?(Ct(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(Ct(t,!1),0===t.strm.avail_out)?1:2},Ht=function(t,e){for(var a,n,r;;){if(t.lookahead<kt){if(Lt(t),t.lookahead<kt&&e===nt)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=Et(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length<t.max_lazy_match&&t.strstart-a<=t.w_size-kt&&(t.match_length=Mt(t,a),t.match_length<=5&&(t.strategy===ct||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){r=t.strstart+t.lookahead-3,n=et(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=r&&(t.ins_h=Et(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,n&&(Ct(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if((n=et(t,0,t.window[t.strstart-1]))&&Ct(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=et(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===st?(Ct(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(Ct(t,!1),0===t.strm.avail_out)?1:2};function Rt(t,e,a,n,r){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=n,this.func=r}var Kt=[new Rt(0,0,0,0,(function(t,e){var a=65535;for(a>t.pending_buf_size-5&&(a=t.pending_buf_size-5);;){if(t.lookahead<=1){if(Lt(t),0===t.lookahead&&e===nt)return 1;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+a;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,Ct(t,!1),0===t.strm.avail_out))return 1;if(t.strstart-t.block_start>=t.w_size-kt&&(Ct(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===st?(Ct(t,!0),0===t.strm.avail_out?3:4):(t.strstart>t.block_start&&(Ct(t,!1),t.strm.avail_out),1)})),new Rt(4,4,8,4,Tt),new Rt(4,5,16,8,Tt),new Rt(4,6,32,32,Tt),new Rt(4,4,16,16,Ht),new Rt(8,16,32,32,Ht),new Rt(8,16,128,128,Ht),new Rt(8,32,128,256,Ht),new Rt(32,128,258,1024,Ht),new Rt(32,258,258,4096,Ht)];function Nt(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=mt,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Bt(this.dyn_ltree),Bt(this.dyn_dtree),Bt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Bt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Bt(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var Ot=function(t){if(!t||!t.state)return Ut(t,ot);t.total_in=t.total_out=0,t.data_type=bt;var e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?42:xt,t.adler=2===e.wrap?0:1,e.last_flush=nt,Z(e),lt},qt=function(t){var e,a=Ot(t);return a===lt&&((e=t.state).window_size=2*e.w_size,Bt(e.head),e.max_lazy_match=Kt[e.level].max_lazy,e.good_match=Kt[e.level].good_length,e.nice_match=Kt[e.level].nice_length,e.max_chain_length=Kt[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0),a},Ft=function(t,e,a,n,r,i){if(!t)return ot;var s=1;if(e===ft&&(e=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),r<1||r>9||a!==mt||n<8||n>15||e<0||e>9||i<0||i>wt)return Ut(t,ot);8===n&&(n=9);var h=new Nt;return t.state=h,h.strm=t,h.wrap=s,h.gzhead=null,h.w_bits=n,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=r+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+3-1)/3),h.window=new Uint8Array(2*h.w_size),h.head=new Uint16Array(h.hash_size),h.prev=new Uint16Array(h.w_size),h.lit_bufsize=1<<r+6,h.pending_buf_size=4*h.lit_bufsize,h.pending_buf=new Uint8Array(h.pending_buf_size),h.d_buf=1*h.lit_bufsize,h.l_buf=3*h.lit_bufsize,h.level=e,h.strategy=i,h.method=a,qt(t)},Gt={deflateInit:function(t,e){return Ft(t,e,mt,15,8,vt)},deflateInit2:Ft,deflateReset:qt,deflateResetKeep:Ot,deflateSetHeader:function(t,e){return t&&t.state?2!==t.state.wrap?ot:(t.state.gzhead=e,lt):ot},deflate:function(t,e){var a,n;if(!t||!t.state||e>ht||e<0)return t?Ut(t,ot):ot;var r=t.state;if(!t.output||!t.input&&0!==t.avail_in||r.status===At&&e!==st)return Ut(t,0===t.avail_out?ut:ot);r.strm=t;var i=r.last_flush;if(r.last_flush=e,42===r.status)if(2===r.wrap)t.adler=0,Dt(r,31),Dt(r,139),Dt(r,8),r.gzhead?(Dt(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),Dt(r,255&r.gzhead.time),Dt(r,r.gzhead.time>>8&255),Dt(r,r.gzhead.time>>16&255),Dt(r,r.gzhead.time>>24&255),Dt(r,9===r.level?2:r.strategy>=pt||r.level<2?4:0),Dt(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(Dt(r,255&r.gzhead.extra.length),Dt(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(t.adler=O(t.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69):(Dt(r,0),Dt(r,0),Dt(r,0),Dt(r,0),Dt(r,0),Dt(r,9===r.level?2:r.strategy>=pt||r.level<2?4:0),Dt(r,3),r.status=xt);else{var s=mt+(r.w_bits-8<<4)<<8;s|=(r.strategy>=pt||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(s|=32),s+=31-s%31,r.status=xt,jt(r,s),0!==r.strstart&&(jt(r,t.adler>>>16),jt(r,65535&t.adler)),t.adler=1}if(69===r.status)if(r.gzhead.extra){for(a=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>a&&(t.adler=O(t.adler,r.pending_buf,r.pending-a,a)),St(t),a=r.pending,r.pending!==r.pending_buf_size));)Dt(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(t.adler=O(t.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=73)}else r.status=73;if(73===r.status)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(t.adler=O(t.adler,r.pending_buf,r.pending-a,a)),St(t),a=r.pending,r.pending===r.pending_buf_size)){n=1;break}n=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,Dt(r,n)}while(0!==n);r.gzhead.hcrc&&r.pending>a&&(t.adler=O(t.adler,r.pending_buf,r.pending-a,a)),0===n&&(r.gzindex=0,r.status=91)}else r.status=91;if(91===r.status)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(t.adler=O(t.adler,r.pending_buf,r.pending-a,a)),St(t),a=r.pending,r.pending===r.pending_buf_size)){n=1;break}n=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,Dt(r,n)}while(0!==n);r.gzhead.hcrc&&r.pending>a&&(t.adler=O(t.adler,r.pending_buf,r.pending-a,a)),0===n&&(r.status=zt)}else r.status=zt;if(r.status===zt&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&St(t),r.pending+2<=r.pending_buf_size&&(Dt(r,255&t.adler),Dt(r,t.adler>>8&255),t.adler=0,r.status=xt)):r.status=xt),0!==r.pending){if(St(t),0===t.avail_out)return r.last_flush=-1,lt}else if(0===t.avail_in&&It(e)<=It(i)&&e!==st)return Ut(t,ut);if(r.status===At&&0!==t.avail_in)return Ut(t,ut);if(0!==t.avail_in||0!==r.lookahead||e!==nt&&r.status!==At){var h=r.strategy===pt?function(t,e){for(var a;;){if(0===t.lookahead&&(Lt(t),0===t.lookahead)){if(e===nt)return 1;break}if(t.match_length=0,a=et(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(Ct(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===st?(Ct(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(Ct(t,!1),0===t.strm.avail_out)?1:2}(r,e):r.strategy===gt?function(t,e){for(var a,n,r,i,s=t.window;;){if(t.lookahead<=yt){if(Lt(t),t.lookahead<=yt&&e===nt)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=s[r=t.strstart-1])===s[++r]&&n===s[++r]&&n===s[++r]){i=t.strstart+yt;do{}while(n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&r<i);t.match_length=yt-(i-r),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=et(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=et(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(Ct(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===st?(Ct(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(Ct(t,!1),0===t.strm.avail_out)?1:2}(r,e):Kt[r.level].func(r,e);if(3!==h&&4!==h||(r.status=At),1===h||3===h)return 0===t.avail_out&&(r.last_flush=-1),lt;if(2===h&&(e===rt?at(r):e!==ht&&($(r,0,0,!1),e===it&&(Bt(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),St(t),0===t.avail_out))return r.last_flush=-1,lt}return e!==st?lt:r.wrap<=0?_t:(2===r.wrap?(Dt(r,255&t.adler),Dt(r,t.adler>>8&255),Dt(r,t.adler>>16&255),Dt(r,t.adler>>24&255),Dt(r,255&t.total_in),Dt(r,t.total_in>>8&255),Dt(r,t.total_in>>16&255),Dt(r,t.total_in>>24&255)):(jt(r,t.adler>>>16),jt(r,65535&t.adler)),St(t),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?lt:_t)},deflateEnd:function(t){if(!t||!t.state)return ot;var e=t.state.status;return 42!==e&&69!==e&&73!==e&&91!==e&&e!==zt&&e!==xt&&e!==At?Ut(t,ot):(t.state=null,e===xt?Ut(t,dt):lt)},deflateSetDictionary:function(t,e){var a=e.length;if(!t||!t.state)return ot;var n=t.state,r=n.wrap;if(2===r||1===r&&42!==n.status||n.lookahead)return ot;if(1===r&&(t.adler=K(t.adler,e,a,0)),n.wrap=0,a>=n.w_size){0===r&&(Bt(n.head),n.strstart=0,n.block_start=0,n.insert=0);var i=new Uint8Array(n.w_size);i.set(e.subarray(a-n.w_size,a),0),e=i,a=n.w_size}var s=t.avail_in,h=t.next_in,l=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,Lt(n);n.lookahead>=3;){var _=n.strstart,o=n.lookahead-2;do{n.ins_h=Et(n,n.ins_h,n.window[_+3-1]),n.prev[_&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=_,_++}while(--o);n.strstart=_,n.lookahead=2,Lt(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,t.next_in=h,t.input=l,t.avail_in=s,n.wrap=r,lt},deflateInfo:\\\"pako deflate (from Nodeca project)\\\"};for(var Jt=new Uint8Array(256),Pt=0;Pt<256;Pt++)Jt[Pt]=Pt>=252?6:Pt>=248?5:Pt>=240?4:Pt>=224?3:Pt>=192?2:1;Jt[254]=Jt[254]=1;var Qt=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\\\"\\\",this.state=null,this.data_type=2,this.adler=0},Vt=Object.prototype.toString,Wt=F,Xt=G,Yt=J,Zt=P,$t=Q,te=V,ee=W,ae=X,ne=Y;function re(){this.options={level:ee,method:ne,chunkSize:16384,windowBits:15,memLevel:8,strategy:ae};var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg=\\\"\\\",this.ended=!1,this.chunks=[],this.strm=new Qt,this.strm.avail_out=0;var e=Gt.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(e!==$t)throw new Error(q[e]);if(t.header&&Gt.deflateSetHeader(this.strm,t.header),t.dictionary){var a;if(a=\\\"[object ArrayBuffer]\\\"===Vt.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(e=Gt.deflateSetDictionary(this.strm,a))!==$t)throw new Error(q[e]);this._dict_set=!0}}function ie(t,e,a){try{t.postMessage({type:\\\"errored\\\",error:e,streamId:a})}catch(n){t.postMessage({type:\\\"errored\\\",error:String(e),streamId:a})}}function se(t){const e=t.strm.adler;return new Uint8Array([3,0,e>>>24&255,e>>>16&255,e>>>8&255,255&e])}re.prototype.push=function(t,e){var a,n,r=this.strm,i=this.options.chunkSize;if(this.ended)return!1;for(n=e===~~e?e:!0===e?Zt:Wt,\\\"[object ArrayBuffer]\\\"===Vt.call(t)?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;;)if(0===r.avail_out&&(r.output=new Uint8Array(i),r.next_out=0,r.avail_out=i),(n===Xt||n===Yt)&&r.avail_out<=6)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else{if((a=Gt.deflate(r,n))===te)return r.next_out>0&&this.onData(r.output.subarray(0,r.next_out)),a=Gt.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===$t;if(0!==r.avail_out){if(n>0&&r.next_out>0)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else if(0===r.avail_in)break}else this.onData(r.output)}return!0},re.prototype.onData=function(t){this.chunks.push(t)},re.prototype.onEnd=function(t){t===$t&&(this.result=function(t){for(var e=0,a=0,n=t.length;a<n;a++)e+=t[a].length;for(var r=new Uint8Array(e),i=0,s=0,h=t.length;i<h;i++){var l=t[i];r.set(l,s),s+=l.length}return r}(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},function(e=self){try{const a=new Map;e.addEventListener(\\\"message\\\",(n=>{try{const r=function(e,a){switch(a.action){case\\\"init\\\":return{type:\\\"initialized\\\",version:\\\"6.1.0\\\"};case\\\"write\\\":{let n=e.get(a.streamId);n||(n=new re,e.set(a.streamId,n));const r=n.chunks.length,i=function(t){if(\\\"function\\\"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,n,r,i,s=t.length,h=0;for(r=0;r<s;r++)a=t.charCodeAt(r),55296==(64512&a)&&r+1<s&&(n=t.charCodeAt(r+1),56320==(64512&n)&&(a=65536+(a-55296<<10)+(n-56320),r++)),h+=a<128?1:a<2048?2:a<65536?3:4;for(e=new Uint8Array(h),i=0,r=0;i<h;r++)a=t.charCodeAt(r),55296==(64512&a)&&r+1<s&&(n=t.charCodeAt(r+1),56320==(64512&n)&&(a=65536+(a-55296<<10)+(n-56320),r++)),a<128?e[i++]=a:a<2048?(e[i++]=192|a>>>6,e[i++]=128|63&a):a<65536?(e[i++]=224|a>>>12,e[i++]=128|a>>>6&63,e[i++]=128|63&a):(e[i++]=240|a>>>18,e[i++]=128|a>>>12&63,e[i++]=128|a>>>6&63,e[i++]=128|63&a);return e}(a.data);return n.push(i,G),{type:\\\"wrote\\\",id:a.id,streamId:a.streamId,result:t(n.chunks.slice(r)),trailer:se(n),additionalBytesCount:i.length}}case\\\"reset\\\":e.delete(a.streamId)}}(a,n.data);r&&e.postMessage(r)}catch(t){ie(e,t,n.data&&\\\"streamId\\\"in n.data?n.data.streamId:void 0)}}))}catch(t){ie(e,t)}}()})();\"])));\n}\nlet state = { status: 0 /* DeflateWorkerStatus.Nil */ };\nexport function startDeflateWorker(configuration, source, onInitializationFailure, createDeflateWorkerImpl = createDeflateWorker) {\n    if (state.status === 0 /* DeflateWorkerStatus.Nil */) {\n        // doStartDeflateWorker updates the state to \"loading\" or \"error\"\n        doStartDeflateWorker(configuration, source, createDeflateWorkerImpl);\n    }\n    switch (state.status) {\n        case 1 /* DeflateWorkerStatus.Loading */:\n            state.initializationFailureCallbacks.push(onInitializationFailure);\n            return state.worker;\n        case 3 /* DeflateWorkerStatus.Initialized */:\n            return state.worker;\n    }\n}\nexport function resetDeflateWorkerState() {\n    if (state.status === 3 /* DeflateWorkerStatus.Initialized */ || state.status === 1 /* DeflateWorkerStatus.Loading */) {\n        state.stop();\n    }\n    state = { status: 0 /* DeflateWorkerStatus.Nil */ };\n}\nexport function getDeflateWorkerStatus() {\n    return state.status;\n}\n/**\n * Starts the deflate worker and handle messages and errors\n *\n * The spec allow browsers to handle worker errors differently:\n * - Chromium throws an exception\n * - Firefox fires an error event\n *\n * more details: https://bugzilla.mozilla.org/show_bug.cgi?id=1736865#c2\n */\nexport function doStartDeflateWorker(configuration, source, createDeflateWorkerImpl = createDeflateWorker) {\n    try {\n        const worker = createDeflateWorkerImpl(configuration);\n        const { stop: removeErrorListener } = addEventListener(configuration, worker, 'error', (error) => {\n            onError(configuration, source, error);\n        });\n        const { stop: removeMessageListener } = addEventListener(configuration, worker, 'message', ({ data }) => {\n            if (data.type === 'errored') {\n                onError(configuration, source, data.error, data.streamId);\n            }\n            else if (data.type === 'initialized') {\n                onInitialized(data.version);\n            }\n        });\n        worker.postMessage({ action: 'init' });\n        setTimeout(() => onTimeout(source), INITIALIZATION_TIME_OUT_DELAY);\n        const stop = () => {\n            removeErrorListener();\n            removeMessageListener();\n        };\n        state = { status: 1 /* DeflateWorkerStatus.Loading */, worker, stop, initializationFailureCallbacks: [] };\n    }\n    catch (error) {\n        onError(configuration, source, error);\n    }\n}\nfunction onTimeout(source) {\n    if (state.status === 1 /* DeflateWorkerStatus.Loading */) {\n        display.error(`${source} failed to start: a timeout occurred while initializing the Worker`);\n        state.initializationFailureCallbacks.forEach((callback) => callback());\n        state = { status: 2 /* DeflateWorkerStatus.Error */ };\n    }\n}\nfunction onInitialized(version) {\n    if (state.status === 1 /* DeflateWorkerStatus.Loading */) {\n        state = { status: 3 /* DeflateWorkerStatus.Initialized */, worker: state.worker, stop: state.stop, version };\n    }\n}\nfunction onError(configuration, source, error, streamId) {\n    if (state.status === 1 /* DeflateWorkerStatus.Loading */ || state.status === 0 /* DeflateWorkerStatus.Nil */) {\n        display.error(`${source} failed to start: an error occurred while creating the Worker:`, error);\n        if (error instanceof Event || (error instanceof Error && isMessageCspRelated(error.message))) {\n            let baseMessage;\n            if (configuration.workerUrl) {\n                baseMessage = `Please make sure the Worker URL ${configuration.workerUrl} is correct and CSP is correctly configured.`;\n            }\n            else {\n                baseMessage = 'Please make sure CSP is correctly configured.';\n            }\n            display.error(`${baseMessage} See documentation at ${DOCS_ORIGIN}/integrations/content_security_policy_logs/#use-csp-with-real-user-monitoring-and-session-replay`);\n        }\n        else {\n            addTelemetryError(error);\n        }\n        if (state.status === 1 /* DeflateWorkerStatus.Loading */) {\n            state.initializationFailureCallbacks.forEach((callback) => callback());\n        }\n        state = { status: 2 /* DeflateWorkerStatus.Error */ };\n    }\n    else {\n        addTelemetryError(error, {\n            worker_version: state.status === 3 /* DeflateWorkerStatus.Initialized */ && state.version,\n            stream_id: streamId,\n        });\n    }\n}\nfunction isMessageCspRelated(message) {\n    return (message.includes('Content Security Policy') ||\n        // Related to `require-trusted-types-for` CSP: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for\n        message.includes(\"requires 'TrustedScriptURL'\"));\n}\n//# sourceMappingURL=deflateWorker.js.map","/**\n * Test for Browser features used while recording\n */\nexport function isBrowserSupported() {\n    return (\n    // Array.from is a bit less supported by browsers than CSSSupportsRule, but has higher chances\n    // to be polyfilled. Test for both to be more confident. We could add more things if we find out\n    // this test is not sufficient.\n    typeof Array.from === 'function' &&\n        typeof CSSSupportsRule === 'function' &&\n        typeof URL.createObjectURL === 'function' &&\n        'forEach' in NodeList.prototype);\n}\n//# sourceMappingURL=isBrowserSupported.js.map","import { getSessionReplayUrl } from '@datadog/browser-rum-core';\nimport { isBrowserSupported } from '../boot/isBrowserSupported';\nexport function getSessionReplayLink(configuration, sessionManager, viewHistory, isRecordingStarted) {\n    const session = sessionManager.findTrackedSession();\n    const errorType = getErrorType(session, isRecordingStarted);\n    const viewContext = viewHistory.findView();\n    return getSessionReplayUrl(configuration, {\n        viewContext,\n        errorType,\n        session,\n    });\n}\nfunction getErrorType(session, isRecordingStarted) {\n    if (!isBrowserSupported()) {\n        return 'browser-not-supported';\n    }\n    if (!session) {\n        // possibilities:\n        // - rum sampled out\n        // - session expired (edge case)\n        return 'rum-not-tracked';\n    }\n    if (session.sessionReplay === 0 /* SessionReplayState.OFF */) {\n        // possibilities\n        // - replay sampled out\n        return 'incorrect-session-plan';\n    }\n    if (!isRecordingStarted) {\n        return 'replay-not-started';\n    }\n}\n//# sourceMappingURL=getSessionReplayLink.js.map","import { asyncRunOnReadyState, monitorError, PageExitReason } from '@datadog/browser-core';\nimport { getSessionReplayLink } from '../domain/getSessionReplayLink';\nexport function createPostStartStrategy(configuration, lifeCycle, sessionManager, viewHistory, loadRecorder, getOrCreateDeflateEncoder) {\n    let status = 0 /* RecorderStatus.Stopped */;\n    let stopRecording;\n    lifeCycle.subscribe(8 /* LifeCycleEventType.SESSION_EXPIRED */, () => {\n        if (status === 2 /* RecorderStatus.Starting */ || status === 3 /* RecorderStatus.Started */) {\n            stop();\n            status = 1 /* RecorderStatus.IntentToStart */;\n        }\n    });\n    // Stop the recorder on page unload to avoid sending records after the page is ended.\n    lifeCycle.subscribe(10 /* LifeCycleEventType.PAGE_EXITED */, (pageExitEvent) => {\n        if (pageExitEvent.reason === PageExitReason.UNLOADING) {\n            stop();\n        }\n    });\n    lifeCycle.subscribe(9 /* LifeCycleEventType.SESSION_RENEWED */, () => {\n        if (status === 1 /* RecorderStatus.IntentToStart */) {\n            start();\n        }\n    });\n    const doStart = async () => {\n        const [startRecordingImpl] = await Promise.all([loadRecorder(), asyncRunOnReadyState(configuration, 'interactive')]);\n        if (status !== 2 /* RecorderStatus.Starting */) {\n            return;\n        }\n        const deflateEncoder = getOrCreateDeflateEncoder();\n        if (!deflateEncoder || !startRecordingImpl) {\n            status = 0 /* RecorderStatus.Stopped */;\n            return;\n        }\n        ;\n        ({ stop: stopRecording } = startRecordingImpl(lifeCycle, configuration, sessionManager, viewHistory, deflateEncoder));\n        status = 3 /* RecorderStatus.Started */;\n    };\n    function start(options) {\n        const session = sessionManager.findTrackedSession();\n        if (canStartRecording(session, options)) {\n            status = 1 /* RecorderStatus.IntentToStart */;\n            return;\n        }\n        if (isRecordingInProgress(status)) {\n            return;\n        }\n        status = 2 /* RecorderStatus.Starting */;\n        // Intentionally not awaiting doStart() to keep it asynchronous\n        doStart().catch(monitorError);\n        if (shouldForceReplay(session, options)) {\n            sessionManager.setForcedReplay();\n        }\n    }\n    function stop() {\n        if (status === 3 /* RecorderStatus.Started */) {\n            stopRecording === null || stopRecording === void 0 ? void 0 : stopRecording();\n        }\n        status = 0 /* RecorderStatus.Stopped */;\n    }\n    return {\n        start,\n        stop,\n        getSessionReplayLink() {\n            return getSessionReplayLink(configuration, sessionManager, viewHistory, status !== 0 /* RecorderStatus.Stopped */);\n        },\n        isRecording: () => status === 3 /* RecorderStatus.Started */,\n    };\n}\nfunction canStartRecording(session, options) {\n    return !session || (session.sessionReplay === 0 /* SessionReplayState.OFF */ && (!options || !options.force));\n}\nfunction isRecordingInProgress(status) {\n    return status === 2 /* RecorderStatus.Starting */ || status === 3 /* RecorderStatus.Started */;\n}\nfunction shouldForceReplay(session, options) {\n    return options && options.force && session.sessionReplay === 0 /* SessionReplayState.OFF */;\n}\n//# sourceMappingURL=postStartStrategy.js.map","// Keep the following in sync with packages/rum-slim/src/entries/main.ts\nimport { defineGlobal, getGlobalObject } from '@datadog/browser-core';\nimport { makeRumPublicApi, startRum } from '@datadog/browser-rum-core';\nimport { makeRecorderApi } from '../boot/recorderApi';\nimport { createDeflateEncoder, startDeflateWorker } from '../domain/deflate';\nimport { lazyLoadRecorder } from '../boot/lazyLoadRecorder';\nexport { DefaultPrivacyLevel } from '@datadog/browser-core';\nconst recorderApi = makeRecorderApi(lazyLoadRecorder);\nexport const datadogRum = makeRumPublicApi(startRum, recorderApi, { startDeflateWorker, createDeflateEncoder });\ndefineGlobal(getGlobalObject(), 'DD_RUM', datadogRum);\n//# sourceMappingURL=main.js.map","import { canUseEventBridge, noop, bridgeSupports, } from '@datadog/browser-core';\nimport { getReplayStats as getReplayStatsImpl } from '../domain/replayStats';\nimport { createDeflateEncoder, getDeflateWorkerStatus, startDeflateWorker, } from '../domain/deflate';\nimport { isBrowserSupported } from './isBrowserSupported';\nimport { createPostStartStrategy } from './postStartStrategy';\nimport { createPreStartStrategy } from './preStartStrategy';\nexport function makeRecorderApi(loadRecorder, createDeflateWorkerImpl) {\n    if ((canUseEventBridge() && !bridgeSupports(\"records\" /* BridgeCapability.RECORDS */)) || !isBrowserSupported()) {\n        return {\n            start: noop,\n            stop: noop,\n            getReplayStats: () => undefined,\n            onRumStart: noop,\n            isRecording: () => false,\n            getSessionReplayLink: () => undefined,\n        };\n    }\n    // eslint-disable-next-line prefer-const\n    let { strategy, shouldStartImmediately } = createPreStartStrategy();\n    return {\n        start: (options) => strategy.start(options),\n        stop: () => strategy.stop(),\n        getSessionReplayLink: () => strategy.getSessionReplayLink(),\n        onRumStart,\n        isRecording: () => \n        // The worker is started optimistically, meaning we could have started to record but its\n        // initialization fails a bit later. This could happen when:\n        // * the worker URL (blob or plain URL) is blocked by CSP in Firefox only (Chromium and Safari\n        // throw an exception when instantiating the worker, and IE doesn't care about CSP)\n        // * the browser fails to load the worker in case the workerUrl is used\n        // * an unexpected error occurs in the Worker before initialization, ex:\n        //   * a runtime exception collected by monitor()\n        //   * a syntax error notified by the browser via an error event\n        // * the worker is unresponsive for some reason and timeouts\n        //\n        // It is not expected to happen often. Nonetheless, the \"replayable\" status on RUM events is\n        // an important part of the Datadog App:\n        // * If we have a false positive (we set has_replay: true even if no replay data is present),\n        // we might display broken links to the Session Replay player.\n        // * If we have a false negative (we don't set has_replay: true even if replay data is\n        // available), it is less noticeable because no link will be displayed.\n        //\n        // Thus, it is better to have false negative, so let's make sure the worker is correctly\n        // initialized before advertizing that we are recording.\n        //\n        // In the future, when the compression worker will also be used for RUM data, this will be\n        // less important since no RUM event will be sent when the worker fails to initialize.\n        getDeflateWorkerStatus() === 3 /* DeflateWorkerStatus.Initialized */ && strategy.isRecording(),\n        getReplayStats: (viewId) => getDeflateWorkerStatus() === 3 /* DeflateWorkerStatus.Initialized */ ? getReplayStatsImpl(viewId) : undefined,\n    };\n    function onRumStart(lifeCycle, configuration, sessionManager, viewHistory, worker) {\n        let cachedDeflateEncoder;\n        function getOrCreateDeflateEncoder() {\n            if (!cachedDeflateEncoder) {\n                worker !== null && worker !== void 0 ? worker : (worker = startDeflateWorker(configuration, 'Datadog Session Replay', () => {\n                    strategy.stop();\n                }, createDeflateWorkerImpl));\n                if (worker) {\n                    cachedDeflateEncoder = createDeflateEncoder(configuration, worker, 1 /* DeflateEncoderStreamId.REPLAY */);\n                }\n            }\n            return cachedDeflateEncoder;\n        }\n        strategy = createPostStartStrategy(configuration, lifeCycle, sessionManager, viewHistory, loadRecorder, getOrCreateDeflateEncoder);\n        if (shouldStartImmediately(configuration)) {\n            strategy.start();\n        }\n    }\n}\n//# sourceMappingURL=recorderApi.js.map","import { noop } from '@datadog/browser-core';\nexport function createPreStartStrategy() {\n    let status = 0 /* PreStartRecorderStatus.None */;\n    return {\n        strategy: {\n            start() {\n                status = 1 /* PreStartRecorderStatus.HadManualStart */;\n            },\n            stop() {\n                status = 2 /* PreStartRecorderStatus.HadManualStop */;\n            },\n            isRecording: () => false,\n            getSessionReplayLink: noop,\n        },\n        shouldStartImmediately(configuration) {\n            return (status === 1 /* PreStartRecorderStatus.HadManualStart */ ||\n                (status === 0 /* PreStartRecorderStatus.None */ && !configuration.startSessionReplayRecordingManually));\n        },\n    };\n}\n//# sourceMappingURL=preStartStrategy.js.map","export async function lazyLoadRecorder() {\n    try {\n        const module = await import(/* webpackChunkName: \"recorder\" */ './startRecording');\n        return module.startRecording;\n    }\n    catch (_a) {\n        /* Prevent collecting the webpack ChunkLoadError as it is already collected as a RUM resource. */\n    }\n}\n//# sourceMappingURL=lazyLoadRecorder.js.map","import { datadogRum } from \"@datadog/browser-rum\"\n\nif (window.datadogEnvironment) {\n  datadogRum.init({\n    applicationId: \"00847d7d-72d5-4ede-91ac-2efdc9af7278\",\n    clientToken: \"pubb2da50a99f90a160463bb01ac07a1019\",\n    site: \"datadoghq.com\",\n    service: \"market-storefront\",\n    env: window.datadogEnvironment,\n    version: window.datadogVersion,\n    sessionSampleRate: window.datadogSampleRate,\n    sessionReplaySampleRate: 0,\n    trackUserInteractions: true,\n    defaultPrivacyLevel: \"mask-user-input\",\n  })\n}\n"],"names":["makePublicApi","stub","publicApi","version","onReady","callback","Object","defineProperty","get","enumerable","defineGlobal","global","name","api","existingGlobalVariable","q","warn","forEach","fn","addEventListener","configuration","eventTarget","eventName","listener","options","addEventListeners","eventNames","once","capture","passive","listenerWithMonitor","event","isTrusted","__ddIsTrusted","allowUntrustedEvents","stop","listenerTarget","window","EventTarget","prototype","add","remove","call","PageExitReason","HIDDEN","UNLOADING","PAGEHIDE","FROZEN","createPageExitObservable","observable","stopListeners","type","document","visibilityState","notify","reason","stopBeforeUnloadListener","isPageExitReason","includes","runOnReadyState","expectedReadyState","readyState","asyncRunOnReadyState","Promise","resolve","INTAKE_SITE_STAGING","INTAKE_SITE_FED_STAGING","INTAKE_SITE_US1","INTAKE_SITE_EU1","INTAKE_SITE_US1_FED","PCI_INTAKE_HOST_US1","INTAKE_URL_PARAMETERS","getConnectivity","_a","navigator","status","onLine","interfaces","connection","undefined","effective_type","effectiveType","NO_ERROR_STACK_PRESENT_MESSAGE","computeRawError","stackTrace","originalError","handlingStack","componentStack","startClocks","nonErrorPrefix","source","handling","isErrorInstance","isError","message","computeMessage","stack","length","url","hasUsableStack","causes","flattenErrorCauses","fingerprint","tryToGetFingerprint","String","dd_fingerprint","error","Error","toString","parentSource","currentError","cause","push","ErrorSource","AGENT","CONSOLE","CUSTOM","LOGGER","NETWORK","SOURCE","REPORT","TelemetryType","log","usage","ALLOWED_FRAME_URLS","TELEMETRY_EXCLUDED_SITES","preStartTelemetryBuffer","onRawTelemetryEventCollected","startTelemetry","telemetryService","contextProvider","alreadySentEvents","Set","telemetryEnabled","site","telemetrySampleRate","telemetryEnabledPerType","telemetryConfigurationSampleRate","telemetryUsageSampleRate","runtimeEnvInfo","is_local_file","location","protocol","is_worker","self","rawEvent","stringifiedEvent","jsonStringify","size","maxTelemetryEventsPerPage","has","date","service","_dd","format_version","telemetry","runtime_env","connectivity","sdk_setup","experimental_features","Array","from","toTelemetryEvent","sendToExtension","addTelemetryError","setContextProvider","provider","enabled","drainPreStartTelemetry","drain","isTelemetryReplicationAllowed","addTelemetryDebug","context","debug","e","formatError","addTelemetryConfiguration","addTelemetryUsage","computeStackTrace","kind","scrubCustomerFrames","filter","frame","some","allowedFrameUrl","startsWith","BUFFER_LIMIT","createBoundedBuffer","buffer","splice","arg","catchUserErrors","errorMsg","args","err","ConsoleApiName","info","globalConsole","console","originalConsoleMethods","keys","PREFIX","display","bind","DOCS_ORIGIN","DOCS_TROUBLESHOOTING","MORE_DETAILS","ExperimentalFeature","enabledExperimentalFeatures","initFeatureFlags","enableExperimentalFeatures","isArray","flag","isExperimentalFeatureEnabled","featureName","getExperimentalFeatures","getGlobalObject","globalThis","this","configurable","globalObject","_dd_temp_","getZoneJsOriginalValue","target","browserWindow","original","Zone","__symbol__","instrumentMethod","targetPrototype","method","onPreCall","computeHandlingStack","stopped","instrumentation","apply","arguments","parameters","postCallCallback","onPostCall","result","instrumentSetter","property","after","originalDescriptor","getOwnPropertyDescriptor","set","stoppedInstrumentation","value","instrumentationWrapper","mergeInto","destination","circularReferenceChecker","WeakSet","hasAlreadyBeenSeen","array","indexOf","createCircularReferenceChecker","Date","getTime","RegExp","flags","ignoreCase","multiline","sticky","unicode","join","merged","i","key","hasOwnProperty","deepClone","combine","sources","onMonitorErrorCollected","debugMode","startMonitorErrorCollection","newOnMonitorErrorCollected","setDebugMode","newDebugMode","monitor","callMonitored","monitorError","displayIfDebugEnabled","Observable","constructor","onFirstSubscribe","observers","subscribe","f","onLastUnsubscribe","unsubscribe","other","data","observer","mergeObservables","observables","globalObservable","subscriptions","map","subscription","requestIdleCallback","opts","cancelIdleCallback","id","start","timeoutId","didTimeout","timeRemaining","Math","max","MAX_TASK_TIME","requestIdleCallbackShim","payload","__ddBrowserSdkExtensionCallback","replacer","space","JSON","stringify","restoreObjectPrototypeToJson","detachToJsonMethod","restoreArrayPrototypeToJson","restoreValuePrototypeToJson","getPrototypeOf","restoreValueToJson","object","objectToJson","toJSON","SANITIZE_DEFAULT_MAX_CHARACTER_COUNT","JSON_PATH_ROOT_ELEMENT","KEY_DECORATION_LENGTH","sanitize","maxCharacterCount","containerQueue","visitedObjectsWithPath","WeakMap","sanitizedData","sanitizeProcessor","serializedSanitizedData","accumulatedCharacterCount","containerToProcess","shift","separatorLength","targetData","path","warnOverCharacterLimit","parentPath","queue","sourceToSanitize","tryToApplyToJSON","description","sanitizePrimitivesAndFunctions","sanitizedSource","sanitizeObjects","sourceAsObject","currentPath","Event","currentTarget","match","changeType","UNKNOWN_FUNCTION","ex","stackProperty","tryToGetString","exString","slice","split","line","stackFrame","parts","CHROME_LINE_RE","exec","isNative","isEval","submatch","CHROME_EVAL_RE","column","func","parseChromeLine","CHROME_ANONYMOUS_FUNCTION_RE","parseChromeAnonymousLine","WINJS_LINE_RE","parseWinLine","GECKO_LINE_RE","GECKO_EVAL_RE","parseGeckoLine","fileUrl","filePosition","candidate","computeStackTraceFromOnErrorMessage","messageObj","ERROR_TYPES_RE","tryToParseMessage","createHandlingStack","formattedStack","toStackTraceString","formatErrorMessage","setTimeout","delay","clearTimeout","setInterval","clearInterval","removeItem","item","index","isChromium","detectBrowserCached","isSafari","browserCache","userAgent","chrome","test","vendor","detectBrowser","ONE_KIBI_BYTE","ONE_MEBI_BYTE","HAS_MULTI_BYTES_CHARACTERS","computeBytesCount","TextEncoder","encode","Blob","concatBuffers","buffers","reduce","total","Uint8Array","offset","throttle","wait","needLeadingExecution","leading","needTrailingExecution","trailing","pendingExecutionWithParameters","pendingTimeoutId","inWaitPeriod","throttled","cancel","noop","performDraw","threshold","random","round","num","decimals","toFixed","isPercentage","isNumber","shallowClone","objectHasValue","isEmptyObject","mapValues","newObject","findLast","predicate","objectValues","values","objectEntries","entries","isServerError","tryToClone","response","clone","ONE_SECOND","ONE_MINUTE","ONE_HOUR","ONE_YEAR","relativeToClocks","relative","timeStamp","getCorrectedTimeStamp","timeStampToClocks","getRelativeTime","relativeTime","correctedOrigin","dateNow","performance","now","getNavigationStart","addDuration","getTimeStamp","currentDrift","toServerDuration","duration","timeStampNow","relativeNow","clocksNow","clocksOrigin","elapsed","end","a","b","timestamp","looksLikeRelativeTime","time","navigationStart","timing","getType","normalizeUrl","buildUrl","href","isValidUrl","getPathName","pathname","base","supportedURL","isURLSupported","originalURL","getSupportedUrl","doc","anchorElement","createElement","implementation","createHTMLDocument","baseElement","head","appendChild","body","URL","getEventBridge","eventBridgeGlobal","DatadogEventBridge","getCapabilities","parse","getPrivacyLevel","getAllowedWebViewHosts","send","eventType","viewId","view","bridgeSupports","capability","bridge","canUseEventBridge","currentHost","hostname","allowedHost","endsWith","MAX_ONGOING_BYTES_COUNT","MAX_ONGOING_REQUESTS","MAX_QUEUE_BYTES_COUNT","MAX_BACKOFF_TIME","INITIAL_BACKOFF_TIME","sendWithRetryStrategy","state","sendStrategy","trackType","reportError","transportStatus","queuedPayloads","bandwidthMonitor","canHandle","onSuccess","retryQueuedPayloads","onFailure","enqueue","scheduleRetry","first","dequeue","currentBackoffTime","min","shouldRetryRequest","ongoingRequestCount","retry","count","lastFailureStatus","isFull","queueFullReported","previousQueue","newPayloadQueue","bytesCount","createHttpRequest","endpointBuilder","bytesLimit","retryState","ongoingByteCount","sendStrategyForRetry","onResponse","canUseKeepAlive","Request","isKeepAliveSupported","fetchUrl","build","fetch","keepalive","mode","then","sendXHR","fetchKeepAliveStrategy","sendOnExit","canUseBeacon","sendBeacon","beaconUrl","hasReportedBeaconError","reportBeaconError","xhrUrl","sendBeaconStrategy","request","XMLHttpRequest","open","setRequestHeader","CUSTOMER_DATA_BYTES_LIMIT","CUSTOMER_COMPRESSED_DATA_BYTES_LIMIT","BYTES_COMPUTATION_THROTTLING_DELAY","createCustomerDataTrackerManager","compressionStatus","customerDataTrackers","Map","alreadyWarned","checkCustomerDataLimit","initialBytesCount","bytesCountLimit","tracker","getBytesCount","displayCustomerDataLimitReachedWarning","createDetachedTracker","createCustomerDataTracker","getOrCreateTracker","setCompressionStatus","newCompressionStatus","getCompressionStatus","clear","bytesCountCache","computeBytesCountThrottled","cancelComputeBytesCount","resetBytesCount","updateCustomerData","resetCustomerData","createContextManager","customerDataTracker","changeObservable","contextManager","getContext","setContext","newContext","clearContext","setContextProperty","removeContextProperty","TrackingConsent","GRANTED","NOT_GRANTED","CONTEXT_STORE_KEY_PREFIX","storageListeners","storeContextManager","productKey","customerDataType","storageKey","buildStorageKey","getFromStorage","rawContext","localStorage","getItem","setItem","createIdentityEncoder","output","outputBytesCount","isAsync","isEmpty","write","additionalEncodedBytesCount","finish","finishSync","rawBytesCount","pendingData","estimateEncodedBytesCount","sanitizeUser","newUser","user","displayAlreadyInitializedError","sdkName","initConfiguration","silentMultipleInit","generateUUID","placeholder","parseInt","replace","COMMA_SEPARATED_KEY_VALUE","findCommaSeparatedValue","rawString","lastIndex","safeTruncate","suffix","lastChar","charCodeAt","correctedLength","startVitalCollection","lifeCycle","pageStateHistory","customVitalsState","addDurationVital","vital","wasInPageStateDuringPeriod","isValid","valueComputedBySdk","rawRumEvent","computed_value","startTime","customerContext","domainContext","processVital","startDurationVital","stopDurationVital","nameOrRef","vitalsByName","vitalsByReference","reference","__dd_vital_reference","stopCallback","vitalStart","stopOptions","stopClocks","buildDurationVital","delete","callPluginsMethod","plugins","methodName","parameter","plugin","fetchObservable","initFetchObservable","input","init","methodFromParams","toUpperCase","responsePromise","startContext","reportFetch","partialContext","assign","responseType","isAborted","_b","signal","aborted","DOMException","code","ABORT_ERR","afterSend","beforeSend","setCookie","expireDelay","setTime","expires","toUTCString","sameSite","crossSite","domain","secure","partitioned","cookie","getCookie","initCookieParsed","getCurrentSiteCache","getInitCookie","findCommaSeparatedValues","deleteCookie","SYNTHETICS_TEST_ID_COOKIE_NAME","SYNTHETICS_RESULT_ID_COOKIE_NAME","SYNTHETICS_INJECTS_RUM_COOKIE_NAME","willSyntheticsInjectRum","Boolean","_DATADOG_SYNTHETICS_INJECTS_RUM","SESSION_STORE_KEY","SESSION_TIME_OUT_DELAY","SESSION_EXPIRATION_DELAY","SESSION_COOKIE_EXPIRATION_DELAY","SessionPersistence","COOKIE","LOCAL_STORAGE","SESSION_ENTRY_REGEXP","SESSION_ENTRY_SEPARATOR","EXPIRED","getExpiredSessionState","previousSessionState","expiredSessionState","isExpired","trackAnonymousUser","anonymousId","floor","pow","padStart","isSessionInNotStartedState","session","isSessionStarted","isSessionInExpiredState","sessionState","created","Number","expire","expandSessionState","toSessionString","toSessionState","sessionString","isValidSessionString","entry","matches","OLD_SESSION_COOKIE_NAME","OLD_RUM_COOKIE_NAME","OLD_LOGS_COOKIE_NAME","RUM_SESSION_KEY","LOGS_SESSION_KEY","selectCookieStrategy","cookieOptions","useSecureSessionCookie","usePartitionedCrossSiteSessionCookie","trackSessionAcrossSubdomains","testCookieName","testCookieValue","domainLevels","candidateDomain","pop","getCurrentSite","buildCookieOptions","isCookieCorrectlySet","areCookiesAuthorized","initCookieStrategy","cookieStore","isLockEnabled","persistSession","retrieveSession","retrieveSessionCookie","expireSession","expireSessionCookie","cookieStoreStrategy","oldSessionId","oldRumType","oldLogsType","tryOldCookiesMigration","LOCAL_STORAGE_TEST_KEY","selectLocalStorageStrategy","testKey","retrievedId","initLocalStorageStrategy","persistInLocalStorage","retrieveSessionFromLocalStorage","expireSessionFromLocalStorage","LOCK_RETRY_DELAY","LOCK_MAX_TRIES","bufferedOperations","ongoingOperations","processSessionStoreOperations","operations","sessionStoreStrategy","numberOfRetries","persistWithLock","lock","currentLock","retrieveStore","next","currentStore","retryLater","processedSession","process","sessionStore","currentNumberOfRetries","nextOperations","STORAGE_POLL_DELAY","selectSessionStoreStrategyType","sessionPersistence","sessionStoreStrategyType","allowFallbackToLocalStorage","startSessionStore","computeSessionState","renewObservable","expireObservable","sessionStateUpdateObservable","watchSessionTimeoutId","synchronizeSession","sessionCache","startSession","throttledExpandOrRenewSession","cancelExpandOrRenewSession","synchronizedSession","trackingType","isTracked","expandOrRenewSessionState","hasSessionInCache","renewSessionInCache","isSessionInCacheOutdated","previousState","newState","expandOrRenewSession","expandSession","getSession","restartSession","updateSessionState","partialSessionState","createEndpointBuilder","configurationTags","buildUrlWithParameters","proxy","normalizedProxyUrl","encodeURIComponent","host","internalAnalyticsSubdomain","usePciIntake","domainParts","extension","buildEndpointHost","createEndpointUrlWithParametersBuilder","clientToken","encoding","tags","concat","reverse","buildEndpointParameters","urlPrefix","TAG_SIZE_LIMIT","buildTag","rawValue","valueSizeLimit","supportUnicodePropertyEscapes","hasForbiddenCharacters","computeTransportConfiguration","env","datacenter","buildTags","endpointBuilders","logsEndpointBuilder","rumEndpointBuilder","sessionReplayEndpointBuilder","computeEndpointBuilders","replicaConfiguration","replica","replicaEndpointBuilders","applicationId","computeReplicaConfiguration","DefaultPrivacyLevel","ALLOW","MASK","MASK_USER_INPUT","TraceContextInjection","ALL","SAMPLED","isString","tag","tagName","isSampleRate","sampleRate","validateAndBuildConfiguration","_c","_d","_e","_f","sessionSampleRate","trackingConsent","storeContextsAcrossPages","batchBytesLimit","eventRateLimiterThreshold","flushTimeout","batchMessagesLimit","messageBytesLimit","isMatchOption","itemType","matchList","list","useStartsWith","getCrypto","crypto","msCrypto","createSpanIdentifier","createIdentifier","createIdentifierImplementationCache","bits","CONSISTENT_TRACE_SAMPLING","getRandomValues","BigUint64Array","areBigIntIdentifiersSupported","createIdentifierUsingBigInt","createIdentifierUsingUint32Array","BigInt","Uint32Array","radix","high","low","str","mod","toPaddedHexadecimalString","traceId","clearTracingIfNeeded","spanId","traceSampled","injectHeadersIfTracingAllowed","sessionManager","inject","findTrackedSession","tracingOption","allowedTracingUrls","find","identifier","knuthFactor","twoPow64","isTraceSampled","traceSampleRate","traceContextInjection","propagatorTypes","tracingHeaders","propagatorType","traceparent","tracestate","b3","makeTracingHeaders","DEFAULT_PROPAGATOR_TYPES","validateAndBuildRumConfiguration","trackFeatureFlagsForEvents","sessionReplaySampleRate","excludedActivityUrls","tracingOptions","option","expectedItem","isTracingOption","validateAndBuildTracingOptions","baseConfiguration","actionNameAttribute","startSessionReplayRecordingManually","rulePsr","workerUrl","compressIntakeRequests","trackUserInteractions","trackViewsManually","trackResources","trackLongTasks","subdomain","defaultPrivacyLevel","enablePrivacyForActionName","customerDataTelemetrySampleRate","getSelectedTracingPropagators","usedTracingPropagators","REMOTE_CONFIGURATION_URL","fetchAndApplyRemoteConfiguration","xhr","responseText","displayRemoteConfigurationFetchingError","remoteConfigurationId","fetchRemoteConfiguration","remoteInitConfiguration","applyRemoteConfiguration","createPreStartStrategy","ignoreInitIfSyntheticsWillInjectRum","startDeflateWorker","getCommonContext","trackingConsentState","doStartRum","bufferApiCalls","firstStartViewCall","deflateWorker","cachedInitConfiguration","cachedConfiguration","trackingConsentStateSubscription","tryStartRum","emptyContext","isGranted","initialViewOptions","startRumResult","doInit","eventBridgeAvailable","overrideInitConfigurationForBridge","baseSerializedConfiguration","session_sample_rate","telemetry_sample_rate","telemetry_configuration_sample_rate","telemetry_usage_sample_rate","use_before_send","use_partitioned_cross_site_session_cookie","use_secure_session_cookie","use_proxy","silent_multiple_init","track_session_across_subdomains","track_anonymous_user","session_persistence","allow_fallback_to_local_storage","store_contexts_across_pages","allow_untrusted_events","tracking_consent","session_replay_sample_rate","start_session_replay_recording_manually","trace_sample_rate","trace_context_injection","action_name_attribute","use_allowed_tracing_urls","selected_tracing_propagators","default_privacy_level","enable_privacy_for_action_name","use_excluded_activity_urls","use_worker_url","compress_intake_requests","track_views_manually","track_user_interactions","track_resources","track_long_task","getConfigurationTelemetry","track_feature_flags_for_events","serializeRumConfiguration","tryToInit","REMOTE_CONFIGURATION","getInternalContext","stopSession","addTiming","startView","setViewName","setViewContext","setViewContextProperty","getViewContext","addAction","action","commonContext","addError","providedError","addFeatureFlagEvaluation","RUM_STORAGE_KEY","makeRumPublicApi","startRumImpl","recorderApi","customerDataTrackerManager","globalContextManager","userContextManager","currentConsent","update","createTrackingConsentState","hasReplay","isRecording","buildCommonContext","strategy","createDeflateEncoder","streamId","onRumStart","viewHistory","preStartStrategy","createPostStartStrategy","sanitizedOptions","feature","rumPublicApi","m","setTrackingConsent","setGlobalContext","getGlobalContext","setGlobalContextProperty","removeGlobalContextProperty","clearGlobalContext","getInitConfiguration","setUser","checkUser","getUser","setUserProperty","sanitizedProperty","removeUserProperty","clearUser","getSessionReplayLink","startSessionReplayRecording","force","stopSessionReplayRecording","getMutationObserverConstructor","MutationObserver","patchedInstance","originalInstance","createEventRateLimiter","limit","onLimitReached","eventCount","allowNextEvent","isLimitReached","getSyntheticsContext","testId","_DATADOG_SYNTHETICS_PUBLIC_ID","getSyntheticsTestId","resultId","_DATADOG_SYNTHETICS_RESULT_ID","getSyntheticsResultId","test_id","result_id","injected","limitModification","modifiableFieldPaths","modifier","fieldPath","fieldType","newValue","current","field","isValidObjectContaining","newType","fields","isValidObject","VIEW_MODIFIABLE_FIELD_PATHS","USER_CUSTOMIZABLE_FIELD_PATHS","ROOT_MODIFIABLE_FIELD_PATHS","modifiableFieldPathsByEvent","startRumAssembly","urlContexts","actionContexts","displayContext","ciVisibilityContext","featureFlagContexts","WRITABLE_RESOURCE_GRAPHQL","eventRateLimiters","syntheticsContext","savedCommonContext","viewHistoryEntry","findView","urlContext","findUrl","actionId","findActionId","rumContext","drift","browser_sdk_version","application","referrer","feature_flags","findFeatureFlagsContext","synthetics","ci_test","serverRumEvent","has_replay","sampled_for_replay","sessionReplay","anonymous_id","usr","rateLimitReached","shouldSend","eventStartTime","isTrackingEnforced","isListedInConfig","featureFlagContext","findFeatureFlagEvaluations","LifeCycle","callbacks","eventCallbacks","END_OF_TIMES","Infinity","CLEAR_OLD_VALUES_INTERVAL","createValueHistory","maxEntries","clearOldValuesInterval","oldTimeThreshold","endTime","clearOldValues","close","unshift","returnInactive","closeActive","latestEntry","findAll","reset","VIEW_CONTEXT_TIME_OUT_DELAY","xhrObservable","xhrContexts","initXhrObservable","stopInstrumentingStart","openXhr","stopInstrumentingSend","hasBeenReported","stopInstrumentingOnReadyStateChange","DONE","onEnd","unsubscribeLoadEndListener","completeContext","sendXhr","stopInstrumentingAbort","abortXhr","createXhrObservable","FAKE_INITIAL_DOCUMENT","RESOURCE_TYPES","initiatorType","_","areInOrder","numbers","isResourceEntryRequestType","computeResourceEntryDuration","responseEnd","computeResourceEntryDetails","hasValidResourceEntryTimings","fetchStart","workerStart","redirectStart","redirectEnd","domainLookupStart","domainLookupEnd","connectStart","secureConnectionStart","connectEnd","requestStart","responseStart","details","download","formatTiming","first_byte","worker","connect","ssl","dns","redirect","hasValidResourceEntryDuration","areCommonTimingsInOrder","areRedirectionTimingsInOrder","hasRedirection","origin","computeResourceEntryProtocol","nextHopProtocol","computeResourceEntryDeliveryType","deliveryType","computeResourceEntrySize","encodedBodySize","decodedBodySize","transferSize","encoded_body_size","decoded_body_size","transfer_size","isAllowedRequestUrl","every","param","isIntakeUrl","DATA_URL_REGEX","MAX_ATTRIBUTE_VALUE_CHAR_LENGTH","isLongDataUrl","substring","sanitizeDataUrl","nextRequestIndex","startRequestCollection","tracer","traceFetch","headers","append","Headers","header","traceXhr","startTracer","requestIndex","getNextRequestIndex","trackXhr","clonedResponse","stream","reader","getReader","chunks","readBytesCount","onDone","bytes","limitExceeded","catch","collectStreamBody","completeBuffer","chunk","readMore","read","done","readBytesFromStream","POSITIVE_INFINITY","waitForResponseToComplete","trackFetch","discardNegativeDuration","trackEventCounts","isChildEvent","onChange","eventCounts","errorCount","longTaskCount","resourceCount","actionCount","frustrationCount","frustration","discarded","retrieveFirstInputTiming","startTimeStamp","timingSent","removeEventListeners","evt","cancelable","entryType","processingStart","processingEnd","sendTiming","sendTimingIfPointerIsNotCancelled","RumPerformanceEntryType","createPerformanceObservable","PerformanceObserver","handlePerformanceEntries","rumPerformanceEntries","RESOURCE","isForbiddenResource","filterRumPerformanceEntries","isObserverInitializing","getEntries","observe","NAVIGATION","LONG_TASK","PAINT","buffered","getEntriesByType","entryTypes","stopFirstInputTiming","resourceTimingBufferFullListener","clearResourceTimings","manageResourceTimingBufferFull","supportPerformanceTimingEvent","FIRST_INPUT","disconnect","supportedEntryTypes","PAGE_ACTIVITY_VALIDATION_DELAY","PAGE_ACTIVITY_END_DELAY","waitPageActivityEnd","domMutationObservable","windowOpenObservable","pageActivityEndCallback","maxDuration","pageActivityObservable","firstRequestIndex","pendingRequestsCount","notifyPageActivity","isExcludedUrl","startEvent","s","isBusy","createPageActivityObservable","pageActivityEndTimeoutId","hasCompleted","validationTimeoutId","complete","hadActivity","maxDurationTimeoutId","pageActivitySubscription","lastChangeTime","doWaitPageActivityEnd","requestUrl","isTextNode","node","nodeType","Node","TEXT_NODE","isElementNode","ELEMENT_NODE","isNodeShadowHost","shadowRoot","isNodeShadowRoot","DOCUMENT_FRAGMENT_NODE","hasChildNodes","childNodes","forEachChildNodes","child","firstChild","nextSibling","getParentNode","parentNode","NodePrivacyLevel","IGNORE","PRIVACY_ATTR_NAME","PRIVACY_ATTR_VALUE_HIDDEN","PRIVACY_CLASS_PREFIX","CENSORED_STRING_MARK","CENSORED_IMG_MARK","FORM_PRIVATE_TAG_NAMES","INPUT","OUTPUT","TEXTAREA","SELECT","OPTION","DATALIST","OPTGROUP","getNodePrivacyLevel","cache","parentNodePrivacyLevel","nodePrivacyLevel","reducePrivacyLevel","getNodeSelfPrivacyLevel","childPrivacyLevel","inputElement","autocomplete","getAttribute","getPrivacySelector","element","nodeName","relAttribute","getLowerCaseAttribute","nameAttribute","propertyAttribute","hasAttribute","toLowerCase","shouldIgnoreElement","shouldMaskNode","privacyLevel","isFormElement","censorText","text","getTextContent","textNode","ignoreWhiteSpace","parentTagName","parentElement","textContent","trim","DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE","ACTION_NAME_PLACEHOLDER","getActionNameFromElementProgrammatically","targetElement","programmaticAttribute","elementWithAttribute","closest","truncate","normalizeWhitespace","priorityStrategies","userProgrammaticAttribute","labels","getActionNameFromTextualContent","nameSource","privacyEnabledActionName","getActionNameFromStandardAttribute","labelledByAttribute","refElement","ownerDocument","getElementById","label","getTextualContent","fallbackStrategies","MAX_PARENTS_TO_CONSIDER","getActionNameFromElementForStrategies","strategies","recursionCounter","actionName","trimmedName","attribute","isContentEditable","innerText","removeTextFromElements","query","querySelectorAll","textToReplace","STABLE_ATTRIBUTES","GLOBALLY_UNIQUE_SELECTOR_GETTERS","getStableAttributeSelector","isGeneratedValue","CSS","escape","UNIQUE_AMONG_CHILDREN_SELECTOR_GETTERS","classList","className","getSelectorFromElement","isConnected","documentElement","contains","targetElementSelector","currentElement","globallyUniqueSelector","findSelector","isSelectorUniqueGlobally","isSelectorUniqueAmongSiblings","combineSelector","getPositionSelector","selector","getAttributeSelector","attributeName","sibling","firstElementChild","elementIndex","nextElementSibling","selectorGetters","childSelector","selectorGetter","elementSelector","currentElementSelector","isSiblingMatching","scopedSelector","supportScopeSelectorCache","querySelector","supportScopeSelector","parent","MAX_DURATION_BETWEEN_CLICKS","MAX_DISTANCE_BETWEEN_CLICKS","createClickChain","firstClick","onFinalize","bufferedClicks","maxDurationBetweenClicksTimeoutId","appendClick","click","stopObservable","tryFinalize","dontAcceptMoreClick","isStopped","tryAppend","second","sqrt","clientX","clientY","isSelectionEmpty","selection","getSelection","isCollapsed","isValidPointerEvent","Element","isPrimary","MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE","computeFrustration","clicks","rageClick","getUserActivity","scroll","isRage","addFrustration","isDead","hasError","hasSelectionChanged","DEAD_CLICK_EXCLUDE_SELECTOR","hasPageActivity","CLICK_ACTION_MAX_DURATION","interactionSelectorCache","updateInteractionSelector","relativeTimestamp","ACTION_CONTEXT_TIME_OUT_DELAY","trackClickActions","history","currentClickChain","stopClickChain","stopActionEventsListener","onPointerDown","onPointerUp","selectionEmptyAtPointerDown","clickContext","userActivity","listeners","localUserActivity","listenActionEvents","pointerDownEvent","clickActionBase","rect","getBoundingClientRect","defaultActionName","getActionNameFromElement","width","height","position","x","left","y","top","computeClickActionBase","hadActivityOnPointerDown","pageActivityEndEvent","processPointerDown","appendClickToClickChain","newClick","stopWaitPageActivityEnd","discard","viewEndedSubscription","endClocks","stopSubscription","startClickAction","validate","finalizeClicks","historyEntry","eventCountsSubscription","activityEndTime","frustrationTypes","newActivityEndTime","frustrationType","domEvents","clickAction","counts","events","processAction","autoActionProperties","isAutoAction","loading_time","long_task","resource","name_source","ACTION_NAME_MASKING","actionEvent","in_foreground","wasInPageStateAt","trackRuntimeError","errorObservable","handleRuntimeError","rawError","stopInstrumentingOnError","errorObj","stopInstrumentingOnUnhandledRejection","instrumentUnhandledRejection","consoleObservablesByApi","initConsoleObservable","apis","consoleObservables","originalConsoleApi","params","formatConsoleParameters","firstErrorParam","buildConsoleLog","createConsoleObservable","RawReportType","intervention","deprecation","cspViolation","initReportObservable","blockedURI","effectiveDirective","buildRawReportError","csp","disposition","buildStack","originalPolicy","sourceFile","lineNumber","columnNumber","buildRawReportErrorFromCspViolation","createCspViolationReportObservable","reportTypes","ReportingObserver","handleReports","reports","report","buildRawReportErrorFromReport","types","createReportObservable","partial","startErrorCollection","consoleLog","trackConsoleError","trackReportError","processError","doStartErrorCollection","handling_stack","component_stack","source_type","IDLE_CALLBACK_TIMEOUT","MAX_EXECUTION_TIME_ON_TIMEOUT","alreadyMatchedEntries","matchRequestResourceEntry","sameNameEntries","getEntriesByName","candidates","errorMargin","isBetween","INITIAL_DOCUMENT_OUTDATED_TRACE_ID_THRESHOLD","getDocumentTraceId","traceIdMeta","traceTimeMeta","createDocumentTraceData","content","getDocumentTraceDataFromMeta","comment","getTraceCommentFromNode","findTraceComment","getDocumentTraceDataFromComment","traceTime","rawTraceTime","COMMENT_NODE","isCommentNode","getNavigationEntry","navigationEntry","timings","numberKey","timingElement","computeTimingsFromDeprecatedPerformanceTiming","retrieveInitialDocumentResourceTiming","startResourceCollection","taskQueue","pendingTasks","run","deadline","executionTimeRemaining","scheduleNextRun","timeout","task","createTaskQueue","retrieveInitialDocumentResourceTimingImpl","handleResource","matchingTiming","tracingInfo","hasBeenTraced","span_id","trace_id","rule_psr","computeRequestTracingInfo","correspondingTimingOverrides","computeResourceEntryMetrics","computeRequestDuration","resourceEvent","status_code","delivery_type","performanceEntry","requestInput","requestInit","processRequest","performanceResourceSubscription","processResourceEntry","computeRawEvent","computeResourceEntryTracingInfo","isType","computeResourceEntryType","entryMetrics","statusCode","responseStatus","renderBlockingStatus","render_blocking_status","FCP_MAXIMUM_DELAY","trackNavigationTimings","getNavigationEntryImpl","stopOnReadyState","waitAfterLoadEvent","loadEventEnd","isIncompleteNavigation","domComplete","domContentLoaded","domContentLoadedEventEnd","domInteractive","loadEvent","firstByte","processNavigationEntry","LCP_MAXIMUM_DELAY","trackFirstHidden","trackInitialViewMetrics","setLoadEvent","scheduleViewUpdate","initialViewMetrics","stopNavigationTracking","navigationTimings","firstHidden","stopFCPTracking","fcpEntry","trackFirstContentfulPaint","firstContentfulPaint","stopLCPTracking","firstInteractionTimestamp","stopEventListener","biggestLcpSize","performanceLcpSubscription","LARGEST_CONTENTFUL_PAINT","lcpEntry","lcpTargetSelector","targetSelector","trackLargestContentfulPaint","largestContentfulPaint","stopFIDTracking","performanceFirstInputSubscription","firstInputEntry","firstInputDelay","firstInputTargetSelector","trackFirstInput","firstInput","trackCumulativeLayoutShift","viewStart","isLayoutShiftSupported","biggestShift","maxClsValue","cumulatedValue","maxValue","isMaxValue","MAX_UPDATE_GAP","MAX_WINDOW_DURATION","slidingSessionWindow","performanceSubscription","LAYOUT_SHIFT","hadRecentInput","attribution","WeakRef","previousRect","currentRect","deref","asRumRect","interactionCountEstimate","minKnownInteractionId","maxKnownInteractionId","getInteractionCount","interactionCount","MAX_INTERACTION_ENTRIES","MAX_INP_VALUE","trackInteractionToNextPaint","viewLoadingType","EVENT","PerformanceEventTiming","getInteractionToNextPaint","setViewEnd","getViewInteractionCount","stopViewInteractionCount","interactionId","durationThreshold","previousInteractionCount","computeViewInteractionCount","trackViewInteractionCount","viewEnd","longestInteractions","sortAndTrimLongestInteractions","sort","interactionIndex","findIndex","interaction","minLongestInteraction","estimateP98Interaction","trackLongestInteractions","interactionToNextPaintTargetSelector","interactionToNextPaintStartTime","interactionToNextPaint","handleEntries","newInteraction","getInteractionSelector","firstInputSubscription","eventSubscription","viewEndTime","getScrollX","scrollX","visual","visualViewport","pageLeft","offsetLeft","pageXOffset","getScrollY","scrollY","pageTop","offsetTop","pageYOffset","viewportObservable","initViewportObservable","updateDimension","getViewportDimension","createViewportObservable","scale","innerWidth","innerHeight","THROTTLE_SCROLL_DURATION","trackScrollMetrics","scrollValues","throttleDuration","scrollTop","scrollHeight","scrollingElement","scrollDepth","computeScrollValues","ResizeObserver","throttledNotify","observerTarget","resizeObserver","eventListener","createScrollValuesObservable","maxScrollDepth","maxScrollHeight","maxScrollHeightTime","shouldUpdate","maxDepth","maxDepthScrollTop","trackCommonViewMetrics","loadingType","commonViewMetrics","stopLoadingTimeTracking","loadType","isWaitingForLoadEvent","isWaitingForActivityLoadingTime","loadingTimeCandidates","invokeCallbackIfAllCandidatesAreReceived","loadingTime","trackLoadingTime","newLoadingTime","stopScrollMetricsTracking","newScrollMetrics","stopCLSTracking","cumulativeLayoutShift","stopINPTracking","getCommonViewMetrics","THROTTLE_VIEW_UPDATE_PERIOD","SESSION_KEEP_ALIVE_INTERVAL","KEEP_TRACKING_AFTER_VIEW_DELAY","trackViews","locationChangeObservable","areViewsTrackedAutomatically","activeViews","locationChangeSubscription","currentView","startNewView","viewOptions","newlyCreatedView","initialLocation","customTimings","documentVersion","sessionIsActive","viewCreatedEvent","cancelScheduleViewUpdate","triggerViewUpdate","stopCommonViewMetricsTracking","stopInitialViewMetricsTracking","stopEventCountsTracking","trackViewEventCounts","keepAliveIntervalId","currentEnd","isActive","sanitized","sanitizeTiming","updatedName","newView","pageExitEvent","oldLocation","newLocation","currentLocation","otherLocation","hash","correspondingId","isHashAnAnchor","getPathFromHash","renewViewOnLocationChange","startViewCollection","pageOpenObserable","_g","_h","_j","_k","_l","_m","_o","_p","_q","_r","replayStats","getReplayStats","pageStates","viewEvent","document_version","replay_stats","page_states","cumulative_layout_shift","cumulative_layout_shift_time","cumulative_layout_shift_target_selector","dom_complete","dom_content_loaded","dom_interactive","first_contentful_paint","first_input_delay","first_input_time","first_input_target_selector","interaction_to_next_paint","interaction_to_next_paint_time","interaction_to_next_paint_target_selector","is_active","largest_contentful_paint","largest_contentful_paint_target_selector","load_event","loading_type","computeViewPerformanceData","time_spent","max_depth","max_depth_scroll_top","max_scroll_height","max_scroll_height_time","privacy","replay_level","custom_timings","processViewUpdate","cls","score","target_selector","previous_rect","current_rect","fcp","fid","inp","lcp","VISIBILITY_CHECK_DELAY","SESSION_CONTEXT_TIMEOUT_DELAY","stopCallbacks","startSessionManager","sessionContextHistory","buildSessionContext","isReplayForced","forcedReplay","trackActivity","expandSessionWhenVisible","visibilityCheckInterval","trackVisibility","cb","trackResume","findSession","startRumSessionManager","rawTrackingType","hasValidRumSession","isTypeTracked","sessionEntity","setForcedReplay","rumSessionType","createBatch","encoder","flushController","upsertBuffer","flushSubscription","flushObservable","upsertMessages","isPageExit","encoderResult","formatPayloadFromEncoder","pendingMessages","flush","addOrUpdate","serializedMessage","estimatedMessageBytesCount","hasMessageFor","removedMessage","messageBytesCount","notifyAfterRemoveMessage","notifyBeforeAddMessage","notifyAfterAddMessage","realMessageBytesCount","upsert","createFlushController","messagesLimit","durationLimit","pageExitObservable","sessionExpireObservable","pageExitSubscription","sessionExpireSubscription","durationLimitTimeoutId","currentBytesCount","currentMessagesCount","flushReason","messagesCount","cancelDurationLimitTimeout","messageBytesCountDiff","startRumBatch","telemetryEventObservable","createEncoder","batch","primary","batchFactoryImp","primaryBatch","createBatchFromConfig","replicaBatch","endpoint","replicated","transformMessage","startBatchWithReplica","URL_CONTEXT_TIME_OUT_DELAY","createLocationChangeObservable","stopHistoryTracking","onHistoryChange","stopInstrumentingPushState","getHistoryInstrumentationTarget","stopInstrumentingReplaceState","removeListener","trackHistory","onLocationChange","stopHashTracking","onHashChange","trackHash","History","FEATURE_FLAG_CONTEXT_TIME_OUT_DELAY","MEASURES_PERIOD_DURATION","currentPeriodMeasures","currentBatchMeasures","batchHasRumEvent","sendCurrentPeriodMeasures","batchCount","initCurrentPeriodMeasures","updateMeasure","measure","sum","mergeMeasure","batchBytesCount","batchMessagesCount","globalContextBytes","userContextBytes","featureFlagBytes","initCurrentBatchMeasures","MAX_PAGE_STATE_ENTRIES","MAX_PAGE_STATE_ENTRIES_SELECTABLE","PAGE_STATE_CONTEXT_TIME_OUT_DELAY","startPageStateHistory","maxPageStateEntriesSelectable","pageStateEntryHistory","currentPageState","addPageState","getPageState","stopEventListeners","persisted","computePageState","nextPageState","pageStateEntries","pageStateServerEntries","pageState","relativeStartTime","hasFocus","createCookieObservable","cookieName","detectCookieChangeStrategy","changeEvent","changed","deleted","listenToCookieStoreChange","watchCookieFallback","WATCH_COOKIE_INTERVAL_DELAY","previousCookieValue","watchCookieIntervalId","cookieValue","CI_VISIBILITY_TEST_ID_COOKIE_NAME","startRum","cleanupTasks","startRumTelemetry","currentContext","startFeatureFlagContexts","startRumSessionManagerStub","startRumEventBridge","batchFlushObservable","startCustomerDataTelemetry","attributes","characterData","childList","subtree","createDOMMutationObservable","stopWindowOpen","createWindowOpenObservable","stopRumEventCollection","viewValueHistory","buildViewHistoryEntry","viewUpdate","startViewHistory","urlContextHistory","previousViewUrl","viewUrl","buildUrlContext","changeTime","startUrlContexts","actionCollection","startActionCollection","viewport","animationFrameId","requestAnimationFrame","unsubscribeViewport","viewportDimension","cancelAnimationFrame","startDisplayContext","cookieObservable","testExecutionId","Cypress","cookieObservableSubscription","test_execution_id","startCiVisibilityContext","startRumEventCollection","stopViewCollection","stopResourceCollection","LONG_ANIMATION_FRAME","stopLongAnimationFrameCollection","entry_type","blocking_duration","blockingDuration","first_ui_event_timestamp","firstUIEventTimestamp","render_start","renderStart","style_and_layout_start","styleAndLayoutStart","start_time","scripts","script","pause_duration","pauseDuration","forced_style_and_layout_duration","forcedStyleAndLayoutDuration","execution_start","executionStart","source_url","sourceURL","source_function_name","sourceFunctionName","source_char_position","sourceCharPosition","invoker","invoker_type","invokerType","window_attribution","windowAttribution","startLongAnimationFrameCollection","performanceLongTaskSubscription","startLongTaskCollection","vitalCollection","internalContext","viewContext","application_id","session_id","user_action","startInternalContext","getSessionReplayUrl","errorType","sessionId","rumConfiguration","getSiteDefaultSubdomain","getDatadogSiteUrl","serializedNodeIds","hasSerializedNode","getSerializedNodeId","getElementInputValue","URL_IN_CSS_REF","ABSOLUTE_URL","DATA_URI","switchToAbsoluteUrl","cssText","cssHref","matchingSubstring","singleQuote","urlWrappedInSingleQuotes","doubleQuote","urlWrappedInDoubleQuotes","urlNotWrappedInQuotes","quote","baseUrl","makeUrlAbsolute","TAG_NAME_REGEX","getValidTagName","processedTagName","censoredImageForSize","RecordType","FullSnapshot","IncrementalSnapshot","Meta","Focus","ViewEnd","VisualViewport","FrustrationRecord","NodeType","Document","DocumentType","Text","CDATA","DocumentFragment","IncrementalSource","Mutation","MouseMove","MouseInteraction","Scroll","ViewportResize","Input","TouchMove","MediaInteraction","StyleSheetRule","MouseInteractionType","MouseUp","MouseDown","Click","ContextMenu","DblClick","Blur","TouchStart","TouchEnd","MediaInteractionType","Play","Pause","serializeStyleSheets","cssStyleSheets","cssStyleSheet","rules","cssRules","cssRule","disabled","media","serializeAttribute","attributeValue","image","naturalWidth","naturalHeight","getCssRulesString","getCssRuleStringForSafari","getCssRuleString","rule","isCSSStyleRule","selectorText","escapeColon","isCSSImportRule","styleSheet","serializeNodeWithId","serializedNode","DOCUMENT_NODE","serializeChildNodes","adoptedStyleSheets","serializeDocumentNode","isShadowRoot","serializationContext","shadowRootsController","addShadowRoot","serializeDocumentFragmentNode","DOCUMENT_TYPE_NODE","documentType","publicId","systemId","isSVG","el","SVGElement","rr_width","rr_height","safeAttrs","formValue","optionElement","selected","stylesheet","styleSheets","_cssText","sheet","checked","mediaElement","rr_mediaState","paused","scrollLeft","elementsScrollPositions","rr_scrollLeft","rr_scrollTop","serializeAttributes","childNodesSerializationOptions","serializeElementNode","serializeTextNode","CDATA_SECTION_NODE","serializeNode","_nextId","serializedNodeWithId","serializeNodeId","setSerializedNodeId","childNode","serializedChildNode","serializeDocument","isTouchEvent","changedTouches","getEventTarget","composed","composedPath","convertMouseEventToLayoutCoordinates","normalized","layoutViewportX","layoutViewportY","visualViewportX","visualViewportY","abs","isVisualViewportFactoredIn","getVisualViewport","assembleIncrementalSnapshot","MOUSE_MOVE_OBSERVER_THRESHOLD","trackMove","moveCb","updatePosition","cancelThrottle","coordinates","tryToComputeCoordinates","timeOffset","positions","isFinite","eventTypeToMouseInteraction","trackMouseInteraction","mouseInteractionCb","recordIds","record","getIdForEvent","SCROLL_OBSERVER_THRESHOLD","trackScroll","scrollCb","scrollPositions","VISUAL_VIEWPORT_OBSERVER_THRESHOLD","trackViewportResize","viewportResizeCb","viewportResizeSubscription","trackVisualViewportResize","visualViewportResizeCb","trackMediaInteraction","mediaInteractionCb","trackStyleSheet","styleSheetCb","checkStyleSheetAndCallback","ownerNode","instrumentationStoppers","CSSStyleSheet","adds","removes","instrumentGroupingCSSRuleClass","parentStyleSheet","getPathToNestedCSSRule","CSSGroupingRule","CSSMediaRule","CSSSupportsRule","stopper","currentRule","parentRule","trackFocus","focusCb","has_focus","trackFrustration","frustrationCb","frustrationSubscription","trackViewEnd","viewEndCb","viewEndSubscription","trackInput","inputCb","lastInputStateMap","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","onElementChange","stopPropertySetterInstrumentation","inputState","isChecked","cbWithDedup","lastInputState","MUTATION_PROCESS_MAX_DELAY","MUTATION_PROCESS_MIN_DELAY","trackMutation","mutationCallback","mutationBatch","processMutationBatch","cancelScheduledFlush","pendingMutations","throttledFlush","addMutations","mutations","createMutationBatch","nodePrivacyLevelCache","mutation","removedNodes","removedNode","traverseRemovedShadowDom","removeShadowRoot","filteredMutations","nodeAndAncestorsHaveSerializedNode","hasBeenSerialized","addedAndMovedNodes","addedNodes","sortedAddedAndMovedNodes","nodes","compareDocumentPosition","DOCUMENT_POSITION_CONTAINED_BY","DOCUMENT_POSITION_CONTAINS","DOCUMENT_POSITION_FOLLOWING","DOCUMENT_POSITION_PRECEDING","addedNodeMutations","nextId","getNextSibling","parentId","removedNodeMutations","processChildListMutations","texts","textMutations","handledNodes","oldValue","processCharacterDataMutations","attributeMutations","handledElements","handledAttributes","emittedMutations","transformedValue","inputValue","emittedMutation","processAttributesMutations","processMutations","takeRecords","attributeOldValue","characterDataOldValue","shadowDomRemovedCallback","initShadowRootsController","controllerByShadowRoot","mutationTracker","inputTracker","scrollTracker","emit","emitAndComputeStats","scrollPositionsByElement","createElementsScrollPositions","stopFullSnapshots","flushMutations","fullSnapshotCallback","takeFullSnapshot","records","initialOffset","startFullSnapshots","initRecordIds","trackers","viewEndRecord","createSegment","creationReason","encodedBytesCount","metadata","creation_reason","records_count","has_full_snapshot","index_in_view","addRecord","prefix","SEGMENT_DURATION_LIMIT","SEGMENT_BYTES_LIMIT","startSegmentCollection","httpRequest","getSegmentContext","nextSegmentCreationReason","unsubscribeViewCreated","flushSegment","unsubscribePageExited","segment","rawSegmentBytesCount","formData","FormData","metadataAndSegmentSizes","raw_segment_size","compressed_segment_size","byteLength","serializedMetadataAndSegmentSizes","buildReplayPayload","expirationTimeoutId","doStartSegmentCollection","computeSegmentContext","startRecording","replayRequest","startRecordBridge","segmentCollection","stopRecording","MAX_STATS_HISTORY","statsPerView","getSegmentsCount","getOrCreateReplayStats","segments_count","addSegment","addWroteData","additionalBytesCount","segments_total_raw_size","toDelete","deleteOldestStats","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","module","__webpack_modules__","d","definition","o","obj","prop","r","Symbol","toStringTag","compressedDataTrailer","compressedData","nextWriteActionId","pendingWriteActions","removeMessageListener","workerResponse","trailer","nextPendingAction","writeCallback","finishCallback","consumeResult","sendResetIfNeeded","postMessage","pendingWriteAction","INITIALIZATION_TIME_OUT_DELAY","createDeflateWorker","Worker","createObjectURL","onInitializationFailure","createDeflateWorkerImpl","removeErrorListener","onError","initializationFailureCallbacks","onTimeout","doStartDeflateWorker","getDeflateWorkerStatus","baseMessage","worker_version","stream_id","isBrowserSupported","NodeList","isRecordingStarted","getErrorType","loadRecorder","getOrCreateDeflateEncoder","doStart","async","startRecordingImpl","all","deflateEncoder","canStartRecording","isRecordingInProgress","shouldForceReplay","shouldStartImmediately","cachedDeflateEncoder","makeRecorderApi","datadogRum","datadogEnvironment","datadogVersion","datadogSampleRate"],"sourceRoot":""}