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5+E,KAAOu+E,EAAqBtgF,KAAK,KAAM2gF,EAAmB5+E,KAAK/B,KAAK2gF,G,KCvFvFlF,EAAoBoC,QAAK/5E,ECGzB,IAAI88E,EAAsBnF,EAAoB,O","sources":["webpack:///webpack/runtime/load script","webpack:///webpack/runtime/consumes","webpack:///./node_modules/@datadog/browser-core/src/tools/display.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/catchUserErrors.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/monitor.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/polyfills.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/getGlobalObject.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/byteUtils.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/getZoneJsOriginalValue.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/timer.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/functionUtils.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/serialisation/jsonStringify.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/objectUtils.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/context/customerDataTracker.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/typeUtils.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/mergeInto.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/serialisation/sanitize.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/observable.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/context/contextManager.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/trackingConsent.ts","webpack:///./node_modules/@datadog/browser-core/src/browser/addEventListener.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/context/storeContextManager.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/encoder.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/stackTrace/computeStackTrace.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/stackTrace/handlingStack.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/error/error.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/experimentalFeatures.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/configuration/intakeSites.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/numberUtils.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/timeUtils.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/sendToExtension.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/connectivity/connectivity.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/arrayUtils.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/boundedBuffer.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/telemetry/rawTelemetryEvent.types.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/telemetry/telemetry.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/user/user.ts","webpack:///./node_modules/@datadog/browser-core/src/boot/displayAlreadyInitializedError.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/stringUtils.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/vital/vitalCollection.ts","webpack:///./node_modules/@datadog/browser-core/src/transport/eventBridge.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/instrumentMethod.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/urlPolyfill.ts","webpack:///./node_modules/@datadog/browser-core/src/browser/fetchObservable.ts","webpack:///./node_modules/@datadog/browser-core/src/browser/cookie.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/synthetics/syntheticsWorkerValues.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/browserDetection.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/session/storeStrategies/sessionStoreStrategy.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/session/sessionConstants.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/session/sessionState.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/session/oldCookiesMigration.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/session/storeStrategies/sessionInCookie.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/session/storeStrategies/sessionInLocalStorage.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/session/sessionStoreOperations.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/session/sessionStore.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/configuration/endpointBuilder.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/configuration/tags.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/configuration/configuration.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/configuration/transportConfiguration.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/matchOption.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/tracing/tracer.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/configuration/configuration.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/configuration/remoteConfiguration.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/boot/preStartRum.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/plugins.ts","webpack:///./node_modules/@datadog/browser-core/src/browser/pageExitObservable.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/browser/domMutationObservable.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/error/error.types.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/eventRateLimiter/createEventRateLimiter.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/limitModification.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/assembly.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/contexts/syntheticsContext.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/abstractLifeCycle.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/lifeCycle.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/valueHistory.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/contexts/viewHistory.ts","webpack:///./node_modules/@datadog/browser-core/src/browser/xhrObservable.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/resource/resourceUtils.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/requestCollection.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/browser/performanceObservable.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/utils/responseUtils.ts","webpack:///./node_modules/@datadog/browser-core/src/tools/readBytesFromStream.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/discardNegativeDuration.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/trackEventCounts.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/browser/firstInputPolyfill.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/waitPageActivityEnd.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/browser/polyfills.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/browser/htmlDomUtils.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/privacy.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/action/getActionNameFromElement.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/getSelectorFromElement.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/action/clickChain.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/action/listenActionEvents.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/action/computeFrustration.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/action/interactionSelectorCache.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/action/trackClickActions.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/action/actionCollection.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/error/trackRuntimeError.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/console/consoleObservable.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/report/reportObservable.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/error/errorCollection.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/error/trackConsoleError.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/error/trackReportError.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/resource/matchRequestResourceEntry.ts","webpack:///./node_modules/@datadog/browser-core/src/browser/runOnReadyState.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/tracing/getDocumentTraceId.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/browser/performanceUtils.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/resource/retrieveInitialDocumentResourceTiming.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/resource/resourceCollection.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackFirstContentfulPaint.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackLargestContentfulPaint.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackFirstHidden.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackInitialViewMetrics.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackNavigationTimings.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackFirstInput.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackCumulativeLayoutShift.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/interactionCountPolyfill.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/browser/viewportObservable.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackInteractionToNextPaint.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/browser/scroll.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackScrollMetrics.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackCommonViewMetrics.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewMetrics/trackLoadingTime.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/trackViews.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/viewCollection.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/view/trackViewEventCounts.ts","webpack:///./node_modules/@datadog/browser-core/src/domain/session/sessionManager.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/rumSessionManager.ts","webpack:///./node_modules/@datadog/browser-core/src/transport/batch.ts","webpack:///./node_modules/@datadog/browser-core/src/transport/sendWithRetryStrategy.ts","webpack:///./node_modules/@datadog/browser-core/src/transport/httpRequest.ts","webpack:///./node_modules/@datadog/browser-core/src/transport/flushController.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/contexts/urlContexts.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/browser/locationChangeObservable.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/contexts/featureFlagContext.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/startCustomerDataTelemetry.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/contexts/pageStateHistory.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/browser/cookieObservable.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/contexts/ciVisibilityContext.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/replayStats.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/serialization/serializationUtils.ts","webpack:///./node_modules/@datadog/browser-rum/src/types/sessionReplayConstants.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/serialization/serializeStyleSheets.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/serialization/serializeAttribute.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/serialization/serializeAttributes.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/serialization/serializeNode.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/serialization/serializeDocument.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/eventsUtils.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/viewports.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/assembly.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackMove.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackMouseInteraction.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackScroll.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackViewportResize.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackMediaInteraction.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackStyleSheet.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackFocus.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackFrustration.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackViewEnd.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackInput.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/mutationBatch.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/trackers/trackMutation.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/record.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/elementsScrollPositions.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/shadowRootsController.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/startFullSnapshots.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/record/recordIds.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/segmentCollection/segment.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/segmentCollection/segmentCollection.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/segmentCollection/buildReplayPayload.ts","webpack:///./node_modules/@datadog/browser-rum/src/boot/isBrowserSupported.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/getSessionReplayLink.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/getSessionReplayUrl.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/deflate/deflateEncoder.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/deflate/deflateWorker.ts","webpack:///./node_modules/@datadog/browser-rum/src/entries/main.ts","webpack:///./node_modules/@datadog/browser-core/src/boot/init.ts","webpack:///./node_modules/@datadog/browser-rum/src/boot/recorderApi.ts","webpack:///./node_modules/@datadog/browser-rum/src/boot/startRecording.ts","webpack:///./node_modules/@datadog/browser-rum/src/domain/startRecordBridge.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/boot/rumPublicApi.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/contexts/commonContext.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/boot/startRum.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/transport/startRumEventBridge.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/transport/startRumBatch.ts","webpack:///./node_modules/@datadog/browser-core/src/transport/startBatchWithReplica.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/contexts/displayContext.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/longAnimationFrame/longAnimationFrameCollection.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/longTask/longTaskCollection.ts","webpack:///./node_modules/@datadog/browser-rum-core/src/domain/contexts/internalContext.ts","webpack:///webpack/container-entry","webpack:///webpack/bootstrap","webpack:///webpack/runtime/compat get default export","webpack:///webpack/runtime/define property getters","webpack:///webpack/runtime/ensure chunk","webpack:///webpack/runtime/get javascript chunk filename","webpack:///webpack/runtime/global","webpack:///webpack/runtime/hasOwnProperty shorthand","webpack:///webpack/runtime/make namespace object","webpack:///webpack/runtime/sharing","webpack:///webpack/runtime/publicPath","webpack:///webpack/runtime/jsonp chunk loading","webpack:///webpack/runtime/nonce","webpack:///webpack/startup"],"sourcesContent":["var inProgress = {};\nvar dataWebpackPrefix = \"mf_core:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","var parseVersion = (str) => {\n\t// see webpack/lib/util/semver.js for original code\n\tvar p=p=>{return p.split(\".\").map((p=>{return+p==p?+p:p}))},n=/^([^-+]+)?(?:-([^+]+))?(?:\\+(.+))?$/.exec(str),r=n[1]?p(n[1]):[];return n[2]&&(r.length++,r.push.apply(r,p(n[2]))),n[3]&&(r.push([]),r.push.apply(r,p(n[3]))),r;\n}\nvar versionLt = (a, b) => {\n\t// see webpack/lib/util/semver.js for original code\n\ta=parseVersion(a),b=parseVersion(b);for(var r=0;;){if(r>=a.length)return r<b.length&&\"u\"!=(typeof b[r])[0];var e=a[r],n=(typeof e)[0];if(r>=b.length)return\"u\"==n;var t=b[r],f=(typeof t)[0];if(n!=f)return\"o\"==n&&\"n\"==f||(\"s\"==f||\"u\"==n);if(\"o\"!=n&&\"u\"!=n&&e!=t)return e<t;r++}\n}\nvar rangeToString = (range) => {\n\t// see webpack/lib/util/semver.js for original code\n\tvar r=range[0],n=\"\";if(1===range.length)return\"*\";if(r+.5){n+=0==r?\">=\":-1==r?\"<\":1==r?\"^\":2==r?\"~\":r>0?\"=\":\"!=\";for(var e=1,a=1;a<range.length;a++){e--,n+=\"u\"==(typeof(t=range[a]))[0]?\"-\":(e>0?\".\":\"\")+(e=2,t)}return n}var g=[];for(a=1;a<range.length;a++){var t=range[a];g.push(0===t?\"not(\"+o()+\")\":1===t?\"(\"+o()+\" || \"+o()+\")\":2===t?g.pop()+\" \"+g.pop():rangeToString(t))}return o();function o(){return g.pop().replace(/^\\((.+)\\)$/,\"$1\")}\n}\nvar satisfy = (range, version) => {\n\t// see webpack/lib/util/semver.js for original code\n\tif(0 in range){version=parseVersion(version);var e=range[0],r=e<0;r&&(e=-e-1);for(var n=0,i=1,a=!0;;i++,n++){var f,s,g=i<range.length?(typeof range[i])[0]:\"\";if(n>=version.length||\"o\"==(s=(typeof(f=version[n]))[0]))return!a||(\"u\"==g?i>e&&!r:\"\"==g!=r);if(\"u\"==s){if(!a||\"u\"!=g)return!1}else if(a)if(g==s)if(i<=e){if(f!=range[i])return!1}else{if(r?f>range[i]:f<range[i])return!1;f!=range[i]&&(a=!1)}else if(\"s\"!=g&&\"n\"!=g){if(r||i<=e)return!1;a=!1,i--}else{if(i<=e||s<g!=r)return!1;a=!1}else\"s\"!=g&&\"n\"!=g&&(a=!1,i--)}}var t=[],o=t.pop.bind(t);for(n=1;n<range.length;n++){var u=range[n];t.push(1==u?o()|o():2==u?o()&o():u?satisfy(u,version):!o())}return!!o();\n}\nvar ensureExistence = (scopeName, key) => {\n\tvar scope = __webpack_require__.S[scopeName];\n\tif(!scope || !__webpack_require__.o(scope, key)) throw new Error(\"Shared module \" + key + \" doesn't exist in shared scope \" + scopeName);\n\treturn scope;\n};\nvar findVersion = (scope, key) => {\n\tvar versions = scope[key];\n\tvar key = Object.keys(versions).reduce((a, b) => {\n\t\treturn !a || versionLt(a, b) ? b : a;\n\t}, 0);\n\treturn key && versions[key]\n};\nvar findSingletonVersionKey = (scope, key) => {\n\tvar versions = scope[key];\n\treturn Object.keys(versions).reduce((a, b) => {\n\t\treturn !a || (!versions[a].loaded && versionLt(a, b)) ? b : a;\n\t}, 0);\n};\nvar getInvalidSingletonVersionMessage = (scope, key, version, requiredVersion) => {\n\treturn \"Unsatisfied version \" + version + \" from \" + (version && scope[key][version].from) + \" of shared singleton module \" + key + \" (required \" + rangeToString(requiredVersion) + \")\"\n};\nvar getSingleton = (scope, scopeName, key, requiredVersion) => {\n\tvar version = findSingletonVersionKey(scope, key);\n\treturn get(scope[key][version]);\n};\nvar getSingletonVersion = (scope, scopeName, key, requiredVersion) => {\n\tvar version = findSingletonVersionKey(scope, key);\n\tif (!satisfy(requiredVersion, version)) warn(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));\n\treturn get(scope[key][version]);\n};\nvar getStrictSingletonVersion = (scope, scopeName, key, requiredVersion) => {\n\tvar version = findSingletonVersionKey(scope, key);\n\tif (!satisfy(requiredVersion, version)) throw new Error(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));\n\treturn get(scope[key][version]);\n};\nvar findValidVersion = (scope, key, requiredVersion) => {\n\tvar versions = scope[key];\n\tvar key = Object.keys(versions).reduce((a, b) => {\n\t\tif (!satisfy(requiredVersion, b)) return a;\n\t\treturn !a || versionLt(a, b) ? b : a;\n\t}, 0);\n\treturn key && versions[key]\n};\nvar getInvalidVersionMessage = (scope, scopeName, key, requiredVersion) => {\n\tvar versions = scope[key];\n\treturn \"No satisfying version (\" + rangeToString(requiredVersion) + \") of shared module \" + key + \" found in shared scope \" + scopeName + \".\\n\" +\n\t\t\"Available versions: \" + Object.keys(versions).map((key) => {\n\t\treturn key + \" from \" + versions[key].from;\n\t}).join(\", \");\n};\nvar getValidVersion = (scope, scopeName, key, requiredVersion) => {\n\tvar entry = findValidVersion(scope, key, requiredVersion);\n\tif(entry) return get(entry);\n\tthrow new Error(getInvalidVersionMessage(scope, scopeName, key, requiredVersion));\n};\nvar warn = (msg) => {\n\tif (typeof console !== \"undefined\" && console.warn) console.warn(msg);\n};\nvar warnInvalidVersion = (scope, scopeName, key, requiredVersion) => {\n\twarn(getInvalidVersionMessage(scope, scopeName, key, requiredVersion));\n};\nvar get = (entry) => {\n\tentry.loaded = 1;\n\treturn entry.get()\n};\nvar init = (fn) => (function(scopeName, a, b, c) {\n\tvar promise = __webpack_require__.I(scopeName);\n\tif (promise && promise.then) return promise.then(fn.bind(fn, scopeName, __webpack_require__.S[scopeName], a, b, c));\n\treturn fn(scopeName, __webpack_require__.S[scopeName], a, b, c);\n});\n\nvar load = /*#__PURE__*/ init((scopeName, scope, key) => {\n\tensureExistence(scopeName, key);\n\treturn get(findVersion(scope, key));\n});\nvar loadFallback = /*#__PURE__*/ init((scopeName, scope, key, fallback) => {\n\treturn scope && __webpack_require__.o(scope, key) ? get(findVersion(scope, key)) : fallback();\n});\nvar loadVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => {\n\tensureExistence(scopeName, key);\n\treturn get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));\n});\nvar loadSingleton = /*#__PURE__*/ init((scopeName, scope, key) => {\n\tensureExistence(scopeName, key);\n\treturn getSingleton(scope, scopeName, key);\n});\nvar loadSingletonVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => {\n\tensureExistence(scopeName, key);\n\treturn getSingletonVersion(scope, scopeName, key, version);\n});\nvar loadStrictVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => {\n\tensureExistence(scopeName, key);\n\treturn getValidVersion(scope, scopeName, key, version);\n});\nvar loadStrictSingletonVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => {\n\tensureExistence(scopeName, key);\n\treturn getStrictSingletonVersion(scope, scopeName, key, version);\n});\nvar loadVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => {\n\tif(!scope || !__webpack_require__.o(scope, key)) return fallback();\n\treturn get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));\n});\nvar loadSingletonFallback = /*#__PURE__*/ init((scopeName, scope, key, fallback) => {\n\tif(!scope || !__webpack_require__.o(scope, key)) return fallback();\n\treturn getSingleton(scope, scopeName, key);\n});\nvar loadSingletonVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => {\n\tif(!scope || !__webpack_require__.o(scope, key)) return fallback();\n\treturn getSingletonVersion(scope, scopeName, key, version);\n});\nvar loadStrictVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => {\n\tvar entry = scope && __webpack_require__.o(scope, key) && findValidVersion(scope, key, version);\n\treturn entry ? get(entry) : fallback();\n});\nvar loadStrictSingletonVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => {\n\tif(!scope || !__webpack_require__.o(scope, key)) return fallback();\n\treturn getStrictSingletonVersion(scope, scopeName, key, version);\n});\nvar installedModules = {};\nvar moduleToHandlerMapping = {\n\t21527: () => (loadSingletonVersionCheckFallback(\"default\", \"react\", [4,18,2,0], () => (__webpack_require__.e(7810).then(() => (() => (__webpack_require__(77810))))))),\n\t62031: () => (loadSingletonVersionCheckFallback(\"default\", \"@emotion/cache\", [1,11,11,0], () => (__webpack_require__.e(2661).then(() => (() => (__webpack_require__(92661))))))),\n\t31874: () => (loadSingletonVersionCheckFallback(\"default\", \"@emotion/react\", [1,11,11,4], () => (Promise.all([__webpack_require__.e(9303), __webpack_require__.e(2031)]).then(() => (() => (__webpack_require__(29303))))))),\n\t34118: () => (loadSingletonVersionCheckFallback(\"default\", \"@emotion/styled\", [1,11,11,0], () => (__webpack_require__.e(4578).then(() => (() => (__webpack_require__(24578))))))),\n\t19309: () => (loadStrictVersionCheckFallback(\"default\", \"@mui/system\", [4,5,15,14], () => (__webpack_require__.e(4245).then(() => (() => (__webpack_require__(84245))))))),\n\t85929: () => (loadSingletonVersionCheckFallback(\"default\", \"react-dom\", [4,18,2,0], () => (__webpack_require__.e(2483).then(() => (() => (__webpack_require__(22483))))))),\n\t360: () => (loadStrictVersionCheckFallback(\"default\", \"html-react-parser\", [1,5,1,8], () => (__webpack_require__.e(900).then(() => (() => (__webpack_require__(10900))))))),\n\t48177: () => (loadStrictVersionCheckFallback(\"default\", \"date-fns\", [1,2,28,0], () => (__webpack_require__.e(5531).then(() => (() => (__webpack_require__(75531))))))),\n\t15720: () => (loadStrictVersionCheckFallback(\"default\", \"@okta/okta-auth-js\", [4,7,4,3], () => (Promise.all([__webpack_require__.e(6146), __webpack_require__.e(3610), __webpack_require__.e(5870)]).then(() => (() => (__webpack_require__(13610))))))),\n\t22503: () => (loadSingletonVersionCheckFallback(\"default\", \"react-router-dom\", [4,6,22,2], () => (Promise.all([__webpack_require__.e(1534), __webpack_require__.e(1342), __webpack_require__.e(5929), __webpack_require__.e(5563)]).then(() => (() => (__webpack_require__(81342))))))),\n\t58771: () => (loadStrictVersionCheckFallback(\"default\", \"@okta/okta-auth-js\", [4,7,4,3], () => (Promise.all([__webpack_require__.e(6146), __webpack_require__.e(5843), __webpack_require__.e(3489)]).then(() => (() => (__webpack_require__(95843))))))),\n\t95563: () => (loadSingletonVersionCheckFallback(\"default\", \"react-router\", [4,6,22,2], () => (Promise.all([__webpack_require__.e(1534), __webpack_require__.e(8689)]).then(() => (() => (__webpack_require__(28689))))))),\n\t19677: () => (loadStrictVersionCheckFallback(\"default\", \"jwt-decode\", [1,3,1,2], () => (__webpack_require__.e(3487).then(() => (() => (__webpack_require__(43487))))))),\n\t22951: () => (loadStrictVersionCheckFallback(\"default\", \"wretch\", [4,1,7,6], () => (__webpack_require__.e(2960).then(() => (() => (__webpack_require__(12960))))))),\n\t48820: () => (loadSingletonVersionCheckFallback(\"default\", \"@im/react-localization\", [1,1,0,349], () => (Promise.all([__webpack_require__.e(3122), __webpack_require__.e(7000), __webpack_require__.e(8412), __webpack_require__.e(5850), __webpack_require__.e(394), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(5929), __webpack_require__.e(4118), __webpack_require__.e(9309), __webpack_require__.e(360), __webpack_require__.e(8177)]).then(() => (() => (__webpack_require__(80394))))))),\n\t60358: () => (loadStrictVersionCheckFallback(\"default\", \"@fullstory/browser\", [1,1,5,1], () => (__webpack_require__.e(4825).then(() => (() => (__webpack_require__(64825))))))),\n\t91319: () => (loadStrictVersionCheckFallback(\"default\", \"@okta/okta-react\", [4,6,7,0], () => (Promise.all([__webpack_require__.e(1844), __webpack_require__.e(5720)]).then(() => (() => (__webpack_require__(41844))))))),\n\t11422: () => (loadStrictVersionCheckFallback(\"default\", \"uuid\", [1,8,3,2], () => (__webpack_require__.e(5836).then(() => (() => (__webpack_require__(35836))))))),\n\t46296: () => (loadSingletonVersionCheckFallback(\"default\", \"@tanstack/react-query\", [4,5,32,1], () => (__webpack_require__.e(6311).then(() => (() => (__webpack_require__(86311))))))),\n\t45459: () => (loadSingletonVersionCheckFallback(\"default\", \"recoil\", [4,0,7,7], () => (Promise.all([__webpack_require__.e(7006), __webpack_require__.e(1527), __webpack_require__.e(5929)]).then(() => (() => (__webpack_require__(27006))))))),\n\t1740: () => (loadStrictVersionCheckFallback(\"default\", \"react-helmet-async\", [1,2,0,4], () => (__webpack_require__.e(300).then(() => (() => (__webpack_require__(70300))))))),\n\t25337: () => (loadSingletonVersionCheckFallback(\"default\", \"@datadog/browser-rum\", [4,5,29,0], () => (() => (__webpack_require__(82702))))),\n\t50766: () => (loadStrictVersionCheckFallback(\"default\", \"@okta/okta-signin-widget\", [4,7,11,2], () => (Promise.all([__webpack_require__.e(4687), __webpack_require__.e(8771)]).then(() => (() => (__webpack_require__(64687))))))),\n\t62701: () => (loadStrictVersionCheckFallback(\"default\", \"@mui/x-license-pro\", [4,6,10,2], () => (__webpack_require__.e(4243).then(() => (() => (__webpack_require__(14243))))))),\n\t68350: () => (loadSingletonVersionCheckFallback(\"default\", \"@im/im-theme\", [1,2,0,878], () => (__webpack_require__.e(8598).then(() => (() => (__webpack_require__(58598)))))))\n};\n// no consumes in initial chunks\nvar chunkMapping = {\n\t\"360\": [\n\t\t360\n\t],\n\t\"1422\": [\n\t\t11422\n\t],\n\t\"1527\": [\n\t\t21527\n\t],\n\t\"1644\": [\n\t\t360,\n\t\t15720,\n\t\t25337,\n\t\t50766\n\t],\n\t\"1740\": [\n\t\t1740\n\t],\n\t\"1874\": [\n\t\t31874\n\t],\n\t\"2019\": [\n\t\t19677,\n\t\t22951\n\t],\n\t\"2031\": [\n\t\t62031\n\t],\n\t\"2503\": [\n\t\t22503\n\t],\n\t\"4118\": [\n\t\t34118\n\t],\n\t\"4256\": [\n\t\t62701,\n\t\t68350\n\t],\n\t\"5459\": [\n\t\t45459\n\t],\n\t\"5563\": [\n\t\t95563\n\t],\n\t\"5720\": [\n\t\t15720\n\t],\n\t\"5929\": [\n\t\t85929\n\t],\n\t\"7431\": [\n\t\t46296\n\t],\n\t\"8177\": [\n\t\t48177\n\t],\n\t\"8771\": [\n\t\t58771\n\t],\n\t\"9309\": [\n\t\t19309\n\t],\n\t\"9925\": [\n\t\t22503,\n\t\t48820,\n\t\t60358,\n\t\t91319,\n\t\t95563\n\t]\n};\nvar startedInstallModules = {};\n__webpack_require__.f.consumes = (chunkId, promises) => {\n\tif(__webpack_require__.o(chunkMapping, chunkId)) {\n\t\tchunkMapping[chunkId].forEach((id) => {\n\t\t\tif(__webpack_require__.o(installedModules, id)) return promises.push(installedModules[id]);\n\t\t\tif(!startedInstallModules[id]) {\n\t\t\tvar onFactory = (factory) => {\n\t\t\t\tinstalledModules[id] = 0;\n\t\t\t\t__webpack_require__.m[id] = (module) => {\n\t\t\t\t\tdelete __webpack_require__.c[id];\n\t\t\t\t\tmodule.exports = factory();\n\t\t\t\t}\n\t\t\t};\n\t\t\tstartedInstallModules[id] = true;\n\t\t\tvar onError = (error) => {\n\t\t\t\tdelete installedModules[id];\n\t\t\t\t__webpack_require__.m[id] = (module) => {\n\t\t\t\t\tdelete __webpack_require__.c[id];\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tvar promise = moduleToHandlerMapping[id]();\n\t\t\t\tif(promise.then) {\n\t\t\t\t\tpromises.push(installedModules[id] = promise.then(onFactory)['catch'](onError));\n\t\t\t\t} else onFactory(promise);\n\t\t\t} catch(e) { onError(e); }\n\t\t\t}\n\t\t});\n\t}\n}","/* 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 */\n\nexport const ConsoleApiName = {\n  log: 'log',\n  debug: 'debug',\n  info: 'info',\n  warn: 'warn',\n  error: 'error',\n} as const\n\nexport type ConsoleApiName = (typeof ConsoleApiName)[keyof typeof ConsoleApiName]\n\ninterface Display {\n  debug: typeof console.debug\n  log: typeof console.log\n  info: typeof console.info\n  warn: typeof console.warn\n  error: typeof console.error\n}\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\n\nexport const originalConsoleMethods = {} as Display\nObject.keys(ConsoleApiName).forEach((name) => {\n  originalConsoleMethods[name as ConsoleApiName] = globalConsole[name as ConsoleApiName]\n})\n\nconst PREFIX = 'Datadog Browser SDK:'\n\nexport const display: 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}\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","import { display } from './display'\n\nexport function catchUserErrors<Args extends any[], R>(fn: (...args: Args) => R, errorMsg: string) {\n  return (...args: Args) => {\n    try {\n      return fn(...args)\n    } catch (err) {\n      display.error(errorMsg, err)\n    }\n  }\n}\n","import { display } from './display'\n\nlet onMonitorErrorCollected: undefined | ((error: unknown) => void)\nlet debugMode = false\n\nexport function startMonitorErrorCollection(newOnMonitorErrorCollected: (error: unknown) => void) {\n  onMonitorErrorCollected = newOnMonitorErrorCollected\n}\n\nexport function setDebugMode(newDebugMode: boolean) {\n  debugMode = newDebugMode\n}\n\nexport function resetMonitor() {\n  onMonitorErrorCollected = undefined\n  debugMode = false\n}\n\nexport function monitored<T extends (...params: any[]) => unknown>(\n  _: any,\n  __: string,\n  descriptor: TypedPropertyDescriptor<T>\n) {\n  const originalMethod = descriptor.value!\n  descriptor.value = function (this: any, ...args: Parameters<T>) {\n    const decorated = onMonitorErrorCollected ? monitor(originalMethod) : originalMethod\n    return decorated.apply(this, args) as ReturnType<T>\n  } as T\n}\n\nexport function monitor<T extends (...args: any[]) => any>(fn: T): T {\n  return function (this: any) {\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n    return callMonitored(fn, this, arguments as unknown as Parameters<T>)\n  } as unknown as T // consider output type has input type\n}\n\nexport function callMonitored<T extends (...args: any[]) => any>(\n  fn: T,\n  context: ThisParameterType<T>,\n  args: Parameters<T>\n): ReturnType<T> | undefined\nexport function callMonitored<T extends (this: void) => any>(fn: T): ReturnType<T> | undefined\nexport function callMonitored<T extends (...args: any[]) => any>(\n  fn: T,\n  context?: any,\n  args?: any\n): ReturnType<T> | undefined {\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n    return fn.apply(context, args)\n  } catch (e) {\n    displayIfDebugEnabled(e)\n    if (onMonitorErrorCollected) {\n      try {\n        onMonitorErrorCollected(e)\n      } catch (e) {\n        displayIfDebugEnabled(e)\n      }\n    }\n  }\n}\n\nexport function displayIfDebugEnabled(...args: any[]) {\n  if (debugMode) {\n    display.error('[MONITOR]', ...args)\n  }\n}\n","export function includes(candidate: string, search: string): boolean\nexport function includes<T>(candidate: T[], search: T): boolean\nexport function includes(candidate: string | unknown[], search: any) {\n  return candidate.indexOf(search) !== -1\n}\n\nexport function arrayFrom<T>(arrayLike: ArrayLike<T> | Set<T>): T[] {\n  if (Array.from) {\n    return Array.from(arrayLike)\n  }\n\n  const array = []\n\n  if (arrayLike instanceof Set) {\n    arrayLike.forEach((item) => array.push(item))\n  } else {\n    for (let i = 0; i < arrayLike.length; i++) {\n      array.push(arrayLike[i])\n    }\n  }\n\n  return array\n}\n\nexport function find<T, S extends T>(\n  array: ArrayLike<T>,\n  predicate: (item: T, index: number) => item is S\n): S | undefined\nexport function find<T>(array: ArrayLike<T>, predicate: (item: T, index: number) => boolean): T | undefined\nexport function find(array: ArrayLike<unknown>, predicate: (item: unknown, index: number) => boolean): unknown {\n  for (let i = 0; i < array.length; i += 1) {\n    const item = array[i]\n    if (predicate(item, i)) {\n      return item\n    }\n  }\n  return undefined\n}\n\nexport function findLast<T, S extends T>(\n  array: T[],\n  predicate: (item: T, index: number, array: T[]) => item is S\n): S | undefined {\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\nexport function forEach<List extends { [index: number]: any }>(\n  list: List,\n  callback: (value: List[number], index: number, parent: List) => void\n) {\n  Array.prototype.forEach.call(list, callback as any)\n}\n\nexport function objectValues<T = unknown>(object: { [key: string]: T }) {\n  return Object.keys(object).map((key) => object[key])\n}\n\nexport function objectEntries<T = unknown>(object: { [key: string]: T }): Array<[string, T]> {\n  return Object.keys(object).map((key) => [key, object[key]])\n}\n\nexport function startsWith(candidate: string, search: string) {\n  return candidate.slice(0, search.length) === search\n}\n\nexport function endsWith(candidate: string, search: string) {\n  return candidate.slice(-search.length) === search\n}\n\ninterface Assignable {\n  [key: string]: any\n}\n\nexport function assign<T, U>(target: T, source: U): T & U\nexport function assign<T, U, V>(target: T, source1: U, source2: V): T & U & V\nexport function assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W\nexport function assign<T, U, V, W, X>(target: T, source1: U, source2: V, source3: W, source4: X): T & U & V & W & X\nexport function assign(target: Assignable, ...toAssign: Assignable[]) {\n  toAssign.forEach((source: Assignable) => {\n    for (const key in source) {\n      if (Object.prototype.hasOwnProperty.call(source, key)) {\n        target[key] = source[key]\n      }\n    }\n  })\n  return target\n}\n","/**\n * inspired by https://mathiasbynens.be/notes/globalthis\n */\n\nexport function getGlobalObject<T = typeof globalThis>(): T {\n  if (typeof globalThis === 'object') {\n    return globalThis as unknown as T\n  }\n  Object.defineProperty(Object.prototype, '_dd_temp_', {\n    get() {\n      return this as object\n    },\n    configurable: true,\n  })\n  // @ts-ignore _dd_temp is defined using defineProperty\n  let globalObject: unknown = _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    } else if (typeof window === 'object') {\n      globalObject = window\n    } else {\n      globalObject = {}\n    }\n  }\n  return globalObject as T\n}\n","export const ONE_KIBI_BYTE = 1024\nexport const ONE_MEBI_BYTE = 1024 * ONE_KIBI_BYTE\n\n// eslint-disable-next-line no-control-regex\nconst HAS_MULTI_BYTES_CHARACTERS = /[^\\u0000-\\u007F]/\n\nexport function computeBytesCount(candidate: string): number {\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\n  if (window.TextEncoder !== undefined) {\n    return new TextEncoder().encode(candidate).length\n  }\n\n  return new Blob([candidate]).size\n}\n\nexport function concatBuffers(buffers: Uint8Array[]) {\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","import { getGlobalObject } from './getGlobalObject'\n\nexport interface BrowserWindowWithZoneJs extends Window {\n  Zone?: {\n    // All Zone.js versions expose the __symbol__ method, but we observed that some website have a\n    // 'Zone' global variable unrelated to Zone.js, so let's consider this method optional\n    // nonetheless.\n    __symbol__?: (name: string) => string\n  }\n}\n\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 extends keyof Target & string>(\n  target: Target,\n  name: Name\n): Target[Name] {\n  const browserWindow = getGlobalObject<BrowserWindowWithZoneJs>()\n  let original: Target[Name] | undefined\n  if (browserWindow.Zone && typeof browserWindow.Zone.__symbol__ === 'function') {\n    original = (target as any)[browserWindow.Zone.__symbol__(name)]\n  }\n  if (!original) {\n    original = target[name]\n  }\n  return original\n}\n","import { getZoneJsOriginalValue } from './getZoneJsOriginalValue'\nimport { monitor } from './monitor'\nimport { getGlobalObject } from './getGlobalObject'\n\nexport type TimeoutId = ReturnType<typeof globalThis.setTimeout>\n\nexport function setTimeout(callback: () => void, delay?: number): TimeoutId {\n  return getZoneJsOriginalValue(getGlobalObject(), 'setTimeout')(monitor(callback), delay)\n}\n\nexport function clearTimeout(timeoutId: TimeoutId | undefined) {\n  getZoneJsOriginalValue(getGlobalObject(), 'clearTimeout')(timeoutId)\n}\n\nexport function setInterval(callback: () => void, delay?: number): TimeoutId {\n  return getZoneJsOriginalValue(getGlobalObject(), 'setInterval')(monitor(callback), delay)\n}\n\nexport function clearInterval(timeoutId: TimeoutId | undefined) {\n  getZoneJsOriginalValue(getGlobalObject(), 'clearInterval')(timeoutId)\n}\n","import type { TimeoutId } from '../timer'\nimport { setTimeout, clearTimeout } from '../timer'\n\n// use lodash API\nexport function throttle<T extends (...args: any[]) => void>(\n  fn: T,\n  wait: number,\n  options?: { leading?: boolean; trailing?: boolean }\n) {\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: Parameters<T> | undefined\n  let pendingTimeoutId: TimeoutId\n\n  return {\n    throttled: (...parameters: Parameters<T>) => {\n      if (inWaitPeriod) {\n        pendingExecutionWithParameters = parameters\n        return\n      }\n      if (needLeadingExecution) {\n        fn(...parameters)\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\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function noop() {}\n","import { noop } from '../utils/functionUtils'\n\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(\n  value: unknown,\n  replacer?: Array<string | number>,\n  space?: string | number\n): string | undefined {\n  if (typeof value !== 'object' || value === null) {\n    return JSON.stringify(value)\n  }\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\n  try {\n    return JSON.stringify(value, replacer, space)\n  } catch {\n    return '<error: unable to serialize object>'\n  } finally {\n    restoreObjectPrototypeToJson()\n    restoreArrayPrototypeToJson()\n    restoreValuePrototypeToJson()\n    restoreValueToJson()\n  }\n}\n\nexport interface ObjectWithToJsonMethod {\n  toJSON?: () => unknown\n}\n\nexport function detachToJsonMethod(value: object) {\n  const object = value as ObjectWithToJsonMethod\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","import { assign } from './polyfills'\n\nexport function shallowClone<T>(object: T): T & Record<string, never> {\n  return assign({}, object)\n}\n\nexport function objectHasValue<T extends { [key: string]: unknown }>(object: T, value: unknown): value is T[keyof T] {\n  return Object.keys(object).some((key) => object[key] === value)\n}\n\nexport function isEmptyObject(object: object) {\n  return Object.keys(object).length === 0\n}\n\nexport function mapValues<A, B>(object: { [key: string]: A }, fn: (arg: A) => B) {\n  const newObject: { [key: string]: B } = {}\n  for (const key of Object.keys(object)) {\n    newObject[key] = fn(object[key])\n  }\n  return newObject\n}\n","import { ONE_KIBI_BYTE, computeBytesCount } from '../../tools/utils/byteUtils'\nimport { throttle } from '../../tools/utils/functionUtils'\nimport type { Context } from '../../tools/serialisation/context'\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify'\nimport { DOCS_TROUBLESHOOTING, MORE_DETAILS, display } from '../../tools/display'\nimport { isEmptyObject } from '../../tools/utils/objectUtils'\nimport type { CustomerDataType } from './contextConstants'\n\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\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\n\nexport const BYTES_COMPUTATION_THROTTLING_DELAY = 200\n\nexport type CustomerDataTracker = ReturnType<typeof createCustomerDataTracker>\nexport type CustomerDataTrackerManager = ReturnType<typeof createCustomerDataTrackerManager>\n\nexport const enum CustomerDataCompressionStatus {\n  Unknown,\n  Enabled,\n  Disabled,\n}\n\nexport function createCustomerDataTrackerManager(\n  compressionStatus: CustomerDataCompressionStatus = CustomerDataCompressionStatus.Disabled\n) {\n  const customerDataTrackers = new Map<CustomerDataType, CustomerDataTracker>()\n\n  let alreadyWarned = false\n  function checkCustomerDataLimit(initialBytesCount = 0) {\n    if (alreadyWarned || compressionStatus === CustomerDataCompressionStatus.Unknown) {\n      return\n    }\n\n    const bytesCountLimit =\n      compressionStatus === CustomerDataCompressionStatus.Disabled\n        ? CUSTOMER_DATA_BYTES_LIMIT\n        : CUSTOMER_COMPRESSED_DATA_BYTES_LIMIT\n\n    let bytesCount = initialBytesCount\n    customerDataTrackers.forEach((tracker) => {\n      bytesCount += tracker.getBytesCount()\n    })\n\n    if (bytesCount > bytesCountLimit) {\n      displayCustomerDataLimitReachedWarning(bytesCountLimit)\n      alreadyWarned = true\n    }\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    /**\n     * Creates a tracker if it doesn't exist, and returns it.\n     */\n    getOrCreateTracker: (type: CustomerDataType) => {\n      if (!customerDataTrackers.has(type)) {\n        customerDataTrackers.set(type, createCustomerDataTracker(checkCustomerDataLimit))\n      }\n      return customerDataTrackers.get(type)!\n    },\n\n    setCompressionStatus: (newCompressionStatus: CustomerDataCompressionStatus) => {\n      if (compressionStatus === CustomerDataCompressionStatus.Unknown) {\n        compressionStatus = newCompressionStatus\n        checkCustomerDataLimit()\n      }\n    },\n\n    getCompressionStatus: () => compressionStatus,\n\n    stop: () => {\n      customerDataTrackers.forEach((tracker) => tracker.stop())\n      customerDataTrackers.clear()\n    },\n  }\n}\n\nexport function createCustomerDataTracker(checkCustomerDataLimit: () => void) {\n  let bytesCountCache = 0\n\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: Context) => {\n    bytesCountCache = computeBytesCount(jsonStringify(context)!)\n    checkCustomerDataLimit()\n  }, BYTES_COMPUTATION_THROTTLING_DELAY)\n\n  const resetBytesCount = () => {\n    cancelComputeBytesCount()\n    bytesCountCache = 0\n  }\n\n  return {\n    updateCustomerData: (context: Context) => {\n      if (isEmptyObject(context)) {\n        resetBytesCount()\n      } else {\n        computeBytesCountThrottled(context)\n      }\n    },\n    resetCustomerData: resetBytesCount,\n    getBytesCount: () => bytesCountCache,\n    stop: () => {\n      cancelComputeBytesCount()\n    },\n  }\n}\n\nfunction displayCustomerDataLimitReachedWarning(bytesCountLimit: number) {\n  display.warn(\n    `Customer data exceeds the recommended ${\n      bytesCountLimit / ONE_KIBI_BYTE\n    }KiB threshold. ${MORE_DETAILS} ${DOCS_TROUBLESHOOTING}/#customer-data-exceeds-the-recommended-threshold-warning`\n  )\n}\n","/**\n * Similar to `typeof`, but distinguish plain objects from `null` and arrays\n */\nexport function getType(value: unknown) {\n  if (value === null) {\n    return 'null'\n  }\n  if (Array.isArray(value)) {\n    return 'array'\n  }\n  return typeof value\n}\n","import { getType } from './utils/typeUtils'\n\ntype Merged<TDestination, TSource> =\n  // case 1 - source is undefined - return destination\n  TSource extends undefined\n    ? TDestination\n    : // case 2 - destination is undefined - return source\n      TDestination extends undefined\n      ? TSource\n      : // case 3 - source is an array - see if it merges or overwrites\n        TSource extends any[]\n        ? TDestination extends any[]\n          ? TDestination & TSource\n          : TSource\n        : // case 4 - source is an object - see if it merges or overwrites\n          TSource extends object\n          ? TDestination extends object\n            ? TDestination extends any[]\n              ? TSource\n              : TDestination & TSource\n            : TSource\n          : // case 5 - cannot merge - return source\n            TSource\n\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<D, S>(\n  destination: D,\n  source: S,\n  circularReferenceChecker = createCircularReferenceChecker()\n): Merged<D, S> {\n  // ignore the source if it is undefined\n  if (source === undefined) {\n    return destination as Merged<D, S>\n  }\n\n  if (typeof source !== 'object' || source === null) {\n    // primitive values - just return source\n    return source as Merged<D, S>\n  } else if (source instanceof Date) {\n    return new Date(source.getTime()) as unknown as Merged<D, S>\n  } else if (source instanceof RegExp) {\n    const flags =\n      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) as unknown as Merged<D, S>\n  }\n\n  if (circularReferenceChecker.hasAlreadyBeenSeen(source)) {\n    // remove circular references\n    return undefined as unknown as Merged<D, S>\n  } else if (Array.isArray(source)) {\n    const merged: any[] = 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 as unknown as Merged<D, S>\n  }\n\n  const merged = getType(destination) === 'object' ? (destination as Record<any, any>) : {}\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 as unknown as Merged<D, S>\n}\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<T>(value: T): T {\n  return mergeInto(undefined, value) as T\n}\n\ntype Combined<A, B> = A extends null ? B : B extends null ? A : Merged<A, B>\n\n/*\n * Performs a deep merge of objects and arrays.\n * - Arguments won't be mutated\n * - Object and arrays in the output value are de-referenced (\"deep cloned\")\n * - Arrays values are merged index by index\n * - Objects are merged by keys\n * - Values get replaced, unless undefined\n */\nexport function combine<A, B>(a: A, b: B): Combined<A, B>\nexport function combine<A, B, C>(a: A, b: B, c: C): Combined<Combined<A, B>, C>\nexport function combine<A, B, C, D>(a: A, b: B, c: C, d: D): Combined<Combined<Combined<A, B>, C>, D>\nexport function combine<A, B, C, D, E>(\n  a: A,\n  b: B,\n  c: C,\n  d: D,\n  e: E\n): Combined<Combined<Combined<Combined<A, B>, C>, D>, E>\nexport function combine<A, B, C, D, E, F>(\n  a: A,\n  b: B,\n  c: C,\n  d: D,\n  e: E,\n  f: F\n): Combined<Combined<Combined<Combined<Combined<A, B>, C>, D>, E>, F>\nexport function combine<A, B, C, D, E, F, G>(\n  a: A,\n  b: B,\n  c: C,\n  d: D,\n  e: E,\n  f: F,\n  g: G\n): Combined<Combined<Combined<Combined<Combined<Combined<A, B>, C>, D>, E>, F>, G>\nexport function combine<A, B, C, D, E, F, G, H>(\n  a: A,\n  b: B,\n  c: C,\n  d: D,\n  e: E,\n  f: F,\n  g: G,\n  h: H\n): Combined<Combined<Combined<Combined<Combined<Combined<Combined<A, B>, C>, D>, E>, F>, G>, H>\nexport function combine(...sources: any[]): unknown {\n  let destination: any\n\n  for (const source of sources) {\n    // Ignore any undefined or null sources.\n    if (source === undefined || source === null) {\n      continue\n    }\n\n    destination = mergeInto(destination, source)\n  }\n\n  return destination as unknown\n}\n\ninterface CircularReferenceChecker {\n  hasAlreadyBeenSeen(value: any): boolean\n}\n\nfunction createCircularReferenceChecker(): CircularReferenceChecker {\n  if (typeof WeakSet !== 'undefined') {\n    const set: WeakSet<any> = 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: any[] = []\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","import { display } from '../display'\nimport { ONE_KIBI_BYTE } from '../utils/byteUtils'\nimport type { Context, ContextArray, ContextValue } from './context'\nimport type { ObjectWithToJsonMethod } from './jsonStringify'\nimport { detachToJsonMethod } from './jsonStringify'\n\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype PrimitivesAndFunctions = string | number | boolean | undefined | null | symbol | bigint | Function\ntype ExtendedContextValue = PrimitivesAndFunctions | object | ExtendedContext | ExtendedContextArray\ntype ExtendedContext = { [key: string]: ExtendedContextValue }\ntype ExtendedContextArray = ExtendedContextValue[]\n\ntype ContainerElementToProcess = {\n  source: ExtendedContextArray | ExtendedContext\n  target: ContextArray | Context\n  path: string\n}\n\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\n// Symbol for the root element of the JSONPath used for visited objects\nconst JSON_PATH_ROOT_ELEMENT = '$'\n\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\n\n/**\n * Ensures user-provided data is 'safe' for the SDK\n * - Deep clones data\n * - Removes cyclic references\n * - Transforms unserializable types to a string representation\n *\n * LIMITATIONS:\n * - Size is in characters, not byte count (may differ according to character encoding)\n * - Size does not take into account indentation that can be applied to JSON.stringify\n * - Non-numerical properties of Arrays are ignored. Same behavior as JSON.stringify\n *\n * @param source              User-provided data meant to be serialized using JSON.stringify\n * @param maxCharacterCount   Maximum number of characters allowed in serialized form\n */\nexport function sanitize(source: string, maxCharacterCount?: number): string | undefined\nexport function sanitize(source: Context, maxCharacterCount?: number): Context\nexport function sanitize(source: unknown, maxCharacterCount?: number): ContextValue\nexport function sanitize(source: unknown, 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\n  // Initial call to sanitizeProcessor - will populate containerQueue if source is an Array or a plain Object\n  const containerQueue: ContainerElementToProcess[] = []\n  const visitedObjectsWithPath = new WeakMap<object, string>()\n  const sanitizedData = sanitizeProcessor(\n    source as ExtendedContextValue,\n    JSON_PATH_ROOT_ELEMENT,\n    undefined,\n    containerQueue,\n    visitedObjectsWithPath\n  )\n  const serializedSanitizedData = JSON.stringify(sanitizedData)\n  let accumulatedCharacterCount = serializedSanitizedData ? serializedSanitizedData.length : 0\n\n  if (accumulatedCharacterCount > maxCharacterCount) {\n    warnOverCharacterLimit(maxCharacterCount, 'discarded', source)\n    return undefined\n  }\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\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(\n          containerToProcess.source[key],\n          containerToProcess.path,\n          key,\n          containerQueue,\n          visitedObjectsWithPath\n        )\n\n        if (targetData !== undefined) {\n          accumulatedCharacterCount += JSON.stringify(targetData).length\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        ;(containerToProcess.target as ContextArray)[key] = targetData\n      }\n    } else {\n      for (const key in containerToProcess.source) {\n        if (Object.prototype.hasOwnProperty.call(containerToProcess.source, key)) {\n          const targetData = sanitizeProcessor(\n            containerToProcess.source[key],\n            containerToProcess.path,\n            key,\n            containerQueue,\n            visitedObjectsWithPath\n          )\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          ;(containerToProcess.target as Context)[key] = targetData\n        }\n      }\n    }\n  }\n\n  // Rebind detached toJSON functions\n  restoreObjectPrototypeToJson()\n  restoreArrayPrototypeToJson()\n\n  return sanitizedData\n}\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(\n  source: ExtendedContextValue,\n  parentPath: string,\n  key: string | number | undefined,\n  queue: ContainerElementToProcess[],\n  visitedObjectsWithPath: WeakMap<object, string>\n) {\n  // Start by handling toJSON, as we want to sanitize its output\n  const sourceToSanitize = tryToApplyToJSON(source)\n\n  if (!sourceToSanitize || typeof sourceToSanitize !== 'object') {\n    return sanitizePrimitivesAndFunctions(sourceToSanitize)\n  }\n\n  const sanitizedSource = sanitizeObjects(sourceToSanitize)\n  if (sanitizedSource !== '[Object]' && sanitizedSource !== '[Array]' && sanitizedSource !== '[Error]') {\n    return sanitizedSource\n  }\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 as object\n  if (visitedObjectsWithPath.has(sourceAsObject)) {\n    return `[Reference seen at ${visitedObjectsWithPath.get(sourceAsObject)!}]`\n  }\n\n  // Add processed source to queue\n  const currentPath = key !== undefined ? `${parentPath}.${key}` : parentPath\n  const target = Array.isArray(sourceToSanitize) ? ([] as ContextArray) : ({} as Context)\n  visitedObjectsWithPath.set(sourceAsObject, currentPath)\n  queue.push({ source: sourceToSanitize as ExtendedContext | ExtendedContextArray, target, path: currentPath })\n\n  return target\n}\n\n/**\n * Handles sanitization of simple, non-object types\n *\n */\nfunction sanitizePrimitivesAndFunctions(value: PrimitivesAndFunctions) {\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    // symbol.description is part of ES2019+\n    type symbolWithDescription = symbol & { description: string }\n    return `[Symbol] ${(value as symbolWithDescription).description || value.toString()}`\n  }\n\n  return value\n}\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 * - IE11 does not return a distinct type for objects such as Map, WeakMap, ... These objects will pass through and their\n * properties enumerated if any.\n *\n */\nfunction sanitizeObjects(value: object) {\n  try {\n    // Handle events - Keep a simple implementation to avoid breaking changes\n    if (value instanceof Event) {\n      return {\n        isTrusted: value.isTrusted,\n      }\n    }\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  } catch {\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}\n\n/**\n * Checks if a toJSON function exists and tries to execute it\n *\n */\nfunction tryToApplyToJSON(value: ExtendedContextValue) {\n  const object = value as ObjectWithToJsonMethod\n  if (object && typeof object.toJSON === 'function') {\n    try {\n      return object.toJSON() as ExtendedContextValue\n    } catch {\n      // If toJSON fails, we continue by trying to serialize the value manually\n    }\n  }\n\n  return value\n}\n\n/**\n * Helper function to display the warning when the accumulated character count is over the limit\n */\nfunction warnOverCharacterLimit(maxCharacterCount: number, changeType: 'discarded' | 'truncated', source: unknown) {\n  display.warn(\n    `The data provided has been ${changeType} as it is over the limit of ${maxCharacterCount} characters:`,\n    source\n  )\n}\n","export interface Subscription {\n  unsubscribe: () => void\n}\n\n// eslint-disable-next-line no-restricted-syntax\nexport class Observable<T> {\n  private observers: Array<(data: T) => void> = []\n  private onLastUnsubscribe?: () => void\n\n  constructor(private onFirstSubscribe?: (observable: Observable<T>) => (() => void) | void) {}\n\n  subscribe(f: (data: T) => void): Subscription {\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\n  notify(data: T) {\n    this.observers.forEach((observer) => observer(data))\n  }\n}\n\nexport function mergeObservables<T>(...observables: Array<Observable<T>>) {\n  return new Observable<T>((globalObservable) => {\n    const subscriptions: Subscription[] = observables.map((observable) =>\n      observable.subscribe((data) => globalObservable.notify(data))\n    )\n    return () => subscriptions.forEach((subscription) => subscription.unsubscribe())\n  })\n}\n","import { deepClone } from '../../tools/mergeInto'\nimport { getType } from '../../tools/utils/typeUtils'\nimport { sanitize } from '../../tools/serialisation/sanitize'\nimport type { Context } from '../../tools/serialisation/context'\nimport { Observable } from '../../tools/observable'\nimport type { CustomerDataTracker } from './customerDataTracker'\n\nexport type ContextManager = ReturnType<typeof createContextManager>\n\nexport function createContextManager(customerDataTracker?: CustomerDataTracker) {\n  let context: Context = {}\n  const changeObservable = new Observable<void>()\n\n  const contextManager = {\n    getContext: () => deepClone(context),\n\n    setContext: (newContext: Context) => {\n      if (getType(newContext) === 'object') {\n        context = sanitize(newContext)\n        customerDataTracker && customerDataTracker.updateCustomerData(context)\n      } else {\n        contextManager.clearContext()\n      }\n      changeObservable.notify()\n    },\n\n    setContextProperty: (key: string, property: any) => {\n      context[key] = sanitize(property)\n      customerDataTracker && customerDataTracker.updateCustomerData(context)\n      changeObservable.notify()\n    },\n\n    removeContextProperty: (key: string) => {\n      delete context[key]\n      customerDataTracker && customerDataTracker.updateCustomerData(context)\n      changeObservable.notify()\n    },\n\n    clearContext: () => {\n      context = {}\n      customerDataTracker && customerDataTracker.resetCustomerData()\n      changeObservable.notify()\n    },\n\n    changeObservable,\n  }\n  return contextManager\n}\n","import { Observable } from '../tools/observable'\n\nexport const TrackingConsent = {\n  GRANTED: 'granted',\n  NOT_GRANTED: 'not-granted',\n} as const\nexport type TrackingConsent = (typeof TrackingConsent)[keyof typeof TrackingConsent]\n\nexport interface TrackingConsentState {\n  tryToInit: (trackingConsent: TrackingConsent) => void\n  update: (trackingConsent: TrackingConsent) => void\n  isGranted: () => boolean\n  observable: Observable<void>\n}\n\nexport function createTrackingConsentState(currentConsent?: TrackingConsent): TrackingConsentState {\n  const observable = new Observable<void>()\n\n  return {\n    tryToInit(trackingConsent: TrackingConsent) {\n      if (!currentConsent) {\n        currentConsent = trackingConsent\n      }\n    },\n    update(trackingConsent: TrackingConsent) {\n      currentConsent = trackingConsent\n      observable.notify()\n    },\n    isGranted() {\n      return currentConsent === TrackingConsent.GRANTED\n    },\n    observable,\n  }\n}\n","import { monitor } from '../tools/monitor'\nimport { getZoneJsOriginalValue } from '../tools/getZoneJsOriginalValue'\nimport type { CookieStore, CookieStoreEventMap, VisualViewport, VisualViewportEventMap } from './browser.types'\n\nexport type TrustableEvent<E extends Event = Event> = E & { __ddIsTrusted?: boolean }\n\nexport const enum DOM_EVENT {\n  BEFORE_UNLOAD = 'beforeunload',\n  CLICK = 'click',\n  DBL_CLICK = 'dblclick',\n  KEY_DOWN = 'keydown',\n  LOAD = 'load',\n  POP_STATE = 'popstate',\n  SCROLL = 'scroll',\n  TOUCH_START = 'touchstart',\n  TOUCH_END = 'touchend',\n  TOUCH_MOVE = 'touchmove',\n  VISIBILITY_CHANGE = 'visibilitychange',\n  PAGE_SHOW = 'pageshow',\n  FREEZE = 'freeze',\n  RESUME = 'resume',\n  DOM_CONTENT_LOADED = 'DOMContentLoaded',\n  POINTER_DOWN = 'pointerdown',\n  POINTER_UP = 'pointerup',\n  POINTER_CANCEL = 'pointercancel',\n  HASH_CHANGE = 'hashchange',\n  PAGE_HIDE = 'pagehide',\n  MOUSE_DOWN = 'mousedown',\n  MOUSE_UP = 'mouseup',\n  MOUSE_MOVE = 'mousemove',\n  FOCUS = 'focus',\n  BLUR = 'blur',\n  CONTEXT_MENU = 'contextmenu',\n  RESIZE = 'resize',\n  CHANGE = 'change',\n  INPUT = 'input',\n  PLAY = 'play',\n  PAUSE = 'pause',\n  SECURITY_POLICY_VIOLATION = 'securitypolicyviolation',\n  SELECTION_CHANGE = 'selectionchange',\n  STORAGE = 'storage',\n}\n\ninterface AddEventListenerOptions {\n  once?: boolean\n  capture?: boolean\n  passive?: boolean\n}\n\ntype EventMapFor<T> = T extends Window\n  ? WindowEventMap & {\n      // TS 4.9.5 does not support `freeze` and `resume` events yet\n      freeze: Event\n      resume: Event\n      // TS 4.9.5 does not define `visibilitychange` on Window (only Document)\n      visibilitychange: Event\n    }\n  : T extends Document\n    ? DocumentEventMap\n    : T extends HTMLElement\n      ? HTMLElementEventMap\n      : T extends VisualViewport\n        ? VisualViewportEventMap\n        : T extends ShadowRoot\n          ? // ShadowRootEventMap is not yet defined in our supported TS version. Instead, use\n            // GlobalEventHandlersEventMap which is more than enough as we only need to listen for events bubbling\n            // through the ShadowRoot like \"change\" or \"input\"\n            GlobalEventHandlersEventMap\n          : T extends XMLHttpRequest\n            ? XMLHttpRequestEventMap\n            : T extends Performance\n              ? PerformanceEventMap\n              : T extends Worker\n                ? WorkerEventMap\n                : T extends CookieStore\n                  ? CookieStoreEventMap\n                  : Record<never, never>\n\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<Target extends EventTarget, EventName extends keyof EventMapFor<Target> & string>(\n  configuration: { allowUntrustedEvents?: boolean | undefined },\n  eventTarget: Target,\n  eventName: EventName,\n  listener: (event: EventMapFor<Target>[EventName] & { type: EventName }) => void,\n  options?: AddEventListenerOptions\n) {\n  return addEventListeners(configuration, eventTarget, [eventName], listener, options)\n}\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<Target extends EventTarget, EventName extends keyof EventMapFor<Target> & string>(\n  configuration: { allowUntrustedEvents?: boolean | undefined },\n  eventTarget: Target,\n  eventNames: EventName[],\n  listener: (event: EventMapFor<Target>[EventName] & { type: EventName }) => void,\n  { once, capture, passive }: AddEventListenerOptions = {}\n) {\n  const listenerWithMonitor = monitor((event: TrustableEvent) => {\n    if (!event.isTrusted && !event.__ddIsTrusted && !configuration.allowUntrustedEvents) {\n      return\n    }\n    if (once) {\n      stop()\n    }\n    listener(event as unknown as EventMapFor<Target>[EventName] & { type: EventName })\n  })\n\n  const options = passive ? { capture, passive } : capture\n\n  const add = getZoneJsOriginalValue(eventTarget, 'addEventListener')\n  eventNames.forEach((eventName) => add.call(eventTarget, eventName, listenerWithMonitor, options))\n\n  function stop() {\n    const remove = getZoneJsOriginalValue(eventTarget, 'removeEventListener')\n    eventNames.forEach((eventName) => remove.call(eventTarget, eventName, listenerWithMonitor, options))\n  }\n\n  return {\n    stop,\n  }\n}\n","import { addEventListener, DOM_EVENT } from '../../browser/addEventListener'\nimport type { Context } from '../../tools/serialisation/context'\nimport type { Configuration } from '../configuration'\nimport { combine } from '../../tools/mergeInto'\nimport type { ContextManager } from './contextManager'\nimport type { CustomerDataType } from './contextConstants'\n\nconst CONTEXT_STORE_KEY_PREFIX = '_dd_c'\n\nconst storageListeners: Array<{ stop: () => void }> = []\n\nexport function storeContextManager(\n  configuration: Configuration,\n  contextManager: ContextManager,\n  productKey: string,\n  customerDataType: CustomerDataType\n) {\n  const storageKey = buildStorageKey(productKey, customerDataType)\n\n  storageListeners.push(\n    addEventListener(configuration, window, DOM_EVENT.STORAGE, ({ key }) => {\n      if (storageKey === key) {\n        synchronizeWithStorage()\n      }\n    })\n  )\n  contextManager.changeObservable.subscribe(dumpToStorage)\n\n  contextManager.setContext(combine(getFromStorage(), contextManager.getContext()))\n\n  function synchronizeWithStorage() {\n    contextManager.setContext(getFromStorage())\n  }\n\n  function dumpToStorage() {\n    localStorage.setItem(storageKey, JSON.stringify(contextManager.getContext()))\n  }\n\n  function getFromStorage() {\n    const rawContext = localStorage.getItem(storageKey)\n    return rawContext !== null ? (JSON.parse(rawContext) as Context) : {}\n  }\n}\n\nexport function buildStorageKey(productKey: string, customerDataType: CustomerDataType) {\n  return `${CONTEXT_STORE_KEY_PREFIX}_${productKey}_${customerDataType}`\n}\n\nexport function removeStorageListeners() {\n  storageListeners.map((listener) => listener.stop())\n}\n","import { computeBytesCount } from './utils/byteUtils'\n\nexport interface Encoder<Output extends string | Uint8Array = string | Uint8Array> {\n  /**\n   * Whether this encoder might call the provided callbacks asynchronously\n   */\n  isAsync: boolean\n\n  /**\n   * Whether some data has been written since the last finish() or finishSync() call\n   */\n  isEmpty: boolean\n\n  /**\n   * Write a string to be encoded.\n   *\n   * This operation can be synchronous or asynchronous depending on the encoder implementation.\n   *\n   * If specified, the callback will be invoked when the operation finishes, unless the operation is\n   * asynchronous and finish() or finishSync() is called in the meantime.\n   */\n  write(data: string, callback?: (additionalEncodedBytesCount: number) => void): void\n\n  /**\n   * Waits for pending data to be encoded and resets the encoder state.\n   *\n   * This operation can be synchronous or asynchronous depending on the encoder implementation.\n   *\n   * The callback will be invoked when the operation finishes, unless the operation is asynchronous\n   * and another call to finish() or finishSync() occurs in the meantime.\n   */\n  finish(callback: (result: EncoderResult<Output>) => void): void\n\n  /**\n   * Resets the encoder state then returns the encoded data and any potential pending data directly,\n   * discarding all pending write operations and finish() callbacks.\n   */\n  finishSync(): EncoderResult<Output> & { pendingData: string }\n\n  /**\n   * Returns a rough estimation of the bytes count if the data was encoded.\n   */\n  estimateEncodedBytesCount(data: string): number\n}\n\nexport interface EncoderResult<Output extends string | Uint8Array = string | Uint8Array> {\n  output: Output\n  outputBytesCount: number\n\n  /**\n   * An encoding type supported by HTTP Content-Encoding, if applicable.\n   * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding#directives\n   */\n  encoding?: 'deflate'\n\n  /**\n   * Total bytes count of the input strings encoded to UTF-8.\n   */\n  rawBytesCount: number\n}\n\nexport function createIdentityEncoder(): Encoder<string> {\n  let output = ''\n  let outputBytesCount = 0\n\n  return {\n    isAsync: false,\n\n    get isEmpty() {\n      return !output\n    },\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\n    finish(callback) {\n      callback(this.finishSync())\n    },\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\n    estimateEncodedBytesCount(data) {\n      return data.length\n    },\n  }\n}\n","/**\n * Cross-browser stack trace computation.\n *\n * Reference implementation: https://github.com/csnover/TraceKit/blob/04530298073c3823de72deb0b97e7b38ca7bcb59/tracekit.js\n */\n\nimport { startsWith } from '../utils/polyfills'\n\nexport interface StackFrame {\n  url?: string\n  func?: string\n  /** The arguments passed to the function, if known. */\n  args?: string[]\n  line?: number\n  column?: number\n  /** An array of source code lines; the middle element corresponds to the correct line. */\n  context?: string[]\n}\n\nexport interface StackTrace {\n  name?: string\n  message?: string\n  url?: string\n  stack: StackFrame[]\n  incomplete?: boolean\n  partial?: boolean\n}\n\nconst UNKNOWN_FUNCTION = '?'\n\nexport function computeStackTrace(ex: unknown): StackTrace {\n  const stack: StackFrame[] = []\n\n  let stackProperty = tryToGetString(ex, 'stack')\n  const exString = String(ex)\n  if (stackProperty && startsWith(stackProperty, exString)) {\n    stackProperty = stackProperty.slice(exString.length)\n  }\n  if (stackProperty) {\n    stackProperty.split('\\n').forEach((line) => {\n      const stackFrame =\n        parseChromeLine(line) || parseChromeAnonymousLine(line) || parseWinLine(line) || parseGeckoLine(line)\n      if (stackFrame) {\n        if (!stackFrame.func && stackFrame.line) {\n          stackFrame.func = UNKNOWN_FUNCTION\n        }\n\n        stack.push(stackFrame)\n      }\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|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)'\nconst filePosition = '(?::(\\\\d+))'\nconst CHROME_LINE_RE = new RegExp(`^\\\\s*at (.*?) ?\\\\(${fileUrl}${filePosition}?${filePosition}?\\\\)?\\\\s*$`, 'i')\n\nconst CHROME_EVAL_RE = new RegExp(`\\\\((\\\\S*)${filePosition}${filePosition}\\\\)`)\n\nfunction parseChromeLine(line: string): StackFrame | undefined {\n  const parts = CHROME_LINE_RE.exec(line)\n\n  if (!parts) {\n    return\n  }\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\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\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}\n\nconst CHROME_ANONYMOUS_FUNCTION_RE = new RegExp(`^\\\\s*at ?${fileUrl}${filePosition}?${filePosition}??\\\\s*$`, 'i')\n\nfunction parseChromeAnonymousLine(line: string): StackFrame | undefined {\n  const parts = CHROME_ANONYMOUS_FUNCTION_RE.exec(line)\n\n  if (!parts) {\n    return\n  }\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}\n\nconst WINJS_LINE_RE =\n  /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i\n\nfunction parseWinLine(line: string): StackFrame | undefined {\n  const parts = WINJS_LINE_RE.exec(line)\n  if (!parts) {\n    return\n  }\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}\n\nconst GECKO_LINE_RE =\n  /^\\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\n\nfunction parseGeckoLine(line: string): StackFrame | undefined {\n  const parts = GECKO_LINE_RE.exec(line)\n  if (!parts) {\n    return\n  }\n\n  const isEval = parts[3] && parts[3].indexOf(' > eval') > -1\n  const submatch = GECKO_EVAL_RE.exec(parts[3])\n\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\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}\n\nfunction tryToGetString(candidate: unknown, property: string) {\n  if (typeof candidate !== 'object' || !candidate || !(property in candidate)) {\n    return undefined\n  }\n  const value = (candidate as { [k: string]: unknown })[property]\n  return typeof value === 'string' ? value : undefined\n}\n\nexport function computeStackTraceFromOnErrorMessage(messageObj: unknown, url?: string, line?: number, column?: number) {\n  const stack = [{ url, column, line }]\n  const { name, message } = tryToParseMessage(messageObj)\n  return {\n    name,\n    message,\n    stack,\n  }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types\nconst ERROR_TYPES_RE =\n  /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/\n\nfunction tryToParseMessage(messageObj: unknown) {\n  let name\n  let message\n  if ({}.toString.call(messageObj) === '[object String]') {\n    ;[, name, message] = ERROR_TYPES_RE.exec(messageObj as string)!\n  }\n  return { name, message }\n}\n","import { callMonitored } from '../monitor'\nimport { noop } from '../utils/functionUtils'\nimport type { StackTrace } from './computeStackTrace'\nimport { computeStackTrace } from './computeStackTrace'\n\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(): string {\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: string\n\n  // IE needs to throw the error to fill in the stack trace\n  if (!error.stack) {\n    try {\n      throw error\n    } catch (e) {\n      noop()\n    }\n  }\n\n  callMonitored(() => {\n    const stackTrace = computeStackTrace(error)\n    stackTrace.stack = stackTrace.stack.slice(internalFramesToSkip)\n    formattedStack = toStackTraceString(stackTrace)\n  })\n\n  return formattedStack!\n}\n\nexport function toStackTraceString(stack: StackTrace) {\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}\n\nexport function formatErrorMessage(stack: StackTrace) {\n  return `${stack.name || 'Error'}: ${stack.message!}`\n}\n","import { sanitize } from '../../tools/serialisation/sanitize'\nimport type { ClocksState } from '../../tools/utils/timeUtils'\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify'\nimport type { StackTrace } from '../../tools/stackTrace/computeStackTrace'\nimport { computeStackTrace } from '../../tools/stackTrace/computeStackTrace'\nimport { toStackTraceString } from '../../tools/stackTrace/handlingStack'\nimport type { ErrorSource, ErrorHandling, RawError, RawErrorCause, ErrorWithCause, NonErrorPrefix } from './error.types'\n\nexport const NO_ERROR_STACK_PRESENT_MESSAGE = 'No stack, consider using an instance of Error'\n\ntype RawErrorParams = {\n  stackTrace?: StackTrace\n  originalError: unknown\n\n  handlingStack?: string\n  startClocks: ClocksState\n  nonErrorPrefix: NonErrorPrefix\n  source: ErrorSource\n  handling: ErrorHandling\n}\n\nexport function computeRawError({\n  stackTrace,\n  originalError,\n  handlingStack,\n  startClocks,\n  nonErrorPrefix,\n  source,\n  handling,\n}: RawErrorParams): RawError {\n  const isErrorInstance = originalError instanceof Error\n\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 as ErrorWithCause, source) : undefined\n  const type = stackTrace ? stackTrace.name : undefined\n  const fingerprint = tryToGetFingerprint(originalError)\n\n  return {\n    startClocks,\n    source,\n    handling,\n    handlingStack,\n    originalError,\n    type,\n    message,\n    stack,\n    causes,\n    fingerprint,\n  }\n}\n\nfunction computeMessage(\n  stackTrace: StackTrace | undefined,\n  isErrorInstance: boolean,\n  nonErrorPrefix: NonErrorPrefix,\n  originalError: unknown\n) {\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?.message && stackTrace?.name\n    ? stackTrace.message\n    : !isErrorInstance\n      ? `${nonErrorPrefix} ${jsonStringify(sanitize(originalError))!}`\n      : 'Empty message'\n}\n\nfunction hasUsableStack(isErrorInstance: boolean, stackTrace?: StackTrace): stackTrace is 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}\n\nexport function tryToGetFingerprint(originalError: unknown) {\n  return originalError instanceof Error && 'dd_fingerprint' in originalError\n    ? String(originalError.dd_fingerprint)\n    : undefined\n}\n\nexport function getFileFromStackTraceString(stack: string) {\n  return /@ (.+)/.exec(stack)?.[1]\n}\n\nexport function flattenErrorCauses(error: ErrorWithCause, parentSource: ErrorSource): RawErrorCause[] | undefined {\n  let currentError = error\n  const causes: RawErrorCause[] = []\n  while (currentError?.cause instanceof Error && causes.length < 10) {\n    const stackTrace = computeStackTrace(currentError.cause)\n    causes.push({\n      message: currentError.cause.message,\n      source: parentSource,\n      type: stackTrace?.name,\n      stack: stackTrace && toStackTraceString(stackTrace),\n    })\n    currentError = currentError.cause\n  }\n  return causes.length ? causes : undefined\n}\n","/**\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\n\nimport { objectHasValue } from './utils/objectUtils'\n\n// eslint-disable-next-line no-restricted-syntax\nexport enum ExperimentalFeature {\n  WRITABLE_RESOURCE_GRAPHQL = 'writable_resource_graphql',\n  REMOTE_CONFIGURATION = 'remote_configuration',\n  UPDATE_VIEW_NAME = 'update_view_name',\n  LONG_ANIMATION_FRAME = 'long_animation_frame',\n  REDUCE_SEGMENT_LIMIT_BATCH_TIME = 'reduce_segment_limit_batch_time',\n}\n\nconst enabledExperimentalFeatures: Set<ExperimentalFeature> = new Set()\n\nexport function initFeatureFlags(enableExperimentalFeatures?: string[] | undefined) {\n  if (Array.isArray(enableExperimentalFeatures)) {\n    addExperimentalFeatures(\n      enableExperimentalFeatures.filter((flag): flag is ExperimentalFeature =>\n        objectHasValue(ExperimentalFeature, flag)\n      )\n    )\n  }\n}\n\nexport function addExperimentalFeatures(enabledFeatures: ExperimentalFeature[]): void {\n  enabledFeatures.forEach((flag) => {\n    enabledExperimentalFeatures.add(flag)\n  })\n}\n\nexport function isExperimentalFeatureEnabled(featureName: ExperimentalFeature): boolean {\n  return enabledExperimentalFeatures.has(featureName)\n}\n\nexport function resetExperimentalFeatures(): void {\n  enabledExperimentalFeatures.clear()\n}\n\nexport function getExperimentalFeatures(): Set<ExperimentalFeature> {\n  return enabledExperimentalFeatures\n}\n","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'\n\nexport const PCI_INTAKE_HOST_US1 = 'pci.browser-intake-datadoghq.com'\n","/**\n * Return true if the draw is successful\n * @param threshold between 0 and 100\n */\nexport function performDraw(threshold: number): boolean {\n  return threshold !== 0 && Math.random() * 100 <= threshold\n}\n\nexport function round(num: number, decimals: 0 | 1 | 2 | 3 | 4) {\n  return +num.toFixed(decimals)\n}\n\nexport function isPercentage(value: unknown) {\n  return isNumber(value) && value >= 0 && value <= 100\n}\n\nexport function isNumber(value: unknown): value is number {\n  return typeof value === 'number'\n}\n","import { isNumber, round } from './numberUtils'\n\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\n\nexport type Duration = number & { d: 'Duration in ms' }\nexport type ServerDuration = number & { s: 'Duration in ns' }\nexport type TimeStamp = number & { t: 'Epoch time' }\nexport type RelativeTime = number & { r: 'Time relative to navigation start' } & { d: 'Duration in ms' }\nexport type ClocksState = { relative: RelativeTime; timeStamp: TimeStamp }\n\nexport function relativeToClocks(relative: RelativeTime) {\n  return { relative, timeStamp: getCorrectedTimeStamp(relative) }\n}\n\nexport function timeStampToClocks(timeStamp: TimeStamp) {\n  return { relative: getRelativeTime(timeStamp), timeStamp }\n}\n\nfunction getCorrectedTimeStamp(relativeTime: RelativeTime) {\n  const correctedOrigin = (dateNow() - performance.now()) as TimeStamp\n  // apply correction only for positive drift\n  if (correctedOrigin > getNavigationStart()) {\n    return Math.round(addDuration(correctedOrigin, relativeTime)) as TimeStamp\n  }\n  return getTimeStamp(relativeTime)\n}\n\nexport function currentDrift() {\n  return Math.round(dateNow() - addDuration(getNavigationStart(), performance.now() as Duration))\n}\n\nexport function toServerDuration(duration: Duration): ServerDuration\nexport function toServerDuration(duration: Duration | undefined): ServerDuration | undefined\nexport function toServerDuration(duration: Duration | undefined) {\n  if (!isNumber(duration)) {\n    return duration\n  }\n  return round(duration * 1e6, 0) as ServerDuration\n}\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}\n\nexport function timeStampNow() {\n  return dateNow() as TimeStamp\n}\n\nexport function relativeNow() {\n  return performance.now() as RelativeTime\n}\n\nexport function clocksNow() {\n  return { relative: relativeNow(), timeStamp: timeStampNow() }\n}\n\nexport function clocksOrigin() {\n  return { relative: 0 as RelativeTime, timeStamp: getNavigationStart() }\n}\n\nexport function elapsed(start: TimeStamp, end: TimeStamp): Duration\nexport function elapsed(start: RelativeTime, end: RelativeTime): Duration\nexport function elapsed(start: number, end: number) {\n  return (end - start) as Duration\n}\n\nexport function addDuration(a: TimeStamp, b: Duration): TimeStamp\nexport function addDuration(a: RelativeTime, b: Duration): RelativeTime\nexport function addDuration(a: Duration, b: Duration): Duration\nexport function addDuration(a: number, b: number) {\n  return a + b\n}\n\n/**\n * Get the time since the navigation was started.\n *\n * Note: this does not use `performance.timeOrigin` because it doesn't seem to reflect the actual\n * time on which the navigation has started: it may be much farther in the past, at least in Firefox 71.\n * Related issue in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1429926\n */\nexport function getRelativeTime(timestamp: TimeStamp) {\n  return (timestamp - getNavigationStart()) as RelativeTime\n}\n\nexport function getTimeStamp(relativeTime: RelativeTime) {\n  return Math.round(addDuration(getNavigationStart(), relativeTime)) as TimeStamp\n}\n\nexport function looksLikeRelativeTime(time: RelativeTime | TimeStamp): time is RelativeTime {\n  return time < ONE_YEAR\n}\n\n/**\n * Navigation start slightly change on some rare cases\n */\nlet navigationStart: TimeStamp | undefined\n\nfunction getNavigationStart() {\n  if (navigationStart === undefined) {\n    navigationStart = performance.timing.navigationStart as TimeStamp\n  }\n  return navigationStart\n}\n","interface BrowserWindow {\n  __ddBrowserSdkExtensionCallback?: (message: unknown) => void\n}\n\ntype ExtensionMessageType = 'logs' | 'record' | 'rum' | 'telemetry'\n\nexport function sendToExtension(type: ExtensionMessageType, payload: unknown) {\n  const callback = (window as BrowserWindow).__ddBrowserSdkExtensionCallback\n  if (callback) {\n    callback({ type, payload })\n  }\n}\n","export type NetworkInterface = 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown'\nexport type EffectiveType = 'slow-2g' | '2g' | '3g' | '4g'\n\ninterface BrowserNavigator extends Navigator {\n  connection?: NetworkInformation\n}\n\nexport interface NetworkInformation {\n  type?: NetworkInterface\n  effectiveType?: EffectiveType\n}\n\nexport interface Connectivity {\n  status: 'connected' | 'not_connected'\n  interfaces?: NetworkInterface[]\n  effective_type?: EffectiveType\n  [key: string]: unknown\n}\n\nexport function getConnectivity(): Connectivity {\n  const navigator = window.navigator as BrowserNavigator\n  return {\n    status: navigator.onLine ? 'connected' : 'not_connected',\n    interfaces: navigator.connection && navigator.connection.type ? [navigator.connection.type] : undefined,\n    effective_type: navigator.connection?.effectiveType,\n  }\n}\n","import { arrayFrom } from './polyfills'\n\nexport function removeDuplicates<T>(array: T[]) {\n  const set = new Set<T>()\n  array.forEach((item) => set.add(item))\n  return arrayFrom(set)\n}\n\nexport function removeItem<T>(array: T[], item: T) {\n  const index = array.indexOf(item)\n  if (index >= 0) {\n    array.splice(index, 1)\n  }\n}\n","import { removeItem } from './utils/arrayUtils'\n\nconst BUFFER_LIMIT = 500\n\nexport interface BoundedBuffer<T = void> {\n  add: (callback: (arg: T) => void) => void\n  remove: (callback: (arg: T) => void) => void\n  drain: (arg: T) => void\n}\n\nexport function createBoundedBuffer<T = void>(): BoundedBuffer<T> {\n  const buffer: Array<(arg: T) => void> = []\n\n  const add: BoundedBuffer<T>['add'] = (callback: (arg: T) => void) => {\n    const length = buffer.push(callback)\n    if (length > BUFFER_LIMIT) {\n      buffer.splice(0, 1)\n    }\n  }\n\n  const remove: BoundedBuffer<T>['remove'] = (callback: (arg: T) => void) => {\n    removeItem(buffer, callback)\n  }\n\n  const drain = (arg: T) => {\n    buffer.forEach((callback) => callback(arg))\n    buffer.length = 0\n  }\n\n  return {\n    add,\n    remove,\n    drain,\n  }\n}\n","import type { TelemetryEvent, TelemetryConfigurationEvent, TelemetryUsageEvent } from './telemetryEvent.types'\n\nexport const TelemetryType = {\n  log: 'log',\n  configuration: 'configuration',\n  usage: 'usage',\n} as const\n\nexport const enum StatusType {\n  debug = 'debug',\n  error = 'error',\n}\n\nexport interface RuntimeEnvInfo {\n  is_local_file: boolean\n  is_worker: boolean\n}\n\nexport type RawTelemetryEvent = TelemetryEvent['telemetry']\nexport type RawTelemetryConfiguration = TelemetryConfigurationEvent['telemetry']['configuration']\nexport type RawTelemetryUsage = TelemetryUsageEvent['telemetry']['usage']\n","import type { Context } from '../../tools/serialisation/context'\nimport { ConsoleApiName } from '../../tools/display'\nimport { NO_ERROR_STACK_PRESENT_MESSAGE } from '../error/error'\nimport { toStackTraceString } from '../../tools/stackTrace/handlingStack'\nimport { getExperimentalFeatures } from '../../tools/experimentalFeatures'\nimport type { Configuration } from '../configuration'\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 { startsWith, arrayFrom, includes, assign } from '../../tools/utils/polyfills'\nimport { performDraw } from '../../tools/utils/numberUtils'\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify'\nimport { combine } from '../../tools/mergeInto'\nimport { NonErrorPrefix } from '../error/error.types'\nimport type { StackTrace } from '../../tools/stackTrace/computeStackTrace'\nimport { computeStackTrace } from '../../tools/stackTrace/computeStackTrace'\nimport { getConnectivity } from '../connectivity'\nimport { createBoundedBuffer } from '../../tools/boundedBuffer'\nimport type { TelemetryEvent } from './telemetryEvent.types'\nimport type {\n  RawTelemetryConfiguration,\n  RawTelemetryEvent,\n  RuntimeEnvInfo,\n  RawTelemetryUsage,\n} from './rawTelemetryEvent.types'\nimport { StatusType, TelemetryType } from './rawTelemetryEvent.types'\n\n// replaced at build time\ndeclare const __BUILD_ENV__SDK_VERSION__: string\ndeclare const __BUILD_ENV__SDK_SETUP__: string\n\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]\n\nexport const enum TelemetryService {\n  LOGS = 'browser-logs-sdk',\n  RUM = 'browser-rum-sdk',\n}\n\nexport interface Telemetry {\n  setContextProvider: (provider: () => Context) => void\n  observable: Observable<TelemetryEvent & Context>\n  enabled: boolean\n}\n\nconst TELEMETRY_EXCLUDED_SITES: string[] = [INTAKE_SITE_US1_FED]\n\n// eslint-disable-next-line local-rules/disallow-side-effects\nlet preStartTelemetryBuffer = createBoundedBuffer()\nlet onRawTelemetryEventCollected = (event: RawTelemetryEvent) => {\n  preStartTelemetryBuffer.add(() => onRawTelemetryEventCollected(event))\n}\n\nexport function startTelemetry(telemetryService: TelemetryService, configuration: Configuration): Telemetry {\n  let contextProvider: () => Context\n  const observable = new Observable<TelemetryEvent & Context>()\n  const alreadySentEvents = new Set<string>()\n\n  const telemetryEnabled =\n    !includes(TELEMETRY_EXCLUDED_SITES, configuration.site) && performDraw(configuration.telemetrySampleRate)\n\n  const telemetryEnabledPerType = {\n    [TelemetryType.log]: telemetryEnabled,\n    [TelemetryType.configuration]: telemetryEnabled && performDraw(configuration.telemetryConfigurationSampleRate),\n    [TelemetryType.usage]: telemetryEnabled && performDraw(configuration.telemetryUsageSampleRate),\n  }\n\n  const runtimeEnvInfo = getRuntimeEnvInfo()\n  onRawTelemetryEventCollected = (rawEvent: RawTelemetryEvent) => {\n    const stringifiedEvent = jsonStringify(rawEvent)!\n    if (\n      telemetryEnabledPerType[rawEvent.type!] &&\n      alreadySentEvents.size < configuration.maxTelemetryEventsPerPage &&\n      !alreadySentEvents.has(stringifiedEvent)\n    ) {\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\n  function toTelemetryEvent(\n    telemetryService: TelemetryService,\n    event: RawTelemetryEvent,\n    runtimeEnvInfo: RuntimeEnvInfo\n  ): TelemetryEvent & Context {\n    return combine(\n      {\n        type: 'telemetry' as const,\n        date: timeStampNow(),\n        service: telemetryService,\n        version: __BUILD_ENV__SDK_VERSION__,\n        source: 'browser' as const,\n        _dd: {\n          format_version: 2 as const,\n        },\n        telemetry: combine(event, {\n          runtime_env: runtimeEnvInfo,\n          connectivity: getConnectivity(),\n          sdk_setup: __BUILD_ENV__SDK_SETUP__,\n        }),\n        experimental_features: arrayFrom(getExperimentalFeatures()),\n      },\n      contextProvider !== undefined ? contextProvider() : {}\n    ) as TelemetryEvent & Context\n  }\n\n  return {\n    setContextProvider: (provider: () => Context) => {\n      contextProvider = provider\n    },\n    observable,\n    enabled: telemetryEnabled,\n  }\n}\nfunction getRuntimeEnvInfo(): RuntimeEnvInfo {\n  return {\n    is_local_file: window.location.protocol === 'file:',\n    is_worker: 'WorkerGlobalScope' in self,\n  }\n}\n\nexport function startFakeTelemetry() {\n  const events: RawTelemetryEvent[] = []\n\n  onRawTelemetryEventCollected = (event: RawTelemetryEvent) => {\n    events.push(event)\n  }\n\n  return events\n}\n\n// need to be called after telemetry context is provided and observers are registered\nexport function drainPreStartTelemetry() {\n  preStartTelemetryBuffer.drain()\n}\n\nexport function resetTelemetry() {\n  preStartTelemetryBuffer = createBoundedBuffer()\n  onRawTelemetryEventCollected = (event: RawTelemetryEvent) => {\n    preStartTelemetryBuffer.add(() => onRawTelemetryEventCollected(event))\n  }\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: Configuration) {\n  return configuration.site === INTAKE_SITE_STAGING\n}\n\nexport function addTelemetryDebug(message: string, context?: Context) {\n  displayIfDebugEnabled(ConsoleApiName.debug, message, context)\n  onRawTelemetryEventCollected(\n    assign(\n      {\n        type: TelemetryType.log,\n        message,\n        status: StatusType.debug,\n      },\n      context\n    )\n  )\n}\n\nexport function addTelemetryError(e: unknown, context?: Context) {\n  onRawTelemetryEventCollected(\n    assign(\n      {\n        type: TelemetryType.log,\n        status: StatusType.error,\n      },\n      formatError(e),\n      context\n    )\n  )\n}\n\nexport function addTelemetryConfiguration(configuration: RawTelemetryConfiguration) {\n  onRawTelemetryEventCollected({\n    type: TelemetryType.configuration,\n    configuration,\n  })\n}\n\nexport function addTelemetryUsage(usage: RawTelemetryUsage) {\n  onRawTelemetryEventCollected({\n    type: TelemetryType.usage,\n    usage,\n  })\n}\n\nexport function formatError(e: unknown) {\n  if (e instanceof Error) {\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: `${NonErrorPrefix.UNCAUGHT} ${jsonStringify(e)!}`,\n  }\n}\n\nexport function scrubCustomerFrames(stackTrace: StackTrace) {\n  stackTrace.stack = stackTrace.stack.filter(\n    (frame) => !frame.url || ALLOWED_FRAME_URLS.some((allowedFrameUrl) => startsWith(frame.url!, allowedFrameUrl))\n  )\n  return stackTrace\n}\n","import type { Context } from '../../tools/serialisation/context'\nimport { display } from '../../tools/display'\nimport { getType } from '../../tools/utils/typeUtils'\nimport { assign } from '../../tools/utils/polyfills'\nimport type { User } from './user.types'\n\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: Context): Context {\n  // We shallow clone only to prevent mutation of user data.\n  const user = assign({}, newUser)\n  const keys = ['id', 'name', 'email']\n  keys.forEach((key) => {\n    if (key in user) {\n      user[key] = String(user[key])\n    }\n  })\n  return user\n}\n\n/**\n * Simple check to ensure user is valid\n */\nexport function checkUser(newUser: User): boolean {\n  const isValid = getType(newUser) === 'object'\n  if (!isValid) {\n    display.error('Unsupported user:', newUser)\n  }\n  return isValid\n}\n","import type { InitConfiguration } from '../domain/configuration'\nimport { display } from '../tools/display'\n\nexport function displayAlreadyInitializedError(sdkName: 'DD_RUM' | 'DD_LOGS', initConfiguration: InitConfiguration) {\n  if (!initConfiguration.silentMultipleInit) {\n    display.error(`${sdkName} is already initialized.`)\n  }\n}\n","/**\n * UUID v4\n * from https://gist.github.com/jed/982883\n */\nexport function generateUUID(placeholder?: string): string {\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}\n\nconst COMMA_SEPARATED_KEY_VALUE = /([\\w-]+)\\s*=\\s*([^;]+)/g\n\nexport function findCommaSeparatedValue(rawString: string, name: string): string | undefined {\n  COMMA_SEPARATED_KEY_VALUE.lastIndex = 0\n  // eslint-disable-next-line no-constant-condition\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    } else {\n      break\n    }\n  }\n}\n\nexport function findCommaSeparatedValues(rawString: string): Map<string, string> {\n  const result = new Map<string, string>()\n  COMMA_SEPARATED_KEY_VALUE.lastIndex = 0\n  // eslint-disable-next-line no-constant-condition\n  while (true) {\n    const match = COMMA_SEPARATED_KEY_VALUE.exec(rawString)\n    if (match) {\n      result.set(match[1], match[2])\n    } else {\n      break\n    }\n  }\n  return result\n}\n\nexport function safeTruncate(candidate: string, length: number, suffix = '') {\n  const lastChar = candidate.charCodeAt(length - 1)\n  const isLastCharSurrogatePair = lastChar >= 0xd800 && lastChar <= 0xdbff\n  const correctedLength = isLastCharSurrogatePair ? length + 1 : length\n\n  if (candidate.length <= correctedLength) {\n    return candidate\n  }\n\n  return `${candidate.slice(0, correctedLength)}${suffix}`\n}\n","import type { ClocksState, Duration, Context } from '@datadog/browser-core'\nimport { clocksNow, combine, elapsed, generateUUID, toServerDuration } from '@datadog/browser-core'\nimport type { LifeCycle, RawRumEventCollectedData } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport type { RawRumVitalEvent } from '../../rawRumEvent.types'\nimport { RumEventType, VitalType } from '../../rawRumEvent.types'\nimport type { PageStateHistory } from '../contexts/pageStateHistory'\nimport { PageState } from '../contexts/pageStateHistory'\n\nexport interface DurationVitalOptions {\n  context?: Context\n  description?: string\n}\n\nexport interface DurationVitalReference {\n  __dd_vital_reference: true\n}\n\nexport interface DurationVitalStart {\n  name: string\n  startClocks: ClocksState\n  context?: Context\n  description?: string\n}\n\nexport interface DurationVital {\n  name: string\n  type: VitalType.DURATION\n  startClocks: ClocksState\n  duration: Duration\n  description?: string\n  context?: Context\n}\n\nexport interface CustomVitalsState {\n  vitalsByName: Map<string, DurationVitalStart>\n  vitalsByReference: WeakMap<DurationVitalReference, DurationVitalStart>\n}\n\nexport function createCustomVitalsState() {\n  const vitalsByName = new Map<string, DurationVitalStart>()\n  const vitalsByReference = new WeakMap<DurationVitalReference, DurationVitalStart>()\n  return { vitalsByName, vitalsByReference }\n}\n\nexport function startVitalCollection(\n  lifeCycle: LifeCycle,\n  pageStateHistory: PageStateHistory,\n  customVitalsState: CustomVitalsState\n) {\n  function isValid(vital: DurationVital) {\n    return !pageStateHistory.wasInPageStateDuringPeriod(PageState.FROZEN, vital.startClocks.relative, vital.duration)\n  }\n\n  function addDurationVital(vital: DurationVital) {\n    if (isValid(vital)) {\n      lifeCycle.notify(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, processVital(vital, true))\n    }\n  }\n\n  return {\n    addDurationVital,\n    startDurationVital: (name: string, options: DurationVitalOptions = {}) =>\n      startDurationVital(customVitalsState, name, options),\n    stopDurationVital: (nameOrRef: string | DurationVitalReference, options: DurationVitalOptions = {}) => {\n      stopDurationVital(addDurationVital, customVitalsState, nameOrRef, options)\n    },\n  }\n}\n\nexport function startDurationVital(\n  { vitalsByName, vitalsByReference }: CustomVitalsState,\n  name: string,\n  options: DurationVitalOptions = {}\n) {\n  const vital = {\n    name,\n    startClocks: clocksNow(),\n    context: options.context,\n    description: options.description,\n  }\n\n  // To avoid leaking implementation details of the vital, we return a reference to it.\n  const reference: DurationVitalReference = { __dd_vital_reference: true }\n\n  vitalsByName.set(name, vital)\n\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\n  return reference\n}\n\nexport function stopDurationVital(\n  stopCallback: (vital: DurationVital) => void,\n  { vitalsByName, vitalsByReference }: CustomVitalsState,\n  nameOrRef: string | DurationVitalReference,\n  options: DurationVitalOptions = {}\n) {\n  const vitalStart = typeof nameOrRef === 'string' ? vitalsByName.get(nameOrRef) : vitalsByReference.get(nameOrRef)\n\n  if (!vitalStart) {\n    return\n  }\n\n  stopCallback(buildDurationVital(vitalStart, vitalStart.startClocks, options, clocksNow()))\n\n  if (typeof nameOrRef === 'string') {\n    vitalsByName.delete(nameOrRef)\n  } else {\n    vitalsByReference.delete(nameOrRef)\n  }\n}\n\nfunction buildDurationVital(\n  vitalStart: DurationVitalStart,\n  startClocks: ClocksState,\n  stopOptions: DurationVitalOptions,\n  stopClocks: ClocksState\n): DurationVital {\n  return {\n    name: vitalStart.name,\n    type: VitalType.DURATION,\n    startClocks,\n    duration: elapsed(startClocks.timeStamp, stopClocks.timeStamp),\n    context: combine(vitalStart.context, stopOptions.context),\n    description: stopOptions.description ?? vitalStart.description,\n  }\n}\n\nfunction processVital(vital: DurationVital, valueComputedBySdk: boolean): RawRumEventCollectedData<RawRumVitalEvent> {\n  const rawRumEvent: RawRumVitalEvent = {\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: RumEventType.VITAL,\n  }\n\n  if (valueComputedBySdk) {\n    rawRumEvent._dd = {\n      vital: {\n        computed_value: true,\n      },\n    }\n  }\n\n  return {\n    rawRumEvent,\n    startTime: vital.startClocks.relative,\n    customerContext: vital.context,\n    domainContext: {},\n  }\n}\n","import { endsWith, includes } from '../tools/utils/polyfills'\nimport { getGlobalObject } from '../tools/getGlobalObject'\nimport type { DefaultPrivacyLevel } from '../domain/configuration'\n\nexport interface BrowserWindowWithEventBridge extends Window {\n  DatadogEventBridge?: DatadogEventBridge\n}\n\nexport interface DatadogEventBridge {\n  getCapabilities?(): string\n  getPrivacyLevel?(): DefaultPrivacyLevel\n  getAllowedWebViewHosts(): string\n  send(msg: string): void\n}\n\nexport const enum BridgeCapability {\n  RECORDS = 'records',\n}\n\nexport function getEventBridge<T, E>() {\n  const eventBridgeGlobal = getEventBridgeGlobal()\n\n  if (!eventBridgeGlobal) {\n    return\n  }\n\n  return {\n    getCapabilities() {\n      return JSON.parse(eventBridgeGlobal.getCapabilities?.() || '[]') as BridgeCapability[]\n    },\n    getPrivacyLevel() {\n      return eventBridgeGlobal.getPrivacyLevel?.()\n    },\n    getAllowedWebViewHosts() {\n      return JSON.parse(eventBridgeGlobal.getAllowedWebViewHosts()) as string[]\n    },\n    send(eventType: T, event: E, viewId?: string) {\n      const view = viewId ? { id: viewId } : undefined\n      eventBridgeGlobal.send(JSON.stringify({ eventType, event, view }))\n    },\n  }\n}\n\nexport function bridgeSupports(capability: BridgeCapability): boolean {\n  const bridge = getEventBridge()\n  return !!bridge && includes(bridge.getCapabilities(), capability)\n}\n\nexport function canUseEventBridge(currentHost = getGlobalObject<Window>().location?.hostname): boolean {\n  const bridge = getEventBridge()\n  return (\n    !!bridge &&\n    bridge\n      .getAllowedWebViewHosts()\n      .some((allowedHost) => currentHost === allowedHost || endsWith(currentHost, `.${allowedHost}`))\n  )\n}\n\nfunction getEventBridgeGlobal() {\n  return getGlobalObject<BrowserWindowWithEventBridge>().DatadogEventBridge\n}\n","import { setTimeout } from './timer'\nimport { callMonitored } from './monitor'\nimport { noop } from './utils/functionUtils'\nimport { arrayFrom, startsWith } from './utils/polyfills'\nimport { createHandlingStack } from './stackTrace/handlingStack'\n\n/**\n * Object passed to the callback of an instrumented method call. See `instrumentMethod` for more\n * info.\n */\nexport type InstrumentedMethodCall<TARGET extends { [key: string]: any }, METHOD extends keyof TARGET> = {\n  /**\n   * The target object on which the method was called.\n   */\n  target: TARGET\n\n  /**\n   * The parameters with which the method was called.\n   *\n   * Note: if needed, parameters can be mutated by the instrumentation\n   */\n  parameters: Parameters<TARGET[METHOD]>\n\n  /**\n   * Registers a callback that will be called after the original method is called, with the method\n   * result passed as argument.\n   */\n  onPostCall: (callback: PostCallCallback<TARGET, METHOD>) => void\n\n  /**\n   * The stack trace of the method call.\n   */\n  handlingStack?: string\n}\n\ntype PostCallCallback<TARGET extends { [key: string]: any }, METHOD extends keyof TARGET> = (\n  result: ReturnType<TARGET[METHOD]>\n) => void\n\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<TARGET extends { [key: string]: any }, METHOD extends keyof TARGET & string>(\n  targetPrototype: TARGET,\n  method: METHOD,\n  onPreCall: (this: null, callInfos: InstrumentedMethodCall<TARGET, METHOD>) => void,\n  { computeHandlingStack }: { computeHandlingStack?: boolean } = {}\n) {\n  let original = targetPrototype[method]\n\n  if (typeof original !== 'function') {\n    if (method in targetPrototype && startsWith(method, 'on')) {\n      original = noop as TARGET[METHOD]\n    } else {\n      return { stop: noop }\n    }\n  }\n\n  let stopped = false\n\n  const instrumentation = function (this: TARGET): ReturnType<TARGET[METHOD]> | undefined {\n    if (stopped) {\n      // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call\n      return original.apply(this, arguments as unknown as Parameters<TARGET[METHOD]>)\n    }\n\n    const parameters = arrayFrom(arguments) as Parameters<TARGET[METHOD]>\n\n    let postCallCallback: PostCallCallback<TARGET, METHOD> | undefined\n\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\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n    const result = original.apply(this, parameters)\n\n    if (postCallCallback) {\n      callMonitored(postCallCallback, null, [result])\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n    return result\n  }\n\n  targetPrototype[method] = instrumentation as TARGET[METHOD]\n\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}\n\nexport function instrumentSetter<TARGET extends { [key: string]: any }, PROPERTY extends keyof TARGET>(\n  targetPrototype: TARGET,\n  property: PROPERTY,\n  after: (target: TARGET, value: TARGET[PROPERTY]) => void\n) {\n  const originalDescriptor = Object.getOwnPropertyDescriptor(targetPrototype, property)\n  if (!originalDescriptor || !originalDescriptor.set || !originalDescriptor.configurable) {\n    return { stop: noop }\n  }\n\n  const stoppedInstrumentation = noop\n  let instrumentation = (target: TARGET, value: TARGET[PROPERTY]) => {\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\n  const instrumentationWrapper = function (this: TARGET, value: TARGET[PROPERTY]) {\n    originalDescriptor.set!.call(this, value)\n    instrumentation(this, value)\n  }\n\n  Object.defineProperty(targetPrototype, property, {\n    set: instrumentationWrapper,\n  })\n\n  return {\n    stop: () => {\n      if (Object.getOwnPropertyDescriptor(targetPrototype, property)?.set === instrumentationWrapper) {\n        Object.defineProperty(targetPrototype, property, originalDescriptor)\n      }\n      instrumentation = stoppedInstrumentation\n    },\n  }\n}\n","import { jsonStringify } from '../serialisation/jsonStringify'\n\nexport function normalizeUrl(url: string) {\n  return buildUrl(url, location.href).href\n}\n\nexport function isValidUrl(url: string) {\n  try {\n    return !!buildUrl(url)\n  } catch {\n    return false\n  }\n}\n\nexport function getPathName(url: string) {\n  const pathname = buildUrl(url).pathname\n  return pathname[0] === '/' ? pathname : `/${pathname}`\n}\n\nexport function buildUrl(url: string, base?: string) {\n  const supportedURL = getSupportedUrl()\n  if (supportedURL) {\n    try {\n      return base !== undefined ? new supportedURL(url, base) : new supportedURL(url)\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}\n\nconst originalURL = URL\nlet isURLSupported: boolean | undefined\nfunction getSupportedUrl(): typeof URL | undefined {\n  if (isURLSupported === undefined) {\n    try {\n      const url = new originalURL('http://test/path')\n      isURLSupported = url.href === 'http://test/path'\n    } catch {\n      isURLSupported = false\n    }\n  }\n  return isURLSupported ? originalURL : undefined\n}\n","import type { InstrumentedMethodCall } from '../tools/instrumentMethod'\nimport { instrumentMethod } from '../tools/instrumentMethod'\nimport { monitor } from '../tools/monitor'\nimport { Observable } from '../tools/observable'\nimport { assign } from '../tools/utils/polyfills'\nimport type { ClocksState } from '../tools/utils/timeUtils'\nimport { clocksNow } from '../tools/utils/timeUtils'\nimport { normalizeUrl } from '../tools/utils/urlPolyfill'\n\ninterface FetchContextBase {\n  method: string\n  startClocks: ClocksState\n  input: unknown\n  init?: RequestInit\n  url: string\n  handlingStack?: string\n}\n\nexport interface FetchStartContext extends FetchContextBase {\n  state: 'start'\n}\n\nexport interface FetchResolveContext extends FetchContextBase {\n  state: 'resolve'\n  status: number\n  response?: Response\n  responseType?: string\n  isAborted: boolean\n  error?: Error\n}\n\nexport type FetchContext = FetchStartContext | FetchResolveContext\n\nlet fetchObservable: Observable<FetchContext> | undefined\n\nexport function initFetchObservable() {\n  if (!fetchObservable) {\n    fetchObservable = createFetchObservable()\n  }\n  return fetchObservable\n}\n\nexport function resetFetchObservable() {\n  fetchObservable = undefined\n}\n\nfunction createFetchObservable() {\n  return new Observable<FetchContext>((observable) => {\n    if (!window.fetch) {\n      return\n    }\n\n    const { stop } = instrumentMethod(window, 'fetch', (call) => beforeSend(call, observable), {\n      computeHandlingStack: true,\n    })\n\n    return stop\n  })\n}\n\nfunction beforeSend(\n  { parameters, onPostCall, handlingStack }: InstrumentedMethodCall<Window, 'fetch'>,\n  observable: Observable<FetchContext>\n) {\n  const [input, init] = parameters\n  let methodFromParams = init && init.method\n\n  if (methodFromParams === undefined && input instanceof Request) {\n    methodFromParams = input.method\n  }\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\n  const context: FetchStartContext = {\n    state: 'start',\n    init,\n    input,\n    method,\n    startClocks,\n    url,\n    handlingStack,\n  }\n\n  observable.notify(context)\n\n  // Those properties can be changed by observable subscribers\n  parameters[0] = context.input as RequestInfo | URL\n  parameters[1] = context.init\n\n  onPostCall((responsePromise) => afterSend(observable, responsePromise, context))\n}\n\nfunction afterSend(\n  observable: Observable<FetchContext>,\n  responsePromise: Promise<Response>,\n  startContext: FetchStartContext\n) {\n  const context = startContext as unknown as FetchResolveContext\n\n  function reportFetch(partialContext: Partial<FetchResolveContext>) {\n    context.state = 'resolve'\n    assign(context, partialContext)\n    observable.notify(context)\n  }\n\n  responsePromise.then(\n    monitor((response) => {\n      reportFetch({\n        response,\n        responseType: response.type,\n        status: response.status,\n        isAborted: false,\n      })\n    }),\n    monitor((error: Error) => {\n      reportFetch({\n        status: 0,\n        isAborted:\n          context.init?.signal?.aborted || (error instanceof DOMException && error.code === DOMException.ABORT_ERR),\n        error,\n      })\n    })\n  )\n}\n","import { display } from '../tools/display'\nimport { ONE_MINUTE, ONE_SECOND } from '../tools/utils/timeUtils'\nimport { findCommaSeparatedValue, findCommaSeparatedValues, generateUUID } from '../tools/utils/stringUtils'\n\nexport interface CookieOptions {\n  secure?: boolean\n  crossSite?: boolean\n  partitioned?: boolean\n  domain?: string\n}\n\nexport function setCookie(name: string, value: string, expireDelay: number, options?: CookieOptions) {\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}\n\nexport function getCookie(name: string) {\n  return findCommaSeparatedValue(document.cookie, name)\n}\n\nlet initCookieParsed: Map<string, string> | undefined\n\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: string) {\n  if (!initCookieParsed) {\n    initCookieParsed = findCommaSeparatedValues(document.cookie)\n  }\n  return initCookieParsed.get(name)\n}\n\nexport function resetInitCookies() {\n  initCookieParsed = undefined\n}\n\nexport function deleteCookie(name: string, options?: CookieOptions) {\n  setCookie(name, '', 0, options)\n}\n\nexport function areCookiesAuthorized(options: CookieOptions): boolean {\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  } catch (error) {\n    display.error(error)\n    return false\n  }\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: string | undefined\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\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","import { getInitCookie } from '../../browser/cookie'\n\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'\n\nexport interface BrowserWindow extends Window {\n  _DATADOG_SYNTHETICS_PUBLIC_ID?: unknown\n  _DATADOG_SYNTHETICS_RESULT_ID?: unknown\n  _DATADOG_SYNTHETICS_INJECTS_RUM?: unknown\n}\n\nexport function willSyntheticsInjectRum(): boolean {\n  return Boolean(\n    (window as BrowserWindow)._DATADOG_SYNTHETICS_INJECTS_RUM || getInitCookie(SYNTHETICS_INJECTS_RUM_COOKIE_NAME)\n  )\n}\n\nexport function getSyntheticsTestId(): string | undefined {\n  const value = (window as BrowserWindow)._DATADOG_SYNTHETICS_PUBLIC_ID || getInitCookie(SYNTHETICS_TEST_ID_COOKIE_NAME)\n  return typeof value === 'string' ? value : undefined\n}\n\nexport function getSyntheticsResultId(): string | undefined {\n  const value =\n    (window as BrowserWindow)._DATADOG_SYNTHETICS_RESULT_ID || getInitCookie(SYNTHETICS_RESULT_ID_COOKIE_NAME)\n  return typeof value === 'string' ? value : undefined\n}\n","// Exported only for tests\nexport const enum Browser {\n  IE,\n  CHROMIUM,\n  SAFARI,\n  OTHER,\n}\n\nexport function isIE() {\n  return detectBrowserCached() === Browser.IE\n}\n\nexport function isChromium() {\n  return detectBrowserCached() === Browser.CHROMIUM\n}\n\nexport function isSafari() {\n  return detectBrowserCached() === Browser.SAFARI\n}\n\nlet browserCache: Browser | undefined\nfunction detectBrowserCached() {\n  return browserCache ?? (browserCache = detectBrowser())\n}\n\n// Exported only for tests\nexport function detectBrowser(browserWindow: Window = window) {\n  const userAgent = browserWindow.navigator.userAgent\n  if ((browserWindow as any).chrome || /HeadlessChrome/.test(userAgent)) {\n    return Browser.CHROMIUM\n  }\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    browserWindow.navigator.vendor?.indexOf('Apple') === 0 ||\n    (/safari/i.test(userAgent) && !/chrome|android/i.test(userAgent))\n  ) {\n    return Browser.SAFARI\n  }\n\n  if ((browserWindow.document as any).documentMode) {\n    return Browser.IE\n  }\n\n  return Browser.OTHER\n}\n","import type { CookieOptions } from '../../../browser/cookie'\nimport type { SessionState } from '../sessionState'\n\nexport const SESSION_STORE_KEY = '_dd_s'\n\nexport type SessionStoreStrategyType = { type: 'Cookie'; cookieOptions: CookieOptions } | { type: 'LocalStorage' }\n\nexport interface SessionStoreStrategy {\n  isLockEnabled: boolean\n  persistSession: (session: SessionState) => void\n  retrieveSession: () => SessionState\n  expireSession: () => void\n}\n","import { ONE_HOUR, ONE_MINUTE } from '../../tools/utils/timeUtils'\n\nexport const SESSION_TIME_OUT_DELAY = 4 * ONE_HOUR\nexport const SESSION_EXPIRATION_DELAY = 15 * ONE_MINUTE\n","import { isEmptyObject } from '../../tools/utils/objectUtils'\nimport { objectEntries } from '../../tools/utils/polyfills'\nimport { dateNow } from '../../tools/utils/timeUtils'\nimport { SESSION_EXPIRATION_DELAY, SESSION_TIME_OUT_DELAY } from './sessionConstants'\n\nconst SESSION_ENTRY_REGEXP = /^([a-zA-Z]+)=([a-z0-9-]+)$/\nconst SESSION_ENTRY_SEPARATOR = '&'\n\nexport const EXPIRED = '1'\n\nexport interface SessionState {\n  id?: string\n  created?: string\n  expire?: string\n  isExpired?: typeof EXPIRED\n\n  [key: string]: string | undefined\n}\n\nexport function getExpiredSessionState(): SessionState {\n  return {\n    isExpired: EXPIRED,\n  }\n}\n\nexport function isSessionInNotStartedState(session: SessionState) {\n  return isEmptyObject(session)\n}\n\nexport function isSessionStarted(session: SessionState) {\n  return !isSessionInNotStartedState(session)\n}\n\nexport function isSessionInExpiredState(session: SessionState) {\n  return session.isExpired !== undefined || !isActiveSession(session)\n}\n\n// An active session is a session in either `Tracked` or `NotTracked` state\nfunction isActiveSession(sessionState: 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 (\n    (sessionState.created === undefined || dateNow() - Number(sessionState.created) < SESSION_TIME_OUT_DELAY) &&\n    (sessionState.expire === undefined || dateNow() < Number(sessionState.expire))\n  )\n}\n\nexport function expandSessionState(session: SessionState) {\n  session.expire = String(dateNow() + SESSION_EXPIRATION_DELAY)\n}\n\nexport function toSessionString(session: SessionState) {\n  return objectEntries(session)\n    .map(([key, value]) => `${key}=${value}`)\n    .join(SESSION_ENTRY_SEPARATOR)\n}\n\nexport function toSessionState(sessionString: string | undefined | null) {\n  const session: SessionState = {}\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        session[key] = value\n      }\n    })\n  }\n  return session\n}\n\nfunction isValidSessionString(sessionString: string | undefined | null): sessionString is string {\n  return (\n    !!sessionString &&\n    (sessionString.indexOf(SESSION_ENTRY_SEPARATOR) !== -1 || SESSION_ENTRY_REGEXP.test(sessionString))\n  )\n}\n","import { getInitCookie } from '../../browser/cookie'\nimport type { SessionStoreStrategy } from './storeStrategies/sessionStoreStrategy'\nimport { SESSION_STORE_KEY } from './storeStrategies/sessionStoreStrategy'\nimport type { SessionState } from './sessionState'\nimport { expandSessionState, isSessionStarted } from './sessionState'\n\nexport const OLD_SESSION_COOKIE_NAME = '_dd'\nexport const OLD_RUM_COOKIE_NAME = '_dd_r'\nexport const OLD_LOGS_COOKIE_NAME = '_dd_l'\n\n// duplicate values to avoid dependency issues\nexport const RUM_SESSION_KEY = 'rum'\nexport const LOGS_SESSION_KEY = 'logs'\n\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: SessionStoreStrategy) {\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: SessionState = {}\n\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\n    if (isSessionStarted(session)) {\n      expandSessionState(session)\n      cookieStoreStrategy.persistSession(session)\n    }\n  }\n}\n","import { isChromium } from '../../../tools/utils/browserDetection'\nimport type { CookieOptions } from '../../../browser/cookie'\nimport { getCurrentSite, areCookiesAuthorized, getCookie, setCookie } from '../../../browser/cookie'\nimport type { InitConfiguration } from '../../configuration'\nimport { tryOldCookiesMigration } from '../oldCookiesMigration'\nimport { SESSION_EXPIRATION_DELAY, SESSION_TIME_OUT_DELAY } from '../sessionConstants'\nimport type { SessionState } from '../sessionState'\nimport { toSessionString, toSessionState, getExpiredSessionState } from '../sessionState'\nimport type { SessionStoreStrategy, SessionStoreStrategyType } from './sessionStoreStrategy'\nimport { SESSION_STORE_KEY } from './sessionStoreStrategy'\n\nexport function selectCookieStrategy(initConfiguration: InitConfiguration): SessionStoreStrategyType | undefined {\n  const cookieOptions = buildCookieOptions(initConfiguration)\n  return areCookiesAuthorized(cookieOptions) ? { type: 'Cookie', cookieOptions } : undefined\n}\n\nexport function initCookieStrategy(cookieOptions: CookieOptions): SessionStoreStrategy {\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: () => expireSessionCookie(cookieOptions),\n  }\n\n  tryOldCookiesMigration(cookieStore)\n\n  return cookieStore\n}\n\nfunction persistSessionCookie(options: CookieOptions) {\n  return (session: SessionState) => {\n    setCookie(SESSION_STORE_KEY, toSessionString(session), SESSION_EXPIRATION_DELAY, options)\n  }\n}\n\nfunction expireSessionCookie(options: CookieOptions) {\n  setCookie(SESSION_STORE_KEY, toSessionString(getExpiredSessionState()), SESSION_TIME_OUT_DELAY, options)\n}\n\nfunction retrieveSessionCookie(): SessionState {\n  const sessionString = getCookie(SESSION_STORE_KEY)\n  return toSessionState(sessionString)\n}\n\nexport function buildCookieOptions(initConfiguration: InitConfiguration) {\n  const cookieOptions: CookieOptions = {}\n\n  cookieOptions.secure =\n    !!initConfiguration.useSecureSessionCookie ||\n    !!initConfiguration.usePartitionedCrossSiteSessionCookie ||\n    !!initConfiguration.useCrossSiteSessionCookie\n  cookieOptions.crossSite =\n    !!initConfiguration.usePartitionedCrossSiteSessionCookie || !!initConfiguration.useCrossSiteSessionCookie\n  cookieOptions.partitioned = !!initConfiguration.usePartitionedCrossSiteSessionCookie\n\n  if (initConfiguration.trackSessionAcrossSubdomains) {\n    cookieOptions.domain = getCurrentSite()\n  }\n\n  return cookieOptions\n}\n","import { generateUUID } from '../../../tools/utils/stringUtils'\nimport type { SessionState } from '../sessionState'\nimport { toSessionString, toSessionState, getExpiredSessionState } from '../sessionState'\nimport type { SessionStoreStrategy, SessionStoreStrategyType } from './sessionStoreStrategy'\nimport { SESSION_STORE_KEY } from './sessionStoreStrategy'\n\nconst LOCAL_STORAGE_TEST_KEY = '_dd_test_'\n\nexport function selectLocalStorageStrategy(): SessionStoreStrategyType | undefined {\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: 'LocalStorage' } : undefined\n  } catch (e) {\n    return undefined\n  }\n}\n\nexport function initLocalStorageStrategy(): SessionStoreStrategy {\n  return {\n    isLockEnabled: false,\n    persistSession: persistInLocalStorage,\n    retrieveSession: retrieveSessionFromLocalStorage,\n    expireSession: expireSessionFromLocalStorage,\n  }\n}\n\nfunction persistInLocalStorage(sessionState: SessionState) {\n  localStorage.setItem(SESSION_STORE_KEY, toSessionString(sessionState))\n}\n\nfunction retrieveSessionFromLocalStorage(): SessionState {\n  const sessionString = localStorage.getItem(SESSION_STORE_KEY)\n  return toSessionState(sessionString)\n}\n\nfunction expireSessionFromLocalStorage() {\n  persistInLocalStorage(getExpiredSessionState())\n}\n","import { setTimeout } from '../../tools/timer'\nimport { generateUUID } from '../../tools/utils/stringUtils'\nimport { assign } from '../../tools/utils/polyfills'\nimport type { SessionStoreStrategy } from './storeStrategies/sessionStoreStrategy'\nimport type { SessionState } from './sessionState'\nimport { expandSessionState, isSessionInExpiredState } from './sessionState'\n\ntype Operations = {\n  process: (sessionState: SessionState) => SessionState | undefined\n  after?: (sessionState: SessionState) => void\n}\n\nexport const LOCK_RETRY_DELAY = 10\nexport const LOCK_MAX_TRIES = 100\nconst bufferedOperations: Operations[] = []\nlet ongoingOperations: Operations | undefined\n\nexport function processSessionStoreOperations(\n  operations: Operations,\n  sessionStoreStrategy: SessionStoreStrategy,\n  numberOfRetries = 0\n) {\n  const { isLockEnabled, persistSession, expireSession } = sessionStoreStrategy\n  const persistWithLock = (session: SessionState) => persistSession(assign({}, session, { lock: currentLock }))\n  const retrieveStore = () => {\n    const session = sessionStoreStrategy.retrieveSession()\n    const lock = session.lock\n\n    if (session.lock) {\n      delete session.lock\n    }\n\n    return {\n      session,\n      lock,\n    }\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: string\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()\n    } else {\n      expandSessionState(processedSession)\n      isLockEnabled ? persistWithLock(processedSession) : persistSession(processedSession)\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  operations.after?.(processedSession || currentStore.session)\n  next(sessionStoreStrategy)\n}\n\nfunction retryLater(operations: Operations, sessionStore: SessionStoreStrategy, currentNumberOfRetries: number) {\n  setTimeout(() => {\n    processSessionStoreOperations(operations, sessionStore, currentNumberOfRetries + 1)\n  }, LOCK_RETRY_DELAY)\n}\n\nfunction next(sessionStore: SessionStoreStrategy) {\n  ongoingOperations = undefined\n  const nextOperations = bufferedOperations.shift()\n  if (nextOperations) {\n    processSessionStoreOperations(nextOperations, sessionStore)\n  }\n}\n","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 type { InitConfiguration } from '../configuration'\nimport { assign } from '../../tools/utils/polyfills'\nimport { selectCookieStrategy, initCookieStrategy } from './storeStrategies/sessionInCookie'\nimport type { SessionStoreStrategyType } from './storeStrategies/sessionStoreStrategy'\nimport {\n  getExpiredSessionState,\n  isSessionInExpiredState,\n  isSessionInNotStartedState,\n  isSessionStarted,\n} from './sessionState'\nimport type { SessionState } from './sessionState'\nimport { initLocalStorageStrategy, selectLocalStorageStrategy } from './storeStrategies/sessionInLocalStorage'\nimport { processSessionStoreOperations } from './sessionStoreOperations'\n\nexport interface SessionStore {\n  expandOrRenewSession: () => void\n  expandSession: () => void\n  getSession: () => SessionState\n  restartSession: () => void\n  renewObservable: Observable<void>\n  expireObservable: Observable<void>\n  sessionStateUpdateObservable: Observable<{ previousState: SessionState; newState: SessionState }>\n  expire: () => void\n  stop: () => void\n  updateSessionState: (state: Partial<SessionState>) => void\n}\n\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/**\n * Checks if cookies are available as the preferred storage\n * Else, checks if LocalStorage is allowed and available\n */\nexport function selectSessionStoreStrategyType(\n  initConfiguration: InitConfiguration\n): SessionStoreStrategyType | undefined {\n  let sessionStoreStrategyType = selectCookieStrategy(initConfiguration)\n  if (!sessionStoreStrategyType && initConfiguration.allowFallbackToLocalStorage) {\n    sessionStoreStrategyType = selectLocalStorageStrategy()\n  }\n  return sessionStoreStrategyType\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<TrackingType extends string>(\n  sessionStoreStrategyType: SessionStoreStrategyType,\n  productKey: string,\n  computeSessionState: (rawTrackingType?: string) => { trackingType: TrackingType; isTracked: boolean }\n): SessionStore {\n  const renewObservable = new Observable<void>()\n  const expireObservable = new Observable<void>()\n  const sessionStateUpdateObservable = new Observable<{ previousState: SessionState; newState: SessionState }>()\n\n  const sessionStoreStrategy =\n    sessionStoreStrategyType.type === 'Cookie'\n      ? initCookieStrategy(sessionStoreStrategyType.cookieOptions)\n      : initLocalStorageStrategy()\n  const { expireSession } = sessionStoreStrategy\n\n  const watchSessionTimeoutId = setInterval(watchSession, STORAGE_POLL_DELAY)\n  let sessionCache: SessionState\n\n  startSession()\n\n  const { throttled: throttledExpandOrRenewSession, cancel: cancelExpandOrRenewSession } = throttle(() => {\n    processSessionStoreOperations(\n      {\n        process: (sessionState) => {\n          if (isSessionInNotStartedState(sessionState)) {\n            return\n          }\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      },\n      sessionStoreStrategy\n    )\n  }, STORAGE_POLL_DELAY)\n\n  function expandSession() {\n    processSessionStoreOperations(\n      {\n        process: (sessionState) => (hasSessionInCache() ? synchronizeSession(sessionState) : undefined),\n      },\n      sessionStoreStrategy\n    )\n  }\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      {\n        process: (sessionState) => (isSessionInExpiredState(sessionState) ? getExpiredSessionState() : undefined),\n        after: synchronizeSession,\n      },\n      sessionStoreStrategy\n    )\n  }\n\n  function synchronizeSession(sessionState: SessionState) {\n    if (isSessionInExpiredState(sessionState)) {\n      sessionState = getExpiredSessionState()\n    }\n    if (hasSessionInCache()) {\n      if (isSessionInCacheOutdated(sessionState)) {\n        expireSessionInCache()\n      } else {\n        sessionStateUpdateObservable.notify({ previousState: sessionCache, newState: sessionState })\n        sessionCache = sessionState\n      }\n    }\n    return sessionState\n  }\n\n  function startSession() {\n    processSessionStoreOperations(\n      {\n        process: (sessionState) => {\n          if (isSessionInNotStartedState(sessionState)) {\n            return getExpiredSessionState()\n          }\n        },\n        after: (sessionState) => {\n          sessionCache = sessionState\n        },\n      },\n      sessionStoreStrategy\n    )\n  }\n\n  function expandOrRenewSessionState(sessionState: SessionState) {\n    if (isSessionInNotStartedState(sessionState)) {\n      return false\n    }\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\n  function hasSessionInCache() {\n    return sessionCache[productKey] !== undefined\n  }\n\n  function isSessionInCacheOutdated(sessionState: SessionState) {\n    return sessionCache.id !== sessionState.id || sessionCache[productKey] !== sessionState[productKey]\n  }\n\n  function expireSessionInCache() {\n    sessionCache = getExpiredSessionState()\n    expireObservable.notify()\n  }\n\n  function renewSessionInCache(sessionState: SessionState) {\n    sessionCache = sessionState\n    renewObservable.notify()\n  }\n\n  function updateSessionState(partialSessionState: Partial<SessionState>) {\n    processSessionStoreOperations(\n      {\n        process: (sessionState) => assign({}, sessionState, partialSessionState),\n        after: synchronizeSession,\n      },\n      sessionStoreStrategy\n    )\n  }\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()\n      synchronizeSession(getExpiredSessionState())\n    },\n    stop: () => {\n      clearInterval(watchSessionTimeoutId)\n    },\n    updateSessionState,\n  }\n}\n","import type { Payload } from '../../transport'\nimport { timeStampNow } from '../../tools/utils/timeUtils'\nimport { normalizeUrl } from '../../tools/utils/urlPolyfill'\nimport { generateUUID } from '../../tools/utils/stringUtils'\nimport type { InitConfiguration } from './configuration'\nimport { INTAKE_SITE_US1, INTAKE_SITE_FED_STAGING, PCI_INTAKE_HOST_US1 } from './intakeSites'\n\n// replaced at build time\ndeclare const __BUILD_ENV__SDK_VERSION__: string\n\nexport type TrackType = 'logs' | 'rum' | 'replay'\nexport type ApiType =\n  | 'xhr'\n  | 'fetch'\n  | 'beacon'\n  // 'manual' reflects that the request have been sent manually, outside of the SDK (ex: via curl or\n  // a Node.js script).\n  | 'manual'\n\nexport type EndpointBuilder = ReturnType<typeof createEndpointBuilder>\n\nexport function createEndpointBuilder(\n  initConfiguration: InitConfiguration,\n  trackType: TrackType,\n  configurationTags: string[]\n) {\n  const buildUrlWithParameters = createEndpointUrlWithParametersBuilder(initConfiguration, trackType)\n\n  return {\n    build(api: ApiType, payload: Payload) {\n      const parameters = buildEndpointParameters(initConfiguration, trackType, configurationTags, api, payload)\n      return buildUrlWithParameters(parameters)\n    },\n    urlPrefix: buildUrlWithParameters(''),\n    trackType,\n  }\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(\n  initConfiguration: InitConfiguration,\n  trackType: TrackType\n): (parameters: string) => string {\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}\n\nfunction buildEndpointHost(trackType: TrackType, initConfiguration: InitConfiguration & { usePciIntake?: boolean }) {\n  const { site = INTAKE_SITE_US1, internalAnalyticsSubdomain } = initConfiguration\n\n  if (trackType === 'logs' && initConfiguration.usePciIntake && site === INTAKE_SITE_US1) {\n    return PCI_INTAKE_HOST_US1\n  }\n\n  if (internalAnalyticsSubdomain && site === INTAKE_SITE_US1) {\n    return `${internalAnalyticsSubdomain}.${INTAKE_SITE_US1}`\n  }\n\n  if (site === INTAKE_SITE_FED_STAGING) {\n    return `http-intake.logs.${site}`\n  }\n\n  const domainParts = site.split('.')\n  const extension = domainParts.pop()\n  return `browser-intake-${domainParts.join('-')}.${extension!}`\n}\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(\n  { clientToken, internalAnalyticsSubdomain }: InitConfiguration,\n  trackType: TrackType,\n  configurationTags: string[],\n  api: ApiType,\n  { retry, encoding }: Payload\n) {\n  const tags = [`sdk_version:${__BUILD_ENV__SDK_VERSION__}`, `api:${api}`].concat(configurationTags)\n  if (retry) {\n    tags.push(`retry_count:${retry.count}`, `retry_after:${retry.lastFailureStatus}`)\n  }\n\n  const parameters = [\n    'ddsource=browser',\n    `ddtags=${encodeURIComponent(tags.join(','))}`,\n    `dd-api-key=${clientToken}`,\n    `dd-evp-origin-version=${encodeURIComponent(__BUILD_ENV__SDK_VERSION__)}`,\n    'dd-evp-origin=browser',\n    `dd-request-id=${generateUUID()}`,\n  ]\n\n  if (encoding) {\n    parameters.push(`dd-evp-encoding=${encoding}`)\n  }\n\n  if (trackType === 'rum') {\n    parameters.push(`batch_time=${timeStampNow()}`)\n  }\n\n  if (internalAnalyticsSubdomain) {\n    parameters.reverse()\n  }\n\n  return parameters.join('&')\n}\n","import { DOCS_ORIGIN, MORE_DETAILS, display } from '../../tools/display'\nimport type { InitConfiguration } from './configuration'\n\nexport const TAG_SIZE_LIMIT = 200\n\nexport function buildTags(configuration: InitConfiguration): string[] {\n  const { env, service, version, datacenter } = configuration\n  const tags = []\n\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\n  return tags\n}\n\nexport function buildTag(key: string, rawValue: string) {\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\n  if (rawValue.length > valueSizeLimit || hasForbiddenCharacters(rawValue)) {\n    display.warn(\n      `${key} value doesn't meet tag requirements and will be sanitized. ${MORE_DETAILS} ${DOCS_ORIGIN}/getting_started/tagging/#defining-tags`\n    )\n  }\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\n  return `${key}:${sanitizedValue}`\n}\n\nfunction hasForbiddenCharacters(rawValue: string) {\n  // Unicode property escapes is not supported in all browsers, so we use a try/catch.\n  // Todo: Remove the try/catch when dropping IE11.\n  if (!supportUnicodePropertyEscapes()) {\n    return false\n  }\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}\n\nexport function supportUnicodePropertyEscapes() {\n  try {\n    new RegExp('[\\\\p{Ll}]', 'u')\n    return true\n  } catch {\n    return false\n  }\n}\n","import { catchUserErrors } from '../../tools/catchUserErrors'\nimport { DOCS_ORIGIN, MORE_DETAILS, display } from '../../tools/display'\nimport type { RawTelemetryConfiguration } from '../telemetry'\nimport type { Duration } from '../../tools/utils/timeUtils'\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 { assign } from '../../tools/utils/polyfills'\nimport { selectSessionStoreStrategyType } from '../session/sessionStore'\nimport type { SessionStoreStrategyType } from '../session/storeStrategies/sessionStoreStrategy'\nimport { TrackingConsent } from '../trackingConsent'\nimport type { TransportConfiguration } from './transportConfiguration'\nimport { computeTransportConfiguration } from './transportConfiguration'\n\nexport const DefaultPrivacyLevel = {\n  ALLOW: 'allow',\n  MASK: 'mask',\n  MASK_USER_INPUT: 'mask-user-input',\n} as const\nexport type DefaultPrivacyLevel = (typeof DefaultPrivacyLevel)[keyof typeof DefaultPrivacyLevel]\n\nexport const TraceContextInjection = {\n  ALL: 'all',\n  SAMPLED: 'sampled',\n} as const\n\nexport type TraceContextInjection = (typeof TraceContextInjection)[keyof typeof TraceContextInjection]\n\nexport interface InitConfiguration {\n  /**\n   * The client token for Datadog. Required for authenticating your application with Datadog.\n   */\n  clientToken: string\n  beforeSend?: GenericBeforeSendCallback | undefined\n  /**\n   * The percentage of sessions tracked. A value between 0 and 100.\n   * @default 100\n   */\n  sessionSampleRate?: number | undefined\n  /**\n   * The percentage of telemetry events sent. A value between 0 and 100.\n   * @default 20\n   */\n  telemetrySampleRate?: number | undefined\n  /**\n   * Initialization fails silently if the RUM Browser SDK is already initialized on the page.\n   * @default false\n   */\n  silentMultipleInit?: boolean | undefined\n  /**\n   * Allows the use of localStorage when cookies cannot be set. This enables the RUM Browser SDK to run in environments that do not provide cookie support.\n   * See [Monitor Electron Applications Using the Browser SDK](https://docs.datadoghq.com/real_user_monitoring/guide/monitor-electron-applications-using-browser-sdk) for further information.\n   * @default false\n   */\n  allowFallbackToLocalStorage?: boolean | undefined\n  /**\n   * Allow listening to DOM events dispatched programmatically ([untrusted events](https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted)). Enabling this option can be useful if you heavily rely on programmatic events, such as in an automated UI test environment.\n   * @default false\n   */\n  allowUntrustedEvents?: boolean | undefined\n  /**\n   * Store global context and user context in localStorage to preserve them along the user navigation.\n   * See [Contexts life cycle](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/?tab=npm#contexts-life-cycle) for further information.\n   * @default false\n   */\n  storeContextsAcrossPages?: boolean | undefined\n  /**\n   * Set the initial user tracking consent state.\n   * See [User tracking consent](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/?tab=npm#user-tracking-consent) for further information.\n   * @default granted\n   */\n  trackingConsent?: TrackingConsent | undefined\n\n  // transport options\n  /**\n   * Optional proxy URL, for example: https://www.proxy.com/path.\n   * See [Proxy Your Browser RUM Data](https://docs.datadoghq.com/real_user_monitoring/guide/proxy-rum-data) for further information.\n   */\n  proxy?: string | ProxyFn | undefined\n  /**\n   * The Datadog [site](https://docs.datadoghq.com/getting_started/site) parameter of your organization.\n   * @default datadoghq.com\n   */\n  site?: string | undefined\n\n  // tag and context options\n  /**\n   * The service name for your application. Follows the [tag syntax requirements](https://docs.datadoghq.com/getting_started/tagging/#define-tags).\n   */\n  service?: string | undefined | null\n  /**\n   * The application’s environment, for example: prod, pre-prod, and staging. Follows the [tag syntax requirements](https://docs.datadoghq.com/getting_started/tagging/#define-tags).\n   */\n  env?: string | undefined | null\n  /**\n   * The application’s version, for example: 1.2.3, 6c44da20, and 2020.02.13. Follows the [tag syntax requirements](https://docs.datadoghq.com/getting_started/tagging/#define-tags).\n   */\n  version?: string | undefined | null\n\n  // cookie options\n  /**\n   * Whether a secure cross-site session cookie is used\n   * @default false\n   * @deprecated use usePartitionedCrossSiteSessionCookie instead\n   */\n  useCrossSiteSessionCookie?: boolean | undefined\n  /**\n   * Use a partitioned secure cross-site session cookie. This allows the RUM Browser SDK to run when the site is loaded from another one (iframe). Implies `useSecureSessionCookie`.\n   * @default false\n   */\n  usePartitionedCrossSiteSessionCookie?: boolean | undefined\n  /**\n   * Use a secure session cookie. This disables RUM events sent on insecure (non-HTTPS) connections.\n   * @default false\n   */\n  useSecureSessionCookie?: boolean | undefined\n  /**\n   * Preserve the session across subdomains for the same site.\n   * @default false\n   */\n  trackSessionAcrossSubdomains?: boolean | undefined\n\n  // internal options\n  /**\n   * [Internal option] Enable experimental features\n   */\n  enableExperimentalFeatures?: string[] | undefined\n  /**\n   * [Internal option] Configure the dual chipping to another datacenter\n   */\n  replica?: ReplicaUserConfiguration | undefined\n  /**\n   * [Internal option] Set the datacenter from where the data is dual chipped\n   */\n  datacenter?: string\n  /**\n   * [Internal option] Datadog internal analytics subdomain\n   */\n  // TODO next major: remove this option and replace usages by proxyFn\n  internalAnalyticsSubdomain?: string\n  /**\n   * [Internal option] The percentage of telemetry configuration sent. A value between 0 and 100.\n   * @default 5\n   */\n  telemetryConfigurationSampleRate?: number\n  /**\n   * [Internal option] The percentage of telemetry usage sent. A value between 0 and 100.\n   * @default 5\n   */\n  telemetryUsageSampleRate?: number\n}\n\n// This type is only used to build the core configuration. Logs and RUM SDKs are using a proper type\n// for this option.\ntype GenericBeforeSendCallback = (event: any, context?: any) => unknown\n\n/**\n * path: /api/vX/product\n * parameters: xxx=yyy&zzz=aaa\n */\ntype ProxyFn = (options: { path: string; parameters: string }) => string\n\ninterface ReplicaUserConfiguration {\n  applicationId?: string\n  clientToken: string\n}\n\nexport interface Configuration extends TransportConfiguration {\n  // Built from init configuration\n  beforeSend: GenericBeforeSendCallback | undefined\n  sessionStoreStrategyType: SessionStoreStrategyType | undefined\n  sessionSampleRate: number\n  telemetrySampleRate: number\n  telemetryConfigurationSampleRate: number\n  telemetryUsageSampleRate: number\n  service: string | undefined\n  silentMultipleInit: boolean\n  allowUntrustedEvents: boolean\n  trackingConsent: TrackingConsent\n  storeContextsAcrossPages: boolean\n\n  // Event limits\n  eventRateLimiterThreshold: number // Limit the maximum number of actions, errors and logs per minutes\n  maxTelemetryEventsPerPage: number\n\n  // Batch configuration\n  batchBytesLimit: number\n  flushTimeout: Duration\n  batchMessagesLimit: number\n  messageBytesLimit: number\n}\n\nfunction isString(tag: unknown, tagName: string): tag is string | undefined | null {\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}\n\nfunction isDatadogSite(site: unknown) {\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}\n\nexport function isSampleRate(sampleRate: unknown, name: string) {\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}\n\nexport function validateAndBuildConfiguration(initConfiguration: InitConfiguration): Configuration | undefined {\n  if (!initConfiguration || !initConfiguration.clientToken) {\n    display.error('Client Token is not configured, we will not send any data.')\n    return\n  }\n\n  if (\n    !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  ) {\n    return\n  }\n\n  if (\n    initConfiguration.trackingConsent !== undefined &&\n    !objectHasValue(TrackingConsent, initConfiguration.trackingConsent)\n  ) {\n    display.error('Tracking Consent should be either \"granted\" or \"not-granted\"')\n    return\n  }\n\n  return assign(\n    {\n      beforeSend:\n        initConfiguration.beforeSend && catchUserErrors(initConfiguration.beforeSend, 'beforeSend threw an error:'),\n      sessionStoreStrategyType: selectSessionStoreStrategyType(initConfiguration),\n      sessionSampleRate: initConfiguration.sessionSampleRate ?? 100,\n      telemetrySampleRate: initConfiguration.telemetrySampleRate ?? 20,\n      telemetryConfigurationSampleRate: initConfiguration.telemetryConfigurationSampleRate ?? 5,\n      telemetryUsageSampleRate: initConfiguration.telemetryUsageSampleRate ?? 5,\n      service: initConfiguration.service || undefined,\n      silentMultipleInit: !!initConfiguration.silentMultipleInit,\n      allowUntrustedEvents: !!initConfiguration.allowUntrustedEvents,\n      trackingConsent: initConfiguration.trackingConsent ?? TrackingConsent.GRANTED,\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\n      eventRateLimiterThreshold: 3000,\n      maxTelemetryEventsPerPage: 15,\n\n      /**\n       * flush automatically, aim to be lower than ALB connection timeout\n       * to maximize connection reuse.\n       */\n      flushTimeout: (30 * ONE_SECOND) as Duration,\n\n      /**\n       * Logs intake limit\n       */\n      batchMessagesLimit: 50,\n      messageBytesLimit: 256 * ONE_KIBI_BYTE,\n    },\n    computeTransportConfiguration(initConfiguration)\n  )\n}\n\nexport function serializeConfiguration(initConfiguration: 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_cross_site_session_cookie: initConfiguration.useCrossSiteSessionCookie,\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    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  } satisfies RawTelemetryConfiguration\n}\n","import { objectValues, assign } from '../../tools/utils/polyfills'\nimport type { InitConfiguration } from './configuration'\nimport type { EndpointBuilder } from './endpointBuilder'\nimport { createEndpointBuilder } from './endpointBuilder'\nimport { buildTags } from './tags'\nimport { INTAKE_SITE_US1, PCI_INTAKE_HOST_US1 } from './intakeSites'\n\nexport interface TransportConfiguration {\n  logsEndpointBuilder: EndpointBuilder\n  rumEndpointBuilder: EndpointBuilder\n  sessionReplayEndpointBuilder: EndpointBuilder\n  isIntakeUrl: (url: string) => boolean\n  replica?: ReplicaConfiguration\n  site: string\n}\n\nexport interface ReplicaConfiguration {\n  applicationId?: string\n  logsEndpointBuilder: EndpointBuilder\n  rumEndpointBuilder: EndpointBuilder\n}\n\nexport function computeTransportConfiguration(initConfiguration: InitConfiguration): TransportConfiguration {\n  const site = initConfiguration.site || INTAKE_SITE_US1\n\n  const tags = buildTags(initConfiguration)\n\n  const endpointBuilders = computeEndpointBuilders(initConfiguration, tags)\n  const intakeUrlPrefixes = computeIntakeUrlPrefixes(endpointBuilders, site)\n\n  const replicaConfiguration = computeReplicaConfiguration(initConfiguration, intakeUrlPrefixes, tags)\n\n  return assign(\n    {\n      isIntakeUrl: (url: string) => intakeUrlPrefixes.some((intakeEndpoint) => url.indexOf(intakeEndpoint) === 0),\n      replica: replicaConfiguration,\n      site,\n    },\n    endpointBuilders\n  )\n}\n\nfunction computeEndpointBuilders(initConfiguration: InitConfiguration, tags: string[]) {\n  return {\n    logsEndpointBuilder: createEndpointBuilder(initConfiguration, 'logs', tags),\n    rumEndpointBuilder: createEndpointBuilder(initConfiguration, 'rum', tags),\n    sessionReplayEndpointBuilder: createEndpointBuilder(initConfiguration, 'replay', tags),\n  }\n}\n\nfunction computeReplicaConfiguration(\n  initConfiguration: InitConfiguration,\n  intakeUrlPrefixes: string[],\n  tags: string[]\n): ReplicaConfiguration | undefined {\n  if (!initConfiguration.replica) {\n    return\n  }\n\n  const replicaConfiguration: InitConfiguration = assign({}, initConfiguration, {\n    site: INTAKE_SITE_US1,\n    clientToken: initConfiguration.replica.clientToken,\n  })\n\n  const replicaEndpointBuilders = {\n    logsEndpointBuilder: createEndpointBuilder(replicaConfiguration, 'logs', tags),\n    rumEndpointBuilder: createEndpointBuilder(replicaConfiguration, 'rum', tags),\n  }\n\n  intakeUrlPrefixes.push(...objectValues(replicaEndpointBuilders).map((builder) => builder.urlPrefix))\n\n  return assign({ applicationId: initConfiguration.replica.applicationId }, replicaEndpointBuilders)\n}\n\nfunction computeIntakeUrlPrefixes(\n  endpointBuilders: ReturnType<typeof computeEndpointBuilders>,\n  site: string\n): string[] {\n  const intakeUrlPrefixes = objectValues(endpointBuilders).map((builder) => builder.urlPrefix)\n\n  if (site === INTAKE_SITE_US1) {\n    intakeUrlPrefixes.push(`https://${PCI_INTAKE_HOST_US1}/`)\n  }\n\n  return intakeUrlPrefixes\n}\n","import { startsWith } from './utils/polyfills'\nimport { display } from './display'\nimport { getType } from './utils/typeUtils'\n\nexport type MatchOption = string | RegExp | ((value: string) => boolean)\n\nexport function isMatchOption(item: unknown): item is MatchOption {\n  const itemType = getType(item)\n  return itemType === 'string' || itemType === 'function' || item instanceof RegExp\n}\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: MatchOption[], value: string, useStartsWith = false): boolean {\n  return list.some((item) => {\n    try {\n      if (typeof item === 'function') {\n        return item(value)\n      } else if (item instanceof RegExp) {\n        return item.test(value)\n      } else if (typeof item === 'string') {\n        return useStartsWith ? startsWith(value, item) : item === value\n      }\n    } catch (e) {\n      display.error(e)\n    }\n    return false\n  })\n}\n","import {\n  objectEntries,\n  shallowClone,\n  performDraw,\n  isNumber,\n  assign,\n  find,\n  getType,\n  isMatchOption,\n  matchList,\n  TraceContextInjection,\n} from '@datadog/browser-core'\nimport type { RumConfiguration } from '../configuration'\nimport type {\n  RumFetchResolveContext,\n  RumFetchStartContext,\n  RumXhrCompleteContext,\n  RumXhrStartContext,\n} from '../requestCollection'\nimport type { RumSessionManager } from '../rumSessionManager'\nimport type { PropagatorType, TracingOption } from './tracer.types'\n\nexport interface Tracer {\n  traceFetch: (context: Partial<RumFetchStartContext>) => void\n  traceXhr: (context: Partial<RumXhrStartContext>, xhr: XMLHttpRequest) => void\n  clearTracingIfNeeded: (context: RumFetchResolveContext | RumXhrCompleteContext) => void\n}\n\ninterface TracingHeaders {\n  [key: string]: string\n}\n\nexport function isTracingOption(item: unknown): item is TracingOption {\n  const expectedItem = item as TracingOption\n  return (\n    getType(expectedItem) === 'object' &&\n    isMatchOption(expectedItem.match) &&\n    Array.isArray(expectedItem.propagatorTypes)\n  )\n}\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: RumFetchResolveContext | RumXhrCompleteContext) {\n  if (context.status === 0 && !context.isAborted) {\n    context.traceId = undefined\n    context.spanId = undefined\n    context.traceSampled = undefined\n  }\n}\n\nexport function startTracer(configuration: RumConfiguration, sessionManager: RumSessionManager): Tracer {\n  return {\n    clearTracingIfNeeded,\n    traceFetch: (context) =>\n      injectHeadersIfTracingAllowed(configuration, context, sessionManager, (tracingHeaders: TracingHeaders) => {\n        if (context.input instanceof Request && !context.init?.headers) {\n          context.input = new Request(context.input)\n          Object.keys(tracingHeaders).forEach((key) => {\n            ;(context.input as Request).headers.append(key, tracingHeaders[key])\n          })\n        } else {\n          context.init = shallowClone(context.init)\n          const headers: Array<[string, string]> = []\n          if (context.init.headers instanceof Headers) {\n            context.init.headers.forEach((value, key) => {\n              headers.push([key, value])\n            })\n          } else if (Array.isArray(context.init.headers)) {\n            context.init.headers.forEach((header) => {\n              headers.push(header)\n            })\n          } else if (context.init.headers) {\n            Object.keys(context.init.headers).forEach((key) => {\n              headers.push([key, (context.init!.headers as Record<string, string>)[key]])\n            })\n          }\n          context.init.headers = headers.concat(objectEntries(tracingHeaders))\n        }\n      }),\n    traceXhr: (context, xhr) =>\n      injectHeadersIfTracingAllowed(configuration, context, sessionManager, (tracingHeaders: TracingHeaders) => {\n        Object.keys(tracingHeaders).forEach((name) => {\n          xhr.setRequestHeader(name, tracingHeaders[name])\n        })\n      }),\n  }\n}\n\nfunction injectHeadersIfTracingAllowed(\n  configuration: RumConfiguration,\n  context: Partial<RumFetchStartContext | RumXhrStartContext>,\n  sessionManager: RumSessionManager,\n  inject: (tracingHeaders: TracingHeaders) => void\n) {\n  if (!isTracingSupported() || !sessionManager.findTrackedSession()) {\n    return\n  }\n\n  const tracingOption = find(configuration.allowedTracingUrls, (tracingOption: TracingOption) =>\n    matchList([tracingOption.match], context.url!, true)\n  )\n  if (!tracingOption) {\n    return\n  }\n  context.traceSampled = !isNumber(configuration.traceSampleRate) || performDraw(configuration.traceSampleRate)\n\n  if (!context.traceSampled && configuration.traceContextInjection !== TraceContextInjection.ALL) {\n    return\n  }\n\n  context.traceId = createTraceIdentifier()\n  context.spanId = createTraceIdentifier()\n\n  inject(makeTracingHeaders(context.traceId, context.spanId, context.traceSampled, tracingOption.propagatorTypes))\n}\n\nexport function isTracingSupported() {\n  return getCrypto() !== undefined\n}\n\nexport function getCrypto() {\n  return window.crypto || (window as any).msCrypto\n}\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(\n  traceId: TraceIdentifier,\n  spanId: TraceIdentifier,\n  traceSampled: boolean,\n  propagatorTypes: PropagatorType[]\n): TracingHeaders {\n  const tracingHeaders: TracingHeaders = {}\n\n  propagatorTypes.forEach((propagatorType) => {\n    switch (propagatorType) {\n      case 'datadog': {\n        assign(tracingHeaders, {\n          'x-datadog-origin': 'rum',\n          'x-datadog-parent-id': spanId.toDecimalString(),\n          'x-datadog-sampling-priority': traceSampled ? '1' : '0',\n          'x-datadog-trace-id': traceId.toDecimalString(),\n        })\n        break\n      }\n      // https://www.w3.org/TR/trace-context/\n      case 'tracecontext': {\n        assign(tracingHeaders, {\n          traceparent: `00-0000000000000000${traceId.toPaddedHexadecimalString()}-${spanId.toPaddedHexadecimalString()}-0${\n            traceSampled ? '1' : '0'\n          }`,\n        })\n        break\n      }\n      // https://github.com/openzipkin/b3-propagation\n      case 'b3': {\n        assign(tracingHeaders, {\n          b3: `${traceId.toPaddedHexadecimalString()}-${spanId.toPaddedHexadecimalString()}-${\n            traceSampled ? '1' : '0'\n          }`,\n        })\n        break\n      }\n      case 'b3multi': {\n        assign(tracingHeaders, {\n          'X-B3-TraceId': traceId.toPaddedHexadecimalString(),\n          'X-B3-SpanId': spanId.toPaddedHexadecimalString(),\n          'X-B3-Sampled': traceSampled ? '1' : '0',\n        })\n        break\n      }\n    }\n  })\n  return tracingHeaders\n}\n\n/* eslint-disable no-bitwise */\nexport interface TraceIdentifier {\n  toDecimalString: () => string\n  toPaddedHexadecimalString: () => string\n}\n\nexport function createTraceIdentifier(): TraceIdentifier {\n  const buffer: Uint8Array = new Uint8Array(8)\n  getCrypto().getRandomValues(buffer)\n  buffer[0] = buffer[0] & 0x7f // force 63-bit\n\n  function readInt32(offset: number) {\n    return buffer[offset] * 16777216 + (buffer[offset + 1] << 16) + (buffer[offset + 2] << 8) + buffer[offset + 3]\n  }\n\n  function toString(radix: number) {\n    let high = readInt32(0)\n    let low = readInt32(4)\n    let str = ''\n\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\n    return str\n  }\n\n  /**\n   * Format used everywhere except the trace intake\n   */\n  function toDecimalString() {\n    return toString(10)\n  }\n\n  /**\n   * Format used by OTel headers\n   */\n  function toPaddedHexadecimalString() {\n    const traceId = toString(16)\n    return Array(17 - traceId.length).join('0') + traceId\n  }\n\n  return {\n    toDecimalString,\n    toPaddedHexadecimalString,\n  }\n}\n/* eslint-enable no-bitwise */\n","import type { Configuration, InitConfiguration, MatchOption, RawTelemetryConfiguration } from '@datadog/browser-core'\nimport {\n  getType,\n  arrayFrom,\n  isMatchOption,\n  serializeConfiguration,\n  assign,\n  DefaultPrivacyLevel,\n  TraceContextInjection,\n  display,\n  objectHasValue,\n  validateAndBuildConfiguration,\n  isSampleRate,\n} from '@datadog/browser-core'\nimport type { RumEventDomainContext } from '../../domainContext.types'\nimport type { RumEvent } from '../../rumEvent.types'\nimport type { RumPlugin } from '../plugins'\nimport { isTracingOption } from '../tracing/tracer'\nimport type { PropagatorType, TracingOption } from '../tracing/tracer.types'\n\nexport const DEFAULT_PROPAGATOR_TYPES: PropagatorType[] = ['tracecontext', 'datadog']\n\nexport interface RumInitConfiguration extends InitConfiguration {\n  // global options\n  /**\n   * The RUM application ID.\n   */\n  applicationId: string\n  /**\n   * Access to every event collected by the RUM SDK before they are sent to Datadog.\n   * It allows:\n   * - Enrich your RUM events with additional context attributes\n   * - Modify your RUM events to modify their content, or redact sensitive sequences (see the list of editable properties)\n   * - Discard selected RUM events\n   *\n   * See [Enrich And Control Browser RUM Data With beforeSend](https://docs.datadoghq.com/real_user_monitoring/guide/enrich-and-control-rum-data) for further information.\n   */\n  beforeSend?: ((event: RumEvent, context: RumEventDomainContext) => boolean) | undefined\n  /**\n   * A list of request origins ignored when computing the page activity.\n   * See [How page activity is calculated](https://docs.datadoghq.com/real_user_monitoring/browser/monitoring_page_performance/#how-page-activity-is-calculated) for further information.\n   */\n  excludedActivityUrls?: MatchOption[] | undefined\n  /**\n   * URL pointing to the Datadog Browser SDK Worker JavaScript file. The URL can be relative or absolute, but is required to have the same origin as the web application.\n   * See [Content Security Policy guidelines](https://docs.datadoghq.com/integrations/content_security_policy_logs/?tab=firefox#use-csp-with-real-user-monitoring-and-session-replay) for further information.\n   */\n  workerUrl?: string\n  /**\n   * Compress requests sent to the Datadog intake to reduce bandwidth usage when sending large amounts of data. The compression is done in a Worker thread.\n   * See [Content Security Policy guidelines](https://docs.datadoghq.com/integrations/content_security_policy_logs/?tab=firefox#use-csp-with-real-user-monitoring-and-session-replay) for further information.\n   */\n  compressIntakeRequests?: boolean | undefined\n  remoteConfigurationId?: string | undefined\n\n  // tracing options\n  /**\n   * A list of request URLs used to inject tracing headers.\n   * See [Connect RUM and Traces](https://docs.datadoghq.com/real_user_monitoring/platform/connect_rum_and_traces/?tab=browserrum) for further information.\n   */\n  allowedTracingUrls?: Array<MatchOption | TracingOption> | undefined\n\n  /**\n   * The percentage of requests to trace: 100 for all, 0 for none.\n   * See [Connect RUM and Traces](https://docs.datadoghq.com/real_user_monitoring/platform/connect_rum_and_traces/?tab=browserrum) for further information.\n   */\n  traceSampleRate?: number | undefined\n  /**\n   * If you set a `traceSampleRate`, to ensure backend services' sampling decisions are still applied, configure the `traceContextInjection` initialization parameter to sampled.\n   * @default all\n   * See [Connect RUM and Traces](https://docs.datadoghq.com/real_user_monitoring/platform/connect_rum_and_traces/?tab=browserrum) for further information.\n   */\n  traceContextInjection?: TraceContextInjection | undefined\n\n  // replay options\n  /**\n   * Allow to protect end user privacy and prevent sensitive organizational information from being collected.\n   * @default mask\n   * See [Replay Privacy Options](https://docs.datadoghq.com/real_user_monitoring/session_replay/browser/privacy_options) for further information.\n   */\n  defaultPrivacyLevel?: DefaultPrivacyLevel | undefined\n  /**\n   * If you are accessing Datadog through a custom subdomain, you can set `subdomain` to include your custom domain in the `getSessionReplayLink()` returned URL .\n   * See [Connect Session Replay To Your Third-Party Tools](https://docs.datadoghq.com/real_user_monitoring/guide/connect-session-replay-to-your-third-party-tools) for further information.\n   */\n  subdomain?: string\n  /**\n   * The percentage of tracked sessions with [Browser RUM & Session Replay pricing](https://www.datadoghq.com/pricing/?product=real-user-monitoring--session-replay#real-user-monitoring--session-replay) features: 100 for all, 0 for none.\n   * See [Configure Your Setup For Browser RUM and Browser RUM & Session Replay Sampling](https://docs.datadoghq.com/real_user_monitoring/guide/sampling-browser-plans) for further information.\n   */\n  sessionReplaySampleRate?: number | undefined\n  /**\n   * If the session is sampled for Session Replay, only start the recording when `startSessionReplayRecording()` is called, instead of at the beginning of the session.\n   * See [Session Replay Usage](https://docs.datadoghq.com/real_user_monitoring/session_replay/browser/#usage) for further information.\n   */\n  startSessionReplayRecordingManually?: boolean | undefined\n\n  /**\n   * Enables privacy control for action names.\n   */\n  enablePrivacyForActionName?: boolean | undefined // TODO next major: remove this option and make privacy for action name the default behavior\n  /**\n   * Enables automatic collection of users actions.\n   * See [Tracking User Actions](https://docs.datadoghq.com/real_user_monitoring/browser/tracking_user_actions) for further information.\n   */\n  trackUserInteractions?: boolean | undefined\n  /**\n   * Specify your own attribute to use to name actions.\n   * See [Declare a name for click actions](https://docs.datadoghq.com/real_user_monitoring/browser/tracking_user_actions/#declare-a-name-for-click-actions) for further information.\n   */\n  actionNameAttribute?: string | undefined\n\n  // view options\n  /**\n   * Allows you to control RUM views creation. See [Override default RUM view names](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/?tab=npm#override-default-rum-view-names) for further information.\n   */\n  trackViewsManually?: boolean | undefined\n  /**\n   * Enables collection of resource events.\n   */\n  trackResources?: boolean | undefined\n  /**\n   * Enables collection of long task events.\n   */\n  trackLongTasks?: boolean | undefined\n\n  /**\n   * List of plugins to enable. The plugins API is unstable and experimental, and may change without\n   * notice. Please use only plugins provided by Datadog matching the version of the SDK you are\n   * using.\n   */\n  betaPlugins?: RumPlugin[] | undefined\n}\n\nexport type HybridInitConfiguration = Omit<RumInitConfiguration, 'applicationId' | 'clientToken'>\n\nexport interface RumConfiguration extends Configuration {\n  // Built from init configuration\n  actionNameAttribute: string | undefined\n  traceSampleRate: number | undefined\n  allowedTracingUrls: TracingOption[]\n  excludedActivityUrls: MatchOption[]\n  workerUrl: string | undefined\n  compressIntakeRequests: boolean\n  applicationId: string\n  defaultPrivacyLevel: DefaultPrivacyLevel\n  enablePrivacyForActionName: boolean\n  sessionReplaySampleRate: number\n  startSessionReplayRecordingManually: boolean\n  trackUserInteractions: boolean\n  trackViewsManually: boolean\n  trackResources: boolean\n  trackLongTasks: boolean\n  version?: string\n  subdomain?: string\n  customerDataTelemetrySampleRate: number\n  traceContextInjection: TraceContextInjection\n  plugins: RumPlugin[]\n}\n\nexport function validateAndBuildRumConfiguration(\n  initConfiguration: RumInitConfiguration\n): RumConfiguration | undefined {\n  if (!initConfiguration.applicationId) {\n    display.error('Application ID is not configured, no RUM data will be collected.')\n    return\n  }\n\n  if (\n    !isSampleRate(initConfiguration.sessionReplaySampleRate, 'Session Replay') ||\n    !isSampleRate(initConfiguration.traceSampleRate, 'Trace')\n  ) {\n    return\n  }\n\n  if (initConfiguration.excludedActivityUrls !== undefined && !Array.isArray(initConfiguration.excludedActivityUrls)) {\n    display.error('Excluded Activity Urls should be an array')\n    return\n  }\n\n  const allowedTracingUrls = validateAndBuildTracingOptions(initConfiguration)\n  if (!allowedTracingUrls) {\n    return\n  }\n\n  const baseConfiguration = validateAndBuildConfiguration(initConfiguration)\n  if (!baseConfiguration) {\n    return\n  }\n\n  return assign(\n    {\n      applicationId: initConfiguration.applicationId,\n      version: initConfiguration.version || undefined,\n      actionNameAttribute: initConfiguration.actionNameAttribute,\n      sessionReplaySampleRate: initConfiguration.sessionReplaySampleRate ?? 0,\n      startSessionReplayRecordingManually: !!initConfiguration.startSessionReplayRecordingManually,\n      traceSampleRate: initConfiguration.traceSampleRate,\n      allowedTracingUrls,\n      excludedActivityUrls: initConfiguration.excludedActivityUrls ?? [],\n      workerUrl: initConfiguration.workerUrl,\n      compressIntakeRequests: !!initConfiguration.compressIntakeRequests,\n      trackUserInteractions: !!initConfiguration.trackUserInteractions,\n      trackViewsManually: !!initConfiguration.trackViewsManually,\n      trackResources: !!initConfiguration.trackResources,\n      trackLongTasks: !!initConfiguration.trackLongTasks,\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.ALL,\n      plugins: initConfiguration.betaPlugins || [],\n    },\n    baseConfiguration\n  )\n}\n\n/**\n * Validates allowedTracingUrls and converts match options to tracing options\n */\nfunction validateAndBuildTracingOptions(initConfiguration: RumInitConfiguration): TracingOption[] | undefined {\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: TracingOption[] = []\n  initConfiguration.allowedTracingUrls.forEach((option) => {\n    if (isMatchOption(option)) {\n      tracingOptions.push({ match: option, propagatorTypes: DEFAULT_PROPAGATOR_TYPES })\n    } else if (isTracingOption(option)) {\n      tracingOptions.push(option)\n    } else {\n      display.warn(\n        'Allowed Tracing Urls parameters should be a string, RegExp, function, or an object. Ignoring parameter',\n        option\n      )\n    }\n  })\n\n  return tracingOptions\n}\n\n/**\n * Combines the selected tracing propagators from the different options in allowedTracingUrls\n */\nfunction getSelectedTracingPropagators(configuration: RumInitConfiguration): PropagatorType[] {\n  const usedTracingPropagators = new Set<PropagatorType>()\n\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      } 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\n  return arrayFrom(usedTracingPropagators)\n}\n\nexport function serializeRumConfiguration(configuration: RumInitConfiguration) {\n  const baseSerializedConfiguration = serializeConfiguration(configuration)\n\n  return assign(\n    {\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:\n        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:\n        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: configuration.betaPlugins?.map((plugin) =>\n        assign({ name: plugin.name }, plugin.getConfigurationTelemetry?.())\n      ),\n    },\n    baseSerializedConfiguration\n  ) satisfies RawTelemetryConfiguration\n}\n","import type { DefaultPrivacyLevel } from '@datadog/browser-core'\nimport { display, addEventListener, assign } from '@datadog/browser-core'\nimport type { RumInitConfiguration } from './configuration'\n\nexport const REMOTE_CONFIGURATION_URL = 'https://d3uc069fcn7uxw.cloudfront.net/configuration'\n\nexport interface RumRemoteConfiguration {\n  sessionSampleRate?: number\n  sessionReplaySampleRate?: number\n  defaultPrivacyLevel?: DefaultPrivacyLevel\n}\n\nexport function fetchAndApplyRemoteConfiguration(\n  initConfiguration: RumInitConfiguration,\n  callback: (initConfiguration: RumInitConfiguration) => void\n) {\n  fetchRemoteConfiguration(initConfiguration, (remoteInitConfiguration) => {\n    callback(applyRemoteConfiguration(initConfiguration, remoteInitConfiguration))\n  })\n}\n\nexport function applyRemoteConfiguration(\n  initConfiguration: RumInitConfiguration,\n  remoteInitConfiguration: RumRemoteConfiguration\n) {\n  return assign({}, initConfiguration, remoteInitConfiguration)\n}\n\nexport function fetchRemoteConfiguration(\n  configuration: RumInitConfiguration,\n  callback: (remoteConfiguration: RumRemoteConfiguration) => void\n) {\n  const xhr = new XMLHttpRequest()\n\n  addEventListener(configuration, xhr, 'load', function () {\n    if (xhr.status === 200) {\n      callback(JSON.parse(xhr.responseText))\n    } else {\n      displayRemoteConfigurationFetchingError()\n    }\n  })\n\n  addEventListener(configuration, xhr, 'error', function () {\n    displayRemoteConfigurationFetchingError()\n  })\n\n  xhr.open('GET', `${REMOTE_CONFIGURATION_URL}/${encodeURIComponent(configuration.remoteConfigurationId!)}.json`)\n  xhr.send()\n}\n\nfunction displayRemoteConfigurationFetchingError() {\n  display.error('Error fetching the remote configuration.')\n}\n","import {\n  createBoundedBuffer,\n  display,\n  canUseEventBridge,\n  displayAlreadyInitializedError,\n  willSyntheticsInjectRum,\n  noop,\n  timeStampNow,\n  clocksNow,\n  assign,\n  getEventBridge,\n  ExperimentalFeature,\n  isExperimentalFeatureEnabled,\n  initFeatureFlags,\n  addTelemetryConfiguration,\n  initFetchObservable,\n} from '@datadog/browser-core'\nimport type { TrackingConsentState, DeflateWorker } from '@datadog/browser-core'\nimport {\n  validateAndBuildRumConfiguration,\n  type RumConfiguration,\n  type RumInitConfiguration,\n} from '../domain/configuration'\nimport type { CommonContext } from '../domain/contexts/commonContext'\nimport type { ViewOptions } from '../domain/view/trackViews'\nimport type { DurationVital, CustomVitalsState } from '../domain/vital/vitalCollection'\nimport { startDurationVital, stopDurationVital } from '../domain/vital/vitalCollection'\nimport { fetchAndApplyRemoteConfiguration, serializeRumConfiguration } from '../domain/configuration'\nimport { callPluginsMethod } from '../domain/plugins'\nimport type { RumPublicApiOptions, Strategy } from './rumPublicApi'\nimport type { StartRumResult } from './startRum'\n\nexport function createPreStartStrategy(\n  { ignoreInitIfSyntheticsWillInjectRum, startDeflateWorker }: RumPublicApiOptions,\n  getCommonContext: () => CommonContext,\n  trackingConsentState: TrackingConsentState,\n  customVitalsState: CustomVitalsState,\n  doStartRum: (\n    configuration: RumConfiguration,\n    deflateWorker: DeflateWorker | undefined,\n    initialViewOptions?: ViewOptions\n  ) => StartRumResult\n): Strategy {\n  const bufferApiCalls = createBoundedBuffer<StartRumResult>()\n\n  let firstStartViewCall:\n    | { options: ViewOptions | undefined; callback: (startRumResult: StartRumResult) => void }\n    | undefined\n  let deflateWorker: DeflateWorker | undefined\n\n  let cachedInitConfiguration: RumInitConfiguration | undefined\n  let cachedConfiguration: RumConfiguration | undefined\n\n  const trackingConsentStateSubscription = trackingConsentState.observable.subscribe(tryStartRum)\n\n  function tryStartRum() {\n    if (!cachedInitConfiguration || !cachedConfiguration || !trackingConsentState.isGranted()) {\n      return\n    }\n\n    trackingConsentStateSubscription.unsubscribe()\n\n    let initialViewOptions: ViewOptions | undefined\n\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\n    const startRumResult = doStartRum(cachedConfiguration, deflateWorker, initialViewOptions)\n\n    bufferApiCalls.drain(startRumResult)\n  }\n\n  function doInit(initConfiguration: RumInitConfiguration) {\n    const eventBridgeAvailable = canUseEventBridge()\n    if (eventBridgeAvailable) {\n      initConfiguration = overrideInitConfigurationForBridge(initConfiguration)\n    }\n\n    // Update the exposed initConfiguration to reflect the bridge and remote configuration overrides\n    cachedInitConfiguration = initConfiguration\n    addTelemetryConfiguration(serializeRumConfiguration(initConfiguration))\n\n    if (cachedConfiguration) {\n      displayAlreadyInitializedError('DD_RUM', initConfiguration)\n      return\n    }\n\n    const configuration = validateAndBuildRumConfiguration(initConfiguration)\n    if (!configuration) {\n      return\n    }\n\n    if (!eventBridgeAvailable && !configuration.sessionStoreStrategyType) {\n      display.warn('No storage available for session. We will not send any data.')\n      return\n    }\n\n    if (configuration.compressIntakeRequests && !eventBridgeAvailable && startDeflateWorker) {\n      deflateWorker = startDeflateWorker(\n        configuration,\n        '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      )\n      if (!deflateWorker) {\n        // `startDeflateWorker` should have logged an error message explaining the issue\n        return\n      }\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\n    trackingConsentState.tryToInit(configuration.trackingConsent)\n    tryStartRum()\n  }\n\n  const addDurationVital = (vital: DurationVital) => {\n    bufferApiCalls.add((startRumResult) => startRumResult.addDurationVital(vital))\n  }\n\n  return {\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\n      // Expose the initial configuration regardless of initialization success.\n      cachedInitConfiguration = initConfiguration\n\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\n      callPluginsMethod(initConfiguration.betaPlugins, 'onInit', { initConfiguration, publicApi })\n\n      if (\n        initConfiguration.remoteConfigurationId &&\n        isExperimentalFeatureEnabled(ExperimentalFeature.REMOTE_CONFIGURATION)\n      ) {\n        fetchAndApplyRemoteConfiguration(initConfiguration, doInit)\n      } else {\n        doInit(initConfiguration)\n      }\n    },\n\n    get initConfiguration() {\n      return cachedInitConfiguration\n    },\n\n    getInternalContext: noop as () => undefined,\n\n    stopSession: noop,\n\n    addTiming(name, time = timeStampNow()) {\n      bufferApiCalls.add((startRumResult) => startRumResult.addTiming(name, time))\n    },\n\n    startView(options, startClocks = clocksNow()) {\n      const callback = (startRumResult: StartRumResult) => {\n        startRumResult.startView(options, startClocks)\n      }\n      bufferApiCalls.add(callback)\n\n      if (!firstStartViewCall) {\n        firstStartViewCall = { options, callback }\n        tryStartRum()\n      }\n    },\n\n    updateViewName(name) {\n      bufferApiCalls.add((startRumResult) => startRumResult.updateViewName(name))\n    },\n\n    setViewContext(context) {\n      bufferApiCalls.add((startRumResult) => startRumResult.setViewContext(context))\n    },\n\n    setViewContextProperty(key, value) {\n      bufferApiCalls.add((startRumResult) => startRumResult.setViewContextProperty(key, value))\n    },\n\n    addAction(action, commonContext = getCommonContext()) {\n      bufferApiCalls.add((startRumResult) => startRumResult.addAction(action, commonContext))\n    },\n\n    addError(providedError, commonContext = getCommonContext()) {\n      bufferApiCalls.add((startRumResult) => startRumResult.addError(providedError, commonContext))\n    },\n\n    addFeatureFlagEvaluation(key, value) {\n      bufferApiCalls.add((startRumResult) => startRumResult.addFeatureFlagEvaluation(key, value))\n    },\n\n    startDurationVital(name, options) {\n      return startDurationVital(customVitalsState, name, options)\n    },\n\n    stopDurationVital(name, options) {\n      stopDurationVital(addDurationVital, customVitalsState, name, options)\n    },\n\n    addDurationVital,\n  }\n}\n\nfunction overrideInitConfigurationForBridge(initConfiguration: RumInitConfiguration): RumInitConfiguration {\n  return assign({}, initConfiguration, {\n    applicationId: '00000000-aaaa-0000-aaaa-000000000000',\n    clientToken: 'empty',\n    sessionSampleRate: 100,\n    defaultPrivacyLevel: initConfiguration.defaultPrivacyLevel ?? getEventBridge()?.getPrivacyLevel(),\n  })\n}\n","import type { RumPublicApi } from '../boot/rumPublicApi'\nimport type { RumInitConfiguration } from './configuration'\n\nexport interface RumPlugin {\n  name: string\n  getConfigurationTelemetry?(): Record<string, unknown>\n  onInit?(options: { initConfiguration: RumInitConfiguration; publicApi: RumPublicApi }): void\n}\n\ntype MethodNames = 'onInit'\ntype MethodParameter<MethodName extends MethodNames> = Parameters<NonNullable<RumPlugin[MethodName]>>[0]\n\nexport function callPluginsMethod<MethodName extends MethodNames>(\n  plugins: RumPlugin[] | undefined,\n  methodName: MethodName,\n  parameter: MethodParameter<MethodName>\n) {\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","import { Observable } from '../tools/observable'\nimport { objectValues, includes } from '../tools/utils/polyfills'\nimport type { Configuration } from '../domain/configuration'\nimport { addEventListeners, addEventListener, DOM_EVENT } from './addEventListener'\n\nexport const PageExitReason = {\n  HIDDEN: 'visibility_hidden',\n  UNLOADING: 'before_unload',\n  PAGEHIDE: 'page_hide',\n  FROZEN: 'page_frozen',\n} as const\n\nexport type PageExitReason = (typeof PageExitReason)[keyof typeof PageExitReason]\n\nexport interface PageExitEvent {\n  reason: PageExitReason\n}\n\nexport function createPageExitObservable(configuration: Configuration): Observable<PageExitEvent> {\n  return new Observable<PageExitEvent>((observable) => {\n    const { stop: stopListeners } = addEventListeners(\n      configuration,\n      window,\n      [DOM_EVENT.VISIBILITY_CHANGE, DOM_EVENT.FREEZE],\n      (event) => {\n        if (event.type === 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        } else if (event.type === 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      },\n      { capture: true }\n    )\n\n    const stopBeforeUnloadListener = addEventListener(configuration, window, DOM_EVENT.BEFORE_UNLOAD, () => {\n      observable.notify({ reason: PageExitReason.UNLOADING })\n    }).stop\n\n    return () => {\n      stopListeners()\n      stopBeforeUnloadListener()\n    }\n  })\n}\n\nexport function isPageExitReason(reason: string | undefined): reason is PageExitReason {\n  return includes(objectValues(PageExitReason), reason)\n}\n","import { monitor, noop, Observable, getZoneJsOriginalValue } from '@datadog/browser-core'\n\nexport function createDOMMutationObservable() {\n  const MutationObserver = getMutationObserverConstructor()\n\n  return new Observable<void>((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}\n\ntype MutationObserverConstructor = new (callback: MutationCallback) => MutationObserver\n\nexport interface BrowserWindow extends Window {\n  MutationObserver?: MutationObserverConstructor\n  Zone?: unknown\n}\n\nexport function getMutationObserverConstructor(): MutationObserverConstructor | undefined {\n  let constructor: MutationObserverConstructor | undefined\n  const browserWindow: BrowserWindow = window\n\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\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\n      const patchedInstance = new browserWindow.MutationObserver(noop) as {\n        originalInstance?: { constructor: MutationObserverConstructor }\n      }\n\n      const originalInstance = getZoneJsOriginalValue(patchedInstance, 'originalInstance')\n      constructor = originalInstance && originalInstance.constructor\n    }\n  }\n\n  if (!constructor) {\n    constructor = browserWindow.MutationObserver\n  }\n\n  return constructor\n}\n","import type { ClocksState } from '../../tools/utils/timeUtils'\n\n// TS v4.6 introduced Error.cause[1] typed as `Error`. TS v4.8 changed Error.cause to be\n// `unknown`[2].\n//\n// Because we still support TS 3.8, we need to declare our own type. We can remove it once we drop\n// support for TS v4.7 and before. The 'cause' property defined by TS needs to be omitted because\n// we define it with a type `unknown` which is incompatible with TS 4.6 and 4.7.\n//\n// [1]: https://devblogs.microsoft.com/typescript/announcing-typescript-4-6/#target-es2022\n// [2]: https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/#lib-d-ts-updates\nexport interface ErrorWithCause extends Omit<Error, 'cause'> {\n  cause?: unknown\n}\n\nexport type RawErrorCause = {\n  message: string\n  source: string\n  type?: string\n  stack?: string\n}\n\nexport type Csp = {\n  disposition: 'enforce' | 'report'\n}\n\nexport interface RawError {\n  startClocks: ClocksState\n  message: string\n  type?: string\n  stack?: string\n  source: ErrorSource\n  originalError?: unknown\n  handling?: ErrorHandling\n  handlingStack?: string\n  causes?: RawErrorCause[]\n  fingerprint?: string\n  csp?: Csp\n}\n\nexport const ErrorSource = {\n  AGENT: 'agent',\n  CONSOLE: 'console',\n  CUSTOM: 'custom',\n  LOGGER: 'logger',\n  NETWORK: 'network',\n  SOURCE: 'source',\n  REPORT: 'report',\n} as const\n\nexport const enum NonErrorPrefix {\n  UNCAUGHT = 'Uncaught',\n  PROVIDED = 'Provided',\n}\n\nexport const enum ErrorHandling {\n  HANDLED = 'handled',\n  UNHANDLED = 'unhandled',\n}\n\nexport type ErrorSource = (typeof ErrorSource)[keyof typeof ErrorSource]\n","import { setTimeout } from '../../tools/timer'\nimport { clocksNow, ONE_MINUTE } from '../../tools/utils/timeUtils'\nimport type { RawError } from '../error/error.types'\nimport { ErrorSource } from '../error/error.types'\n\nexport type EventRateLimiter = ReturnType<typeof createEventRateLimiter>\n\nexport function createEventRateLimiter(\n  eventType: string,\n  limit: number,\n  onLimitReached: (limitError: RawError) => void\n) {\n  let eventCount = 0\n  let allowNextEvent = false\n\n  return {\n    isLimitReached() {\n      if (eventCount === 0) {\n        setTimeout(() => {\n          eventCount = 0\n        }, ONE_MINUTE)\n      }\n\n      eventCount += 1\n      if (eventCount <= limit || allowNextEvent) {\n        allowNextEvent = false\n        return false\n      }\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        } finally {\n          allowNextEvent = false\n        }\n      }\n\n      return true\n    },\n  }\n}\n","import { sanitize, deepClone, getType, objectEntries } from '@datadog/browser-core'\nimport type { Context } from '@datadog/browser-core'\n\nexport type ModifiableFieldPaths = Record<string, 'string' | 'object'>\n\n/**\n * Current limitation:\n * - field path do not support array, 'a.b.c' only\n */\nexport function limitModification<T extends Context, Result>(\n  object: T,\n  modifiableFieldPaths: ModifiableFieldPaths,\n  modifier: (object: T) => Result\n): Result | undefined {\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    } else if (fieldType === 'object' && (newType === 'undefined' || newType === 'null')) {\n      set(object, fieldPath, {})\n    }\n  })\n  return result\n}\n\nfunction get(object: unknown, path: string) {\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}\n\nfunction set(object: unknown, path: string, value: unknown) {\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    } else {\n      current[field] = value\n    }\n  }\n}\n\nfunction isValidObject(object: unknown): object is Record<string, unknown> {\n  return getType(object) === 'object'\n}\n\nfunction isValidObjectContaining(object: unknown, field: string): object is Record<string, unknown> {\n  return isValidObject(object) && Object.prototype.hasOwnProperty.call(object, field)\n}\n","import type { Context, RawError, EventRateLimiter, User } from '@datadog/browser-core'\nimport {\n  combine,\n  isEmptyObject,\n  timeStampNow,\n  currentDrift,\n  display,\n  createEventRateLimiter,\n  canUseEventBridge,\n  assign,\n  round,\n  isExperimentalFeatureEnabled,\n  ExperimentalFeature,\n  getConnectivity,\n} from '@datadog/browser-core'\nimport type { RumEventDomainContext } from '../domainContext.types'\nimport type {\n  RawRumErrorEvent,\n  RawRumEvent,\n  RawRumLongTaskEvent,\n  RawRumResourceEvent,\n  RumContext,\n} from '../rawRumEvent.types'\nimport { RumEventType } from '../rawRumEvent.types'\nimport type { RumEvent } from '../rumEvent.types'\nimport { getSyntheticsContext } from './contexts/syntheticsContext'\nimport type { CiVisibilityContext } from './contexts/ciVisibilityContext'\nimport type { LifeCycle } from './lifeCycle'\nimport { LifeCycleEventType } from './lifeCycle'\nimport type { ViewHistory } from './contexts/viewHistory'\nimport { SessionReplayState, type RumSessionManager } from './rumSessionManager'\nimport type { UrlContexts } from './contexts/urlContexts'\nimport type { RumConfiguration } from './configuration'\nimport type { ActionContexts } from './action/actionCollection'\nimport type { DisplayContext } from './contexts/displayContext'\nimport type { CommonContext } from './contexts/commonContext'\nimport type { ModifiableFieldPaths } from './limitModification'\nimport { limitModification } from './limitModification'\n\n// replaced at build time\ndeclare const __BUILD_ENV__SDK_VERSION__: string\n\nconst enum SessionType {\n  SYNTHETICS = 'synthetics',\n  USER = 'user',\n  CI_TEST = 'ci_test',\n}\n\nconst VIEW_MODIFIABLE_FIELD_PATHS: ModifiableFieldPaths = {\n  'view.name': 'string',\n  'view.url': 'string',\n  'view.referrer': 'string',\n}\n\nconst USER_CUSTOMIZABLE_FIELD_PATHS: ModifiableFieldPaths = {\n  context: 'object',\n}\n\nconst ROOT_MODIFIABLE_FIELD_PATHS: ModifiableFieldPaths = {\n  service: 'string',\n  version: 'string',\n}\n\nlet modifiableFieldPathsByEvent: { [key in RumEventType]: ModifiableFieldPaths }\n\ntype Mutable<T> = { -readonly [P in keyof T]: T[P] }\n\nexport function startRumAssembly(\n  configuration: RumConfiguration,\n  lifeCycle: LifeCycle,\n  sessionManager: RumSessionManager,\n  viewHistory: ViewHistory,\n  urlContexts: UrlContexts,\n  actionContexts: ActionContexts,\n  displayContext: DisplayContext,\n  ciVisibilityContext: CiVisibilityContext,\n  getCommonContext: () => CommonContext,\n  reportError: (error: RawError) => void\n) {\n  modifiableFieldPathsByEvent = {\n    [RumEventType.VIEW]: assign({}, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS),\n    [RumEventType.ERROR]: assign(\n      {\n        'error.message': 'string',\n        'error.stack': 'string',\n        'error.resource.url': 'string',\n        'error.fingerprint': 'string',\n      },\n      USER_CUSTOMIZABLE_FIELD_PATHS,\n      VIEW_MODIFIABLE_FIELD_PATHS,\n      ROOT_MODIFIABLE_FIELD_PATHS\n    ),\n    [RumEventType.RESOURCE]: assign(\n      {\n        'resource.url': 'string',\n      },\n      isExperimentalFeatureEnabled(ExperimentalFeature.WRITABLE_RESOURCE_GRAPHQL)\n        ? {\n            'resource.graphql': 'object',\n          }\n        : {},\n      USER_CUSTOMIZABLE_FIELD_PATHS,\n      VIEW_MODIFIABLE_FIELD_PATHS,\n      ROOT_MODIFIABLE_FIELD_PATHS\n    ),\n    [RumEventType.ACTION]: assign(\n      {\n        'action.target.name': 'string',\n      },\n      USER_CUSTOMIZABLE_FIELD_PATHS,\n      VIEW_MODIFIABLE_FIELD_PATHS,\n      ROOT_MODIFIABLE_FIELD_PATHS\n    ),\n    [RumEventType.LONG_TASK]: assign({}, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS),\n    [RumEventType.VITAL]: assign({}, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS),\n  }\n  const eventRateLimiters = {\n    [RumEventType.ERROR]: createEventRateLimiter(\n      RumEventType.ERROR,\n      configuration.eventRateLimiterThreshold,\n      reportError\n    ),\n    [RumEventType.ACTION]: createEventRateLimiter(\n      RumEventType.ACTION,\n      configuration.eventRateLimiterThreshold,\n      reportError\n    ),\n    [RumEventType.VITAL]: createEventRateLimiter(\n      RumEventType.VITAL,\n      configuration.eventRateLimiterThreshold,\n      reportError\n    ),\n  }\n\n  const syntheticsContext = getSyntheticsContext()\n  lifeCycle.subscribe(\n    LifeCycleEventType.RAW_RUM_EVENT_COLLECTED,\n    ({ 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\n        const rumContext: 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() ? __BUILD_ENV__SDK_VERSION__ : 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              ? SessionType.SYNTHETICS\n              : ciVisibilityContext.get()\n                ? SessionType.CI_TEST\n                : SessionType.USER,\n          },\n          view: {\n            id: viewHistoryEntry.id,\n            name: viewHistoryEntry.name,\n            url: urlContext.url,\n            referrer: urlContext.referrer,\n          },\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\n        const serverRumEvent = combine(rumContext as RumContext & Context, rawRumEvent) as RumEvent & Context\n        serverRumEvent.context = combine(commonContext.context, viewHistoryEntry.context, customerContext)\n\n        if (!('has_replay' in serverRumEvent.session)) {\n          ;(serverRumEvent.session as Mutable<RumEvent['session']>).has_replay = commonContext.hasReplay\n        }\n        if (serverRumEvent.type === 'view') {\n          ;(serverRumEvent.session as Mutable<RumEvent['session']>).sampled_for_replay =\n            session.sessionReplay === SessionReplayState.SAMPLED\n        }\n\n        if (!isEmptyObject(commonContext.user)) {\n          ;(serverRumEvent.usr as Mutable<RumEvent['usr']>) = commonContext.user as User & Context\n        }\n\n        if (shouldSend(serverRumEvent, configuration.beforeSend, domainContext, eventRateLimiters)) {\n          if (isEmptyObject(serverRumEvent.context)) {\n            delete serverRumEvent.context\n          }\n          lifeCycle.notify(LifeCycleEventType.RUM_EVENT_COLLECTED, serverRumEvent)\n        }\n      }\n    }\n  )\n}\n\nfunction shouldSend(\n  event: RumEvent & Context,\n  beforeSend: RumConfiguration['beforeSend'],\n  domainContext: RumEventDomainContext,\n  eventRateLimiters: { [key in RumEventType]?: EventRateLimiter }\n) {\n  if (beforeSend) {\n    const result = limitModification(event, modifiableFieldPathsByEvent[event.type], (event) =>\n      beforeSend(event, domainContext)\n    )\n    if (result === false && event.type !== RumEventType.VIEW) {\n      return false\n    }\n    if (result === false) {\n      display.warn(\"Can't dismiss view events using beforeSend!\")\n    }\n  }\n\n  const rateLimitReached = eventRateLimiters[event.type]?.isLimitReached()\n\n  return !rateLimitReached\n}\n\nfunction needToAssembleWithAction(\n  event: RawRumEvent\n): event is RawRumErrorEvent | RawRumResourceEvent | RawRumLongTaskEvent {\n  return [RumEventType.ERROR, RumEventType.RESOURCE, RumEventType.LONG_TASK].indexOf(event.type) !== -1\n}\n","import { getSyntheticsResultId, getSyntheticsTestId, willSyntheticsInjectRum } from '@datadog/browser-core'\n\nexport function getSyntheticsContext() {\n  const testId = getSyntheticsTestId()\n  const resultId = getSyntheticsResultId()\n\n  if (testId && resultId) {\n    return {\n      test_id: testId,\n      result_id: resultId,\n      injected: willSyntheticsInjectRum(),\n    }\n  }\n}\n","import type { Subscription } from './observable'\n\n/**\n * Type helper to extract event types that have \"void\" data. This allows to call `notify` without a\n * second argument. Ex:\n *\n * ```\n * interface EventMap {\n *   foo: void\n * }\n * const LifeCycle = AbstractLifeCycle<EventMap>\n * new LifeCycle().notify('foo')\n * ```\n */\ntype EventTypesWithoutData<EventMap> = {\n  [K in keyof EventMap]: EventMap[K] extends void ? K : never\n}[keyof EventMap]\n\n// eslint-disable-next-line no-restricted-syntax\nexport class AbstractLifeCycle<EventMap> {\n  private callbacks: { [key in keyof EventMap]?: Array<(data: any) => void> } = {}\n\n  notify<EventType extends EventTypesWithoutData<EventMap>>(eventType: EventType): void\n  notify<EventType extends keyof EventMap>(eventType: EventType, data: EventMap[EventType]): void\n  notify(eventType: keyof EventMap, data?: unknown) {\n    const eventCallbacks = this.callbacks[eventType]\n    if (eventCallbacks) {\n      eventCallbacks.forEach((callback) => callback(data))\n    }\n  }\n\n  subscribe<EventType extends keyof EventMap>(\n    eventType: EventType,\n    callback: (data: EventMap[EventType]) => void\n  ): Subscription {\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","import type { Context, PageExitEvent, RawError, RelativeTime } from '@datadog/browser-core'\nimport { AbstractLifeCycle } from '@datadog/browser-core'\nimport type { RumEventDomainContext } from '../domainContext.types'\nimport type { RawRumEvent } from '../rawRumEvent.types'\nimport type { RumEvent } from '../rumEvent.types'\nimport type { CommonContext } from './contexts/commonContext'\nimport type { RequestCompleteEvent, RequestStartEvent } from './requestCollection'\nimport type { AutoAction } from './action/actionCollection'\nimport type { ViewEvent, ViewCreatedEvent, ViewEndedEvent } from './view/trackViews'\n\nexport const enum LifeCycleEventType {\n  // Contexts (like viewHistory) should be opened using prefixed BEFORE_XXX events and closed using prefixed AFTER_XXX events\n  // It ensures the context is available during the non prefixed event callbacks\n  AUTO_ACTION_COMPLETED,\n  BEFORE_VIEW_CREATED,\n  VIEW_CREATED,\n  VIEW_UPDATED,\n  VIEW_ENDED,\n  AFTER_VIEW_ENDED,\n  REQUEST_STARTED,\n  REQUEST_COMPLETED,\n\n  // The SESSION_EXPIRED lifecycle event has been introduced to represent when a session has expired\n  // and trigger cleanup tasks related to this, prior to renewing the session. Its implementation is\n  // slightly naive: it is not triggered as soon as the session is expired, but rather just before\n  // notifying that the session is renewed. Thus, the session id is already set to the newly renewed\n  // session.\n  //\n  // This implementation is \"good enough\" for our use-cases. Improving this is not trivial,\n  // primarily because multiple instances of the SDK may be managing the same session cookie at\n  // the same time, for example when using Logs and RUM on the same page, or opening multiple tabs\n  // on the same domain.\n  SESSION_EXPIRED,\n  SESSION_RENEWED,\n  PAGE_EXITED,\n  RAW_RUM_EVENT_COLLECTED,\n  RUM_EVENT_COLLECTED,\n  RAW_ERROR_COLLECTED,\n}\n\n// This is a workaround for an issue occurring when the Browser SDK is included in a TypeScript\n// project configured with `isolatedModules: true`. Even if the const enum is declared in this\n// module, we cannot use it directly to define the EventMap interface keys (TS error: \"Cannot access\n// ambient const enums when the '--isolatedModules' flag is provided.\").\n//\n// Using a plain enum would fix the issue, but would also add 2KB to the minified bundle. By using\n// this workaround, we can keep using a const enum without impacting the bundle size (since it is a\n// \"declare\" statement, it will only be used during typecheck and completely ignored when building\n// JavaScript).\n//\n// See issues:\n// * https://github.com/DataDog/browser-sdk/issues/2208\n// * https://github.com/microsoft/TypeScript/issues/54152\ndeclare const LifeCycleEventTypeAsConst: {\n  AUTO_ACTION_COMPLETED: LifeCycleEventType.AUTO_ACTION_COMPLETED\n  BEFORE_VIEW_CREATED: LifeCycleEventType.BEFORE_VIEW_CREATED\n  VIEW_CREATED: LifeCycleEventType.VIEW_CREATED\n  VIEW_UPDATED: LifeCycleEventType.VIEW_UPDATED\n  VIEW_ENDED: LifeCycleEventType.VIEW_ENDED\n  AFTER_VIEW_ENDED: LifeCycleEventType.AFTER_VIEW_ENDED\n  REQUEST_STARTED: LifeCycleEventType.REQUEST_STARTED\n  REQUEST_COMPLETED: LifeCycleEventType.REQUEST_COMPLETED\n  SESSION_EXPIRED: LifeCycleEventType.SESSION_EXPIRED\n  SESSION_RENEWED: LifeCycleEventType.SESSION_RENEWED\n  PAGE_EXITED: LifeCycleEventType.PAGE_EXITED\n  RAW_RUM_EVENT_COLLECTED: LifeCycleEventType.RAW_RUM_EVENT_COLLECTED\n  RUM_EVENT_COLLECTED: LifeCycleEventType.RUM_EVENT_COLLECTED\n  RAW_ERROR_COLLECTED: LifeCycleEventType.RAW_ERROR_COLLECTED\n}\n\n// Note: this interface needs to be exported even if it is not used outside of this module, else TS\n// fails to build the rum-core package with error TS4058\nexport interface LifeCycleEventMap {\n  [LifeCycleEventTypeAsConst.AUTO_ACTION_COMPLETED]: AutoAction\n  [LifeCycleEventTypeAsConst.BEFORE_VIEW_CREATED]: ViewCreatedEvent\n  [LifeCycleEventTypeAsConst.VIEW_CREATED]: ViewCreatedEvent\n  [LifeCycleEventTypeAsConst.VIEW_UPDATED]: ViewEvent\n  [LifeCycleEventTypeAsConst.VIEW_ENDED]: ViewEndedEvent\n  [LifeCycleEventTypeAsConst.AFTER_VIEW_ENDED]: ViewEndedEvent\n  [LifeCycleEventTypeAsConst.REQUEST_STARTED]: RequestStartEvent\n  [LifeCycleEventTypeAsConst.REQUEST_COMPLETED]: RequestCompleteEvent\n  [LifeCycleEventTypeAsConst.SESSION_EXPIRED]: void\n  [LifeCycleEventTypeAsConst.SESSION_RENEWED]: void\n  [LifeCycleEventTypeAsConst.PAGE_EXITED]: PageExitEvent\n  [LifeCycleEventTypeAsConst.RAW_RUM_EVENT_COLLECTED]: RawRumEventCollectedData\n  [LifeCycleEventTypeAsConst.RUM_EVENT_COLLECTED]: RumEvent & Context\n  [LifeCycleEventTypeAsConst.RAW_ERROR_COLLECTED]: {\n    error: RawError\n    savedCommonContext?: CommonContext\n    customerContext?: Context\n  }\n}\n\nexport interface RawRumEventCollectedData<E extends RawRumEvent = RawRumEvent> {\n  startTime: RelativeTime\n  savedCommonContext?: CommonContext\n  customerContext?: Context\n  rawRumEvent: E\n  domainContext: RumEventDomainContext<E['type']>\n}\n\nexport const LifeCycle = AbstractLifeCycle<LifeCycleEventMap>\nexport type LifeCycle = AbstractLifeCycle<LifeCycleEventMap>\n","import { setInterval, clearInterval } from './timer'\nimport type { TimeoutId } from './timer'\nimport { removeItem } from './utils/arrayUtils'\nimport type { Duration, RelativeTime } from './utils/timeUtils'\nimport { addDuration, relativeNow, ONE_MINUTE } from './utils/timeUtils'\n\nconst END_OF_TIMES = Infinity as RelativeTime\n\nexport interface ValueHistoryEntry<T> {\n  startTime: RelativeTime\n  endTime: RelativeTime\n  value: T\n  remove(): void\n  close(endTime: RelativeTime): void\n}\n\nexport const CLEAR_OLD_VALUES_INTERVAL = ONE_MINUTE\n\n/**\n * Store and keep track of values spans. This whole cache assumes that values are added in\n * chronological order (i.e. all entries have an increasing start time).\n */\nexport interface ValueHistory<Value> {\n  add: (value: Value, startTime: RelativeTime) => ValueHistoryEntry<Value>\n  find: (startTime?: RelativeTime, options?: { returnInactive: boolean }) => Value | undefined\n\n  closeActive: (endTime: RelativeTime) => void\n  findAll: (startTime?: RelativeTime, duration?: Duration) => Value[]\n  reset: () => void\n  stop: () => void\n}\n\nexport function createValueHistory<Value>({\n  expireDelay,\n  maxEntries,\n}: {\n  expireDelay: number\n  maxEntries?: number\n}): ValueHistory<Value> {\n  let entries: Array<ValueHistoryEntry<Value>> = []\n  const clearOldValuesInterval: TimeoutId = setInterval(() => clearOldValues(), CLEAR_OLD_VALUES_INTERVAL)\n\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  /**\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: Value, startTime: RelativeTime): ValueHistoryEntry<Value> {\n    const entry: ValueHistoryEntry<Value> = {\n      value,\n      startTime,\n      endTime: END_OF_TIMES,\n      remove: () => {\n        removeItem(entries, entry)\n      },\n      close: (endTime: RelativeTime) => {\n        entry.endTime = endTime\n      },\n    }\n\n    if (maxEntries && entries.length >= maxEntries) {\n      entries.pop()\n    }\n\n    entries.unshift(entry)\n\n    return entry\n  }\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(\n    startTime: RelativeTime = END_OF_TIMES,\n    options: { returnInactive: boolean } = { returnInactive: false }\n  ): Value | undefined {\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  /**\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: RelativeTime) {\n    const latestEntry = entries[0]\n    if (latestEntry && latestEntry.endTime === END_OF_TIMES) {\n      latestEntry.close(endTime)\n    }\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: RelativeTime = END_OF_TIMES, duration = 0 as Duration): Value[] {\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  /**\n   * Remove all entries from this collection.\n   */\n  function reset() {\n    entries = []\n  }\n\n  /**\n   * Stop internal garbage collection of past entries.\n   */\n  function stop() {\n    clearInterval(clearOldValuesInterval)\n  }\n\n  return { add, find, closeActive, findAll, reset, stop }\n}\n","import type { RelativeTime, ClocksState, Context } from '@datadog/browser-core'\nimport { SESSION_TIME_OUT_DELAY, createValueHistory } from '@datadog/browser-core'\nimport type { LifeCycle } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport type { ViewCreatedEvent, ViewEvent } from '../view/trackViews'\n\nexport const VIEW_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY\n\nexport interface ViewHistoryEntry {\n  service?: string\n  version?: string\n  context?: Context | undefined\n  id: string\n  name?: string\n  startClocks: ClocksState\n}\n\nexport interface ViewHistory {\n  findView: (startTime?: RelativeTime) => ViewHistoryEntry | undefined\n  stop: () => void\n}\n\nexport function startViewHistory(lifeCycle: LifeCycle): ViewHistory {\n  const viewValueHistory = createValueHistory<ViewHistoryEntry>({ expireDelay: VIEW_CONTEXT_TIME_OUT_DELAY })\n\n  lifeCycle.subscribe(LifeCycleEventType.BEFORE_VIEW_CREATED, (view) => {\n    viewValueHistory.add(buildViewHistoryEntry(view), view.startClocks.relative)\n  })\n\n  lifeCycle.subscribe(LifeCycleEventType.AFTER_VIEW_ENDED, ({ endClocks }) => {\n    viewValueHistory.closeActive(endClocks.relative)\n  })\n\n  lifeCycle.subscribe(LifeCycleEventType.VIEW_UPDATED, (viewUpdate: ViewEvent) => {\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\n  lifeCycle.subscribe(LifeCycleEventType.SESSION_RENEWED, () => {\n    viewValueHistory.reset()\n  })\n\n  function buildViewHistoryEntry(view: ViewCreatedEvent) {\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\n  return {\n    findView: (startTime) => viewValueHistory.find(startTime),\n    stop: () => {\n      viewValueHistory.stop()\n    },\n  }\n}\n","import type { InstrumentedMethodCall } from '../tools/instrumentMethod'\nimport { instrumentMethod } from '../tools/instrumentMethod'\nimport { Observable } from '../tools/observable'\nimport type { Duration, ClocksState } from '../tools/utils/timeUtils'\nimport { elapsed, clocksNow, timeStampNow } from '../tools/utils/timeUtils'\nimport { normalizeUrl } from '../tools/utils/urlPolyfill'\nimport { shallowClone } from '../tools/utils/objectUtils'\nimport type { Configuration } from '../domain/configuration'\nimport { addEventListener } from './addEventListener'\n\nexport interface XhrOpenContext {\n  state: 'open'\n  method: string\n  url: string\n}\n\nexport interface XhrStartContext extends Omit<XhrOpenContext, 'state'> {\n  state: 'start'\n  startClocks: ClocksState\n  isAborted: boolean\n  xhr: XMLHttpRequest\n  handlingStack?: string\n}\n\nexport interface XhrCompleteContext extends Omit<XhrStartContext, 'state'> {\n  state: 'complete'\n  duration: Duration\n  status: number\n}\n\nexport type XhrContext = XhrOpenContext | XhrStartContext | XhrCompleteContext\n\nlet xhrObservable: Observable<XhrContext> | undefined\nconst xhrContexts = new WeakMap<XMLHttpRequest, XhrContext>()\n\nexport function initXhrObservable(configuration: Configuration) {\n  if (!xhrObservable) {\n    xhrObservable = createXhrObservable(configuration)\n  }\n  return xhrObservable\n}\n\nfunction createXhrObservable(configuration: Configuration) {\n  return new Observable<XhrContext>((observable) => {\n    const { stop: stopInstrumentingStart } = instrumentMethod(XMLHttpRequest.prototype, 'open', openXhr)\n\n    const { stop: stopInstrumentingSend } = instrumentMethod(\n      XMLHttpRequest.prototype,\n      'send',\n      (call) => {\n        sendXhr(call, configuration, observable)\n      },\n      { computeHandlingStack: true }\n    )\n\n    const { stop: stopInstrumentingAbort } = instrumentMethod(XMLHttpRequest.prototype, 'abort', abortXhr)\n\n    return () => {\n      stopInstrumentingStart()\n      stopInstrumentingSend()\n      stopInstrumentingAbort()\n    }\n  })\n}\n\nfunction openXhr({ target: xhr, parameters: [method, url] }: InstrumentedMethodCall<XMLHttpRequest, 'open'>) {\n  xhrContexts.set(xhr, {\n    state: 'open',\n    method: String(method).toUpperCase(),\n    url: normalizeUrl(String(url)),\n  })\n}\n\nfunction sendXhr(\n  { target: xhr, handlingStack }: InstrumentedMethodCall<XMLHttpRequest, 'send'>,\n  configuration: Configuration,\n  observable: Observable<XhrContext>\n) {\n  const context = xhrContexts.get(xhr)\n  if (!context) {\n    return\n  }\n\n  const startContext = context as XhrStartContext\n  startContext.state = 'start'\n  startContext.startClocks = clocksNow()\n  startContext.isAborted = false\n  startContext.xhr = xhr\n  startContext.handlingStack = handlingStack\n\n  let hasBeenReported = false\n\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\n  const onEnd = () => {\n    unsubscribeLoadEndListener()\n    stopInstrumentingOnReadyStateChange()\n    if (hasBeenReported) {\n      return\n    }\n    hasBeenReported = true\n\n    const completeContext = context as XhrCompleteContext\n    completeContext.state = 'complete'\n    completeContext.duration = elapsed(startContext.startClocks.timeStamp, timeStampNow())\n    completeContext.status = xhr.status\n    observable.notify(shallowClone(completeContext))\n  }\n\n  const { stop: unsubscribeLoadEndListener } = addEventListener(configuration, xhr, 'loadend', onEnd)\n\n  observable.notify(startContext)\n}\n\nfunction abortXhr({ target: xhr }: InstrumentedMethodCall<XMLHttpRequest, 'abort'>) {\n  const context = xhrContexts.get(xhr) as XhrStartContext | undefined\n  if (context) {\n    context.isAborted = true\n  }\n}\n","import type { RelativeTime, ServerDuration } from '@datadog/browser-core'\nimport {\n  addTelemetryDebug,\n  elapsed,\n  getPathName,\n  includes,\n  isValidUrl,\n  ResourceType,\n  toServerDuration,\n} from '@datadog/browser-core'\n\nimport type { RumPerformanceResourceTiming } from '../../browser/performanceObservable'\n\nimport type { ResourceEntryDetailsElement } from '../../rawRumEvent.types'\nimport type { RumConfiguration } from '../configuration'\n\nexport interface ResourceEntryDetails {\n  redirect?: ResourceEntryDetailsElement\n  dns?: ResourceEntryDetailsElement\n  connect?: ResourceEntryDetailsElement\n  ssl?: ResourceEntryDetailsElement\n  first_byte?: ResourceEntryDetailsElement\n  download?: ResourceEntryDetailsElement\n}\n\nexport const FAKE_INITIAL_DOCUMENT = 'initial_document'\n\nconst RESOURCE_TYPES: Array<[ResourceType, (initiatorType: string, path: string) => boolean]> = [\n  [ResourceType.DOCUMENT, (initiatorType: string) => FAKE_INITIAL_DOCUMENT === initiatorType],\n  [ResourceType.XHR, (initiatorType: string) => 'xmlhttprequest' === initiatorType],\n  [ResourceType.FETCH, (initiatorType: string) => 'fetch' === initiatorType],\n  [ResourceType.BEACON, (initiatorType: string) => 'beacon' === initiatorType],\n  [ResourceType.CSS, (_: string, path: string) => /\\.css$/i.test(path)],\n  [ResourceType.JS, (_: string, path: string) => /\\.js$/i.test(path)],\n  [\n    ResourceType.IMAGE,\n    (initiatorType: string, path: string) =>\n      includes(['image', 'img', 'icon'], initiatorType) || /\\.(gif|jpg|jpeg|tiff|png|svg|ico)$/i.exec(path) !== null,\n  ],\n  [ResourceType.FONT, (_: string, path: string) => /\\.(woff|eot|woff2|ttf)$/i.exec(path) !== null],\n  [\n    ResourceType.MEDIA,\n    (initiatorType: string, path: string) =>\n      includes(['audio', 'video'], initiatorType) || /\\.(mp3|mp4)$/i.exec(path) !== null,\n  ],\n]\n\nexport function computeResourceEntryType(entry: RumPerformanceResourceTiming) {\n  const url = entry.name\n  if (!isValidUrl(url)) {\n    addTelemetryDebug(`Failed to construct URL for \"${entry.name}\"`)\n    return 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 ResourceType.OTHER\n}\n\nfunction areInOrder(...numbers: number[]) {\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}\n\nexport function isResourceEntryRequestType(entry: RumPerformanceResourceTiming) {\n  return entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch'\n}\n\nexport function computeResourceEntryDuration(entry: RumPerformanceResourceTiming): ServerDuration {\n  const { duration, startTime, responseEnd } = entry\n\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\n  return toServerDuration(duration)\n}\n\nexport function computeResourceEntryDetails(entry: RumPerformanceResourceTiming): ResourceEntryDetails | undefined {\n  if (!hasValidResourceEntryTimings(entry)) {\n    return undefined\n  }\n  const {\n    startTime,\n    fetchStart,\n    redirectStart,\n    redirectEnd,\n    domainLookupStart,\n    domainLookupEnd,\n    connectStart,\n    secureConnectionStart,\n    connectEnd,\n    requestStart,\n    responseStart,\n    responseEnd,\n  } = entry\n\n  const details: ResourceEntryDetails = {\n    download: formatTiming(startTime, responseStart, responseEnd),\n    first_byte: formatTiming(startTime, requestStart, responseStart),\n  }\n\n  // Make sure a connection occurred\n  if (fetchStart < connectEnd) {\n    details.connect = formatTiming(startTime, connectStart, connectEnd)\n\n    // Make sure a secure connection occurred\n    if (connectStart <= secureConnectionStart && secureConnectionStart <= connectEnd) {\n      details.ssl = formatTiming(startTime, secureConnectionStart, connectEnd)\n    }\n  }\n\n  // Make sure a domain lookup occurred\n  if (fetchStart < domainLookupEnd) {\n    details.dns = formatTiming(startTime, domainLookupStart, domainLookupEnd)\n  }\n\n  // Make sure a redirection occurred\n  if (startTime < redirectEnd) {\n    details.redirect = formatTiming(startTime, redirectStart, redirectEnd)\n  }\n\n  return details\n}\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: RumPerformanceResourceTiming) {\n  return entry.duration >= 0\n}\n\nexport function hasValidResourceEntryTimings(entry: RumPerformanceResourceTiming) {\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(\n    entry.startTime,\n    entry.fetchStart,\n    entry.domainLookupStart,\n    entry.domainLookupEnd,\n    entry.connectStart,\n    entry.connectEnd,\n    entry.requestStart,\n    entry.responseStart,\n    entry.responseEnd\n  )\n\n  const areRedirectionTimingsInOrder = hasRedirection(entry)\n    ? areInOrder(entry.startTime, entry.redirectStart, entry.redirectEnd, entry.fetchStart)\n    : true\n\n  return areCommonTimingsInOrder && areRedirectionTimingsInOrder\n}\n\nfunction hasRedirection(entry: RumPerformanceResourceTiming) {\n  return entry.redirectEnd > entry.startTime\n}\nfunction formatTiming(origin: RelativeTime, start: RelativeTime, end: RelativeTime) {\n  if (origin <= start && start <= end) {\n    return {\n      duration: toServerDuration(elapsed(start, end)),\n      start: toServerDuration(elapsed(origin, start)),\n    }\n  }\n}\n\nexport function computeResourceEntrySize(entry: RumPerformanceResourceTiming) {\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}\n\nexport function isAllowedRequestUrl(configuration: RumConfiguration, url: string) {\n  return url && !configuration.isIntakeUrl(url)\n}\n\nconst DATA_URL_REGEX = /data:(.+)?(;base64)?,/g\nexport const MAX_ATTRIBUTE_VALUE_CHAR_LENGTH = 24_000\n\nexport function isLongDataUrl(url: string): boolean {\n  if (url.length <= MAX_ATTRIBUTE_VALUE_CHAR_LENGTH) {\n    return false\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}\n\nexport function sanitizeDataUrl(url: string): string {\n  return `${url.match(DATA_URL_REGEX)![0]}[...]`\n}\n","import type {\n  Duration,\n  XhrCompleteContext,\n  XhrStartContext,\n  ClocksState,\n  FetchStartContext,\n  FetchResolveContext,\n} from '@datadog/browser-core'\nimport {\n  RequestType,\n  initFetchObservable,\n  initXhrObservable,\n  readBytesFromStream,\n  elapsed,\n  timeStampNow,\n  tryToClone,\n} from '@datadog/browser-core'\nimport type { RumSessionManager } from '..'\nimport type { RumConfiguration } from './configuration'\nimport type { LifeCycle } from './lifeCycle'\nimport { LifeCycleEventType } from './lifeCycle'\nimport { isAllowedRequestUrl } from './resource/resourceUtils'\nimport type { TraceIdentifier, Tracer } from './tracing/tracer'\nimport { startTracer } from './tracing/tracer'\n\nexport interface CustomContext {\n  requestIndex: number\n  spanId?: TraceIdentifier\n  traceId?: TraceIdentifier\n  traceSampled?: boolean\n}\nexport interface RumFetchStartContext extends FetchStartContext, CustomContext {}\nexport interface RumFetchResolveContext extends FetchResolveContext, CustomContext {}\nexport interface RumXhrStartContext extends XhrStartContext, CustomContext {}\nexport interface RumXhrCompleteContext extends XhrCompleteContext, CustomContext {}\n\nexport interface RequestStartEvent {\n  requestIndex: number\n  url: string\n}\nexport interface RequestCompleteEvent {\n  requestIndex: number\n  type: RequestType\n  method: string\n  url: string\n  status: number\n  responseType?: string\n  startClocks: ClocksState\n  duration: Duration\n  spanId?: TraceIdentifier\n  traceId?: TraceIdentifier\n  traceSampled?: boolean\n  xhr?: XMLHttpRequest\n  response?: Response\n  input?: unknown\n  init?: RequestInit\n  error?: Error\n  isAborted: boolean\n  handlingStack?: string\n}\n\nlet nextRequestIndex = 1\n\nexport function startRequestCollection(\n  lifeCycle: LifeCycle,\n  configuration: RumConfiguration,\n  sessionManager: RumSessionManager\n) {\n  const tracer = startTracer(configuration, sessionManager)\n  trackXhr(lifeCycle, configuration, tracer)\n  trackFetch(lifeCycle, configuration, tracer)\n}\n\nexport function trackXhr(lifeCycle: LifeCycle, configuration: RumConfiguration, tracer: Tracer) {\n  const subscription = initXhrObservable(configuration).subscribe((rawContext) => {\n    const context = rawContext as RumXhrStartContext | RumXhrCompleteContext\n    if (!isAllowedRequestUrl(configuration, context.url)) {\n      return\n    }\n\n    switch (context.state) {\n      case 'start':\n        tracer.traceXhr(context, context.xhr)\n        context.requestIndex = getNextRequestIndex()\n\n        lifeCycle.notify(LifeCycleEventType.REQUEST_STARTED, {\n          requestIndex: context.requestIndex,\n          url: context.url,\n        })\n        break\n      case 'complete':\n        tracer.clearTracingIfNeeded(context)\n        lifeCycle.notify(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: RequestType.XHR,\n          url: context.url,\n          xhr: context.xhr,\n          isAborted: context.isAborted,\n          handlingStack: context.handlingStack,\n        })\n        break\n    }\n  })\n\n  return { stop: () => subscription.unsubscribe() }\n}\n\nexport function trackFetch(lifeCycle: LifeCycle, configuration: RumConfiguration, tracer: Tracer) {\n  const subscription = initFetchObservable().subscribe((rawContext) => {\n    const context = rawContext as RumFetchResolveContext | RumFetchStartContext\n    if (!isAllowedRequestUrl(configuration, context.url)) {\n      return\n    }\n\n    switch (context.state) {\n      case 'start':\n        tracer.traceFetch(context)\n        context.requestIndex = getNextRequestIndex()\n\n        lifeCycle.notify(LifeCycleEventType.REQUEST_STARTED, {\n          requestIndex: context.requestIndex,\n          url: context.url,\n        })\n        break\n      case 'resolve':\n        waitForResponseToComplete(context, (duration: Duration) => {\n          tracer.clearTracingIfNeeded(context)\n          lifeCycle.notify(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: 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}\n\nfunction getNextRequestIndex() {\n  const result = nextRequestIndex\n  nextRequestIndex += 1\n  return result\n}\n\nfunction waitForResponseToComplete(context: RumFetchResolveContext, callback: (duration: Duration) => void) {\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  } else {\n    readBytesFromStream(\n      clonedResponse.body,\n      () => {\n        callback(elapsed(context.startClocks.timeStamp, timeStampNow()))\n      },\n      {\n        bytesLimit: Number.POSITIVE_INFINITY,\n        collectStreamBody: false,\n      }\n    )\n  }\n}\n","import type { Duration, RelativeTime, TimeoutId } from '@datadog/browser-core'\nimport { addEventListener, Observable, setTimeout, clearTimeout, monitor, includes } from '@datadog/browser-core'\nimport type { RumConfiguration } from '../domain/configuration'\nimport { hasValidResourceEntryDuration, isAllowedRequestUrl } from '../domain/resource/resourceUtils'\nimport { retrieveFirstInputTiming } from './firstInputPolyfill'\n\ntype RumPerformanceObserverConstructor = new (callback: PerformanceObserverCallback) => RumPerformanceObserver\n\nexport interface BrowserWindow extends Window {\n  PerformanceObserver: RumPerformanceObserverConstructor\n  performance: Performance & { interactionCount?: number }\n}\n\nexport interface RumPerformanceObserver extends PerformanceObserver {\n  observe(options?: PerformanceObserverInit & { durationThreshold?: number }): void\n}\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 performance entry\n// eslint-disable-next-line no-restricted-syntax\nexport enum RumPerformanceEntryType {\n  EVENT = 'event',\n  FIRST_INPUT = 'first-input',\n  LARGEST_CONTENTFUL_PAINT = 'largest-contentful-paint',\n  LAYOUT_SHIFT = 'layout-shift',\n  LONG_TASK = 'longtask',\n  LONG_ANIMATION_FRAME = 'long-animation-frame',\n  NAVIGATION = 'navigation',\n  PAINT = 'paint',\n  RESOURCE = 'resource',\n}\n\nexport interface RumPerformanceLongTaskTiming {\n  name: string\n  entryType: RumPerformanceEntryType.LONG_TASK\n  startTime: RelativeTime\n  duration: Duration\n  toJSON(): Omit<PerformanceEntry, 'toJSON'>\n}\n\nexport interface RumPerformanceResourceTiming {\n  entryType: RumPerformanceEntryType.RESOURCE\n  initiatorType: string\n  responseStatus?: number\n  name: string\n  startTime: RelativeTime\n  duration: Duration\n  fetchStart: RelativeTime\n  domainLookupStart: RelativeTime\n  domainLookupEnd: RelativeTime\n  connectStart: RelativeTime\n  secureConnectionStart: RelativeTime\n  connectEnd: RelativeTime\n  requestStart: RelativeTime\n  responseStart: RelativeTime\n  responseEnd: RelativeTime\n  redirectStart: RelativeTime\n  redirectEnd: RelativeTime\n  decodedBodySize: number\n  encodedBodySize: number\n  transferSize: number\n  renderBlockingStatus?: string\n  traceId?: string\n  toJSON(): Omit<PerformanceEntry, 'toJSON'>\n}\n\nexport interface RumPerformancePaintTiming {\n  entryType: RumPerformanceEntryType.PAINT\n  name: 'first-paint' | 'first-contentful-paint'\n  startTime: RelativeTime\n}\n\nexport interface RumPerformanceNavigationTiming extends Omit<RumPerformanceResourceTiming, 'entryType'> {\n  entryType: RumPerformanceEntryType.NAVIGATION\n  initiatorType: 'navigation'\n  name: string\n\n  domComplete: RelativeTime\n  domContentLoadedEventEnd: RelativeTime\n  domInteractive: RelativeTime\n  loadEventEnd: RelativeTime\n\n  toJSON(): Omit<RumPerformanceNavigationTiming, 'toJSON'>\n}\n\nexport interface RumLargestContentfulPaintTiming {\n  entryType: RumPerformanceEntryType.LARGEST_CONTENTFUL_PAINT\n  startTime: RelativeTime\n  size: number\n  element?: Element\n  toJSON(): Omit<RumLargestContentfulPaintTiming, 'toJSON'>\n}\n\nexport interface RumFirstInputTiming {\n  entryType: RumPerformanceEntryType.FIRST_INPUT\n  startTime: RelativeTime\n  processingStart: RelativeTime\n  processingEnd: RelativeTime\n  duration: Duration\n  target?: Node\n  interactionId?: number\n  name: string\n}\n\nexport interface RumPerformanceEventTiming {\n  entryType: RumPerformanceEntryType.EVENT\n  startTime: RelativeTime\n  processingStart: RelativeTime\n  processingEnd: RelativeTime\n  duration: Duration\n  interactionId?: number\n  target?: Node\n  name: string\n}\n\nexport interface RumLayoutShiftTiming {\n  entryType: RumPerformanceEntryType.LAYOUT_SHIFT\n  startTime: RelativeTime\n  value: number\n  hadRecentInput: boolean\n  sources?: Array<{\n    node?: Node\n  }>\n}\n\n// Documentation https://developer.chrome.com/docs/web-platform/long-animation-frames#better-attribution\nexport type RumPerformanceScriptTiming = {\n  duration: Duration\n  entryType: 'script'\n  executionStart: RelativeTime\n  forcedStyleAndLayoutDuration: Duration\n  invoker: string // e.g. \"https://static.datadoghq.com/static/c/93085/chunk-bc4db53278fd4c77a637.min.js\"\n  invokerType:\n    | 'user-callback'\n    | 'event-listener'\n    | 'resolve-promise'\n    | 'reject-promise'\n    | 'classic-script'\n    | 'module-script'\n  name: 'script'\n  pauseDuration: Duration\n  sourceCharPosition: number\n  sourceFunctionName: string\n  sourceURL: string\n  startTime: RelativeTime\n  window: Window\n  windowAttribution: string\n}\n\nexport interface RumPerformanceLongAnimationFrameTiming {\n  blockingDuration: Duration\n  duration: Duration\n  entryType: RumPerformanceEntryType.LONG_ANIMATION_FRAME\n  firstUIEventTimestamp: RelativeTime\n  name: 'long-animation-frame'\n  renderStart: RelativeTime\n  scripts: RumPerformanceScriptTiming[]\n  startTime: RelativeTime\n  styleAndLayoutStart: RelativeTime\n}\n\nexport type RumPerformanceEntry =\n  | RumPerformanceResourceTiming\n  | RumPerformanceLongTaskTiming\n  | RumPerformanceLongAnimationFrameTiming\n  | RumPerformancePaintTiming\n  | RumPerformanceNavigationTiming\n  | RumLargestContentfulPaintTiming\n  | RumFirstInputTiming\n  | RumPerformanceEventTiming\n  | RumLayoutShiftTiming\n\nexport type EntryTypeToReturnType = {\n  [RumPerformanceEntryType.EVENT]: RumPerformanceEventTiming\n  [RumPerformanceEntryType.FIRST_INPUT]: RumFirstInputTiming\n  [RumPerformanceEntryType.LARGEST_CONTENTFUL_PAINT]: RumLargestContentfulPaintTiming\n  [RumPerformanceEntryType.LAYOUT_SHIFT]: RumLayoutShiftTiming\n  [RumPerformanceEntryType.PAINT]: RumPerformancePaintTiming\n  [RumPerformanceEntryType.LONG_TASK]: RumPerformanceLongTaskTiming\n  [RumPerformanceEntryType.LONG_ANIMATION_FRAME]: RumPerformanceLongAnimationFrameTiming\n  [RumPerformanceEntryType.NAVIGATION]: RumPerformanceNavigationTiming\n  [RumPerformanceEntryType.RESOURCE]: RumPerformanceResourceTiming\n}\n\nexport function createPerformanceObservable<T extends RumPerformanceEntryType>(\n  configuration: RumConfiguration,\n  options: { type: T; buffered?: boolean; durationThreshold?: number }\n) {\n  return new Observable<Array<EntryTypeToReturnType[T]>>((observable) => {\n    if (!window.PerformanceObserver) {\n      return\n    }\n\n    const handlePerformanceEntries = (entries: PerformanceEntryList) => {\n      const rumPerformanceEntries = filterRumPerformanceEntries(\n        configuration,\n        entries as Array<EntryTypeToReturnType[T]>\n      )\n      if (rumPerformanceEntries.length > 0) {\n        observable.notify(rumPerformanceEntries)\n      }\n    }\n\n    let timeoutId: TimeoutId | undefined\n    let isObserverInitializing = true\n    const observer = new PerformanceObserver(\n      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        } else {\n          handlePerformanceEntries(entries.getEntries())\n        }\n      })\n    )\n    try {\n      observer.observe(options)\n    } catch {\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 (includes(fallbackSupportedEntryTypes, options.type)) {\n        if (options.buffered) {\n          timeoutId = setTimeout(() => handlePerformanceEntries(performance.getEntriesByType(options.type)))\n        }\n        try {\n          observer.observe({ entryTypes: [options.type] })\n        } catch {\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\n    manageResourceTimingBufferFull(configuration)\n\n    let stopFirstInputTiming: (() => void) | undefined\n    if (\n      !supportPerformanceTimingEvent(RumPerformanceEntryType.FIRST_INPUT) &&\n      options.type === RumPerformanceEntryType.FIRST_INPUT\n    ) {\n      ;({ stop: stopFirstInputTiming } = retrieveFirstInputTiming(configuration, (timing) => {\n        handlePerformanceEntries([timing])\n      }))\n    }\n\n    return () => {\n      observer.disconnect()\n      if (stopFirstInputTiming) {\n        stopFirstInputTiming()\n      }\n      clearTimeout(timeoutId)\n    }\n  })\n}\n\nlet resourceTimingBufferFullListener: { stop: () => void }\nfunction manageResourceTimingBufferFull(configuration: RumConfiguration) {\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?.stop()\n  }\n}\n\nfunction supportPerformanceObject() {\n  return window.performance !== undefined && 'getEntries' in performance\n}\n\nexport function supportPerformanceTimingEvent(entryType: RumPerformanceEntryType) {\n  return (\n    window.PerformanceObserver &&\n    PerformanceObserver.supportedEntryTypes !== undefined &&\n    PerformanceObserver.supportedEntryTypes.includes(entryType)\n  )\n}\n\nfunction filterRumPerformanceEntries<T extends RumPerformanceEntryType>(\n  configuration: RumConfiguration,\n  entries: Array<EntryTypeToReturnType[T]>\n) {\n  return entries.filter((entry) => !isForbiddenResource(configuration, entry))\n}\n\nfunction isForbiddenResource(configuration: RumConfiguration, entry: RumPerformanceEntry) {\n  return (\n    entry.entryType === RumPerformanceEntryType.RESOURCE &&\n    (!isAllowedRequestUrl(configuration, entry.name) || !hasValidResourceEntryDuration(entry))\n  )\n}\n","export function isServerError(status: number) {\n  return status >= 500\n}\n\nexport function tryToClone(response: Response): Response | undefined {\n  try {\n    return response.clone()\n  } catch (e) {\n    // clone can throw if the response has already been used by another instrumentation or is disturbed\n    return\n  }\n}\n","import { monitor } from './monitor'\nimport { noop } from './utils/functionUtils'\n\ntype Options = {\n  bytesLimit: number\n  collectStreamBody?: boolean\n}\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(\n  stream: ReadableStream<Uint8Array>,\n  callback: (error?: Error, bytes?: Uint8Array, limitExceeded?: boolean) => void,\n  options: Options\n) {\n  const reader = stream.getReader()\n  const chunks: Uint8Array[] = []\n  let readBytesCount = 0\n\n  readMore()\n\n  function readMore() {\n    reader.read().then(\n      monitor((result: ReadableStreamReadResult<Uint8Array>) => {\n        if (result.done) {\n          onDone()\n          return\n        }\n\n        if (options.collectStreamBody) {\n          chunks.push(result.value)\n        }\n        readBytesCount += result.value.length\n\n        if (readBytesCount > options.bytesLimit) {\n          onDone()\n        } else {\n          readMore()\n        }\n      }),\n      monitor((error) => callback(error))\n    )\n  }\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    )\n\n    let bytes: Uint8Array | undefined\n    let limitExceeded: boolean | undefined\n    if (options.collectStreamBody) {\n      let completeBuffer: Uint8Array\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      } 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\n    callback(undefined, bytes, limitExceeded)\n  }\n}\n","import type { ServerDuration } from '@datadog/browser-core'\nimport { isNumber } from '@datadog/browser-core'\n\nexport function discardNegativeDuration(duration: ServerDuration | undefined): ServerDuration | undefined {\n  return isNumber(duration) && duration < 0 ? undefined : duration\n}\n","import { noop } from '@datadog/browser-core'\nimport { RumEventType } from '../rawRumEvent.types'\nimport type { RumActionEvent, RumErrorEvent, RumLongTaskEvent, RumResourceEvent } from '../rumEvent.types'\nimport type { LifeCycle } from './lifeCycle'\nimport { LifeCycleEventType } from './lifeCycle'\n\nexport interface EventCounts {\n  errorCount: number\n  actionCount: number\n  longTaskCount: number\n  resourceCount: number\n  frustrationCount: number\n}\n\nexport function trackEventCounts({\n  lifeCycle,\n  isChildEvent,\n  onChange: callback = noop,\n}: {\n  lifeCycle: LifeCycle\n  isChildEvent: (event: RumActionEvent | RumErrorEvent | RumLongTaskEvent | RumResourceEvent) => boolean\n  onChange?: () => void\n}) {\n  const eventCounts: EventCounts = {\n    errorCount: 0,\n    longTaskCount: 0,\n    resourceCount: 0,\n    actionCount: 0,\n    frustrationCount: 0,\n  }\n\n  const subscription = lifeCycle.subscribe(LifeCycleEventType.RUM_EVENT_COLLECTED, (event): void => {\n    if (event.type === 'view' || event.type === 'vital' || !isChildEvent(event)) {\n      return\n    }\n    switch (event.type) {\n      case RumEventType.ERROR:\n        eventCounts.errorCount += 1\n        callback()\n        break\n      case 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 RumEventType.LONG_TASK:\n        eventCounts.longTaskCount += 1\n        callback()\n        break\n      case RumEventType.RESOURCE:\n        if (!event._dd?.discarded) {\n          eventCounts.resourceCount += 1\n          callback()\n        }\n        break\n    }\n  })\n\n  return {\n    stop: () => {\n      subscription.unsubscribe()\n    },\n    eventCounts,\n  }\n}\n","import type { Duration, RelativeTime } from '@datadog/browser-core'\nimport { addEventListeners, dateNow, DOM_EVENT, relativeNow } from '@datadog/browser-core'\nimport type { RumConfiguration } from '../domain/configuration'\n\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(\n  configuration: RumConfiguration,\n  callback: (timing: PerformanceEventTiming) => void\n) {\n  const startTimeStamp = dateNow()\n  let timingSent = false\n\n  const { stop: removeEventListeners } = addEventListeners(\n    configuration,\n    window,\n    [DOM_EVENT.CLICK, DOM_EVENT.MOUSE_DOWN, DOM_EVENT.KEY_DOWN, DOM_EVENT.TOUCH_START, DOM_EVENT.POINTER_DOWN],\n    (evt) => {\n      // Only count cancelable events, which should trigger behavior important to the user.\n      if (!evt.cancelable) {\n        return\n      }\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: PerformanceEventTiming = {\n        entryType: 'first-input',\n        processingStart: relativeNow(),\n        processingEnd: relativeNow(),\n        startTime: evt.timeStamp as RelativeTime,\n        duration: 0 as Duration, // arbitrary value to avoid nullable duration and simplify INP logic\n        name: '',\n        cancelable: false,\n        target: null,\n        toJSON: () => ({}),\n      }\n\n      if (evt.type === DOM_EVENT.POINTER_DOWN) {\n        sendTimingIfPointerIsNotCancelled(configuration, timing)\n      } else {\n        sendTiming(timing)\n      }\n    },\n    { passive: true, capture: true }\n  )\n\n  return { stop: removeEventListeners }\n\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: RumConfiguration, timing: PerformanceEventTiming) {\n    addEventListeners(\n      configuration,\n      window,\n      [DOM_EVENT.POINTER_UP, DOM_EVENT.POINTER_CANCEL],\n      (event) => {\n        if (event.type === DOM_EVENT.POINTER_UP) {\n          sendTiming(timing)\n        }\n      },\n      { once: true }\n    )\n  }\n\n  function sendTiming(timing: PerformanceEventTiming) {\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","import type { Subscription, TimeoutId, TimeStamp } from '@datadog/browser-core'\nimport {\n  instrumentMethod,\n  matchList,\n  monitor,\n  Observable,\n  timeStampNow,\n  setTimeout,\n  clearTimeout,\n} from '@datadog/browser-core'\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../browser/performanceObservable'\nimport type { RumConfiguration } from './configuration'\nimport type { LifeCycle } from './lifeCycle'\nimport { LifeCycleEventType } from './lifeCycle'\n\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\nexport interface PageActivityEvent {\n  isBusy: boolean\n}\n\nexport type PageActivityEndEvent = { hadActivity: true; end: TimeStamp } | { hadActivity: false }\n\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(\n  lifeCycle: LifeCycle,\n  domMutationObservable: Observable<void>,\n  configuration: RumConfiguration,\n  pageActivityEndCallback: (event: PageActivityEndEvent) => void,\n  maxDuration?: number\n) {\n  const pageActivityObservable = createPageActivityObservable(lifeCycle, domMutationObservable, configuration)\n  return doWaitPageActivityEnd(pageActivityObservable, pageActivityEndCallback, maxDuration)\n}\n\nexport function doWaitPageActivityEnd(\n  pageActivityObservable: Observable<PageActivityEvent>,\n  pageActivityEndCallback: (event: PageActivityEndEvent) => void,\n  maxDuration?: number\n) {\n  let pageActivityEndTimeoutId: TimeoutId\n  let hasCompleted = false\n\n  const validationTimeoutId = setTimeout(\n    monitor(() => complete({ hadActivity: false })),\n    PAGE_ACTIVITY_VALIDATION_DELAY\n  )\n  const maxDurationTimeoutId =\n    maxDuration !== undefined\n      ? setTimeout(\n          monitor(() => complete({ hadActivity: true, end: timeStampNow() })),\n          maxDuration\n        )\n      : undefined\n\n  const pageActivitySubscription = pageActivityObservable.subscribe(({ isBusy }) => {\n    clearTimeout(validationTimeoutId)\n    clearTimeout(pageActivityEndTimeoutId)\n    const lastChangeTime = timeStampNow()\n    if (!isBusy) {\n      pageActivityEndTimeoutId = setTimeout(\n        monitor(() => complete({ hadActivity: true, end: lastChangeTime })),\n        PAGE_ACTIVITY_END_DELAY\n      )\n    }\n  })\n\n  const stop = () => {\n    hasCompleted = true\n    clearTimeout(validationTimeoutId)\n    clearTimeout(pageActivityEndTimeoutId)\n    clearTimeout(maxDurationTimeoutId)\n    pageActivitySubscription.unsubscribe()\n  }\n\n  function complete(event: PageActivityEndEvent) {\n    if (hasCompleted) {\n      return\n    }\n    stop()\n    pageActivityEndCallback(event)\n  }\n  return { stop }\n}\n\nexport function createPageActivityObservable(\n  lifeCycle: LifeCycle,\n  domMutationObservable: Observable<void>,\n  configuration: RumConfiguration\n): Observable<PageActivityEvent> {\n  return new Observable<PageActivityEvent>((observable) => {\n    const subscriptions: Subscription[] = []\n    let firstRequestIndex: undefined | number\n    let pendingRequestsCount = 0\n\n    subscriptions.push(\n      domMutationObservable.subscribe(notifyPageActivity),\n      createPerformanceObservable(configuration, { type: RumPerformanceEntryType.RESOURCE }).subscribe((entries) => {\n        if (entries.some((entry) => !isExcludedUrl(configuration, entry.name))) {\n          notifyPageActivity()\n        }\n      }),\n      lifeCycle.subscribe(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      }),\n      lifeCycle.subscribe(LifeCycleEventType.REQUEST_COMPLETED, (request) => {\n        if (\n          isExcludedUrl(configuration, request.url) ||\n          firstRequestIndex === undefined ||\n          // If the request started before the tracking start, ignore it\n          request.requestIndex < firstRequestIndex\n        ) {\n          return\n        }\n        pendingRequestsCount -= 1\n        notifyPageActivity()\n      })\n    )\n\n    const { stop: stopTrackingWindowOpen } = trackWindowOpen(notifyPageActivity)\n\n    return () => {\n      stopTrackingWindowOpen()\n      subscriptions.forEach((s) => s.unsubscribe())\n    }\n\n    function notifyPageActivity() {\n      observable.notify({ isBusy: pendingRequestsCount > 0 })\n    }\n  })\n}\n\nfunction isExcludedUrl(configuration: RumConfiguration, requestUrl: string): boolean {\n  return matchList(configuration.excludedActivityUrls, requestUrl)\n}\n\nfunction trackWindowOpen(callback: () => void) {\n  return instrumentMethod(window, 'open', callback)\n}\n","// https://github.com/jquery/jquery/blob/a684e6ba836f7c553968d7d026ed7941e1a612d8/src/selector/escapeSelector.js\nexport function cssEscape(str: string) {\n  if (window.CSS && window.CSS.escape) {\n    return window.CSS.escape(str)\n  }\n\n  // eslint-disable-next-line no-control-regex\n  return str.replace(/([\\0-\\x1f\\x7f]|^-?\\d)|^-$|[^\\x80-\\uFFFF\\w-]/g, function (ch, asCodePoint) {\n    if (asCodePoint) {\n      // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER\n      if (ch === '\\0') {\n        return '\\uFFFD'\n      }\n      // Control characters and (dependent upon position) numbers get escaped as code points\n      return `${ch.slice(0, -1)}\\\\${ch.charCodeAt(ch.length - 1).toString(16)} `\n    }\n    // Other potentially-special ASCII characters get backslash-escaped\n    return `\\\\${ch}`\n  })\n}\n\nexport function elementMatches(element: Element & { msMatchesSelector?(selector: string): boolean }, selector: string) {\n  if (element.matches) {\n    return element.matches(selector)\n  }\n  // IE11 support\n  if (element.msMatchesSelector) {\n    return element.msMatchesSelector(selector)\n  }\n  return false\n}\n\n/**\n * Return the parentElement of an node\n *\n * In cases where parentElement is not supported, such as in IE11 for SVG nodes, we fallback to parentNode\n */\nexport function getParentElement(node: Node): HTMLElement | null {\n  if (node.parentElement) {\n    return node.parentElement\n  }\n\n  while (node.parentNode) {\n    if (node.parentNode.nodeType === Node.ELEMENT_NODE) {\n      return node.parentNode as HTMLElement\n    }\n    node = node.parentNode\n  }\n\n  return null\n}\n\n/**\n * Return the classList of an element or an array of classes if classList is not supported\n *\n * In cases where classList is not supported, such as in IE11 for SVG and MathML elements,\n * we fallback to using element.getAttribute('class').\n * We opt for element.getAttribute('class') over element.className because className returns an SVGAnimatedString for SVG elements.\n */\nexport function getClassList(element: Element): DOMTokenList | string[] {\n  if (element.classList) {\n    return element.classList\n  }\n\n  const classes = (element.getAttribute('class') || '').trim()\n  return classes ? classes.split(/\\s+/) : []\n}\n\n// ie11 supports WeakMap but not WeakSet\nconst PLACEHOLDER = 1\n// eslint-disable-next-line no-restricted-syntax\nexport class WeakSet<T extends object> {\n  private map = new WeakMap<T, typeof PLACEHOLDER>()\n\n  constructor(initialValues?: T[]) {\n    if (initialValues) {\n      initialValues.forEach((value) => this.map.set(value, PLACEHOLDER))\n    }\n  }\n\n  add(value: T) {\n    this.map.set(value, PLACEHOLDER)\n\n    return this\n  }\n\n  delete(value: T) {\n    return this.map.delete(value)\n  }\n\n  has(value: T) {\n    return this.map.has(value)\n  }\n}\n","export function isTextNode(node: Node): node is Text {\n  return node.nodeType === Node.TEXT_NODE\n}\n\nexport function isCommentNode(node: Node): node is Comment {\n  return node.nodeType === Node.COMMENT_NODE\n}\n\nexport function isElementNode(node: Node): node is Element {\n  return node.nodeType === Node.ELEMENT_NODE\n}\n\nexport function isNodeShadowHost(node: Node): node is Element & { shadowRoot: ShadowRoot } {\n  return isElementNode(node) && Boolean(node.shadowRoot)\n}\n\nexport function isNodeShadowRoot(node: Node): node is ShadowRoot {\n  const shadowRoot = node as ShadowRoot\n  return !!shadowRoot.host && shadowRoot.nodeType === Node.DOCUMENT_FRAGMENT_NODE && isElementNode(shadowRoot.host)\n}\n\nexport function hasChildNodes(node: Node) {\n  return node.childNodes.length > 0 || isNodeShadowHost(node)\n}\n\nexport function forEachChildNodes(node: Node, callback: (child: Node) => void) {\n  let child = node.firstChild\n\n  while (child) {\n    callback(child)\n\n    child = child.nextSibling\n  }\n\n  if (isNodeShadowHost(node)) {\n    callback(node.shadowRoot)\n  }\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: Node): Node | null {\n  return isNodeShadowRoot(node) ? node.host : node.parentNode\n}\n","import { DefaultPrivacyLevel } from '@datadog/browser-core'\nimport { isElementNode, getParentNode, isTextNode } from '../browser/htmlDomUtils'\nimport { elementMatches } from '../browser/polyfills'\n\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} as const\nexport type NodePrivacyLevel = (typeof NodePrivacyLevel)[keyof typeof NodePrivacyLevel]\n\nexport const PRIVACY_ATTR_NAME = 'data-dd-privacy'\n\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\n// Privacy Classes - not all customers can set plain HTML attributes, so support classes too\nexport const PRIVACY_CLASS_PREFIX = 'dd-privacy-'\n\n// Private Replacement Templates\nexport const CENSORED_STRING_MARK = '***'\nexport const CENSORED_IMG_MARK = 'data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=='\n\nexport const FORM_PRIVATE_TAG_NAMES: { [tagName: string]: true } = {\n  INPUT: true,\n  OUTPUT: true,\n  TEXTAREA: true,\n  SELECT: true,\n  OPTION: true,\n  DATALIST: true,\n  OPTGROUP: true,\n}\n\nconst TEXT_MASKING_CHAR = 'x'\n\nexport type NodePrivacyLevelCache = Map<Node, NodePrivacyLevel>\n\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(\n  node: Node,\n  defaultPrivacyLevel: NodePrivacyLevel,\n  cache?: NodePrivacyLevelCache\n): NodePrivacyLevel {\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/**\n * Reduces the next privacy level based on self + parent privacy levels\n */\nexport function reducePrivacyLevel(\n  childPrivacyLevel: NodePrivacyLevel | undefined,\n  parentNodePrivacyLevel: NodePrivacyLevel\n): NodePrivacyLevel {\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/**\n * Determines the node's own privacy level without checking for ancestors.\n */\nexport function getNodeSelfPrivacyLevel(node: Node): NodePrivacyLevel | undefined {\n  // Only Element types can have a privacy level set\n  if (!isElementNode(node)) {\n    return\n  }\n\n  // Overrules for replay purpose\n  if (node.tagName === 'BASE') {\n    return NodePrivacyLevel.ALLOW\n  }\n\n  // Overrules to enforce end-user protection\n  if (node.tagName === 'INPUT') {\n    const inputElement = node as HTMLInputElement\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]\n    if (autocomplete && autocomplete.indexOf('cc-') === 0) {\n      return NodePrivacyLevel.MASK\n    }\n  }\n\n  // Check HTML privacy attributes and classes\n  if (elementMatches(node, getPrivacySelector(NodePrivacyLevel.HIDDEN))) {\n    return NodePrivacyLevel.HIDDEN\n  }\n\n  if (elementMatches(node, getPrivacySelector(NodePrivacyLevel.MASK))) {\n    return NodePrivacyLevel.MASK\n  }\n\n  if (elementMatches(node, getPrivacySelector(NodePrivacyLevel.MASK_USER_INPUT))) {\n    return NodePrivacyLevel.MASK_USER_INPUT\n  }\n\n  if (elementMatches(node, getPrivacySelector(NodePrivacyLevel.ALLOW))) {\n    return NodePrivacyLevel.ALLOW\n  }\n\n  if (shouldIgnoreElement(node)) {\n    return NodePrivacyLevel.IGNORE\n  }\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: Node, privacyLevel: NodePrivacyLevel) {\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}\n\nfunction isFormElement(node: Node | null): boolean {\n  if (!node || node.nodeType !== node.ELEMENT_NODE) {\n    return false\n  }\n  const element = node as HTMLInputElement\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/**\n * Text censoring non-destructively maintains whitespace characters in order to preserve text shape\n * during replay.\n */\nexport const censorText = (text: string) => text.replace(/\\S/g, TEXT_MASKING_CHAR)\n\nexport function getTextContent(\n  textNode: Node,\n  ignoreWhiteSpace: boolean,\n  parentNodePrivacyLevel: NodePrivacyLevel\n): string | undefined {\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 = textNode.parentElement?.tagName\n  let textContent = textNode.textContent || ''\n\n  if (ignoreWhiteSpace && !textContent.trim()) {\n    return\n  }\n\n  const nodePrivacyLevel = parentNodePrivacyLevel\n\n  const isScript = parentTagName === 'SCRIPT'\n\n  if (isScript) {\n    // For perf reasons, we don't record script (heuristic)\n    textContent = CENSORED_STRING_MARK\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  } 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    ) {\n      if (!textContent.trim()) {\n        return\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    } else {\n      textContent = censorText(textContent)\n    }\n  }\n  return textContent\n}\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: Element): boolean {\n  if (element.nodeName === 'SCRIPT') {\n    return true\n  }\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  }\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  }\n\n  function getLowerCaseAttribute(name: string) {\n    return (element.getAttribute(name) || '').toLowerCase()\n  }\n\n  return false\n}\n\nexport function getPrivacySelector(privacyLevel: string) {\n  return `[${PRIVACY_ATTR_NAME}=\"${privacyLevel}\"], .${PRIVACY_CLASS_PREFIX}${privacyLevel}`\n}\n","import { safeTruncate, isIE, find } from '@datadog/browser-core'\nimport { getParentElement } from '../../browser/polyfills'\nimport { NodePrivacyLevel, getPrivacySelector } from '../privacy'\nimport type { RumConfiguration } from '../configuration'\n\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(\n  element: Element,\n  { enablePrivacyForActionName, actionNameAttribute: userProgrammaticAttribute }: RumConfiguration,\n  nodePrivacyLevel?: NodePrivacyLevel\n): string {\n  // Proceed to get the action name in two steps:\n  // * first, get the name programmatically, explicitly defined by the user.\n  // * then, use strategies that are known to return good results. Those strategies will be used on\n  //   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 =\n    getActionNameFromElementProgrammatically(element, DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE) ||\n    (userProgrammaticAttribute && getActionNameFromElementProgrammatically(element, userProgrammaticAttribute))\n\n  if (nodePrivacyLevel === NodePrivacyLevel.MASK) {\n    return defaultActionName || ACTION_NAME_PLACEHOLDER\n  }\n\n  return (\n    defaultActionName ||\n    getActionNameFromElementForStrategies(\n      element,\n      userProgrammaticAttribute,\n      priorityStrategies,\n      enablePrivacyForActionName\n    ) ||\n    getActionNameFromElementForStrategies(\n      element,\n      userProgrammaticAttribute,\n      fallbackStrategies,\n      enablePrivacyForActionName\n    ) ||\n    ''\n  )\n}\n\nfunction getActionNameFromElementProgrammatically(targetElement: Element, programmaticAttribute: string) {\n  let elementWithAttribute\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  // If available, use element.closest() to match get the attribute from the element or any of its\n  // parent.  Else fallback to a more traditional implementation.\n  if (supportsElementClosest()) {\n    elementWithAttribute = targetElement.closest(`[${programmaticAttribute}]`)\n  } else {\n    let element: Element | null = targetElement\n    while (element) {\n      if (element.hasAttribute(programmaticAttribute)) {\n        elementWithAttribute = element\n        break\n      }\n      element = getParentElement(element)\n    }\n  }\n\n  if (!elementWithAttribute) {\n    return\n  }\n  const name = elementWithAttribute.getAttribute(programmaticAttribute)!\n  return truncate(normalizeWhitespace(name.trim()))\n}\n\ntype NameStrategy = (\n  element: Element | HTMLElement | HTMLInputElement | HTMLSelectElement,\n  userProgrammaticAttribute: string | undefined,\n  privacyEnabledActionName?: boolean\n) => string | undefined | null\n\nconst priorityStrategies: NameStrategy[] = [\n  // associated LABEL text\n  (element, userProgrammaticAttribute, privacy) => {\n    // IE does not support element.labels, so we fallback to a CSS selector based on the element id\n    // instead\n    if (supportsLabelProperty()) {\n      if ('labels' in element && element.labels && element.labels.length > 0) {\n        return getTextualContent(element.labels[0], userProgrammaticAttribute)\n      }\n    } else if (element.id) {\n      const label =\n        element.ownerDocument &&\n        find(element.ownerDocument.querySelectorAll('label'), (label) => label.htmlFor === element.id)\n      return label && getTextualContent(label, userProgrammaticAttribute, privacy)\n    }\n  },\n  // INPUT button (and associated) value\n  (element) => {\n    if (element.nodeName === 'INPUT') {\n      const input = element as HTMLInputElement\n      const type = input.getAttribute('type')\n      if (type === 'button' || type === 'submit' || type === 'reset') {\n        return input.value\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 getTextualContent(element, userProgrammaticAttribute, privacyEnabledActionName)\n    }\n  },\n  (element) => element.getAttribute('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 labelledByAttribute\n        .split(/\\s+/)\n        .map((id) => getElementById(element, id))\n        .filter((label): label is HTMLElement => Boolean(label))\n        .map((element) => getTextualContent(element, userProgrammaticAttribute, privacyEnabledActionName))\n        .join(' ')\n    }\n  },\n  (element) => element.getAttribute('alt'),\n  (element) => element.getAttribute('name'),\n  (element) => element.getAttribute('title'),\n  (element) => element.getAttribute('placeholder'),\n  // SELECT first OPTION text\n  (element, userProgrammaticAttribute) => {\n    if ('options' in element && element.options.length > 0) {\n      return getTextualContent(element.options[0], userProgrammaticAttribute)\n    }\n  },\n]\n\nconst fallbackStrategies: NameStrategy[] = [\n  (element, userProgrammaticAttribute, privacyEnabledActionName) =>\n    getTextualContent(element, userProgrammaticAttribute, privacyEnabledActionName),\n]\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(\n  targetElement: Element,\n  userProgrammaticAttribute: string | undefined,\n  strategies: NameStrategy[],\n  privacyEnabledActionName?: boolean\n) {\n  let element: Element | null = targetElement\n  let recursionCounter = 0\n  while (\n    recursionCounter <= MAX_PARENTS_TO_CONSIDER &&\n    element &&\n    element.nodeName !== 'BODY' &&\n    element.nodeName !== 'HTML' &&\n    element.nodeName !== 'HEAD'\n  ) {\n    for (const strategy of strategies) {\n      const name = strategy(element, userProgrammaticAttribute, privacyEnabledActionName)\n      if (typeof name === 'string') {\n        const trimmedName = name.trim()\n        if (trimmedName) {\n          return truncate(normalizeWhitespace(trimmedName))\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 = getParentElement(element)\n    recursionCounter += 1\n  }\n}\n\nfunction normalizeWhitespace(s: string) {\n  return s.replace(/\\s+/g, ' ')\n}\n\nfunction truncate(s: string) {\n  return s.length > 100 ? `${safeTruncate(s, 100)} [...]` : s\n}\n\nfunction getElementById(refElement: Element, id: string) {\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}\n\nfunction getTextualContent(\n  element: Element | HTMLElement,\n  userProgrammaticAttribute: string | undefined,\n  privacyEnabledActionName?: boolean\n) {\n  if ((element as HTMLElement).isContentEditable) {\n    return\n  }\n\n  if ('innerText' in element) {\n    let text = element.innerText\n\n    const removeTextFromElements = (query: string) => {\n      const list = element.querySelectorAll<Element | HTMLElement>(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\n    if (!supportsInnerTextScriptAndStyleRemoval()) {\n      // remove the inner text of SCRIPT and STYLES from the result. This is a bit dirty, but should\n      // be relatively fast and work in most cases.\n      removeTextFromElements('script, style')\n    }\n\n    // remove the text of elements with programmatic attribute value\n    removeTextFromElements(`[${DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE}]`)\n\n    if (userProgrammaticAttribute) {\n      removeTextFromElements(`[${userProgrammaticAttribute}]`)\n    }\n\n    if (privacyEnabledActionName) {\n      // remove the text of elements with privacy override\n      removeTextFromElements(\n        `${getPrivacySelector(NodePrivacyLevel.HIDDEN)}, ${getPrivacySelector(NodePrivacyLevel.MASK)}`\n      )\n    }\n\n    return text\n  }\n\n  return element.textContent\n}\n\n/**\n * Returns true if element.innerText excludes the text from inline SCRIPT and STYLE element. This\n * should be the case everywhere except on Internet Explorer 10 and 11 (see [1])\n *\n * The innerText property relies on what is actually rendered to compute its output, so to check if\n * it actually excludes SCRIPT and STYLE content, a solution would be to create a style element, set\n * its content to '*', inject it in the document body, and check if the style element innerText\n * property returns '*'. Using a new `document` instance won't work as it is not rendered.\n *\n * This solution requires specific CSP rules (see [2]) to be set by the customer. We want to avoid\n * this, so instead we rely on browser detection. In case of false negative, the impact should be\n * low, since we rely on this result to remove the SCRIPT and STYLE innerText (which will be empty)\n * from a parent element innerText.\n *\n * [1]: https://web.archive.org/web/20210602165716/http://perfectionkills.com/the-poor-misunderstood-innerText/#diff-with-textContent\n * [2]: https://github.com/DataDog/browser-sdk/issues/1084\n */\nfunction supportsInnerTextScriptAndStyleRemoval() {\n  return !isIE()\n}\n\n/**\n * Returns true if the browser supports the element.labels property.  This should be the case\n * everywhere except on Internet Explorer.\n * Note: The result is computed lazily, because we don't want any DOM access when the SDK is\n * evaluated.\n */\nlet supportsLabelPropertyResult: boolean | undefined\nfunction supportsLabelProperty() {\n  if (supportsLabelPropertyResult === undefined) {\n    supportsLabelPropertyResult = 'labels' in HTMLInputElement.prototype\n  }\n  return supportsLabelPropertyResult\n}\n\n/**\n * Returns true if the browser supports the element.closest method.  This should be the case\n * everywhere except on Internet Explorer.\n * Note: The result is computed lazily, because we don't want any DOM access when the SDK is\n * evaluated.\n */\nlet supportsElementClosestResult: boolean | undefined\nfunction supportsElementClosest() {\n  if (supportsElementClosestResult === undefined) {\n    supportsElementClosestResult = 'closest' in HTMLElement.prototype\n  }\n  return supportsElementClosestResult\n}\n","import { cssEscape, elementMatches, getClassList, getParentElement } from '../browser/polyfills'\nimport { DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE } from './action/getActionNameFromElement'\n\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\ntype SelectorGetter = (element: Element, actionNameAttribute: string | undefined) => string | undefined\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: SelectorGetter[] = [getStableAttributeSelector, getIDSelector]\n\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: SelectorGetter[] = [\n  getStableAttributeSelector,\n  getClassSelector,\n  getTagNameSelector,\n]\n\nexport function getSelectorFromElement(\n  targetElement: Element,\n  actionNameAttribute: string | undefined\n): string | undefined {\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: string | undefined\n  let currentElement: Element | null = targetElement\n\n  while (currentElement && currentElement.nodeName !== 'HTML') {\n    const globallyUniqueSelector = findSelector(\n      currentElement,\n      GLOBALLY_UNIQUE_SELECTOR_GETTERS,\n      isSelectorUniqueGlobally,\n      actionNameAttribute,\n      targetElementSelector\n    )\n    if (globallyUniqueSelector) {\n      return globallyUniqueSelector\n    }\n\n    const uniqueSelectorAmongChildren = findSelector(\n      currentElement,\n      UNIQUE_AMONG_CHILDREN_SELECTOR_GETTERS,\n      isSelectorUniqueAmongSiblings,\n      actionNameAttribute,\n      targetElementSelector\n    )\n    targetElementSelector =\n      uniqueSelectorAmongChildren || combineSelector(getPositionSelector(currentElement), targetElementSelector)\n\n    currentElement = getParentElement(currentElement)\n  }\n\n  return targetElementSelector\n}\n\nfunction isGeneratedValue(value: string) {\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}\n\nfunction getIDSelector(element: Element): string | undefined {\n  if (element.id && !isGeneratedValue(element.id)) {\n    return `#${cssEscape(element.id)}`\n  }\n}\n\nfunction getClassSelector(element: Element): string | undefined {\n  if (element.tagName === 'BODY') {\n    return\n  }\n  const classList = getClassList(element)\n  for (let i = 0; i < classList.length; i += 1) {\n    const className = classList[i]\n    if (isGeneratedValue(className)) {\n      continue\n    }\n\n    return `${cssEscape(element.tagName)}.${cssEscape(className)}`\n  }\n}\n\nfunction getTagNameSelector(element: Element): string {\n  return cssEscape(element.tagName)\n}\n\nfunction getStableAttributeSelector(element: Element, actionNameAttribute: string | undefined): string | undefined {\n  if (actionNameAttribute) {\n    const selector = getAttributeSelector(actionNameAttribute)\n    if (selector) {\n      return selector\n    }\n  }\n\n  for (const attributeName of STABLE_ATTRIBUTES) {\n    const selector = getAttributeSelector(attributeName)\n    if (selector) {\n      return selector\n    }\n  }\n\n  function getAttributeSelector(attributeName: string) {\n    if (element.hasAttribute(attributeName)) {\n      return `${cssEscape(element.tagName)}[${attributeName}=\"${cssEscape(element.getAttribute(attributeName)!)}\"]`\n    }\n  }\n}\n\nfunction getPositionSelector(element: Element): string {\n  let sibling = getParentElement(element)!.firstElementChild\n  let elementIndex = 1\n\n  while (sibling && sibling !== element) {\n    if (sibling.tagName === element.tagName) {\n      elementIndex += 1\n    }\n    sibling = sibling.nextElementSibling\n  }\n\n  return `${cssEscape(element.tagName)}:nth-of-type(${elementIndex})`\n}\n\nfunction findSelector(\n  element: Element,\n  selectorGetters: SelectorGetter[],\n  predicate: (element: Element, elementSelector: string, childSelector: string | undefined) => boolean,\n  actionNameAttribute: string | undefined,\n  childSelector: string | undefined\n) {\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/**\n * Check whether the selector is unique among the whole document.\n */\nfunction isSelectorUniqueGlobally(\n  element: Element,\n  elementSelector: string,\n  childSelector: string | undefined\n): boolean {\n  return element.ownerDocument.querySelectorAll(combineSelector(elementSelector, childSelector)).length === 1\n}\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(\n  currentElement: Element,\n  currentElementSelector: string,\n  childSelector: string | undefined\n): boolean {\n  let isSiblingMatching: (sibling: Element) => boolean\n\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) => elementMatches(sibling, currentElementSelector)\n  } else {\n    const scopedSelector = supportScopeSelector()\n      ? combineSelector(`${currentElementSelector}:scope`, childSelector)\n      : combineSelector(currentElementSelector, childSelector)\n    isSiblingMatching = (sibling) => sibling.querySelector(scopedSelector) !== null\n  }\n\n  const parent = getParentElement(currentElement)!\n  let sibling = parent.firstElementChild\n  while (sibling) {\n    if (sibling !== currentElement && isSiblingMatching(sibling)) {\n      return false\n    }\n    sibling = sibling.nextElementSibling\n  }\n\n  return true\n}\n\nfunction combineSelector(parent: string, child: string | undefined): string {\n  return child ? `${parent}>${child}` : parent\n}\n\nlet supportScopeSelectorCache: boolean | undefined\nexport function supportScopeSelector() {\n  if (supportScopeSelectorCache === undefined) {\n    try {\n      document.querySelector(':scope')\n      supportScopeSelectorCache = true\n    } catch {\n      supportScopeSelectorCache = false\n    }\n  }\n  return supportScopeSelectorCache\n}\n\n/**\n * Polyfill-utility for the `isConnected` property not supported in IE11\n */\nfunction isConnected(element: Element): boolean {\n  if (\n    'isConnected' in\n    // cast is to make sure `element` is not inferred as `never` after the check\n    (element as { isConnected?: boolean })\n  ) {\n    return element.isConnected\n  }\n\n  return element.ownerDocument.documentElement.contains(element)\n}\n","import type { TimeoutId } from '@datadog/browser-core'\nimport { ONE_SECOND, clearTimeout, setTimeout } from '@datadog/browser-core'\nimport type { Click } from './trackClickActions'\n\nexport interface ClickChain {\n  tryAppend: (click: Click) => boolean\n  stop: () => void\n}\n\nexport const MAX_DURATION_BETWEEN_CLICKS = ONE_SECOND\nexport const MAX_DISTANCE_BETWEEN_CLICKS = 100\n\nconst enum ClickChainStatus {\n  WaitingForMoreClicks,\n  WaitingForClicksToStop,\n  Finalized,\n}\n\nexport function createClickChain(firstClick: Click, onFinalize: (clicks: Click[]) => void): ClickChain {\n  const bufferedClicks: Click[] = []\n  let status = ClickChainStatus.WaitingForMoreClicks\n  let maxDurationBetweenClicksTimeoutId: TimeoutId | undefined\n  appendClick(firstClick)\n\n  function appendClick(click: Click) {\n    click.stopObservable.subscribe(tryFinalize)\n    bufferedClicks.push(click)\n    clearTimeout(maxDurationBetweenClicksTimeoutId)\n    maxDurationBetweenClicksTimeoutId = setTimeout(dontAcceptMoreClick, MAX_DURATION_BETWEEN_CLICKS)\n  }\n\n  function tryFinalize() {\n    if (status === ClickChainStatus.WaitingForClicksToStop && bufferedClicks.every((click) => click.isStopped())) {\n      status = ClickChainStatus.Finalized\n      onFinalize(bufferedClicks)\n    }\n  }\n\n  function dontAcceptMoreClick() {\n    clearTimeout(maxDurationBetweenClicksTimeoutId)\n    if (status === ClickChainStatus.WaitingForMoreClicks) {\n      status = ClickChainStatus.WaitingForClicksToStop\n      tryFinalize()\n    }\n  }\n\n  return {\n    tryAppend: (click) => {\n      if (status !== ClickChainStatus.WaitingForMoreClicks) {\n        return false\n      }\n\n      if (\n        bufferedClicks.length > 0 &&\n        !areEventsSimilar(bufferedClicks[bufferedClicks.length - 1].event, click.event)\n      ) {\n        dontAcceptMoreClick()\n        return false\n      }\n\n      appendClick(click)\n      return true\n    },\n    stop: () => {\n      dontAcceptMoreClick()\n    },\n  }\n}\n\n/**\n * Checks whether two events are similar by comparing their target, position and timestamp\n */\nfunction areEventsSimilar(first: MouseEvent, second: MouseEvent) {\n  return (\n    first.target === second.target &&\n    mouseEventDistance(first, second) <= MAX_DISTANCE_BETWEEN_CLICKS &&\n    first.timeStamp - second.timeStamp <= MAX_DURATION_BETWEEN_CLICKS\n  )\n}\n\nfunction mouseEventDistance(origin: MouseEvent, other: MouseEvent) {\n  return Math.sqrt(Math.pow(origin.clientX - other.clientX, 2) + Math.pow(origin.clientY - other.clientY, 2))\n}\n","import { addEventListener, DOM_EVENT } from '@datadog/browser-core'\nimport type { RelativeTime } from '@datadog/browser-core'\nimport type { RumConfiguration } from '../configuration'\n\nexport type ExtraPointerEventFields = {\n  target: Element\n  timeStamp: RelativeTime\n}\nexport type MouseEventOnElement = PointerEvent & ExtraPointerEventFields\n\nexport interface UserActivity {\n  selection: boolean\n  input: boolean\n  scroll: boolean\n}\nexport interface ActionEventsHooks<ClickContext> {\n  onPointerDown: (event: MouseEventOnElement) => ClickContext | undefined\n  onPointerUp: (context: ClickContext, event: MouseEventOnElement, getUserActivity: () => UserActivity) => void\n}\n\nexport function listenActionEvents<ClickContext>(\n  configuration: RumConfiguration,\n  { onPointerDown, onPointerUp }: ActionEventsHooks<ClickContext>\n) {\n  let selectionEmptyAtPointerDown: boolean\n  let userActivity: UserActivity = {\n    selection: false,\n    input: false,\n    scroll: false,\n  }\n  let clickContext: ClickContext | undefined\n\n  const listeners = [\n    addEventListener(\n      configuration,\n      window,\n      DOM_EVENT.POINTER_DOWN,\n      (event: PointerEvent) => {\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      },\n      { capture: true }\n    ),\n\n    addEventListener(\n      configuration,\n      window,\n      DOM_EVENT.SELECTION_CHANGE,\n      () => {\n        if (!selectionEmptyAtPointerDown || !isSelectionEmpty()) {\n          userActivity.selection = true\n        }\n      },\n      { capture: true }\n    ),\n\n    addEventListener(\n      configuration,\n      window,\n      DOM_EVENT.SCROLL,\n      () => {\n        userActivity.scroll = true\n      },\n      { capture: true, passive: true }\n    ),\n\n    addEventListener(\n      configuration,\n      window,\n      DOM_EVENT.POINTER_UP,\n      (event: PointerEvent) => {\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      },\n      { capture: true }\n    ),\n\n    addEventListener(\n      configuration,\n      window,\n      DOM_EVENT.INPUT,\n      () => {\n        userActivity.input = true\n      },\n      { capture: true }\n    ),\n  ]\n\n  return {\n    stop: () => {\n      listeners.forEach((listener) => listener.stop())\n    },\n  }\n}\n\nfunction isSelectionEmpty(): boolean {\n  const selection = window.getSelection()\n  return !selection || selection.isCollapsed\n}\n\nfunction isValidPointerEvent(event: PointerEvent): event is MouseEventOnElement {\n  return (\n    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}\n","import { ONE_SECOND } from '@datadog/browser-core'\nimport { FrustrationType } from '../../rawRumEvent.types'\nimport { elementMatches } from '../../browser/polyfills'\nimport type { Click } from './trackClickActions'\n\nconst MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE = 3\n\nexport function computeFrustration(clicks: Click[], rageClick: Click) {\n  if (isRage(clicks)) {\n    rageClick.addFrustration(FrustrationType.RAGE_CLICK)\n    if (clicks.some(isDead)) {\n      rageClick.addFrustration(FrustrationType.DEAD_CLICK)\n    }\n    if (rageClick.hasError) {\n      rageClick.addFrustration(FrustrationType.ERROR_CLICK)\n    }\n    return { isRage: true }\n  }\n\n  const hasSelectionChanged = clicks.some((click) => click.getUserActivity().selection)\n  clicks.forEach((click) => {\n    if (click.hasError) {\n      click.addFrustration(FrustrationType.ERROR_CLICK)\n    }\n    if (\n      isDead(click) &&\n      // Avoid considering clicks part of a double-click or triple-click selections as dead clicks\n      !hasSelectionChanged\n    ) {\n      click.addFrustration(FrustrationType.DEAD_CLICK)\n    }\n  })\n  return { isRage: false }\n}\n\nexport function isRage(clicks: Click[]) {\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 (\n      clicks[i + MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE - 1].event.timeStamp - clicks[i].event.timeStamp <=\n      ONE_SECOND\n    ) {\n      return true\n    }\n  }\n  return false\n}\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] *'\n\nexport function isDead(click: Click) {\n  if (click.hasPageActivity || click.getUserActivity().input || click.getUserActivity().scroll) {\n    return false\n  }\n  return !elementMatches(click.event.target, DEAD_CLICK_EXCLUDE_SELECTOR)\n}\n","import { elapsed, ONE_SECOND, relativeNow } from '@datadog/browser-core'\nimport type { RelativeTime } from '@datadog/browser-core'\n\n// Maximum duration for click actions\nexport const CLICK_ACTION_MAX_DURATION = 10 * ONE_SECOND\nexport const interactionSelectorCache = new Map<RelativeTime, string>()\n\nexport function getInteractionSelector(relativeTimestamp: RelativeTime) {\n  const selector = interactionSelectorCache.get(relativeTimestamp)\n  interactionSelectorCache.delete(relativeTimestamp)\n  return selector\n}\n\nexport function updateInteractionSelector(relativeTimestamp: RelativeTime, selector: string) {\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","import type { Duration, ClocksState, RelativeTime, TimeStamp, ValueHistory } from '@datadog/browser-core'\nimport {\n  includes,\n  timeStampNow,\n  Observable,\n  assign,\n  getRelativeTime,\n  ONE_MINUTE,\n  generateUUID,\n  clocksNow,\n  elapsed,\n  createValueHistory,\n} from '@datadog/browser-core'\nimport type { FrustrationType } from '../../rawRumEvent.types'\nimport { ActionType } from '../../rawRumEvent.types'\nimport type { LifeCycle } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport { trackEventCounts } from '../trackEventCounts'\nimport { PAGE_ACTIVITY_VALIDATION_DELAY, waitPageActivityEnd } from '../waitPageActivityEnd'\nimport { getSelectorFromElement } from '../getSelectorFromElement'\nimport { getNodePrivacyLevel, NodePrivacyLevel } from '../privacy'\nimport type { RumConfiguration } from '../configuration'\nimport type { ClickChain } from './clickChain'\nimport { createClickChain } from './clickChain'\nimport { getActionNameFromElement } from './getActionNameFromElement'\nimport type { MouseEventOnElement, UserActivity } from './listenActionEvents'\nimport { listenActionEvents } from './listenActionEvents'\nimport { computeFrustration } from './computeFrustration'\nimport { CLICK_ACTION_MAX_DURATION, updateInteractionSelector } from './interactionSelectorCache'\n\ninterface ActionCounts {\n  errorCount: number\n  longTaskCount: number\n  resourceCount: number\n}\n\nexport interface ClickAction {\n  type: ActionType.CLICK\n  id: string\n  name: string\n  target?: {\n    selector: string | undefined\n    width: number\n    height: number\n  }\n  position?: { x: number; y: number }\n  startClocks: ClocksState\n  duration?: Duration\n  counts: ActionCounts\n  event: MouseEventOnElement\n  frustrationTypes: FrustrationType[]\n  events: Event[]\n}\n\nexport interface ActionContexts {\n  findActionId: (startTime?: RelativeTime) => string | string[] | undefined\n}\n\ntype ClickActionIdHistory = ValueHistory<ClickAction['id']>\n\nexport const ACTION_CONTEXT_TIME_OUT_DELAY = 5 * ONE_MINUTE // arbitrary\n\nexport function trackClickActions(\n  lifeCycle: LifeCycle,\n  domMutationObservable: Observable<void>,\n  configuration: RumConfiguration\n) {\n  const history: ClickActionIdHistory = createValueHistory({ expireDelay: ACTION_CONTEXT_TIME_OUT_DELAY })\n  const stopObservable = new Observable<void>()\n  let currentClickChain: ClickChain | undefined\n\n  lifeCycle.subscribe(LifeCycleEventType.SESSION_RENEWED, () => {\n    history.reset()\n  })\n\n  lifeCycle.subscribe(LifeCycleEventType.VIEW_ENDED, stopClickChain)\n\n  const { stop: stopActionEventsListener } = listenActionEvents<{\n    clickActionBase: ClickActionBase\n    hadActivityOnPointerDown: () => boolean\n  }>(configuration, {\n    onPointerDown: (pointerDownEvent) =>\n      processPointerDown(configuration, lifeCycle, domMutationObservable, pointerDownEvent),\n    onPointerUp: ({ clickActionBase, hadActivityOnPointerDown }, startEvent, getUserActivity) => {\n      startClickAction(\n        configuration,\n        lifeCycle,\n        domMutationObservable,\n        history,\n        stopObservable,\n        appendClickToClickChain,\n        clickActionBase,\n        startEvent,\n        getUserActivity,\n        hadActivityOnPointerDown\n      )\n    },\n  })\n\n  const actionContexts: ActionContexts = {\n    findActionId: (startTime?: RelativeTime) => history.findAll(startTime),\n  }\n\n  return {\n    stop: () => {\n      stopClickChain()\n      stopObservable.notify()\n      stopActionEventsListener()\n    },\n    actionContexts,\n  }\n\n  function appendClickToClickChain(click: 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\n  function stopClickChain() {\n    if (currentClickChain) {\n      currentClickChain.stop()\n    }\n  }\n}\n\nfunction processPointerDown(\n  configuration: RumConfiguration,\n  lifeCycle: LifeCycle,\n  domMutationObservable: Observable<void>,\n  pointerDownEvent: MouseEventOnElement\n) {\n  const nodePrivacyLevel = configuration.enablePrivacyForActionName\n    ? getNodePrivacyLevel(pointerDownEvent.target, configuration.defaultPrivacyLevel)\n    : NodePrivacyLevel.ALLOW\n\n  if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n    return undefined\n  }\n\n  const clickActionBase = computeClickActionBase(pointerDownEvent, nodePrivacyLevel, configuration)\n\n  let hadActivityOnPointerDown = false\n\n  waitPageActivityEnd(\n    lifeCycle,\n    domMutationObservable,\n    configuration,\n    (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  )\n\n  return { clickActionBase, hadActivityOnPointerDown: () => hadActivityOnPointerDown }\n}\n\nfunction startClickAction(\n  configuration: RumConfiguration,\n  lifeCycle: LifeCycle,\n  domMutationObservable: Observable<void>,\n  history: ClickActionIdHistory,\n  stopObservable: Observable<void>,\n  appendClickToClickChain: (click: Click) => void,\n  clickActionBase: ClickActionBase,\n  startEvent: MouseEventOnElement,\n  getUserActivity: () => UserActivity,\n  hadActivityOnPointerDown: () => boolean\n) {\n  const click = newClick(lifeCycle, history, getUserActivity, clickActionBase, startEvent)\n  appendClickToClickChain(click)\n\n  const selector = clickActionBase?.target?.selector\n  if (selector) {\n    updateInteractionSelector(startEvent.timeStamp, selector)\n  }\n\n  const { stop: stopWaitPageActivityEnd } = waitPageActivityEnd(\n    lifeCycle,\n    domMutationObservable,\n    configuration,\n    (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      } else {\n        if (pageActivityEndEvent.hadActivity) {\n          click.stop(pageActivityEndEvent.end)\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    },\n    CLICK_ACTION_MAX_DURATION\n  )\n\n  const viewEndedSubscription = lifeCycle.subscribe(LifeCycleEventType.VIEW_ENDED, ({ endClocks }) => {\n    click.stop(endClocks.timeStamp)\n  })\n\n  const stopSubscription = stopObservable.subscribe(() => {\n    click.stop()\n  })\n\n  click.stopObservable.subscribe(() => {\n    viewEndedSubscription.unsubscribe()\n    stopWaitPageActivityEnd()\n    stopSubscription.unsubscribe()\n  })\n}\n\ntype ClickActionBase = Pick<ClickAction, 'type' | 'name' | 'target' | 'position'>\n\nfunction computeClickActionBase(\n  event: MouseEventOnElement,\n  nodePrivacyLevel: NodePrivacyLevel,\n  configuration: RumConfiguration\n): ClickActionBase {\n  const rect = event.target.getBoundingClientRect()\n  const selector = getSelectorFromElement(event.target, configuration.actionNameAttribute)\n  if (selector) {\n    updateInteractionSelector(event.timeStamp, selector)\n  }\n\n  return {\n    type: 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: getActionNameFromElement(event.target, configuration, nodePrivacyLevel),\n  }\n}\n\nconst enum ClickStatus {\n  // Initial state, the click is still ongoing.\n  ONGOING,\n  // The click is no more ongoing but still needs to be validated or discarded.\n  STOPPED,\n  // Final state, the click has been stopped and validated or discarded.\n  FINALIZED,\n}\n\nexport type Click = ReturnType<typeof newClick>\n\nfunction newClick(\n  lifeCycle: LifeCycle,\n  history: ClickActionIdHistory,\n  getUserActivity: () => UserActivity,\n  clickActionBase: ClickActionBase,\n  startEvent: MouseEventOnElement\n) {\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) =>\n      event.action !== undefined &&\n      (Array.isArray(event.action.id) ? includes(event.action.id, id) : event.action.id === id),\n  })\n  let status = ClickStatus.ONGOING\n  let activityEndTime: undefined | TimeStamp\n  const frustrationTypes: FrustrationType[] = []\n  const stopObservable = new Observable<void>()\n\n  function stop(newActivityEndTime?: TimeStamp) {\n    if (status !== ClickStatus.ONGOING) {\n      return\n    }\n    activityEndTime = newActivityEndTime\n    status = ClickStatus.STOPPED\n    if (activityEndTime) {\n      historyEntry.close(getRelativeTime(activityEndTime))\n    } else {\n      historyEntry.remove()\n    }\n    eventCountsSubscription.stop()\n    stopObservable.notify()\n  }\n\n  return {\n    event: startEvent,\n    stop,\n    stopObservable,\n\n    get hasError() {\n      return eventCountsSubscription.eventCounts.errorCount > 0\n    },\n    get hasPageActivity() {\n      return activityEndTime !== undefined\n    },\n    getUserActivity,\n    addFrustration: (frustrationType: FrustrationType) => {\n      frustrationTypes.push(frustrationType)\n    },\n    startClocks,\n\n    isStopped: () => status === ClickStatus.STOPPED || status === ClickStatus.FINALIZED,\n\n    clone: () => newClick(lifeCycle, history, getUserActivity, clickActionBase, startEvent),\n\n    validate: (domEvents?: Event[]) => {\n      stop()\n      if (status !== ClickStatus.STOPPED) {\n        return\n      }\n\n      const { resourceCount, errorCount, longTaskCount } = eventCountsSubscription.eventCounts\n      const clickAction: ClickAction = assign(\n        {\n          type: ActionType.CLICK as const,\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 ?? [startEvent],\n          event: startEvent,\n        },\n        clickActionBase\n      )\n      lifeCycle.notify(LifeCycleEventType.AUTO_ACTION_COMPLETED, clickAction)\n      status = ClickStatus.FINALIZED\n    },\n\n    discard: () => {\n      stop()\n      status = ClickStatus.FINALIZED\n    },\n  }\n}\n\nexport function finalizeClicks(clicks: Click[], rageClick: Click) {\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  } else {\n    rageClick.discard()\n    clicks.forEach((click) => click.validate())\n  }\n}\n","import type { ClocksState, Context, Observable } from '@datadog/browser-core'\nimport { noop, assign, combine, toServerDuration, generateUUID } from '@datadog/browser-core'\n\nimport { discardNegativeDuration } from '../discardNegativeDuration'\nimport type { RawRumActionEvent } from '../../rawRumEvent.types'\nimport { ActionType, RumEventType } from '../../rawRumEvent.types'\nimport type { LifeCycle, RawRumEventCollectedData } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport type { RumConfiguration } from '../configuration'\nimport type { CommonContext } from '../contexts/commonContext'\nimport type { PageStateHistory } from '../contexts/pageStateHistory'\nimport { PageState } from '../contexts/pageStateHistory'\nimport type { RumActionEventDomainContext } from '../../domainContext.types'\nimport type { ActionContexts, ClickAction } from './trackClickActions'\nimport { trackClickActions } from './trackClickActions'\n\nexport type { ActionContexts }\n\nexport interface CustomAction {\n  type: ActionType.CUSTOM\n  name: string\n  startClocks: ClocksState\n  context?: Context\n  handlingStack?: string\n}\n\nexport type AutoAction = ClickAction\n\nexport function startActionCollection(\n  lifeCycle: LifeCycle,\n  domMutationObservable: Observable<void>,\n  configuration: RumConfiguration,\n  pageStateHistory: PageStateHistory\n) {\n  lifeCycle.subscribe(LifeCycleEventType.AUTO_ACTION_COMPLETED, (action) =>\n    lifeCycle.notify(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, processAction(action, pageStateHistory))\n  )\n\n  let actionContexts: ActionContexts = { findActionId: noop as () => undefined }\n  if (configuration.trackUserInteractions) {\n    actionContexts = trackClickActions(lifeCycle, domMutationObservable, configuration).actionContexts\n  }\n\n  return {\n    addAction: (action: CustomAction, savedCommonContext?: CommonContext) => {\n      lifeCycle.notify(\n        LifeCycleEventType.RAW_RUM_EVENT_COLLECTED,\n        assign(\n          {\n            savedCommonContext,\n          },\n          processAction(action, pageStateHistory)\n        )\n      )\n    },\n    actionContexts,\n  }\n}\n\nfunction processAction(\n  action: AutoAction | CustomAction,\n  pageStateHistory: PageStateHistory\n): RawRumEventCollectedData<RawRumActionEvent> {\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          },\n        },\n      }\n    : undefined\n  const customerContext = !isAutoAction(action) ? action.context : undefined\n  const actionEvent: RawRumActionEvent = combine(\n    {\n      action: {\n        id: generateUUID(),\n        target: {\n          name: action.name,\n        },\n        type: action.type,\n      },\n      date: action.startClocks.timeStamp,\n      type: RumEventType.ACTION as const,\n      view: { in_foreground: pageStateHistory.wasInPageStateAt(PageState.ACTIVE, action.startClocks.relative) },\n    },\n    autoActionProperties\n  )\n\n  const domainContext: RumActionEventDomainContext = isAutoAction(action) ? { events: action.events } : {}\n\n  if (!isAutoAction(action) && action.handlingStack) {\n    domainContext.handlingStack = action.handlingStack\n  }\n\n  return {\n    customerContext,\n    rawRumEvent: actionEvent,\n    startTime: action.startClocks.relative,\n    domainContext,\n  }\n}\n\nfunction isAutoAction(action: AutoAction | CustomAction): action is AutoAction {\n  return action.type !== ActionType.CUSTOM\n}\n","import { instrumentMethod } from '../../tools/instrumentMethod'\nimport type { Observable } from '../../tools/observable'\nimport { clocksNow } from '../../tools/utils/timeUtils'\nimport type { StackTrace } from '../../tools/stackTrace/computeStackTrace'\nimport { computeStackTrace, computeStackTraceFromOnErrorMessage } from '../../tools/stackTrace/computeStackTrace'\nimport { computeRawError } from './error'\nimport type { RawError } from './error.types'\nimport { ErrorHandling, ErrorSource, NonErrorPrefix } from './error.types'\n\nexport type UnhandledErrorCallback = (stackTrace: StackTrace, originalError?: any) => any\n\nexport function trackRuntimeError(errorObservable: Observable<RawError>) {\n  const handleRuntimeError = (stackTrace: StackTrace, originalError?: any) => {\n    const rawError = computeRawError({\n      stackTrace,\n      originalError,\n      startClocks: clocksNow(),\n      nonErrorPrefix: NonErrorPrefix.UNCAUGHT,\n      source: ErrorSource.SOURCE,\n      handling: ErrorHandling.UNHANDLED,\n    })\n    errorObservable.notify(rawError)\n  }\n  const { stop: stopInstrumentingOnError } = instrumentOnError(handleRuntimeError)\n  const { stop: stopInstrumentingOnUnhandledRejection } = instrumentUnhandledRejection(handleRuntimeError)\n\n  return {\n    stop: () => {\n      stopInstrumentingOnError()\n      stopInstrumentingOnUnhandledRejection()\n    },\n  }\n}\n\nexport function instrumentOnError(callback: UnhandledErrorCallback) {\n  return instrumentMethod(window, 'onerror', ({ parameters: [messageObj, url, line, column, errorObj] }) => {\n    let stackTrace\n    if (errorObj instanceof Error) {\n      stackTrace = computeStackTrace(errorObj)\n    } else {\n      stackTrace = computeStackTraceFromOnErrorMessage(messageObj, url, line, column)\n    }\n    callback(stackTrace, errorObj ?? messageObj)\n  })\n}\n\nexport function instrumentUnhandledRejection(callback: UnhandledErrorCallback) {\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","import { flattenErrorCauses, 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 { find } from '../../tools/utils/polyfills'\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify'\nimport type { RawError } from '../error/error.types'\nimport { ErrorHandling, 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'\n\nexport type ConsoleLog = NonErrorConsoleLog | ErrorConsoleLog\n\ninterface NonErrorConsoleLog extends ConsoleLogBase {\n  api: Exclude<ConsoleApiName, typeof ConsoleApiName.error>\n  error: undefined\n}\n\nexport interface ErrorConsoleLog extends ConsoleLogBase {\n  api: typeof ConsoleApiName.error\n  error: RawError\n}\n\ninterface ConsoleLogBase {\n  message: string\n  api: ConsoleApiName\n  handlingStack: string\n}\n\ntype ConsoleLogForApi<T extends ConsoleApiName> = T extends typeof ConsoleApiName.error\n  ? ErrorConsoleLog\n  : NonErrorConsoleLog\n\nlet consoleObservablesByApi: { [K in ConsoleApiName]?: Observable<ConsoleLogForApi<K>> } = {}\n\nexport function initConsoleObservable<T extends ConsoleApiName[]>(apis: T): Observable<ConsoleLogForApi<T[number]>> {\n  const consoleObservables = apis.map((api) => {\n    if (!consoleObservablesByApi[api]) {\n      consoleObservablesByApi[api] = createConsoleObservable(api) as any // we are sure that the observable created for this api will yield the expected ConsoleLog type\n    }\n    return consoleObservablesByApi[api] as unknown as Observable<ConsoleLogForApi<T[number]>>\n  })\n\n  return mergeObservables(...consoleObservables)\n}\n\nexport function resetConsoleObservable() {\n  consoleObservablesByApi = {}\n}\n\nfunction createConsoleObservable(api: ConsoleApiName) {\n  return new Observable<ConsoleLog>((observable) => {\n    const originalConsoleApi = globalConsole[api]\n\n    globalConsole[api] = (...params: unknown[]) => {\n      originalConsoleApi.apply(console, params)\n      const handlingStack = createHandlingStack()\n\n      callMonitored(() => {\n        observable.notify(buildConsoleLog(params, api, handlingStack))\n      })\n    }\n\n    return () => {\n      globalConsole[api] = originalConsoleApi\n    }\n  })\n}\n\nfunction buildConsoleLog(params: unknown[], api: ConsoleApiName, handlingStack: string): ConsoleLog {\n  const message = params.map((param) => formatConsoleParameters(param)).join(' ')\n  let error: RawError | undefined\n\n  if (api === ConsoleApiName.error) {\n    const firstErrorParam = find(params, (param: unknown): param is Error => param instanceof Error)\n\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: ErrorHandling.HANDLED,\n      handlingStack,\n    }\n  }\n\n  return {\n    api,\n    message,\n    error,\n    handlingStack,\n  } as ConsoleLog\n}\n\nfunction formatConsoleParameters(param: unknown) {\n  if (typeof param === 'string') {\n    return sanitize(param)\n  }\n  if (param instanceof Error) {\n    return formatErrorMessage(computeStackTrace(param))\n  }\n  return jsonStringify(sanitize(param), undefined, 2)\n}\n","import { toStackTraceString } from '../../tools/stackTrace/handlingStack'\nimport { monitor } from '../../tools/monitor'\nimport { mergeObservables, Observable } from '../../tools/observable'\nimport { addEventListener, DOM_EVENT } from '../../browser/addEventListener'\nimport { assign, includes } from '../../tools/utils/polyfills'\nimport { safeTruncate } from '../../tools/utils/stringUtils'\nimport type { Configuration } from '../configuration'\nimport type { RawError } from '../error/error.types'\nimport { ErrorHandling, ErrorSource } from '../error/error.types'\nimport { clocksNow } from '../../tools/utils/timeUtils'\nimport type { ReportType, InterventionReport, DeprecationReport } from './browser.types'\n\nexport const RawReportType = {\n  intervention: 'intervention',\n  deprecation: 'deprecation',\n  cspViolation: 'csp_violation',\n} as const\n\nexport type RawReportType = (typeof RawReportType)[keyof typeof RawReportType]\n\nexport type RawReportError = RawError & {\n  originalError: SecurityPolicyViolationEvent | DeprecationReport | InterventionReport\n}\n\nexport function initReportObservable(configuration: Configuration, apis: RawReportType[]) {\n  const observables: Array<Observable<RawReportError>> = []\n\n  if (includes(apis, RawReportType.cspViolation)) {\n    observables.push(createCspViolationReportObservable(configuration))\n  }\n\n  const reportTypes = apis.filter((api: RawReportType): api is ReportType => api !== RawReportType.cspViolation)\n  if (reportTypes.length) {\n    observables.push(createReportObservable(reportTypes))\n  }\n\n  return mergeObservables(...observables)\n}\n\nfunction createReportObservable(reportTypes: ReportType[]) {\n  return new Observable<RawReportError>((observable) => {\n    if (!window.ReportingObserver) {\n      return\n    }\n\n    const handleReports = monitor((reports: Array<DeprecationReport | InterventionReport>, _: ReportingObserver) =>\n      reports.forEach((report) => observable.notify(buildRawReportErrorFromReport(report)))\n    ) as ReportingObserverCallback\n\n    const observer = new window.ReportingObserver(handleReports, {\n      types: reportTypes,\n      buffered: true,\n    })\n\n    observer.observe()\n    return () => {\n      observer.disconnect()\n    }\n  })\n}\n\nfunction createCspViolationReportObservable(configuration: Configuration) {\n  return new Observable<RawReportError>((observable) => {\n    const { stop } = addEventListener(configuration, document, DOM_EVENT.SECURITY_POLICY_VIOLATION, (event) => {\n      observable.notify(buildRawReportErrorFromCspViolation(event))\n    })\n\n    return stop\n  })\n}\n\nfunction buildRawReportErrorFromReport(report: DeprecationReport | InterventionReport): RawReportError {\n  const { type, body } = report\n\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}\n\nfunction buildRawReportErrorFromCspViolation(event: SecurityPolicyViolationEvent): RawReportError {\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(\n      event.effectiveDirective,\n      event.originalPolicy\n        ? `${message} of the policy \"${safeTruncate(event.originalPolicy, 100, '...')}\"`\n        : 'no policy',\n      event.sourceFile,\n      event.lineNumber,\n      event.columnNumber\n    ),\n  })\n}\n\nfunction buildRawReportError(partial: Omit<RawReportError, 'startClocks' | 'source' | 'handling'>): RawReportError {\n  return assign(\n    {\n      startClocks: clocksNow(),\n      source: ErrorSource.REPORT,\n      handling: ErrorHandling.UNHANDLED,\n    },\n    partial\n  )\n}\n\nfunction buildStack(\n  name: string,\n  message: string,\n  sourceFile: string | null,\n  lineNumber: number | null,\n  columnNumber: number | null\n): string | undefined {\n  return sourceFile\n    ? toStackTraceString({\n        name,\n        message,\n        stack: [\n          {\n            func: '?',\n            url: sourceFile,\n            line: lineNumber ?? undefined,\n            column: columnNumber ?? undefined,\n          },\n        ],\n      })\n    : undefined\n}\n","import type { Context, RawError, ClocksState } from '@datadog/browser-core'\nimport {\n  isEmptyObject,\n  assign,\n  ErrorSource,\n  generateUUID,\n  computeRawError,\n  ErrorHandling,\n  computeStackTrace,\n  Observable,\n  trackRuntimeError,\n  NonErrorPrefix,\n} from '@datadog/browser-core'\nimport type { RumConfiguration } from '../configuration'\nimport type { RawRumErrorEvent } from '../../rawRumEvent.types'\nimport { RumEventType } from '../../rawRumEvent.types'\nimport type { LifeCycle, RawRumEventCollectedData } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport type { FeatureFlagContexts } from '../contexts/featureFlagContext'\nimport type { CommonContext } from '../contexts/commonContext'\nimport type { PageStateHistory } from '../contexts/pageStateHistory'\nimport { PageState } from '../contexts/pageStateHistory'\nimport type { RumErrorEventDomainContext } from '../../domainContext.types'\nimport { trackConsoleError } from './trackConsoleError'\nimport { trackReportError } from './trackReportError'\n\nexport interface ProvidedError {\n  startClocks: ClocksState\n  error: unknown\n  context?: Context\n  handlingStack: string\n}\n\nexport function startErrorCollection(\n  lifeCycle: LifeCycle,\n  configuration: RumConfiguration,\n  pageStateHistory: PageStateHistory,\n  featureFlagContexts: FeatureFlagContexts\n) {\n  const errorObservable = new Observable<RawError>()\n\n  trackConsoleError(errorObservable)\n  trackRuntimeError(errorObservable)\n  trackReportError(configuration, errorObservable)\n\n  errorObservable.subscribe((error) => lifeCycle.notify(LifeCycleEventType.RAW_ERROR_COLLECTED, { error }))\n\n  return doStartErrorCollection(lifeCycle, pageStateHistory, featureFlagContexts)\n}\n\nexport function doStartErrorCollection(\n  lifeCycle: LifeCycle,\n  pageStateHistory: PageStateHistory,\n  featureFlagContexts: FeatureFlagContexts\n) {\n  lifeCycle.subscribe(LifeCycleEventType.RAW_ERROR_COLLECTED, ({ error, customerContext, savedCommonContext }) => {\n    lifeCycle.notify(\n      LifeCycleEventType.RAW_RUM_EVENT_COLLECTED,\n      assign(\n        {\n          customerContext,\n          savedCommonContext,\n        },\n        processError(error, pageStateHistory, featureFlagContexts)\n      )\n    )\n  })\n\n  return {\n    addError: (\n      { error, handlingStack, startClocks, context: customerContext }: ProvidedError,\n      savedCommonContext?: CommonContext\n    ) => {\n      const stackTrace = error instanceof Error ? computeStackTrace(error) : undefined\n      const rawError = computeRawError({\n        stackTrace,\n        originalError: error,\n        handlingStack,\n        startClocks,\n        nonErrorPrefix: NonErrorPrefix.PROVIDED,\n        source: ErrorSource.CUSTOM,\n        handling: ErrorHandling.HANDLED,\n      })\n\n      lifeCycle.notify(LifeCycleEventType.RAW_ERROR_COLLECTED, {\n        customerContext,\n        savedCommonContext,\n        error: rawError,\n      })\n    },\n  }\n}\n\nfunction processError(\n  error: RawError,\n  pageStateHistory: PageStateHistory,\n  featureFlagContexts: FeatureFlagContexts\n): RawRumEventCollectedData<RawRumErrorEvent> {\n  const rawRumEvent: RawRumErrorEvent = {\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      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: RumEventType.ERROR as const,\n    view: { in_foreground: pageStateHistory.wasInPageStateAt(PageState.ACTIVE, error.startClocks.relative) },\n  }\n\n  const featureFlagContext = featureFlagContexts.findFeatureFlagEvaluations(error.startClocks.relative)\n  if (featureFlagContext && !isEmptyObject(featureFlagContext)) {\n    rawRumEvent.feature_flags = featureFlagContext\n  }\n\n  const domainContext: RumErrorEventDomainContext = {\n    error: error.originalError,\n    handlingStack: error.handlingStack,\n  }\n\n  return {\n    rawRumEvent,\n    startTime: error.startClocks.relative,\n    domainContext,\n  }\n}\n","import type { Observable, RawError } from '@datadog/browser-core'\nimport { initConsoleObservable, ConsoleApiName } from '@datadog/browser-core'\n\nexport function trackConsoleError(errorObservable: Observable<RawError>) {\n  const subscription = initConsoleObservable([ConsoleApiName.error]).subscribe((consoleLog) =>\n    errorObservable.notify(consoleLog.error)\n  )\n\n  return {\n    stop: () => {\n      subscription.unsubscribe()\n    },\n  }\n}\n","import type { Observable, RawError } from '@datadog/browser-core'\nimport { initReportObservable, RawReportType } from '@datadog/browser-core'\nimport type { RumConfiguration } from '../configuration'\n\nexport function trackReportError(configuration: RumConfiguration, errorObservable: Observable<RawError>) {\n  const subscription = initReportObservable(configuration, [\n    RawReportType.cspViolation,\n    RawReportType.intervention,\n  ]).subscribe((rawError) => errorObservable.notify(rawError))\n\n  return {\n    stop: () => {\n      subscription.unsubscribe()\n    },\n  }\n}\n","import type { Duration, RelativeTime } from '@datadog/browser-core'\nimport { addDuration } from '@datadog/browser-core'\nimport type { RumPerformanceResourceTiming } from '../../browser/performanceObservable'\nimport type { RequestCompleteEvent } from '../requestCollection'\nimport { WeakSet } from '../../browser/polyfills'\nimport { hasValidResourceEntryDuration, hasValidResourceEntryTimings } from './resourceUtils'\n\ninterface Timing {\n  startTime: RelativeTime\n  duration: Duration\n}\n\nconst alreadyMatchedEntries = new WeakSet<PerformanceEntry>()\n\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: RequestCompleteEvent) {\n  if (!performance || !('getEntriesByName' in performance)) {\n    return\n  }\n  const sameNameEntries = performance.getEntriesByName(request.url, 'resource') as RumPerformanceResourceTiming[]\n\n  if (!sameNameEntries.length || !('toJSON' in sameNameEntries[0])) {\n    return\n  }\n\n  const candidates = sameNameEntries\n    .filter((entry) => !alreadyMatchedEntries.has(entry))\n    .filter((entry) => hasValidResourceEntryDuration(entry) && hasValidResourceEntryTimings(entry))\n    .filter((entry) =>\n      isBetween(\n        entry,\n        request.startClocks.relative,\n        endTime({ startTime: request.startClocks.relative, duration: request.duration })\n      )\n    )\n\n  if (candidates.length === 1) {\n    alreadyMatchedEntries.add(candidates[0])\n\n    return candidates[0].toJSON() as RumPerformanceResourceTiming\n  }\n\n  return\n}\n\nfunction endTime(timing: Timing) {\n  return addDuration(timing.startTime, timing.duration)\n}\n\nfunction isBetween(timing: Timing, start: RelativeTime, end: RelativeTime) {\n  const errorMargin = 1 as Duration\n  return timing.startTime >= start - errorMargin && endTime(timing) <= addDuration(end, errorMargin)\n}\n","import type { Configuration } from '../domain/configuration'\nimport { noop } from '../tools/utils/functionUtils'\nimport { DOM_EVENT, addEventListener } from './addEventListener'\n\nexport function runOnReadyState(\n  configuration: Configuration,\n  expectedReadyState: 'complete' | 'interactive',\n  callback: () => void\n): { stop: () => void } {\n  if (document.readyState === expectedReadyState || document.readyState === 'complete') {\n    callback()\n    return { stop: noop }\n  }\n  const eventName = expectedReadyState === 'complete' ? DOM_EVENT.LOAD : DOM_EVENT.DOM_CONTENT_LOADED\n  return addEventListener(configuration, window, eventName, callback, { once: true })\n}\n","import type { TimeStamp } from '@datadog/browser-core'\nimport { dateNow, findCommaSeparatedValue, ONE_MINUTE } from '@datadog/browser-core'\nimport { isCommentNode, isTextNode } from '../../browser/htmlDomUtils'\n\ninterface DocumentTraceData {\n  traceId: string\n  traceTime: TimeStamp\n}\n\nexport const INITIAL_DOCUMENT_OUTDATED_TRACE_ID_THRESHOLD = 2 * ONE_MINUTE\n\nexport function getDocumentTraceId(document: Document): string | undefined {\n  const data = getDocumentTraceDataFromMeta(document) || getDocumentTraceDataFromComment(document)\n\n  if (!data || data.traceTime <= dateNow() - INITIAL_DOCUMENT_OUTDATED_TRACE_ID_THRESHOLD) {\n    return undefined\n  }\n\n  return data.traceId\n}\n\nexport function getDocumentTraceDataFromMeta(document: Document): DocumentTraceData | undefined {\n  const traceIdMeta = document.querySelector<HTMLMetaElement>('meta[name=dd-trace-id]')\n  const traceTimeMeta = document.querySelector<HTMLMetaElement>('meta[name=dd-trace-time]')\n  return createDocumentTraceData(traceIdMeta && traceIdMeta.content, traceTimeMeta && traceTimeMeta.content)\n}\n\nexport function getDocumentTraceDataFromComment(document: Document): DocumentTraceData | undefined {\n  const comment = findTraceComment(document)\n  if (!comment) {\n    return undefined\n  }\n  return createDocumentTraceData(\n    findCommaSeparatedValue(comment, 'trace-id'),\n    findCommaSeparatedValue(comment, 'trace-time')\n  )\n}\n\nexport function createDocumentTraceData(\n  traceId: string | undefined | null,\n  rawTraceTime: string | undefined | null\n): DocumentTraceData | undefined {\n  const traceTime = rawTraceTime && (Number(rawTraceTime) as TimeStamp)\n  if (!traceId || !traceTime) {\n    return undefined\n  }\n\n  return {\n    traceId,\n    traceTime,\n  }\n}\n\nexport function findTraceComment(document: Document): string | undefined {\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\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}\n\nfunction getTraceCommentFromNode(node: Node | null) {\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","import type { RelativeTime, TimeStamp } from '@datadog/browser-core'\nimport { assign, getRelativeTime, isNumber } from '@datadog/browser-core'\nimport {\n  RumPerformanceEntryType,\n  supportPerformanceTimingEvent,\n  type RumPerformanceNavigationTiming,\n} from './performanceObservable'\n\nexport function getNavigationEntry(): RumPerformanceNavigationTiming {\n  if (supportPerformanceTimingEvent(RumPerformanceEntryType.NAVIGATION)) {\n    const navigationEntry = performance.getEntriesByType(\n      RumPerformanceEntryType.NAVIGATION\n    )[0] as unknown as RumPerformanceNavigationTiming\n    if (navigationEntry) {\n      return navigationEntry\n    }\n  }\n\n  const timings = computeTimingsFromDeprecatedPerformanceTiming()\n  const entry = assign(\n    {\n      entryType: RumPerformanceEntryType.NAVIGATION as const,\n      initiatorType: 'navigation' as const,\n      name: window.location.href,\n      startTime: 0 as RelativeTime,\n      duration: timings.responseEnd,\n      decodedBodySize: 0,\n      encodedBodySize: 0,\n      transferSize: 0,\n      toJSON: () => assign({}, entry, { toJSON: undefined }),\n    },\n    timings\n  )\n  return entry\n}\n\nexport type TimingsFromDeprecatedPerformanceTiming = {\n  -readonly [key in keyof Omit<PerformanceTiming, 'toJSON'>]: RelativeTime\n}\n\nexport function computeTimingsFromDeprecatedPerformanceTiming() {\n  const result: Partial<TimingsFromDeprecatedPerformanceTiming> = {}\n  const timing = performance.timing\n\n  for (const key in timing) {\n    if (isNumber(timing[key as keyof PerformanceTiming])) {\n      const numberKey = key as keyof TimingsFromDeprecatedPerformanceTiming\n      const timingElement = timing[numberKey] as TimeStamp\n      result[numberKey] = timingElement === 0 ? (0 as RelativeTime) : getRelativeTime(timingElement)\n    }\n  }\n  return result as TimingsFromDeprecatedPerformanceTiming\n}\n","import { assign, runOnReadyState } from '@datadog/browser-core'\nimport { RumPerformanceEntryType } from '../../browser/performanceObservable'\nimport type { RumPerformanceResourceTiming } from '../../browser/performanceObservable'\nimport type { RumConfiguration } from '../configuration'\nimport { getDocumentTraceId } from '../tracing/getDocumentTraceId'\nimport { getNavigationEntry } from '../../browser/performanceUtils'\nimport { FAKE_INITIAL_DOCUMENT } from './resourceUtils'\n\nexport function retrieveInitialDocumentResourceTiming(\n  configuration: RumConfiguration,\n  callback: (timing: RumPerformanceResourceTiming) => void\n) {\n  runOnReadyState(configuration, 'interactive', () => {\n    const entry = assign(getNavigationEntry().toJSON(), {\n      entryType: RumPerformanceEntryType.RESOURCE as const,\n      initiatorType: FAKE_INITIAL_DOCUMENT,\n      traceId: getDocumentTraceId(document),\n      toJSON: () => assign({}, entry, { toJSON: undefined }),\n    })\n    callback(entry)\n  })\n}\n","import type { ClocksState, Duration } from '@datadog/browser-core'\nimport {\n  combine,\n  generateUUID,\n  RequestType,\n  ResourceType,\n  toServerDuration,\n  relativeToClocks,\n  assign,\n  isNumber,\n} from '@datadog/browser-core'\nimport type { RumConfiguration } from '../configuration'\nimport {\n  RumPerformanceEntryType,\n  createPerformanceObservable,\n  type RumPerformanceResourceTiming,\n} from '../../browser/performanceObservable'\nimport type { RumXhrResourceEventDomainContext, RumFetchResourceEventDomainContext } from '../../domainContext.types'\nimport type { RawRumResourceEvent } from '../../rawRumEvent.types'\nimport { RumEventType } from '../../rawRumEvent.types'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport type { RawRumEventCollectedData, LifeCycle } from '../lifeCycle'\nimport type { RequestCompleteEvent } from '../requestCollection'\nimport type { PageStateHistory } from '../contexts/pageStateHistory'\nimport { PageState } from '../contexts/pageStateHistory'\nimport { createTraceIdentifier } from '../tracing/tracer'\nimport { matchRequestResourceEntry } from './matchRequestResourceEntry'\nimport {\n  computeResourceEntryDetails,\n  computeResourceEntryDuration,\n  computeResourceEntryType,\n  computeResourceEntrySize,\n  isResourceEntryRequestType,\n  isLongDataUrl,\n  sanitizeDataUrl,\n} from './resourceUtils'\nimport { retrieveInitialDocumentResourceTiming } from './retrieveInitialDocumentResourceTiming'\n\nexport function startResourceCollection(\n  lifeCycle: LifeCycle,\n  configuration: RumConfiguration,\n  pageStateHistory: PageStateHistory,\n  retrieveInitialDocumentResourceTimingImpl = retrieveInitialDocumentResourceTiming\n) {\n  lifeCycle.subscribe(LifeCycleEventType.REQUEST_COMPLETED, (request: RequestCompleteEvent) => {\n    const rawEvent = processRequest(request, configuration, pageStateHistory)\n    if (rawEvent) {\n      lifeCycle.notify(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, rawEvent)\n    }\n  })\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        const rawEvent = processResourceEntry(entry, configuration)\n        if (rawEvent) {\n          lifeCycle.notify(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, rawEvent)\n        }\n      }\n    }\n  })\n\n  retrieveInitialDocumentResourceTimingImpl(configuration, (timing) => {\n    const rawEvent = processResourceEntry(timing, configuration)\n    if (rawEvent) {\n      lifeCycle.notify(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, rawEvent)\n    }\n  })\n\n  return {\n    stop: () => {\n      performanceResourceSubscription.unsubscribe()\n    },\n  }\n}\n\nfunction processRequest(\n  request: RequestCompleteEvent,\n  configuration: RumConfiguration,\n  pageStateHistory: PageStateHistory\n): RawRumEventCollectedData<RawRumResourceEvent> | undefined {\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\n  const type = request.type === RequestType.XHR ? ResourceType.XHR : ResourceType.FETCH\n\n  const correspondingTimingOverrides = matchingTiming ? computeResourceEntryMetrics(matchingTiming) : undefined\n\n  const duration = computeRequestDuration(pageStateHistory, startClocks, request.duration)\n\n  const resourceEvent = combine(\n    {\n      date: startClocks.timeStamp,\n      resource: {\n        id: generateUUID(),\n        type,\n        duration,\n        method: request.method,\n        status_code: request.status,\n        url: isLongDataUrl(request.url) ? sanitizeDataUrl(request.url) : request.url,\n      },\n      type: RumEventType.RESOURCE as const,\n      _dd: {\n        discarded: !configuration.trackResources,\n      },\n    },\n    tracingInfo,\n    correspondingTimingOverrides\n  )\n\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    } as RumFetchResourceEventDomainContext | RumXhrResourceEventDomainContext,\n  }\n}\n\nfunction processResourceEntry(\n  entry: RumPerformanceResourceTiming,\n  configuration: RumConfiguration\n): RawRumEventCollectedData<RawRumResourceEvent> | undefined {\n  const startClocks = relativeToClocks(entry.startTime)\n  const tracingInfo = computeResourceEntryTracingInfo(entry, configuration)\n  if (!configuration.trackResources && !tracingInfo) {\n    return\n  }\n\n  const type = computeResourceEntryType(entry)\n  const entryMetrics = computeResourceEntryMetrics(entry)\n\n  const resourceEvent = combine(\n    {\n      date: startClocks.timeStamp,\n      resource: {\n        id: generateUUID(),\n        type,\n        url: entry.name,\n        status_code: discardZeroStatus(entry.responseStatus),\n      },\n      type: RumEventType.RESOURCE as const,\n      _dd: {\n        discarded: !configuration.trackResources,\n      },\n    },\n    tracingInfo,\n    entryMetrics\n  )\n  return {\n    startTime: startClocks.relative,\n    rawRumEvent: resourceEvent,\n    domainContext: {\n      performanceEntry: entry,\n    },\n  }\n}\n\nfunction computeResourceEntryMetrics(entry: RumPerformanceResourceTiming) {\n  const { renderBlockingStatus } = entry\n  return {\n    resource: assign(\n      {\n        duration: computeResourceEntryDuration(entry),\n        render_blocking_status: renderBlockingStatus,\n      },\n      computeResourceEntrySize(entry),\n      computeResourceEntryDetails(entry)\n    ),\n  }\n}\n\nfunction computeRequestTracingInfo(request: RequestCompleteEvent, configuration: RumConfiguration) {\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!.toDecimalString(),\n      trace_id: request.traceId!.toDecimalString(),\n      rule_psr: getRulePsr(configuration),\n    },\n  }\n}\n\nfunction computeResourceEntryTracingInfo(entry: RumPerformanceResourceTiming, configuration: RumConfiguration) {\n  const hasBeenTraced = entry.traceId\n  if (!hasBeenTraced) {\n    return undefined\n  }\n  return {\n    _dd: {\n      trace_id: entry.traceId,\n      span_id: createTraceIdentifier().toDecimalString(),\n      rule_psr: getRulePsr(configuration),\n    },\n  }\n}\n\n/**\n * @returns number between 0 and 1 which represents trace sample rate\n */\nfunction getRulePsr(configuration: RumConfiguration) {\n  return isNumber(configuration.traceSampleRate) ? configuration.traceSampleRate / 100 : undefined\n}\n\nfunction computeRequestDuration(pageStateHistory: PageStateHistory, startClocks: ClocksState, duration: Duration) {\n  return !pageStateHistory.wasInPageStateDuringPeriod(PageState.FROZEN, startClocks.relative, duration)\n    ? toServerDuration(duration)\n    : undefined\n}\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: number | undefined): number | undefined {\n  return statusCode === 0 ? undefined : statusCode\n}\n","import type { RelativeTime } from '@datadog/browser-core'\nimport { ONE_MINUTE, find } from '@datadog/browser-core'\nimport type { RumPerformancePaintTiming } from '../../../browser/performanceObservable'\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../../../browser/performanceObservable'\nimport type { RumConfiguration } from '../../configuration'\nimport type { FirstHidden } from './trackFirstHidden'\n\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\n\nexport function trackFirstContentfulPaint(\n  configuration: RumConfiguration,\n  firstHidden: FirstHidden,\n  callback: (fcpTiming: RelativeTime) => void\n) {\n  const performanceSubscription = createPerformanceObservable(configuration, {\n    type: RumPerformanceEntryType.PAINT,\n    buffered: true,\n  }).subscribe((entries) => {\n    const fcpEntry = find(\n      entries,\n      (entry): entry is RumPerformancePaintTiming =>\n        entry.name === 'first-contentful-paint' &&\n        entry.startTime < firstHidden.timeStamp &&\n        entry.startTime < FCP_MAXIMUM_DELAY\n    )\n    if (fcpEntry) {\n      callback(fcpEntry.startTime)\n    }\n  })\n  return {\n    stop: performanceSubscription.unsubscribe,\n  }\n}\n","import type { RelativeTime } from '@datadog/browser-core'\nimport { DOM_EVENT, ONE_MINUTE, addEventListeners, findLast } from '@datadog/browser-core'\nimport type { RumConfiguration } from '../../configuration'\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../../../browser/performanceObservable'\nimport type { RumLargestContentfulPaintTiming } from '../../../browser/performanceObservable'\nimport { getSelectorFromElement } from '../../getSelectorFromElement'\nimport type { FirstHidden } from './trackFirstHidden'\n\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\nexport interface LargestContentfulPaint {\n  value: RelativeTime\n  targetSelector?: string\n}\n\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(\n  configuration: RumConfiguration,\n  firstHidden: FirstHidden,\n  eventTarget: Window,\n  callback: (largestContentfulPaint: LargestContentfulPaint) => void\n) {\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(\n    configuration,\n    eventTarget,\n    [DOM_EVENT.POINTER_DOWN, DOM_EVENT.KEY_DOWN],\n    (event) => {\n      firstInteractionTimestamp = event.timeStamp\n    },\n    { capture: true, once: true }\n  )\n\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(\n      entries,\n      (entry): entry is RumLargestContentfulPaintTiming =>\n        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    )\n\n    if (lcpEntry) {\n      let lcpTargetSelector\n      if (lcpEntry.element) {\n        lcpTargetSelector = getSelectorFromElement(lcpEntry.element, configuration.actionNameAttribute)\n      }\n\n      callback({\n        value: lcpEntry.startTime,\n        targetSelector: lcpTargetSelector,\n      })\n      biggestLcpSize = lcpEntry.size\n    }\n  })\n\n  return {\n    stop: () => {\n      stopEventListener()\n      performanceLcpSubscription.unsubscribe()\n    },\n  }\n}\n","import type { RelativeTime } from '@datadog/browser-core'\nimport { addEventListeners, DOM_EVENT } from '@datadog/browser-core'\nimport type { RumConfiguration } from '../../configuration'\n\nexport type FirstHidden = ReturnType<typeof trackFirstHidden>\n\nexport function trackFirstHidden(configuration: RumConfiguration, eventTarget: Window = window) {\n  let timeStamp: RelativeTime\n  let stopListeners: () => void | undefined\n\n  if (document.visibilityState === 'hidden') {\n    timeStamp = 0 as RelativeTime\n  } else {\n    timeStamp = Infinity as RelativeTime\n    ;({ stop: stopListeners } = addEventListeners(\n      configuration,\n      eventTarget,\n      [DOM_EVENT.PAGE_HIDE, DOM_EVENT.VISIBILITY_CHANGE],\n      (event) => {\n        if (event.type === DOM_EVENT.PAGE_HIDE || document.visibilityState === 'hidden') {\n          timeStamp = event.timeStamp as RelativeTime\n          stopListeners()\n        }\n      },\n      { capture: true }\n    ))\n  }\n\n  return {\n    get timeStamp() {\n      return timeStamp\n    },\n    stop() {\n      stopListeners?.()\n    },\n  }\n}\n","import type { Duration } from '@datadog/browser-core'\nimport type { RumConfiguration } from '../../configuration'\nimport { trackFirstContentfulPaint } from './trackFirstContentfulPaint'\nimport type { FirstInput } from './trackFirstInput'\nimport { trackFirstInput } from './trackFirstInput'\nimport type { NavigationTimings } from './trackNavigationTimings'\nimport { trackNavigationTimings } from './trackNavigationTimings'\nimport type { LargestContentfulPaint } from './trackLargestContentfulPaint'\nimport { trackLargestContentfulPaint } from './trackLargestContentfulPaint'\nimport { trackFirstHidden } from './trackFirstHidden'\n\nexport interface InitialViewMetrics {\n  firstContentfulPaint?: Duration\n  navigationTimings?: NavigationTimings\n  largestContentfulPaint?: LargestContentfulPaint\n  firstInput?: FirstInput\n}\n\nexport function trackInitialViewMetrics(\n  configuration: RumConfiguration,\n  setLoadEvent: (loadEnd: Duration) => void,\n  scheduleViewUpdate: () => void\n) {\n  const initialViewMetrics: InitialViewMetrics = {}\n\n  const { stop: stopNavigationTracking } = trackNavigationTimings(configuration, (navigationTimings) => {\n    setLoadEvent(navigationTimings.loadEvent)\n    initialViewMetrics.navigationTimings = navigationTimings\n    scheduleViewUpdate()\n  })\n\n  const firstHidden = trackFirstHidden(configuration)\n  const { stop: stopFCPTracking } = trackFirstContentfulPaint(configuration, firstHidden, (firstContentfulPaint) => {\n    initialViewMetrics.firstContentfulPaint = firstContentfulPaint\n    scheduleViewUpdate()\n  })\n\n  const { stop: stopLCPTracking } = trackLargestContentfulPaint(\n    configuration,\n    firstHidden,\n    window,\n    (largestContentfulPaint) => {\n      initialViewMetrics.largestContentfulPaint = largestContentfulPaint\n      scheduleViewUpdate()\n    }\n  )\n\n  const { stop: stopFIDTracking } = trackFirstInput(configuration, firstHidden, (firstInput) => {\n    initialViewMetrics.firstInput = firstInput\n    scheduleViewUpdate()\n  })\n\n  function stop() {\n    stopNavigationTracking()\n    stopFCPTracking()\n    stopLCPTracking()\n    stopFIDTracking()\n    firstHidden.stop()\n  }\n\n  return {\n    stop,\n    initialViewMetrics,\n  }\n}\n","import type { Duration, TimeoutId } from '@datadog/browser-core'\nimport { setTimeout, relativeNow, runOnReadyState, clearTimeout } from '@datadog/browser-core'\nimport type { RumPerformanceNavigationTiming } from '../../../browser/performanceObservable'\nimport type { RumConfiguration } from '../../configuration'\nimport { getNavigationEntry } from '../../../browser/performanceUtils'\n\nexport interface NavigationTimings {\n  domComplete: Duration\n  domContentLoaded: Duration\n  domInteractive: Duration\n  loadEvent: Duration\n  firstByte: Duration | undefined\n}\n\n// This is a subset of \"RumPerformanceNavigationTiming\" that only contains the relevant fields for\n// computing navigation timings. This is useful to mock the navigation entry in tests.\nexport type RelevantNavigationTiming = Pick<\n  RumPerformanceNavigationTiming,\n  'domComplete' | 'domContentLoadedEventEnd' | 'domInteractive' | 'loadEventEnd' | 'responseStart'\n>\n\nexport function trackNavigationTimings(\n  configuration: RumConfiguration,\n  callback: (timings: NavigationTimings) => void,\n  getNavigationEntryImpl: () => RelevantNavigationTiming = getNavigationEntry\n) {\n  return waitAfterLoadEvent(configuration, () => {\n    const entry = getNavigationEntryImpl()\n\n    if (!isIncompleteNavigation(entry)) {\n      callback(processNavigationEntry(entry))\n    }\n  })\n}\n\nfunction processNavigationEntry(entry: RelevantNavigationTiming): NavigationTimings {\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}\n\nfunction isIncompleteNavigation(entry: RelevantNavigationTiming) {\n  return entry.loadEventEnd <= 0\n}\n\nfunction waitAfterLoadEvent(configuration: RumConfiguration, callback: () => void) {\n  let timeoutId: TimeoutId | undefined\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","import type { Duration, RelativeTime } from '@datadog/browser-core'\nimport { elapsed, find } from '@datadog/browser-core'\nimport { isElementNode } from '../../../browser/htmlDomUtils'\nimport type { RumConfiguration } from '../../configuration'\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../../../browser/performanceObservable'\nimport type { RumFirstInputTiming } from '../../../browser/performanceObservable'\nimport { getSelectorFromElement } from '../../getSelectorFromElement'\nimport type { FirstHidden } from './trackFirstHidden'\n\nexport interface FirstInput {\n  delay: Duration\n  time: RelativeTime\n  targetSelector?: string\n}\n\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(\n  configuration: RumConfiguration,\n  firstHidden: FirstHidden,\n  callback: (firstInput: FirstInput) => void\n) {\n  const performanceFirstInputSubscription = createPerformanceObservable(configuration, {\n    type: RumPerformanceEntryType.FIRST_INPUT,\n    buffered: true,\n  }).subscribe((entries) => {\n    const firstInputEntry = find(\n      entries,\n      (entry): entry is RumFirstInputTiming => entry.startTime < firstHidden.timeStamp\n    )\n    if (firstInputEntry) {\n      const firstInputDelay = elapsed(firstInputEntry.startTime, firstInputEntry.processingStart)\n      let firstInputTargetSelector\n\n      if (firstInputEntry.target && isElementNode(firstInputEntry.target)) {\n        firstInputTargetSelector = getSelectorFromElement(firstInputEntry.target, configuration.actionNameAttribute)\n      }\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 as Duration),\n        time: firstInputEntry.startTime,\n        targetSelector: firstInputTargetSelector,\n      })\n    }\n  })\n\n  return {\n    stop: () => {\n      performanceFirstInputSubscription.unsubscribe()\n    },\n  }\n}\n","import { round, find, ONE_SECOND, noop, elapsed } from '@datadog/browser-core'\nimport type { Duration, RelativeTime, WeakRef, WeakRefConstructor } from '@datadog/browser-core'\nimport { isElementNode } from '../../../browser/htmlDomUtils'\nimport type { RumLayoutShiftTiming } from '../../../browser/performanceObservable'\nimport {\n  supportPerformanceTimingEvent,\n  RumPerformanceEntryType,\n  createPerformanceObservable,\n} from '../../../browser/performanceObservable'\nimport { getSelectorFromElement } from '../../getSelectorFromElement'\nimport type { RumConfiguration } from '../../configuration'\n\nexport interface CumulativeLayoutShift {\n  value: number\n  targetSelector?: string\n  time?: Duration\n}\n\ndeclare const WeakRef: WeakRefConstructor\n\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(\n  configuration: RumConfiguration,\n  viewStart: RelativeTime,\n  callback: (cumulativeLayoutShift: CumulativeLayoutShift) => void\n) {\n  if (!isLayoutShiftSupported()) {\n    return {\n      stop: noop,\n    }\n  }\n\n  let maxClsValue = 0\n  let maxClsTarget: WeakRef<HTMLElement> | undefined\n  let maxClsStartTime: Duration | undefined\n\n  // if no layout shift happen the value should be reported as 0\n  callback({\n    value: 0,\n  })\n\n  const window = slidingSessionWindow()\n  const performanceSubscription = createPerformanceObservable(configuration, {\n    type: RumPerformanceEntryType.LAYOUT_SHIFT,\n    buffered: true,\n  }).subscribe((entries) => {\n    for (const entry of entries) {\n      if (entry.hadRecentInput || entry.startTime < viewStart) {\n        continue\n      }\n\n      const { cumulatedValue, isMaxValue } = window.update(entry)\n\n      if (isMaxValue) {\n        const target = getTargetFromSource(entry.sources)\n        maxClsTarget = target ? new WeakRef(target) : undefined\n        maxClsStartTime = elapsed(viewStart, entry.startTime)\n      }\n\n      if (cumulatedValue > maxClsValue) {\n        maxClsValue = cumulatedValue\n        const target = maxClsTarget?.deref()\n\n        callback({\n          value: round(maxClsValue, 4),\n          targetSelector: target && getSelectorFromElement(target, configuration.actionNameAttribute),\n          time: maxClsStartTime,\n        })\n      }\n    }\n  })\n\n  return {\n    stop: () => {\n      performanceSubscription.unsubscribe()\n    },\n  }\n}\n\nfunction getTargetFromSource(sources?: Array<{ node?: Node }>) {\n  if (!sources) {\n    return\n  }\n\n  return find(sources, (source): source is { node: HTMLElement } => !!source.node && isElementNode(source.node))?.node\n}\n\nexport const MAX_WINDOW_DURATION = 5 * ONE_SECOND\nconst MAX_UPDATE_GAP = ONE_SECOND\n\nfunction slidingSessionWindow() {\n  let cumulatedValue = 0\n  let startTime: RelativeTime\n  let endTime: RelativeTime\n  let maxValue = 0\n\n  return {\n    update: (entry: RumLayoutShiftTiming) => {\n      const shouldCreateNewWindow =\n        startTime === undefined ||\n        entry.startTime - endTime >= MAX_UPDATE_GAP ||\n        entry.startTime - startTime >= MAX_WINDOW_DURATION\n\n      let isMaxValue: boolean\n\n      if (shouldCreateNewWindow) {\n        startTime = endTime = entry.startTime\n        maxValue = cumulatedValue = entry.value\n        isMaxValue = true\n      } else {\n        cumulatedValue += entry.value\n        endTime = entry.startTime\n        isMaxValue = entry.value > maxValue\n\n        if (isMaxValue) {\n          maxValue = entry.value\n        }\n      }\n\n      return {\n        cumulatedValue,\n        isMaxValue,\n      }\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","/**\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 */\n\nimport { monitor } from '@datadog/browser-core'\nimport type {\n  BrowserWindow,\n  RumPerformanceEventTiming,\n  RumPerformanceObserver,\n} from '../../../browser/performanceObservable'\n\nlet observer: RumPerformanceObserver | undefined\n\nlet interactionCountEstimate = 0\nlet minKnownInteractionId = Infinity\nlet maxKnownInteractionId = 0\n\nexport function initInteractionCountPolyfill() {\n  if ('interactionCount' in performance || observer) {\n    return\n  }\n\n  observer = new (window as BrowserWindow).PerformanceObserver(\n    monitor((entries: PerformanceObserverEntryList) => {\n      entries.getEntries().forEach((e) => {\n        const entry = e as unknown as RumPerformanceEventTiming\n\n        if (entry.interactionId) {\n          minKnownInteractionId = Math.min(minKnownInteractionId, entry.interactionId)\n          maxKnownInteractionId = Math.max(maxKnownInteractionId, entry.interactionId)\n\n          interactionCountEstimate = (maxKnownInteractionId - minKnownInteractionId) / 7 + 1\n        }\n      })\n    })\n  )\n\n  observer.observe({ type: 'event', buffered: true, durationThreshold: 0 })\n}\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 = () =>\n  observer ? interactionCountEstimate : (window as BrowserWindow).performance.interactionCount! || 0\n","import { Observable, throttle, addEventListener, DOM_EVENT } from '@datadog/browser-core'\nimport type { RumConfiguration } from '../domain/configuration'\n\nexport interface ViewportDimension {\n  height: number\n  width: number\n}\n\nlet viewportObservable: Observable<ViewportDimension> | undefined\n\nexport function initViewportObservable(configuration: RumConfiguration) {\n  if (!viewportObservable) {\n    viewportObservable = createViewportObservable(configuration)\n  }\n  return viewportObservable\n}\n\nexport function createViewportObservable(configuration: RumConfiguration) {\n  return new Observable<ViewportDimension>((observable) => {\n    const { throttled: updateDimension } = throttle(() => {\n      observable.notify(getViewportDimension())\n    }, 200)\n\n    return addEventListener(configuration, window, DOM_EVENT.RESIZE, updateDimension, { capture: true, passive: true })\n      .stop\n  })\n}\n\n// excludes the width and height of any rendered classic scrollbar that is fixed to the visual viewport\nexport function getViewportDimension(): ViewportDimension {\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\n  return {\n    width: Number(window.innerWidth || 0),\n    height: Number(window.innerHeight || 0),\n  }\n}\n","import { elapsed, noop, ONE_MINUTE } from '@datadog/browser-core'\nimport type { Duration, RelativeTime } from '@datadog/browser-core'\nimport {\n  createPerformanceObservable,\n  RumPerformanceEntryType,\n  supportPerformanceTimingEvent,\n} from '../../../browser/performanceObservable'\nimport type { RumFirstInputTiming, RumPerformanceEventTiming } from '../../../browser/performanceObservable'\nimport { ViewLoadingType } from '../../../rawRumEvent.types'\nimport { getSelectorFromElement } from '../../getSelectorFromElement'\nimport { isElementNode } from '../../../browser/htmlDomUtils'\nimport { getInteractionSelector } from '../../action/interactionSelectorCache'\nimport type { RumConfiguration } from '../../configuration'\nimport { getInteractionCount, initInteractionCountPolyfill } from './interactionCountPolyfill'\n\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) as Duration\n\nexport interface InteractionToNextPaint {\n  value: Duration\n  targetSelector?: string\n  time?: Duration\n}\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(\n  configuration: RumConfiguration,\n  viewStart: RelativeTime,\n  viewLoadingType: ViewLoadingType\n) {\n  if (!isInteractionToNextPaintSupported()) {\n    return {\n      getInteractionToNextPaint: () => undefined,\n      setViewEnd: noop,\n      stop: noop,\n    }\n  }\n\n  const { getViewInteractionCount, stopViewInteractionCount } = trackViewInteractionCount(viewLoadingType)\n\n  let viewEnd = Infinity as RelativeTime\n\n  const longestInteractions = trackLongestInteractions(getViewInteractionCount)\n  let interactionToNextPaint = -1 as Duration\n  let interactionToNextPaintTargetSelector: string | undefined\n  let interactionToNextPaintStartTime: Duration | undefined\n\n  function handleEntries(entries: Array<RumPerformanceEventTiming | RumFirstInputTiming>) {\n    for (const entry of entries) {\n      if (\n        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      ) {\n        longestInteractions.process(entry)\n      }\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(\n          newInteraction.target,\n          configuration.actionNameAttribute\n        )\n      }\n    }\n  }\n\n  const firstInputSubscription = createPerformanceObservable(configuration, {\n    type: RumPerformanceEntryType.FIRST_INPUT,\n    buffered: true,\n  }).subscribe(handleEntries)\n\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\n  return {\n    getInteractionToNextPaint: (): InteractionToNextPaint | undefined => {\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) as Duration,\n          targetSelector: interactionToNextPaintTargetSelector,\n          time: interactionToNextPaintStartTime,\n        }\n      } else if (getViewInteractionCount()) {\n        return {\n          value: 0 as Duration,\n        }\n      }\n    },\n    setViewEnd: (viewEndTime: RelativeTime) => {\n      viewEnd = viewEndTime\n      stopViewInteractionCount()\n    },\n    stop: () => {\n      eventSubscription.unsubscribe()\n      firstInputSubscription.unsubscribe()\n    },\n  }\n}\n\nfunction trackLongestInteractions(getViewInteractionCount: () => number) {\n  const longestInteractions: Array<RumPerformanceEventTiming | RumFirstInputTiming> = []\n\n  function sortAndTrimLongestInteractions() {\n    longestInteractions.sort((a, b) => b.duration - a.duration).splice(MAX_INTERACTION_ENTRIES)\n  }\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: RumPerformanceEventTiming | RumFirstInputTiming) {\n      const interactionIndex = longestInteractions.findIndex(\n        (interaction) => entry.interactionId === interaction.interactionId\n      )\n\n      const minLongestInteraction = longestInteractions[longestInteractions.length - 1]\n\n      if (interactionIndex !== -1) {\n        if (entry.duration > longestInteractions[interactionIndex].duration) {\n          longestInteractions[interactionIndex] = entry\n          sortAndTrimLongestInteractions()\n        }\n      } else if (\n        longestInteractions.length < MAX_INTERACTION_ENTRIES ||\n        entry.duration > minLongestInteraction.duration\n      ) {\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(): RumPerformanceEventTiming | RumFirstInputTiming | undefined {\n      const interactionIndex = Math.min(longestInteractions.length - 1, Math.floor(getViewInteractionCount() / 50))\n      return longestInteractions[interactionIndex]\n    },\n  }\n}\n\nexport function trackViewInteractionCount(viewLoadingType: ViewLoadingType) {\n  initInteractionCountPolyfill()\n  const previousInteractionCount = viewLoadingType === ViewLoadingType.INITIAL_LOAD ? 0 : getInteractionCount()\n  let state: { stopped: false } | { stopped: true; interactionCount: number } = { stopped: false }\n\n  function computeViewInteractionCount() {\n    return getInteractionCount() - previousInteractionCount\n  }\n\n  return {\n    getViewInteractionCount: () => {\n      if (state.stopped) {\n        return state.interactionCount\n      }\n\n      return computeViewInteractionCount()\n    },\n    stopViewInteractionCount: () => {\n      state = { stopped: true, interactionCount: computeViewInteractionCount() }\n    },\n  }\n}\n\nexport function isInteractionToNextPaintSupported() {\n  return (\n    supportPerformanceTimingEvent(RumPerformanceEntryType.EVENT) &&\n    window.PerformanceEventTiming &&\n    'interactionId' in PerformanceEventTiming.prototype\n  )\n}\n","export function getScrollX() {\n  let scrollX\n  const visual = window.visualViewport\n  if (visual) {\n    scrollX = visual.pageLeft - visual.offsetLeft\n  } else if (window.scrollX !== undefined) {\n    scrollX = window.scrollX\n  } else {\n    scrollX = window.pageXOffset || 0\n  }\n  return Math.round(scrollX)\n}\n\nexport function getScrollY() {\n  let scrollY\n  const visual = window.visualViewport\n  if (visual) {\n    scrollY = visual.pageTop - visual.offsetTop\n  } else if (window.scrollY !== undefined) {\n    scrollY = window.scrollY\n  } else {\n    scrollY = window.pageYOffset || 0\n  }\n  return Math.round(scrollY)\n}\n","import type { ClocksState, Duration } from '@datadog/browser-core'\nimport {\n  Observable,\n  ONE_SECOND,\n  elapsed,\n  relativeNow,\n  throttle,\n  addEventListener,\n  DOM_EVENT,\n  monitor,\n} from '@datadog/browser-core'\nimport type { RumConfiguration } from '../../configuration'\nimport { getScrollY } from '../../../browser/scroll'\nimport { getViewportDimension } from '../../../browser/viewportObservable'\n\n/** Arbitrary scroll throttle duration */\nexport const THROTTLE_SCROLL_DURATION = ONE_SECOND\n\nexport interface ScrollMetrics {\n  maxDepth: number\n  maxScrollHeight: number\n  maxDepthScrollTop: number\n  maxScrollHeightTime: Duration\n}\n\nexport function trackScrollMetrics(\n  configuration: RumConfiguration,\n  viewStart: ClocksState,\n  callback: (scrollMetrics: ScrollMetrics) => void,\n  scrollValues = createScrollValuesObservable(configuration)\n) {\n  let maxScrollDepth = 0\n  let maxScrollHeight = 0\n  let maxScrollHeightTime = 0 as Duration\n\n  const subscription = scrollValues.subscribe(({ scrollDepth, scrollTop, scrollHeight }) => {\n    let shouldUpdate = false\n\n    if (scrollDepth > maxScrollDepth) {\n      maxScrollDepth = scrollDepth\n      shouldUpdate = true\n    }\n\n    if (scrollHeight > maxScrollHeight) {\n      maxScrollHeight = scrollHeight\n      const now = relativeNow()\n      maxScrollHeightTime = elapsed(viewStart.relative, now)\n      shouldUpdate = true\n    }\n\n    if (shouldUpdate) {\n      callback({\n        maxDepth: Math.min(maxScrollDepth, maxScrollHeight),\n        maxDepthScrollTop: scrollTop,\n        maxScrollHeight,\n        maxScrollHeightTime,\n      })\n    }\n  })\n\n  return {\n    stop: () => subscription.unsubscribe(),\n  }\n}\n\nexport interface ScrollValues {\n  scrollDepth: number\n  scrollTop: number\n  scrollHeight: number\n}\n\nexport function computeScrollValues() {\n  const scrollTop = getScrollY()\n\n  const { height } = getViewportDimension()\n\n  const scrollHeight = Math.round((document.scrollingElement || document.documentElement).scrollHeight)\n\n  const scrollDepth = Math.round(height + scrollTop)\n\n  return {\n    scrollHeight,\n    scrollDepth,\n    scrollTop,\n  }\n}\n\nexport function createScrollValuesObservable(\n  configuration: RumConfiguration,\n  throttleDuration = THROTTLE_SCROLL_DURATION\n): Observable<ScrollValues> {\n  return new Observable<ScrollValues>((observable) => {\n    function notify() {\n      observable.notify(computeScrollValues())\n    }\n\n    if (window.ResizeObserver) {\n      const throttledNotify = throttle(notify, throttleDuration, {\n        leading: false,\n        trailing: true,\n      })\n\n      const observerTarget = document.scrollingElement || document.documentElement\n      const resizeObserver = new ResizeObserver(monitor(throttledNotify.throttled))\n      resizeObserver.observe(observerTarget)\n      const eventListener = addEventListener(configuration, window, DOM_EVENT.SCROLL, throttledNotify.throttled, {\n        passive: true,\n      })\n\n      return () => {\n        throttledNotify.cancel()\n        resizeObserver.unobserve(observerTarget)\n        eventListener.stop()\n      }\n    }\n  })\n}\n","import type { ClocksState, Duration, Observable } from '@datadog/browser-core'\nimport type { ViewLoadingType } from '../../../rawRumEvent.types'\nimport type { RumConfiguration } from '../../configuration'\nimport type { LifeCycle } from '../../lifeCycle'\nimport type { CumulativeLayoutShift } from './trackCumulativeLayoutShift'\nimport { trackCumulativeLayoutShift } from './trackCumulativeLayoutShift'\nimport type { InteractionToNextPaint } from './trackInteractionToNextPaint'\nimport { trackInteractionToNextPaint } from './trackInteractionToNextPaint'\nimport { trackLoadingTime } from './trackLoadingTime'\nimport type { ScrollMetrics } from './trackScrollMetrics'\nimport { trackScrollMetrics } from './trackScrollMetrics'\n\nexport interface CommonViewMetrics {\n  loadingTime?: Duration\n  cumulativeLayoutShift?: CumulativeLayoutShift\n  interactionToNextPaint?: InteractionToNextPaint\n  scroll?: ScrollMetrics\n}\n\nexport function trackCommonViewMetrics(\n  lifeCycle: LifeCycle,\n  domMutationObservable: Observable<void>,\n  configuration: RumConfiguration,\n  scheduleViewUpdate: () => void,\n  loadingType: ViewLoadingType,\n  viewStart: ClocksState\n) {\n  const commonViewMetrics: CommonViewMetrics = {}\n\n  const { stop: stopLoadingTimeTracking, setLoadEvent } = trackLoadingTime(\n    lifeCycle,\n    domMutationObservable,\n    configuration,\n    loadingType,\n    viewStart,\n    (newLoadingTime) => {\n      commonViewMetrics.loadingTime = newLoadingTime\n      scheduleViewUpdate()\n    }\n  )\n\n  const { stop: stopScrollMetricsTracking } = trackScrollMetrics(configuration, viewStart, (newScrollMetrics) => {\n    commonViewMetrics.scroll = newScrollMetrics\n  })\n\n  const { stop: stopCLSTracking } = trackCumulativeLayoutShift(\n    configuration,\n    viewStart.relative,\n    (cumulativeLayoutShift) => {\n      commonViewMetrics.cumulativeLayoutShift = cumulativeLayoutShift\n      scheduleViewUpdate()\n    }\n  )\n\n  const {\n    stop: stopINPTracking,\n    getInteractionToNextPaint,\n    setViewEnd,\n  } = trackInteractionToNextPaint(configuration, viewStart.relative, loadingType)\n\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","import type { ClocksState, Duration, Observable } from '@datadog/browser-core'\nimport { elapsed } from '@datadog/browser-core'\nimport { waitPageActivityEnd } from '../../waitPageActivityEnd'\nimport type { RumConfiguration } from '../../configuration'\nimport type { LifeCycle } from '../../lifeCycle'\nimport { ViewLoadingType } from '../../../rawRumEvent.types'\nimport { trackFirstHidden } from './trackFirstHidden'\n\nexport function trackLoadingTime(\n  lifeCycle: LifeCycle,\n  domMutationObservable: Observable<void>,\n  configuration: RumConfiguration,\n  loadType: ViewLoadingType,\n  viewStart: ClocksState,\n  callback: (loadingTime: Duration) => void\n) {\n  let isWaitingForLoadEvent = loadType === ViewLoadingType.INITIAL_LOAD\n  let isWaitingForActivityLoadingTime = true\n  const loadingTimeCandidates: Duration[] = []\n  const firstHidden = trackFirstHidden(configuration)\n\n  function invokeCallbackIfAllCandidatesAreReceived() {\n    if (!isWaitingForActivityLoadingTime && !isWaitingForLoadEvent && loadingTimeCandidates.length > 0) {\n      const loadingTime = Math.max(...loadingTimeCandidates)\n      if (loadingTime < firstHidden.timeStamp) {\n        callback(loadingTime as Duration)\n      }\n    }\n  }\n\n  const { stop } = waitPageActivityEnd(lifeCycle, domMutationObservable, 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\n  return {\n    stop: () => {\n      stop()\n      firstHidden.stop()\n    },\n    setLoadEvent: (loadEvent: Duration) => {\n      if (isWaitingForLoadEvent) {\n        isWaitingForLoadEvent = false\n        loadingTimeCandidates.push(loadEvent)\n        invokeCallbackIfAllCandidatesAreReceived()\n      }\n    },\n  }\n}\n","import type {\n  Duration,\n  ClocksState,\n  TimeStamp,\n  Subscription,\n  RelativeTime,\n  Context,\n  ContextValue,\n} from '@datadog/browser-core'\nimport {\n  noop,\n  PageExitReason,\n  shallowClone,\n  elapsed,\n  generateUUID,\n  ONE_MINUTE,\n  throttle,\n  clocksNow,\n  clocksOrigin,\n  timeStampNow,\n  display,\n  looksLikeRelativeTime,\n  setInterval,\n  clearInterval,\n  setTimeout,\n  Observable,\n  isExperimentalFeatureEnabled,\n  ExperimentalFeature,\n  createContextManager,\n} from '@datadog/browser-core'\nimport type { ViewCustomTimings } from '../../rawRumEvent.types'\nimport { ViewLoadingType } from '../../rawRumEvent.types'\nimport type { LifeCycle } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport type { EventCounts } from '../trackEventCounts'\nimport type { LocationChange } from '../../browser/locationChangeObservable'\nimport type { RumConfiguration, RumInitConfiguration } from '../configuration'\nimport { trackViewEventCounts } from './trackViewEventCounts'\nimport { trackInitialViewMetrics } from './viewMetrics/trackInitialViewMetrics'\nimport type { InitialViewMetrics } from './viewMetrics/trackInitialViewMetrics'\nimport type { CommonViewMetrics } from './viewMetrics/trackCommonViewMetrics'\nimport { trackCommonViewMetrics } from './viewMetrics/trackCommonViewMetrics'\n\nexport interface ViewEvent {\n  id: string\n  name?: string\n  service?: string\n  version?: string\n  context?: Context\n  location: Readonly<Location>\n  commonViewMetrics: CommonViewMetrics\n  initialViewMetrics: InitialViewMetrics\n  customTimings: ViewCustomTimings\n  eventCounts: EventCounts\n  documentVersion: number\n  startClocks: ClocksState\n  duration: Duration\n  isActive: boolean\n  sessionIsActive: boolean\n  loadingType: ViewLoadingType\n}\n\nexport interface ViewCreatedEvent {\n  id: string\n  name?: string\n  service?: string\n  version?: string\n  context?: Context\n  startClocks: ClocksState\n}\n\nexport interface ViewEndedEvent {\n  endClocks: ClocksState\n}\n\nexport const THROTTLE_VIEW_UPDATE_PERIOD = 3000\nexport const SESSION_KEEP_ALIVE_INTERVAL = 5 * ONE_MINUTE\n\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\n\nexport interface ViewOptions {\n  name?: string\n  service?: RumInitConfiguration['service']\n  version?: RumInitConfiguration['version']\n  context?: Context\n}\n\nexport function trackViews(\n  location: Location,\n  lifeCycle: LifeCycle,\n  domMutationObservable: Observable<void>,\n  configuration: RumConfiguration,\n  locationChangeObservable: Observable<LocationChange>,\n  areViewsTrackedAutomatically: boolean,\n  initialViewOptions?: ViewOptions\n) {\n  const activeViews: Set<ReturnType<typeof newView>> = new Set()\n  let currentView = startNewView(ViewLoadingType.INITIAL_LOAD, clocksOrigin(), initialViewOptions)\n\n  startViewLifeCycle()\n\n  let locationChangeSubscription: Subscription\n  if (areViewsTrackedAutomatically) {\n    locationChangeSubscription = renewViewOnLocationChange(locationChangeObservable)\n  }\n\n  function startNewView(loadingType: ViewLoadingType, startClocks?: ClocksState, viewOptions?: ViewOptions) {\n    const newlyCreatedView = newView(\n      lifeCycle,\n      domMutationObservable,\n      configuration,\n      location,\n      loadingType,\n      startClocks,\n      viewOptions\n    )\n    activeViews.add(newlyCreatedView)\n    newlyCreatedView.stopObservable.subscribe(() => {\n      activeViews.delete(newlyCreatedView)\n    })\n    return newlyCreatedView\n  }\n\n  function startViewLifeCycle() {\n    lifeCycle.subscribe(LifeCycleEventType.SESSION_RENEWED, () => {\n      // Renew view on session renewal\n      currentView = startNewView(ViewLoadingType.ROUTE_CHANGE, undefined, {\n        name: currentView.name,\n        service: currentView.service,\n        version: currentView.version,\n        context: currentView.contextManager.getContext(),\n      })\n    })\n\n    lifeCycle.subscribe(LifeCycleEventType.SESSION_EXPIRED, () => {\n      currentView.end({ sessionIsActive: false })\n    })\n\n    // End the current view on page unload\n    lifeCycle.subscribe(LifeCycleEventType.PAGE_EXITED, (pageExitEvent) => {\n      if (pageExitEvent.reason === PageExitReason.UNLOADING) {\n        currentView.end()\n      }\n    })\n  }\n\n  function renewViewOnLocationChange(locationChangeObservable: Observable<LocationChange>) {\n    return locationChangeObservable.subscribe(({ oldLocation, newLocation }) => {\n      if (areDifferentLocation(oldLocation, newLocation)) {\n        currentView.end()\n        currentView = startNewView(ViewLoadingType.ROUTE_CHANGE)\n      }\n    })\n  }\n\n  return {\n    addTiming: (name: string, time: RelativeTime | TimeStamp = timeStampNow()) => {\n      currentView.addTiming(name, time)\n    },\n    startView: (options?: ViewOptions, startClocks?: ClocksState) => {\n      currentView.end({ endClocks: startClocks })\n      currentView = startNewView(ViewLoadingType.ROUTE_CHANGE, startClocks, options)\n    },\n    setViewContext: (context: Context) => {\n      currentView.contextManager.setContext(context)\n    },\n    setViewContextProperty: (key: string, value: ContextValue) => {\n      currentView.contextManager.setContextProperty(key, value)\n    },\n    updateViewName: (name: string) => {\n      currentView.updateViewName(name)\n    },\n\n    stop: () => {\n      if (locationChangeSubscription) {\n        locationChangeSubscription.unsubscribe()\n      }\n      currentView.end()\n      activeViews.forEach((view) => view.stop())\n    },\n  }\n}\n\nfunction newView(\n  lifeCycle: LifeCycle,\n  domMutationObservable: Observable<void>,\n  configuration: RumConfiguration,\n  initialLocation: Location,\n  loadingType: ViewLoadingType,\n  startClocks: ClocksState = clocksNow(),\n  viewOptions?: ViewOptions\n) {\n  // Setup initial values\n  const id = generateUUID()\n  const stopObservable = new Observable<void>()\n  const customTimings: ViewCustomTimings = {}\n  let documentVersion = 0\n  let endClocks: ClocksState | undefined\n  const location = shallowClone(initialLocation)\n  const contextManager = createContextManager()\n\n  let sessionIsActive = true\n  let name: string | undefined\n  let service: string | undefined\n  let version: string | undefined\n  let context: Context | undefined\n\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\n  const viewCreatedEvent = {\n    id,\n    name,\n    startClocks,\n    service,\n    version,\n    context,\n  }\n  lifeCycle.notify(LifeCycleEventType.BEFORE_VIEW_CREATED, viewCreatedEvent)\n  lifeCycle.notify(LifeCycleEventType.VIEW_CREATED, viewCreatedEvent)\n\n  // Update the view every time the measures are changing\n  const { throttled: scheduleViewUpdate, cancel: cancelScheduleViewUpdate } = throttle(\n    triggerViewUpdate,\n    THROTTLE_VIEW_UPDATE_PERIOD,\n    {\n      leading: false,\n    }\n  )\n\n  const {\n    setLoadEvent,\n    setViewEnd,\n    stop: stopCommonViewMetricsTracking,\n    stopINPTracking,\n    getCommonViewMetrics,\n  } = trackCommonViewMetrics(\n    lifeCycle,\n    domMutationObservable,\n    configuration,\n    scheduleViewUpdate,\n    loadingType,\n    startClocks\n  )\n\n  const { stop: stopInitialViewMetricsTracking, initialViewMetrics } =\n    loadingType === ViewLoadingType.INITIAL_LOAD\n      ? trackInitialViewMetrics(configuration, setLoadEvent, scheduleViewUpdate)\n      : { stop: noop, initialViewMetrics: {} as InitialViewMetrics }\n\n  const { stop: stopEventCountsTracking, eventCounts } = trackViewEventCounts(lifeCycle, id, scheduleViewUpdate)\n\n  // Session keep alive\n  const keepAliveIntervalId = setInterval(triggerViewUpdate, SESSION_KEEP_ALIVE_INTERVAL)\n\n  // Initial view update\n  triggerViewUpdate()\n  contextManager.changeObservable.subscribe(triggerViewUpdate)\n\n  function triggerViewUpdate() {\n    cancelScheduleViewUpdate()\n    documentVersion += 1\n    const currentEnd = endClocks === undefined ? timeStampNow() : endClocks.timeStamp\n    lifeCycle.notify(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\n  return {\n    get name() {\n      return name\n    },\n    service,\n    version,\n    contextManager,\n    stopObservable,\n    end(options: { endClocks?: ClocksState; sessionIsActive?: boolean } = {}) {\n      if (endClocks) {\n        // view already ended\n        return\n      }\n      endClocks = options.endClocks ?? clocksNow()\n      sessionIsActive = options.sessionIsActive ?? true\n\n      lifeCycle.notify(LifeCycleEventType.VIEW_ENDED, { endClocks })\n      lifeCycle.notify(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: string, time: RelativeTime | TimeStamp) {\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    updateViewName(updatedName: string) {\n      if (!isExperimentalFeatureEnabled(ExperimentalFeature.UPDATE_VIEW_NAME)) {\n        return\n      }\n      name = updatedName\n      triggerViewUpdate()\n    },\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: string) {\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}\n\nfunction areDifferentLocation(currentLocation: Location, otherLocation: Location) {\n  return (\n    currentLocation.pathname !== otherLocation.pathname ||\n    (!isHashAnAnchor(otherLocation.hash) &&\n      getPathFromHash(otherLocation.hash) !== getPathFromHash(currentLocation.hash))\n  )\n}\n\nfunction isHashAnAnchor(hash: string) {\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}\n\nfunction getPathFromHash(hash: string) {\n  const index = hash.indexOf('?')\n  return index < 0 ? hash : hash.slice(0, index)\n}\n","import type { Duration, ServerDuration, Observable } from '@datadog/browser-core'\nimport { isEmptyObject, mapValues, toServerDuration } from '@datadog/browser-core'\nimport { discardNegativeDuration } from '../discardNegativeDuration'\nimport type { RecorderApi } from '../../boot/rumPublicApi'\nimport type { RawRumViewEvent } from '../../rawRumEvent.types'\nimport { RumEventType } from '../../rawRumEvent.types'\nimport type { LifeCycle, RawRumEventCollectedData } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport type { LocationChange } from '../../browser/locationChangeObservable'\nimport type { RumConfiguration } from '../configuration'\nimport type { FeatureFlagContexts } from '../contexts/featureFlagContext'\nimport type { PageStateHistory } from '../contexts/pageStateHistory'\nimport type { ViewEvent, ViewOptions } from './trackViews'\nimport { trackViews } from './trackViews'\n\nexport function startViewCollection(\n  lifeCycle: LifeCycle,\n  configuration: RumConfiguration,\n  location: Location,\n  domMutationObservable: Observable<void>,\n  locationChangeObservable: Observable<LocationChange>,\n  featureFlagContexts: FeatureFlagContexts,\n  pageStateHistory: PageStateHistory,\n  recorderApi: RecorderApi,\n  initialViewOptions?: ViewOptions\n) {\n  lifeCycle.subscribe(LifeCycleEventType.VIEW_UPDATED, (view) =>\n    lifeCycle.notify(\n      LifeCycleEventType.RAW_RUM_EVENT_COLLECTED,\n      processViewUpdate(view, configuration, featureFlagContexts, recorderApi, pageStateHistory)\n    )\n  )\n  return trackViews(\n    location,\n    lifeCycle,\n    domMutationObservable,\n    configuration,\n    locationChangeObservable,\n    !configuration.trackViewsManually,\n    initialViewOptions\n  )\n}\n\nfunction processViewUpdate(\n  view: ViewEvent,\n  configuration: RumConfiguration,\n  featureFlagContexts: FeatureFlagContexts,\n  recorderApi: RecorderApi,\n  pageStateHistory: PageStateHistory\n): RawRumEventCollectedData<RawRumViewEvent> {\n  const replayStats = recorderApi.getReplayStats(view.id)\n  const featureFlagContext = featureFlagContexts.findFeatureFlagEvaluations(view.startClocks.relative)\n  const pageStates = pageStateHistory.findAll(view.startClocks.relative, view.duration)\n  const viewEvent: RawRumViewEvent = {\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: RumEventType.VIEW,\n    view: {\n      action: {\n        count: view.eventCounts.actionCount,\n      },\n      frustration: {\n        count: view.eventCounts.frustrationCount,\n      },\n      cumulative_layout_shift: view.commonViewMetrics.cumulativeLayoutShift?.value,\n      cumulative_layout_shift_time: toServerDuration(view.commonViewMetrics.cumulativeLayoutShift?.time),\n      cumulative_layout_shift_target_selector: view.commonViewMetrics.cumulativeLayoutShift?.targetSelector,\n      first_byte: toServerDuration(view.initialViewMetrics.navigationTimings?.firstByte),\n      dom_complete: toServerDuration(view.initialViewMetrics.navigationTimings?.domComplete),\n      dom_content_loaded: toServerDuration(view.initialViewMetrics.navigationTimings?.domContentLoaded),\n      dom_interactive: toServerDuration(view.initialViewMetrics.navigationTimings?.domInteractive),\n      error: {\n        count: view.eventCounts.errorCount,\n      },\n      first_contentful_paint: toServerDuration(view.initialViewMetrics.firstContentfulPaint),\n      first_input_delay: toServerDuration(view.initialViewMetrics.firstInput?.delay),\n      first_input_time: toServerDuration(view.initialViewMetrics.firstInput?.time),\n      first_input_target_selector: view.initialViewMetrics.firstInput?.targetSelector,\n      interaction_to_next_paint: toServerDuration(view.commonViewMetrics.interactionToNextPaint?.value),\n      interaction_to_next_paint_time: toServerDuration(view.commonViewMetrics.interactionToNextPaint?.time),\n      interaction_to_next_paint_target_selector: view.commonViewMetrics.interactionToNextPaint?.targetSelector,\n      is_active: view.isActive,\n      name: view.name,\n      largest_contentful_paint: toServerDuration(view.initialViewMetrics.largestContentfulPaint?.value),\n      largest_contentful_paint_target_selector: view.initialViewMetrics.largestContentfulPaint?.targetSelector,\n      load_event: toServerDuration(view.initialViewMetrics.navigationTimings?.loadEvent),\n      loading_time: discardNegativeDuration(toServerDuration(view.commonViewMetrics.loadingTime)),\n      loading_type: view.loadingType,\n      long_task: {\n        count: view.eventCounts.longTaskCount,\n      },\n      resource: {\n        count: view.eventCounts.resourceCount,\n      },\n      time_spent: toServerDuration(view.duration),\n    },\n    feature_flags: featureFlagContext && !isEmptyObject(featureFlagContext) ? featureFlagContext : undefined,\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(\n      view.customTimings,\n      toServerDuration as (duration: Duration) => ServerDuration\n    )\n  }\n\n  return {\n    rawRumEvent: viewEvent,\n    startTime: view.startClocks.relative,\n    domainContext: {\n      location: view.location,\n    },\n  }\n}\n","import type { LifeCycle } from '../lifeCycle'\nimport { trackEventCounts } from '../trackEventCounts'\n\nexport function trackViewEventCounts(lifeCycle: LifeCycle, viewId: string, onChange: () => void) {\n  const { stop, eventCounts } = trackEventCounts({\n    lifeCycle,\n    isChildEvent: (event) => event.view.id === viewId,\n    onChange,\n  })\n\n  return {\n    stop,\n    eventCounts,\n  }\n}\n","import { Observable } from '../../tools/observable'\nimport type { Context } from '../../tools/serialisation/context'\nimport { createValueHistory } from '../../tools/valueHistory'\nimport type { RelativeTime } from '../../tools/utils/timeUtils'\nimport { relativeNow, clocksOrigin, ONE_MINUTE } from '../../tools/utils/timeUtils'\nimport { DOM_EVENT, addEventListener, addEventListeners } from '../../browser/addEventListener'\nimport { clearInterval, setInterval } from '../../tools/timer'\nimport type { Configuration } from '../configuration'\nimport type { TrackingConsentState } from '../trackingConsent'\nimport { SESSION_TIME_OUT_DELAY } from './sessionConstants'\nimport { startSessionStore } from './sessionStore'\nimport type { SessionState } from './sessionState'\n\nexport interface SessionManager<TrackingType extends string> {\n  findSession: (\n    startTime?: RelativeTime,\n    options?: { returnInactive: boolean }\n  ) => SessionContext<TrackingType> | undefined\n  renewObservable: Observable<void>\n  expireObservable: Observable<void>\n  sessionStateUpdateObservable: Observable<{ previousState: SessionState; newState: SessionState }>\n  expire: () => void\n  updateSessionState: (state: Partial<SessionState>) => void\n}\n\nexport interface SessionContext<TrackingType extends string> extends Context {\n  id: string\n  trackingType: TrackingType\n  isReplayForced: boolean\n}\n\nexport const VISIBILITY_CHECK_DELAY = ONE_MINUTE\nconst SESSION_CONTEXT_TIMEOUT_DELAY = SESSION_TIME_OUT_DELAY\nlet stopCallbacks: Array<() => void> = []\n\nexport function startSessionManager<TrackingType extends string>(\n  configuration: Configuration,\n  productKey: string,\n  computeSessionState: (rawTrackingType?: string) => { trackingType: TrackingType; isTracked: boolean },\n  trackingConsentState: TrackingConsentState\n): SessionManager<TrackingType> {\n  const renewObservable = new Observable<void>()\n  const expireObservable = new Observable<void>()\n\n  // TODO - Improve configuration type and remove assertion\n  const sessionStore = startSessionStore(configuration.sessionStoreStrategyType!, productKey, computeSessionState)\n  stopCallbacks.push(() => sessionStore.stop())\n\n  const sessionContextHistory = createValueHistory<SessionContext<TrackingType>>({\n    expireDelay: SESSION_CONTEXT_TIMEOUT_DELAY,\n  })\n  stopCallbacks.push(() => sessionContextHistory.stop())\n\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\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\n  trackingConsentState.observable.subscribe(() => {\n    if (trackingConsentState.isGranted()) {\n      sessionStore.expandOrRenewSession()\n    } else {\n      sessionStore.expire()\n    }\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\n  function buildSessionContext() {\n    return {\n      id: sessionStore.getSession().id!,\n      trackingType: sessionStore.getSession()[productKey] as TrackingType,\n      isReplayForced: !!sessionStore.getSession().forcedReplay,\n    }\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}\n\nexport function stopSessionManager() {\n  stopCallbacks.forEach((e) => e())\n  stopCallbacks = []\n}\n\nfunction trackActivity(configuration: Configuration, expandOrRenewSession: () => void) {\n  const { stop } = addEventListeners(\n    configuration,\n    window,\n    [DOM_EVENT.CLICK, DOM_EVENT.TOUCH_START, DOM_EVENT.KEY_DOWN, DOM_EVENT.SCROLL],\n    expandOrRenewSession,\n    { capture: true, passive: true }\n  )\n  stopCallbacks.push(stop)\n}\n\nfunction trackVisibility(configuration: Configuration, expandSession: () => void) {\n  const expandSessionWhenVisible = () => {\n    if (document.visibilityState === 'visible') {\n      expandSession()\n    }\n  }\n\n  const { stop } = addEventListener(configuration, document, DOM_EVENT.VISIBILITY_CHANGE, expandSessionWhenVisible)\n  stopCallbacks.push(stop)\n\n  const visibilityCheckInterval = setInterval(expandSessionWhenVisible, VISIBILITY_CHECK_DELAY)\n  stopCallbacks.push(() => {\n    clearInterval(visibilityCheckInterval)\n  })\n}\n\nfunction trackResume(configuration: Configuration, cb: () => void) {\n  const { stop } = addEventListener(configuration, window, DOM_EVENT.RESUME, cb, { capture: true })\n  stopCallbacks.push(stop)\n}\n","import type { RelativeTime, TrackingConsentState } from '@datadog/browser-core'\nimport {\n  BridgeCapability,\n  Observable,\n  bridgeSupports,\n  noop,\n  performDraw,\n  startSessionManager,\n} from '@datadog/browser-core'\nimport type { RumConfiguration } from './configuration'\nimport type { LifeCycle } from './lifeCycle'\nimport { LifeCycleEventType } from './lifeCycle'\n\nexport const RUM_SESSION_KEY = 'rum'\n\nexport interface RumSessionManager {\n  findTrackedSession: (startTime?: RelativeTime) => RumSession | undefined\n  expire: () => void\n  expireObservable: Observable<void>\n  setForcedReplay: () => void\n}\n\nexport type RumSession = {\n  id: string\n  sessionReplay: SessionReplayState\n}\n\nexport const enum RumTrackingType {\n  NOT_TRACKED = '0',\n  TRACKED_WITH_SESSION_REPLAY = '1',\n  TRACKED_WITHOUT_SESSION_REPLAY = '2',\n}\n\nexport const enum SessionReplayState {\n  OFF,\n  SAMPLED,\n  FORCED,\n}\n\nexport function startRumSessionManager(\n  configuration: RumConfiguration,\n  lifeCycle: LifeCycle,\n  trackingConsentState: TrackingConsentState\n): RumSessionManager {\n  const sessionManager = startSessionManager(\n    configuration,\n    RUM_SESSION_KEY,\n    (rawTrackingType) => computeSessionState(configuration, rawTrackingType),\n    trackingConsentState\n  )\n\n  sessionManager.expireObservable.subscribe(() => {\n    lifeCycle.notify(LifeCycleEventType.SESSION_EXPIRED)\n  })\n\n  sessionManager.renewObservable.subscribe(() => {\n    lifeCycle.notify(LifeCycleEventType.SESSION_RENEWED)\n  })\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\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:\n          session.trackingType === RumTrackingType.TRACKED_WITH_SESSION_REPLAY\n            ? SessionReplayState.SAMPLED\n            : session.isReplayForced\n              ? SessionReplayState.FORCED\n              : SessionReplayState.OFF,\n      }\n    },\n    expire: sessionManager.expire,\n    expireObservable: sessionManager.expireObservable,\n    setForcedReplay: () => sessionManager.updateSessionState({ forcedReplay: '1' }),\n  }\n}\n\n/**\n * Start a tracked replay session stub\n */\nexport function startRumSessionManagerStub(): RumSessionManager {\n  const session: RumSession = {\n    id: '00000000-aaaa-0000-aaaa-000000000000',\n    sessionReplay: bridgeSupports(BridgeCapability.RECORDS) ? SessionReplayState.SAMPLED : SessionReplayState.OFF,\n  }\n  return {\n    findTrackedSession: () => session,\n    expire: noop,\n    expireObservable: new Observable(),\n    setForcedReplay: noop,\n  }\n}\n\nfunction computeSessionState(configuration: RumConfiguration, rawTrackingType?: string) {\n  let trackingType: RumTrackingType\n  if (hasValidRumSession(rawTrackingType)) {\n    trackingType = rawTrackingType\n  } else if (!performDraw(configuration.sessionSampleRate)) {\n    trackingType = RumTrackingType.NOT_TRACKED\n  } else if (!performDraw(configuration.sessionReplaySampleRate)) {\n    trackingType = RumTrackingType.TRACKED_WITHOUT_SESSION_REPLAY\n  } else {\n    trackingType = RumTrackingType.TRACKED_WITH_SESSION_REPLAY\n  }\n  return {\n    trackingType,\n    isTracked: isTypeTracked(trackingType),\n  }\n}\n\nfunction hasValidRumSession(trackingType?: string): trackingType is RumTrackingType {\n  return (\n    trackingType === RumTrackingType.NOT_TRACKED ||\n    trackingType === RumTrackingType.TRACKED_WITH_SESSION_REPLAY ||\n    trackingType === RumTrackingType.TRACKED_WITHOUT_SESSION_REPLAY\n  )\n}\n\nfunction isTypeTracked(rumSessionType: RumTrackingType | undefined) {\n  return (\n    rumSessionType === RumTrackingType.TRACKED_WITHOUT_SESSION_REPLAY ||\n    rumSessionType === RumTrackingType.TRACKED_WITH_SESSION_REPLAY\n  )\n}\n","import { DOCS_TROUBLESHOOTING, MORE_DETAILS, display } from '../tools/display'\nimport type { Context } from '../tools/serialisation/context'\nimport { objectValues } from '../tools/utils/polyfills'\nimport { isPageExitReason } from '../browser/pageExitObservable'\nimport { jsonStringify } from '../tools/serialisation/jsonStringify'\nimport type { Encoder, EncoderResult } from '../tools/encoder'\nimport { computeBytesCount } from '../tools/utils/byteUtils'\nimport type { HttpRequest, Payload } from './httpRequest'\nimport type { FlushController, FlushEvent } from './flushController'\n\nexport interface Batch {\n  flushController: FlushController\n  add: (message: Context) => void\n  upsert: (message: Context, key: string) => void\n  stop: () => void\n}\n\nexport function createBatch({\n  encoder,\n  request,\n  flushController,\n  messageBytesLimit,\n}: {\n  encoder: Encoder\n  request: HttpRequest\n  flushController: FlushController\n  messageBytesLimit: number\n}): Batch {\n  let upsertBuffer: { [key: string]: string } = {}\n  const flushSubscription = flushController.flushObservable.subscribe((event) => flush(event))\n\n  function push(serializedMessage: string, estimatedMessageBytesCount: number, key?: string) {\n    flushController.notifyBeforeAddMessage(estimatedMessageBytesCount)\n\n    if (key !== undefined) {\n      upsertBuffer[key] = serializedMessage\n      flushController.notifyAfterAddMessage()\n    } else {\n      encoder.write(encoder.isEmpty ? serializedMessage : `\\n${serializedMessage}`, (realMessageBytesCount) => {\n        flushController.notifyAfterAddMessage(realMessageBytesCount - estimatedMessageBytesCount)\n      })\n    }\n  }\n\n  function hasMessageFor(key?: string): key is string {\n    return key !== undefined && upsertBuffer[key] !== undefined\n  }\n\n  function remove(key: string) {\n    const removedMessage = upsertBuffer[key]\n    delete upsertBuffer[key]\n    const messageBytesCount = encoder.estimateEncodedBytesCount(removedMessage)\n    flushController.notifyAfterRemoveMessage(messageBytesCount)\n  }\n\n  function addOrUpdate(message: Context, key?: string) {\n    const serializedMessage = jsonStringify(message)!\n\n    const estimatedMessageBytesCount = encoder.estimateEncodedBytesCount(serializedMessage)\n\n    if (estimatedMessageBytesCount >= messageBytesLimit) {\n      display.warn(\n        `Discarded a message whose size was bigger than the maximum allowed size ${messageBytesLimit}KB. ${MORE_DETAILS} ${DOCS_TROUBLESHOOTING}/#technical-limitations`\n      )\n      return\n    }\n\n    if (hasMessageFor(key)) {\n      remove(key)\n    }\n\n    push(serializedMessage, estimatedMessageBytesCount, key)\n  }\n\n  function flush(event: FlushEvent) {\n    const upsertMessages = objectValues(upsertBuffer).join('\\n')\n    upsertBuffer = {}\n\n    const isPageExit = isPageExitReason(event.reason)\n    const send = isPageExit ? request.sendOnExit : request.send\n\n    if (\n      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    ) {\n      const encoderResult = encoder.finishSync()\n\n      // Send encoded messages\n      if (encoderResult.outputBytesCount) {\n        send(formatPayloadFromEncoder(encoderResult))\n      }\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    } 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\n  return {\n    flushController,\n    add: addOrUpdate,\n    upsert: addOrUpdate,\n    stop: flushSubscription.unsubscribe,\n  }\n}\n\nfunction formatPayloadFromEncoder(encoderResult: EncoderResult): Payload {\n  let data: string | Blob\n  if (typeof encoderResult.output === 'string') {\n    data = encoderResult.output\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\n  return {\n    data,\n    bytesCount: encoderResult.outputBytesCount,\n    encoding: encoderResult.encoding,\n  }\n}\n","import type { TrackType } from '../domain/configuration'\nimport { 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 type { RawError } from '../domain/error/error.types'\nimport { ErrorSource } from '../domain/error/error.types'\nimport type { Payload, HttpResponse } from './httpRequest'\n\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\n\nconst enum TransportStatus {\n  UP,\n  FAILURE_DETECTED,\n  DOWN,\n}\n\nconst enum RetryReason {\n  AFTER_SUCCESS,\n  AFTER_RESUME,\n}\n\nexport interface RetryState {\n  transportStatus: TransportStatus\n  currentBackoffTime: number\n  bandwidthMonitor: ReturnType<typeof newBandwidthMonitor>\n  queuedPayloads: ReturnType<typeof newPayloadQueue>\n  queueFullReported: boolean\n}\n\ntype SendStrategy = (payload: Payload, onResponse: (r: HttpResponse) => void) => void\n\nexport function sendWithRetryStrategy(\n  payload: Payload,\n  state: RetryState,\n  sendStrategy: SendStrategy,\n  trackType: TrackType,\n  reportError: (error: RawError) => void\n) {\n  if (\n    state.transportStatus === TransportStatus.UP &&\n    state.queuedPayloads.size() === 0 &&\n    state.bandwidthMonitor.canHandle(payload)\n  ) {\n    send(payload, state, sendStrategy, {\n      onSuccess: () => retryQueuedPayloads(RetryReason.AFTER_SUCCESS, state, sendStrategy, trackType, reportError),\n      onFailure: () => {\n        state.queuedPayloads.enqueue(payload)\n        scheduleRetry(state, sendStrategy, trackType, reportError)\n      },\n    })\n  } else {\n    state.queuedPayloads.enqueue(payload)\n  }\n}\n\nfunction scheduleRetry(\n  state: RetryState,\n  sendStrategy: SendStrategy,\n  trackType: TrackType,\n  reportError: (error: RawError) => void\n) {\n  if (state.transportStatus !== 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(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}\n\nfunction send(\n  payload: Payload,\n  state: RetryState,\n  sendStrategy: SendStrategy,\n  { onSuccess, onFailure }: { onSuccess: () => void; onFailure: () => void }\n) {\n  state.bandwidthMonitor.add(payload)\n  sendStrategy(payload, (response) => {\n    state.bandwidthMonitor.remove(payload)\n    if (!shouldRetryRequest(response)) {\n      state.transportStatus = TransportStatus.UP\n      onSuccess()\n    } else {\n      // do not consider transport down if another ongoing request could succeed\n      state.transportStatus =\n        state.bandwidthMonitor.ongoingRequestCount > 0 ? TransportStatus.FAILURE_DETECTED : TransportStatus.DOWN\n      payload.retry = {\n        count: payload.retry ? payload.retry.count + 1 : 1,\n        lastFailureStatus: response.status,\n      }\n      onFailure()\n    }\n  })\n}\n\nfunction retryQueuedPayloads(\n  reason: RetryReason,\n  state: RetryState,\n  sendStrategy: SendStrategy,\n  trackType: TrackType,\n  reportError: (error: RawError) => void\n) {\n  if (reason === 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}\n\nfunction shouldRetryRequest(response: HttpResponse) {\n  return (\n    response.type !== 'opaque' &&\n    ((response.status === 0 && !navigator.onLine) ||\n      response.status === 408 ||\n      response.status === 429 ||\n      isServerError(response.status))\n  )\n}\n\nexport function newRetryState(): RetryState {\n  return {\n    transportStatus: TransportStatus.UP,\n    currentBackoffTime: INITIAL_BACKOFF_TIME,\n    bandwidthMonitor: newBandwidthMonitor(),\n    queuedPayloads: newPayloadQueue(),\n    queueFullReported: false,\n  }\n}\n\nfunction newPayloadQueue() {\n  const queue: Payload[] = []\n  return {\n    bytesCount: 0,\n    enqueue(payload: 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}\n\nfunction newBandwidthMonitor() {\n  return {\n    ongoingRequestCount: 0,\n    ongoingByteCount: 0,\n    canHandle(payload: Payload) {\n      return (\n        this.ongoingRequestCount === 0 ||\n        (this.ongoingByteCount + payload.bytesCount <= MAX_ONGOING_BYTES_COUNT &&\n          this.ongoingRequestCount < MAX_ONGOING_REQUESTS)\n      )\n    },\n    add(payload: Payload) {\n      this.ongoingRequestCount += 1\n      this.ongoingByteCount += payload.bytesCount\n    },\n    remove(payload: Payload) {\n      this.ongoingRequestCount -= 1\n      this.ongoingByteCount -= payload.bytesCount\n    },\n  }\n}\n","import type { EndpointBuilder, Configuration } from '../domain/configuration'\nimport { addTelemetryError } from '../domain/telemetry'\nimport type { Context } from '../tools/serialisation/context'\nimport { monitor } from '../tools/monitor'\nimport { addEventListener } from '../browser/addEventListener'\nimport type { RawError } from '../domain/error/error.types'\nimport { newRetryState, sendWithRetryStrategy } from './sendWithRetryStrategy'\n\n/**\n * Use POST request without content type to:\n * - avoid CORS preflight requests\n * - allow usage of sendBeacon\n *\n * multiple elements are sent separated by \\n in order\n * to be parsed correctly without content type header\n */\n\nexport type HttpRequest = ReturnType<typeof createHttpRequest>\n\nexport interface HttpResponse extends Context {\n  status: number\n  type?: ResponseType\n}\n\nexport interface Payload {\n  data: string | FormData | Blob\n  bytesCount: number\n  retry?: RetryInfo\n  encoding?: 'deflate'\n}\n\nexport interface RetryInfo {\n  count: number\n  lastFailureStatus: number\n}\n\nexport function createHttpRequest(\n  configuration: Configuration,\n  endpointBuilder: EndpointBuilder,\n  bytesLimit: number,\n  reportError: (error: RawError) => void\n) {\n  const retryState = newRetryState()\n  const sendStrategyForRetry = (payload: Payload, onResponse: (r: HttpResponse) => void) =>\n    fetchKeepAliveStrategy(configuration, endpointBuilder, bytesLimit, payload, onResponse)\n\n  return {\n    send: (payload: 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: Payload) => {\n      sendBeaconStrategy(configuration, endpointBuilder, bytesLimit, payload)\n    },\n  }\n}\n\nfunction sendBeaconStrategy(\n  configuration: Configuration,\n  endpointBuilder: EndpointBuilder,\n  bytesLimit: number,\n  payload: Payload\n) {\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\n      if (isQueued) {\n        return\n      }\n    } catch (e) {\n      reportBeaconError(e)\n    }\n  }\n\n  const xhrUrl = endpointBuilder.build('xhr', payload)\n  sendXHR(configuration, xhrUrl, payload.data)\n}\n\nlet hasReportedBeaconError = false\n\nfunction reportBeaconError(e: unknown) {\n  if (!hasReportedBeaconError) {\n    hasReportedBeaconError = true\n    addTelemetryError(e)\n  }\n}\n\nexport function fetchKeepAliveStrategy(\n  configuration: Configuration,\n  endpointBuilder: EndpointBuilder,\n  bytesLimit: number,\n  payload: Payload,\n  onResponse?: (r: HttpResponse) => void\n) {\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(\n      monitor((response: Response) => onResponse?.({ status: response.status, type: response.type })),\n      monitor(() => {\n        const xhrUrl = endpointBuilder.build('xhr', payload)\n        // failed to queue the request\n        sendXHR(configuration, xhrUrl, payload.data, onResponse)\n      })\n    )\n  } else {\n    const xhrUrl = endpointBuilder.build('xhr', payload)\n    sendXHR(configuration, xhrUrl, payload.data, onResponse)\n  }\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  } catch {\n    return false\n  }\n}\n\nexport function sendXHR(\n  configuration: Configuration,\n  url: string,\n  data: Payload['data'],\n  onResponse?: (r: HttpResponse) => void\n) {\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    configuration,\n    request,\n    'loadend',\n    () => {\n      onResponse?.({ status: request.status })\n    },\n    {\n      // prevent multiple onResponse callbacks\n      // if the xhr instance is reused by a third party\n      once: true,\n    }\n  )\n  request.send(data)\n}\n","import type { PageExitEvent, PageExitReason } from '../browser/pageExitObservable'\nimport { Observable } from '../tools/observable'\nimport type { TimeoutId } from '../tools/timer'\nimport { clearTimeout, setTimeout } from '../tools/timer'\nimport type { Duration } from '../tools/utils/timeUtils'\n\nexport type FlushReason = PageExitReason | 'duration_limit' | 'bytes_limit' | 'messages_limit' | 'session_expire'\n\nexport type FlushController = ReturnType<typeof createFlushController>\nexport interface FlushEvent {\n  reason: FlushReason\n  bytesCount: number\n  messagesCount: number\n}\n\ninterface FlushControllerOptions {\n  messagesLimit: number\n  bytesLimit: number\n  durationLimit: Duration\n  pageExitObservable: Observable<PageExitEvent>\n  sessionExpireObservable: Observable<void>\n}\n\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({\n  messagesLimit,\n  bytesLimit,\n  durationLimit,\n  pageExitObservable,\n  sessionExpireObservable,\n}: FlushControllerOptions) {\n  const pageExitSubscription = pageExitObservable.subscribe((event) => flush(event.reason))\n  const sessionExpireSubscription = sessionExpireObservable.subscribe(() => flush('session_expire'))\n\n  const flushObservable = new Observable<FlushEvent>(() => () => {\n    pageExitSubscription.unsubscribe()\n    sessionExpireSubscription.unsubscribe()\n  })\n\n  let currentBytesCount = 0\n  let currentMessagesCount = 0\n\n  function flush(flushReason: FlushReason) {\n    if (currentMessagesCount === 0) {\n      return\n    }\n\n    const messagesCount = currentMessagesCount\n    const bytesCount = currentBytesCount\n\n    currentMessagesCount = 0\n    currentBytesCount = 0\n    cancelDurationLimitTimeout()\n\n    flushObservable.notify({\n      reason: flushReason,\n      messagesCount,\n      bytesCount,\n    })\n  }\n\n  let durationLimitTimeoutId: TimeoutId | undefined\n  function scheduleDurationLimitTimeout() {\n    if (durationLimitTimeoutId === undefined) {\n      durationLimitTimeoutId = setTimeout(() => {\n        flush('duration_limit')\n      }, durationLimit)\n    }\n  }\n\n  function cancelDurationLimitTimeout() {\n    clearTimeout(durationLimitTimeoutId)\n    durationLimitTimeoutId = undefined\n  }\n\n  return {\n    flushObservable,\n    get messagesCount() {\n      return currentMessagesCount\n    },\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: number) {\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    /**\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\n      if (currentMessagesCount >= messagesLimit) {\n        flush('messages_limit')\n      } else if (currentBytesCount >= bytesLimit) {\n        flush('bytes_limit')\n      }\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: number) {\n      currentBytesCount -= messageBytesCount\n      currentMessagesCount -= 1\n      if (currentMessagesCount === 0) {\n        cancelDurationLimitTimeout()\n      }\n    },\n  }\n}\n","import type { RelativeTime, Observable } from '@datadog/browser-core'\nimport { SESSION_TIME_OUT_DELAY, relativeNow, createValueHistory } from '@datadog/browser-core'\nimport type { LocationChange } from '../../browser/locationChangeObservable'\nimport type { LifeCycle } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\n\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 */\n\nexport const URL_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY\n\nexport interface UrlContext {\n  url: string\n  referrer: string\n}\n\nexport interface UrlContexts {\n  findUrl: (startTime?: RelativeTime) => UrlContext | undefined\n  stop: () => void\n}\n\nexport function startUrlContexts(\n  lifeCycle: LifeCycle,\n  locationChangeObservable: Observable<LocationChange>,\n  location: Location\n) {\n  const urlContextHistory = createValueHistory<UrlContext>({ expireDelay: URL_CONTEXT_TIME_OUT_DELAY })\n\n  let previousViewUrl: string | undefined\n\n  lifeCycle.subscribe(LifeCycleEventType.BEFORE_VIEW_CREATED, ({ startClocks }) => {\n    const viewUrl = location.href\n    urlContextHistory.add(\n      buildUrlContext({\n        url: viewUrl,\n        referrer: !previousViewUrl ? document.referrer : previousViewUrl,\n      }),\n      startClocks.relative\n    )\n    previousViewUrl = viewUrl\n  })\n\n  lifeCycle.subscribe(LifeCycleEventType.AFTER_VIEW_ENDED, ({ endClocks }) => {\n    urlContextHistory.closeActive(endClocks.relative)\n  })\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(\n        buildUrlContext({\n          url: newLocation.href,\n          referrer: current.referrer,\n        }),\n        changeTime\n      )\n    }\n  })\n\n  function buildUrlContext({ url, referrer }: { url: string; referrer: string }) {\n    return {\n      url,\n      referrer,\n    }\n  }\n\n  return {\n    findUrl: (startTime?: RelativeTime) => urlContextHistory.find(startTime),\n    stop: () => {\n      locationChangeSubscription.unsubscribe()\n      urlContextHistory.stop()\n    },\n  }\n}\n","import { addEventListener, DOM_EVENT, instrumentMethod, Observable, shallowClone } from '@datadog/browser-core'\nimport type { RumConfiguration } from '../domain/configuration'\n\nexport interface LocationChange {\n  oldLocation: Readonly<Location>\n  newLocation: Readonly<Location>\n}\n\nexport function createLocationChangeObservable(configuration: RumConfiguration, location: Location) {\n  let currentLocation = shallowClone(location)\n\n  return new Observable<LocationChange>((observable) => {\n    const { stop: stopHistoryTracking } = trackHistory(configuration, onLocationChange)\n    const { stop: stopHashTracking } = trackHash(configuration, onLocationChange)\n\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\n    return () => {\n      stopHistoryTracking()\n      stopHashTracking()\n    }\n  })\n}\n\nfunction trackHistory(configuration: RumConfiguration, onHistoryChange: () => void) {\n  const { stop: stopInstrumentingPushState } = instrumentMethod(\n    getHistoryInstrumentationTarget('pushState'),\n    'pushState',\n    ({ onPostCall }) => {\n      onPostCall(onHistoryChange)\n    }\n  )\n  const { stop: stopInstrumentingReplaceState } = instrumentMethod(\n    getHistoryInstrumentationTarget('replaceState'),\n    'replaceState',\n    ({ onPostCall }) => {\n      onPostCall(onHistoryChange)\n    }\n  )\n  const { stop: removeListener } = addEventListener(configuration, window, DOM_EVENT.POP_STATE, onHistoryChange)\n\n  return {\n    stop: () => {\n      stopInstrumentingPushState()\n      stopInstrumentingReplaceState()\n      removeListener()\n    },\n  }\n}\n\nfunction trackHash(configuration: RumConfiguration, onHashChange: () => void) {\n  return addEventListener(configuration, window, DOM_EVENT.HASH_CHANGE, onHashChange)\n}\n\nfunction getHistoryInstrumentationTarget(methodName: 'pushState' | 'replaceState') {\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","import type { RelativeTime, ContextValue, Context, CustomerDataTracker } from '@datadog/browser-core'\nimport { SESSION_TIME_OUT_DELAY, createValueHistory } from '@datadog/browser-core'\nimport type { LifeCycle } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\n\nexport const FEATURE_FLAG_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY\nexport const BYTES_COMPUTATION_THROTTLING_DELAY = 200\n\nexport type FeatureFlagContext = Context\n\nexport interface FeatureFlagContexts {\n  findFeatureFlagEvaluations: (startTime?: RelativeTime) => FeatureFlagContext | undefined\n  addFeatureFlagEvaluation: (key: string, value: ContextValue) => void\n  stop: () => void\n}\n\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(\n  lifeCycle: LifeCycle,\n  customerDataTracker: CustomerDataTracker\n): FeatureFlagContexts {\n  const featureFlagContexts = createValueHistory<FeatureFlagContext>({\n    expireDelay: FEATURE_FLAG_CONTEXT_TIME_OUT_DELAY,\n  })\n\n  lifeCycle.subscribe(LifeCycleEventType.BEFORE_VIEW_CREATED, ({ startClocks }) => {\n    featureFlagContexts.add({}, startClocks.relative)\n    customerDataTracker.resetCustomerData()\n  })\n\n  lifeCycle.subscribe(LifeCycleEventType.AFTER_VIEW_ENDED, ({ endClocks }) => {\n    featureFlagContexts.closeActive(endClocks.relative)\n  })\n\n  return {\n    findFeatureFlagEvaluations: (startTime?: RelativeTime) => featureFlagContexts.find(startTime),\n    addFeatureFlagEvaluation: (key: string, value: ContextValue) => {\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","import type { Context, CustomerDataTrackerManager, FlushEvent, Observable, Telemetry } from '@datadog/browser-core'\nimport {\n  includes,\n  performDraw,\n  ONE_SECOND,\n  addTelemetryDebug,\n  setInterval,\n  CustomerDataType,\n} from '@datadog/browser-core'\nimport { RumEventType } from '../rawRumEvent.types'\nimport type { RumEvent } from '../rumEvent.types'\nimport type { RumConfiguration } from './configuration'\nimport type { LifeCycle } from './lifeCycle'\nimport { LifeCycleEventType } from './lifeCycle'\n\nexport const MEASURES_PERIOD_DURATION = 10 * ONE_SECOND\n\ntype Measure = {\n  min: number\n  max: number\n  sum: number\n}\n\ntype CurrentPeriodMeasures = {\n  batchCount: number\n  batchBytesCount: Measure\n  batchMessagesCount: Measure\n  globalContextBytes: Measure\n  userContextBytes: Measure\n  featureFlagBytes: Measure\n}\n\ntype CurrentBatchMeasures = {\n  globalContextBytes: Measure\n  userContextBytes: Measure\n  featureFlagBytes: Measure\n}\n\nlet currentPeriodMeasures: CurrentPeriodMeasures\nlet currentBatchMeasures: CurrentBatchMeasures\nlet batchHasRumEvent: boolean\n\nexport function startCustomerDataTelemetry(\n  configuration: RumConfiguration,\n  telemetry: Telemetry,\n  lifeCycle: LifeCycle,\n  customerDataTrackerManager: CustomerDataTrackerManager,\n  batchFlushObservable: Observable<FlushEvent>\n) {\n  const customerDataTelemetryEnabled = telemetry.enabled && performDraw(configuration.customerDataTelemetrySampleRate)\n  if (!customerDataTelemetryEnabled) {\n    return\n  }\n\n  initCurrentPeriodMeasures()\n  initCurrentBatchMeasures()\n\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(LifeCycleEventType.RUM_EVENT_COLLECTED, (event: RumEvent & Context) => {\n    batchHasRumEvent = true\n    updateMeasure(\n      currentBatchMeasures.globalContextBytes,\n      customerDataTrackerManager.getOrCreateTracker(CustomerDataType.GlobalContext).getBytesCount()\n    )\n\n    updateMeasure(\n      currentBatchMeasures.userContextBytes,\n      customerDataTrackerManager.getOrCreateTracker(CustomerDataType.User).getBytesCount()\n    )\n\n    updateMeasure(\n      currentBatchMeasures.featureFlagBytes,\n      includes([RumEventType.VIEW, RumEventType.ERROR], event.type)\n        ? customerDataTrackerManager.getOrCreateTracker(CustomerDataType.FeatureFlag).getBytesCount()\n        : 0\n    )\n  })\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\n  setInterval(sendCurrentPeriodMeasures, MEASURES_PERIOD_DURATION)\n}\n\nfunction sendCurrentPeriodMeasures() {\n  if (currentPeriodMeasures.batchCount === 0) {\n    return\n  }\n\n  addTelemetryDebug('Customer data measures', currentPeriodMeasures)\n  initCurrentPeriodMeasures()\n}\n\nfunction createMeasure(): Measure {\n  return { min: Infinity, max: 0, sum: 0 }\n}\n\nfunction updateMeasure(measure: Measure, value: number) {\n  measure.sum += value\n  measure.min = Math.min(measure.min, value)\n  measure.max = Math.max(measure.max, value)\n}\n\nfunction mergeMeasure(target: Measure, source: Measure) {\n  target.sum += source.sum\n  target.min = Math.min(target.min, source.min)\n  target.max = Math.max(target.max, source.max)\n}\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}\n\nfunction initCurrentBatchMeasures() {\n  batchHasRumEvent = false\n  currentBatchMeasures = {\n    globalContextBytes: createMeasure(),\n    userContextBytes: createMeasure(),\n    featureFlagBytes: createMeasure(),\n  }\n}\n","import type { Duration, RelativeTime } from '@datadog/browser-core'\nimport {\n  elapsed,\n  createValueHistory,\n  SESSION_TIME_OUT_DELAY,\n  toServerDuration,\n  addEventListeners,\n  relativeNow,\n  DOM_EVENT,\n} from '@datadog/browser-core'\nimport type { RumConfiguration } from '../configuration'\nimport type { PageStateServerEntry } from '../../rawRumEvent.types'\n\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\n\nexport const PAGE_STATE_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY\n\nexport const enum PageState {\n  ACTIVE = 'active',\n  PASSIVE = 'passive',\n  HIDDEN = 'hidden',\n  FROZEN = 'frozen',\n  TERMINATED = 'terminated',\n}\n\nexport type PageStateEntry = { state: PageState; startTime: RelativeTime }\n\nexport interface PageStateHistory {\n  findAll: (startTime: RelativeTime, duration: Duration) => PageStateServerEntry[] | undefined\n  wasInPageStateAt: (state: PageState, startTime: RelativeTime) => boolean\n  wasInPageStateDuringPeriod: (state: PageState, startTime: RelativeTime, duration: Duration) => boolean\n  addPageState(nextPageState: PageState, startTime?: RelativeTime): void\n  stop: () => void\n}\n\nexport function startPageStateHistory(\n  configuration: RumConfiguration,\n  maxPageStateEntriesSelectable = MAX_PAGE_STATE_ENTRIES_SELECTABLE\n): PageStateHistory {\n  const pageStateEntryHistory = createValueHistory<PageStateEntry>({\n    expireDelay: PAGE_STATE_CONTEXT_TIME_OUT_DELAY,\n    maxEntries: MAX_PAGE_STATE_ENTRIES,\n  })\n\n  let currentPageState: PageState\n  addPageState(getPageState(), relativeNow())\n\n  const { stop: stopEventListeners } = addEventListeners(\n    configuration,\n    window,\n    [\n      DOM_EVENT.PAGE_SHOW,\n      DOM_EVENT.FOCUS,\n      DOM_EVENT.BLUR,\n      DOM_EVENT.VISIBILITY_CHANGE,\n      DOM_EVENT.RESUME,\n      DOM_EVENT.FREEZE,\n      DOM_EVENT.PAGE_HIDE,\n    ],\n    (event) => {\n      addPageState(computePageState(event), event.timeStamp as RelativeTime)\n    },\n    { capture: true }\n  )\n\n  function addPageState(nextPageState: PageState, startTime = relativeNow()) {\n    if (nextPageState === currentPageState) {\n      return\n    }\n\n    currentPageState = nextPageState\n    pageStateEntryHistory.closeActive(startTime)\n    pageStateEntryHistory.add({ state: currentPageState, startTime }, startTime)\n  }\n\n  const pageStateHistory = {\n    findAll: (eventStartTime: RelativeTime, duration: Duration): PageStateServerEntry[] | undefined => {\n      const pageStateEntries = pageStateEntryHistory.findAll(eventStartTime, duration)\n\n      if (pageStateEntries.length === 0) {\n        return\n      }\n\n      const pageStateServerEntries = []\n      // limit the number of entries to return\n      const limit = Math.max(0, pageStateEntries.length - maxPageStateEntriesSelectable)\n\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\n        pageStateServerEntries.push({\n          state: pageState.state,\n          start: toServerDuration(relativeStartTime),\n        })\n      }\n\n      return pageStateServerEntries\n    },\n    wasInPageStateAt: (state: PageState, startTime: RelativeTime) =>\n      pageStateHistory.wasInPageStateDuringPeriod(state, startTime, 0 as Duration),\n    wasInPageStateDuringPeriod: (state: PageState, startTime: RelativeTime, duration: Duration) =>\n      pageStateEntryHistory.findAll(startTime, duration).some((pageState) => pageState.state === state),\n    addPageState,\n    stop: () => {\n      stopEventListeners()\n      pageStateEntryHistory.stop()\n    },\n  }\n  return pageStateHistory\n}\n\nfunction computePageState(event: Event & { type: DOM_EVENT }) {\n  if (event.type === DOM_EVENT.FREEZE) {\n    return PageState.FROZEN\n  } else if (event.type === DOM_EVENT.PAGE_HIDE) {\n    return (event as PageTransitionEvent).persisted ? PageState.FROZEN : PageState.TERMINATED\n  }\n  return getPageState()\n}\n\nfunction getPageState() {\n  if (document.visibilityState === 'hidden') {\n    return PageState.HIDDEN\n  }\n\n  if (document.hasFocus()) {\n    return PageState.ACTIVE\n  }\n\n  return PageState.PASSIVE\n}\n","import type { Configuration, CookieStore } from '@datadog/browser-core'\nimport {\n  setInterval,\n  clearInterval,\n  Observable,\n  addEventListener,\n  ONE_SECOND,\n  findCommaSeparatedValue,\n  DOM_EVENT,\n  find,\n} from '@datadog/browser-core'\n\nexport interface CookieStoreWindow extends Window {\n  cookieStore?: CookieStore\n}\n\nexport type CookieObservable = ReturnType<typeof createCookieObservable>\n\nexport function createCookieObservable(configuration: Configuration, cookieName: string) {\n  const detectCookieChangeStrategy = (window as CookieStoreWindow).cookieStore\n    ? listenToCookieStoreChange(configuration)\n    : watchCookieFallback\n\n  return new Observable<string | undefined>((observable) =>\n    detectCookieChangeStrategy(cookieName, (event) => observable.notify(event))\n  )\n}\n\nfunction listenToCookieStoreChange(configuration: Configuration) {\n  return (cookieName: string, callback: (event: string | undefined) => void) => {\n    const listener = addEventListener(\n      configuration,\n      (window as CookieStoreWindow).cookieStore!,\n      DOM_EVENT.CHANGE,\n      (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 =\n          find(event.changed, (event) => event.name === cookieName) ||\n          find(event.deleted, (event) => event.name === cookieName)\n        if (changeEvent) {\n          callback(changeEvent.value)\n        }\n      }\n    )\n    return listener.stop\n  }\n}\n\nexport const WATCH_COOKIE_INTERVAL_DELAY = ONE_SECOND\n\nfunction watchCookieFallback(cookieName: string, callback: (event: string | undefined) => void) {\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\n  return () => {\n    clearInterval(watchCookieIntervalId)\n  }\n}\n","import { getInitCookie, type Configuration } from '@datadog/browser-core'\n\nimport { createCookieObservable } from '../../browser/cookieObservable'\n\nexport const CI_VISIBILITY_TEST_ID_COOKIE_NAME = 'datadog-ci-visibility-test-execution-id'\n\nexport interface CiTestWindow extends Window {\n  Cypress?: {\n    env: (key: string) => string | undefined\n  }\n}\n\nexport type CiVisibilityContext = ReturnType<typeof startCiVisibilityContext>\n\nexport function startCiVisibilityContext(\n  configuration: Configuration,\n  cookieObservable = createCookieObservable(configuration, CI_VISIBILITY_TEST_ID_COOKIE_NAME)\n) {\n  let testExecutionId =\n    getInitCookie(CI_VISIBILITY_TEST_ID_COOKIE_NAME) || (window as CiTestWindow).Cypress?.env('traceId')\n\n  const cookieObservableSubscription = cookieObservable.subscribe((value) => {\n    testExecutionId = value\n  })\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","import type { ReplayStats } from '@datadog/browser-rum-core'\n\nexport const MAX_STATS_HISTORY = 10\nlet statsPerView: Map<string, ReplayStats> | undefined\n\nexport function getSegmentsCount(viewId: string) {\n  return getOrCreateReplayStats(viewId).segments_count\n}\n\nexport function addSegment(viewId: string) {\n  getOrCreateReplayStats(viewId).segments_count += 1\n}\n\nexport function addRecord(viewId: string) {\n  getOrCreateReplayStats(viewId).records_count += 1\n}\n\nexport function addWroteData(viewId: string, additionalBytesCount: number) {\n  getOrCreateReplayStats(viewId).segments_total_raw_size += additionalBytesCount\n}\n\nexport function getReplayStats(viewId: string) {\n  return statsPerView?.get(viewId)\n}\n\nexport function resetReplayStats() {\n  statsPerView = undefined\n}\n\nfunction getOrCreateReplayStats(viewId: string) {\n  if (!statsPerView) {\n    statsPerView = new Map()\n  }\n\n  let replayStats: ReplayStats\n  if (statsPerView.has(viewId)) {\n    replayStats = statsPerView.get(viewId)!\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\n  return replayStats\n}\n\nfunction deleteOldestStats() {\n  if (!statsPerView) {\n    return\n  }\n  if (statsPerView.keys) {\n    const toDelete = statsPerView.keys().next().value\n    if (toDelete) {\n      statsPerView.delete(toDelete)\n    }\n  } else {\n    // IE11 doesn't support map.keys\n    let isFirst = true\n    statsPerView.forEach((_value, key) => {\n      if (isFirst) {\n        statsPerView!.delete(key)\n        isFirst = false\n      }\n    })\n  }\n}\n","import { buildUrl } from '@datadog/browser-core'\nimport { getParentNode, isNodeShadowRoot, CENSORED_STRING_MARK, shouldMaskNode } from '@datadog/browser-rum-core'\nimport type { NodePrivacyLevel } from '@datadog/browser-rum-core'\nimport type { NodeWithSerializedNode } from './serialization.types'\n\nconst serializedNodeIds = new WeakMap<Node, number>()\n\nexport function hasSerializedNode(node: Node): node is NodeWithSerializedNode {\n  return serializedNodeIds.has(node)\n}\n\nexport function nodeAndAncestorsHaveSerializedNode(node: Node): node is NodeWithSerializedNode {\n  let current: Node | null = node\n  while (current) {\n    if (!hasSerializedNode(current) && !isNodeShadowRoot(current)) {\n      return false\n    }\n    current = getParentNode(current)\n  }\n  return true\n}\n\nexport function getSerializedNodeId(node: NodeWithSerializedNode): number\nexport function getSerializedNodeId(node: Node): number | undefined\nexport function getSerializedNodeId(node: Node) {\n  return serializedNodeIds.get(node)\n}\n\nexport function setSerializedNodeId(node: Node, serializeNodeId: number) {\n  serializedNodeIds.set(node, serializeNodeId)\n}\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: Element, nodePrivacyLevel: 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 as HTMLInputElement | HTMLTextAreaElement).value\n\n  if (shouldMaskNode(element, nodePrivacyLevel)) {\n    const type = (element as HTMLInputElement | HTMLTextAreaElement).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    } else if (!value || tagName === 'OPTION') {\n      // <Option> value provides no benefit\n      return\n    }\n    return CENSORED_STRING_MARK\n  }\n\n  if (tagName === 'OPTION' || tagName === 'SELECT') {\n    return (element as HTMLOptionElement | HTMLSelectElement).value\n  }\n\n  if (tagName !== 'INPUT' && tagName !== 'TEXTAREA') {\n    return\n  }\n\n  return value\n}\n\nexport const URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")([^\"]*)\"|([^)]*))\\)/gm\nexport const ABSOLUTE_URL = /^[A-Za-z]+:|^\\/\\//\nexport const DATA_URI = /^data:.*,/i\n\nexport function switchToAbsoluteUrl(cssText: string, cssHref: string | null): string {\n  return cssText.replace(\n    URL_IN_CSS_REF,\n    (\n      matchingSubstring: string,\n      singleQuote: string | undefined,\n      urlWrappedInSingleQuotes: string | undefined,\n      doubleQuote: string | undefined,\n      urlWrappedInDoubleQuotes: string | undefined,\n      urlNotWrappedInQuotes: string | undefined\n    ) => {\n      const url = urlWrappedInSingleQuotes || urlWrappedInDoubleQuotes || urlNotWrappedInQuotes\n\n      if (!cssHref || !url || ABSOLUTE_URL.test(url) || DATA_URI.test(url)) {\n        return matchingSubstring\n      }\n\n      const quote = singleQuote || doubleQuote || ''\n      return `url(${quote}${makeUrlAbsolute(url, cssHref)}${quote})`\n    }\n  )\n}\n\nexport function makeUrlAbsolute(url: string, baseUrl: string): string {\n  try {\n    return buildUrl(url, baseUrl).href\n  } catch (_) {\n    return url\n  }\n}\n\nconst TAG_NAME_REGEX = /[^a-z1-6-_]/\nexport function getValidTagName(tagName: string): string {\n  const processedTagName = tagName.toLowerCase().trim()\n\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\n  return processedTagName\n}\n\nexport function censoredImageForSize(width: number, height: number) {\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","import type * as SessionReplay from './sessionReplay'\n\nexport const RecordType: {\n  FullSnapshot: SessionReplay.BrowserFullSnapshotRecord['type']\n  IncrementalSnapshot: SessionReplay.BrowserIncrementalSnapshotRecord['type']\n  Meta: SessionReplay.MetaRecord['type']\n  Focus: SessionReplay.FocusRecord['type']\n  ViewEnd: SessionReplay.ViewEndRecord['type']\n  VisualViewport: SessionReplay.VisualViewportRecord['type']\n  FrustrationRecord: SessionReplay.FrustrationRecord['type']\n} = {\n  FullSnapshot: 2,\n  IncrementalSnapshot: 3,\n  Meta: 4,\n  Focus: 6,\n  ViewEnd: 7,\n  VisualViewport: 8,\n  FrustrationRecord: 9,\n} as const\n\nexport type RecordType = (typeof RecordType)[keyof typeof RecordType]\n\nexport const NodeType: {\n  Document: SessionReplay.DocumentNode['type']\n  DocumentType: SessionReplay.DocumentTypeNode['type']\n  Element: SessionReplay.ElementNode['type']\n  Text: SessionReplay.TextNode['type']\n  CDATA: SessionReplay.CDataNode['type']\n  DocumentFragment: SessionReplay.DocumentFragmentNode['type']\n} = {\n  Document: 0,\n  DocumentType: 1,\n  Element: 2,\n  Text: 3,\n  CDATA: 4,\n  DocumentFragment: 11,\n} as const\n\nexport type NodeType = (typeof NodeType)[keyof typeof NodeType]\n\nexport const IncrementalSource: {\n  Mutation: SessionReplay.BrowserMutationData['source']\n  MouseMove: Exclude<SessionReplay.MousemoveData['source'], 6>\n  MouseInteraction: SessionReplay.MouseInteractionData['source']\n  Scroll: SessionReplay.ScrollData['source']\n  ViewportResize: SessionReplay.ViewportResizeData['source']\n  Input: SessionReplay.InputData['source']\n  TouchMove: Exclude<SessionReplay.MousemoveData['source'], 1>\n  MediaInteraction: SessionReplay.MediaInteractionData['source']\n  StyleSheetRule: SessionReplay.StyleSheetRuleData['source']\n} = {\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} as const\n\nexport type IncrementalSource = (typeof IncrementalSource)[keyof typeof IncrementalSource]\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} as const\n\nexport type MouseInteractionType = (typeof MouseInteractionType)[keyof typeof MouseInteractionType]\n\nexport const MediaInteractionType = {\n  Play: 0,\n  Pause: 1,\n} as const\n\nexport type MediaInteractionType = (typeof MediaInteractionType)[keyof typeof MediaInteractionType]\n","import type { StyleSheet } from '../../../types'\n\nexport function serializeStyleSheets(cssStyleSheets: CSSStyleSheet[] | undefined): StyleSheet[] | undefined {\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\n    const styleSheet: 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","import { startsWith } from '@datadog/browser-core'\nimport {\n  NodePrivacyLevel,\n  PRIVACY_ATTR_NAME,\n  CENSORED_STRING_MARK,\n  CENSORED_IMG_MARK,\n  STABLE_ATTRIBUTES,\n  isLongDataUrl,\n  sanitizeDataUrl,\n} from '@datadog/browser-rum-core'\nimport type { RumConfiguration } from '@datadog/browser-rum-core'\nimport { censoredImageForSize } from './serializationUtils'\n\nexport function serializeAttribute(\n  element: Element,\n  nodePrivacyLevel: NodePrivacyLevel,\n  attributeName: string,\n  configuration: RumConfiguration\n): string | number | boolean | null {\n  if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n    // dup condition for direct access case\n    return null\n  }\n  const attributeValue = element.getAttribute(attributeName)\n  if (\n    nodePrivacyLevel === NodePrivacyLevel.MASK &&\n    attributeName !== PRIVACY_ATTR_NAME &&\n    !STABLE_ATTRIBUTES.includes(attributeName) &&\n    attributeName !== configuration.actionNameAttribute\n  ) {\n    const tagName = element.tagName\n\n    switch (attributeName) {\n      // Mask Attribute text content\n      case 'title':\n      case 'alt':\n      case 'placeholder':\n        return CENSORED_STRING_MARK\n    }\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 as HTMLImageElement\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\n    // mask source URLs\n    if (tagName === 'SOURCE' && (attributeName === 'src' || attributeName === 'srcset')) {\n      return CENSORED_IMG_MARK\n    }\n\n    // mask <a> URLs\n    if (tagName === 'A' && attributeName === 'href') {\n      return CENSORED_STRING_MARK\n    }\n\n    // mask data-* attributes\n    if (attributeValue && startsWith(attributeName, 'data-')) {\n      // Exception: it's safe to reveal the `${PRIVACY_ATTR_NAME}` attr\n      return CENSORED_STRING_MARK\n    }\n\n    // mask iframe srcdoc\n    if (tagName === 'IFRAME' && attributeName === 'srcdoc') {\n      return CENSORED_STRING_MARK\n    }\n  }\n\n  if (!attributeValue || typeof attributeValue !== 'string') {\n    return attributeValue\n  }\n\n  // Minimum Fix for customer.\n  if (isLongDataUrl(attributeValue)) {\n    return sanitizeDataUrl(attributeValue)\n  }\n\n  return attributeValue\n}\n","import { NodePrivacyLevel, shouldMaskNode } from '@datadog/browser-rum-core'\nimport { isSafari } from '@datadog/browser-core'\nimport { getElementInputValue, switchToAbsoluteUrl, getValidTagName } from './serializationUtils'\nimport type { SerializeOptions } from './serialization.types'\nimport { SerializationContextStatus } from './serialization.types'\nimport { serializeAttribute } from './serializeAttribute'\n\nexport function serializeAttributes(\n  element: Element,\n  nodePrivacyLevel: NodePrivacyLevel,\n  options: SerializeOptions\n): Record<string, string | number | boolean> {\n  if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n    return {}\n  }\n  const safeAttrs: Record<string, string | number | boolean> = {}\n  const tagName = getValidTagName(element.tagName)\n  const doc = element.ownerDocument\n\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\n  if (\n    (element as HTMLInputElement).value &&\n    (tagName === 'textarea' || tagName === 'select' || tagName === 'option' || tagName === 'input')\n  ) {\n    const formValue = getElementInputValue(element, nodePrivacyLevel)\n    if (formValue !== undefined) {\n      safeAttrs.value = formValue\n    }\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 as HTMLOptionElement\n    if (optionElement.selected) {\n      safeAttrs.selected = optionElement.selected\n    }\n  }\n\n  // remote css\n  if (tagName === 'link') {\n    const stylesheet = Array.from(doc.styleSheets).find((s) => s.href === (element as HTMLLinkElement).href)\n    const cssText = getCssRulesString(stylesheet)\n    if (cssText && stylesheet) {\n      safeAttrs._cssText = cssText\n    }\n  }\n\n  // dynamic stylesheet\n  if (tagName === 'style' && (element as HTMLStyleElement).sheet) {\n    const cssText = getCssRulesString((element as HTMLStyleElement).sheet)\n    if (cssText) {\n      safeAttrs._cssText = cssText\n    }\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 as HTMLInputElement\n  if (tagName === 'input' && (inputElement.type === 'radio' || inputElement.type === 'checkbox')) {\n    if (nodePrivacyLevel === NodePrivacyLevel.ALLOW) {\n      safeAttrs.checked = !!inputElement.checked\n    } else if (shouldMaskNode(inputElement, nodePrivacyLevel)) {\n      delete safeAttrs.checked\n    }\n  }\n\n  /**\n   * Serialize the media playback state\n   */\n  if (tagName === 'audio' || tagName === 'video') {\n    const mediaElement = element as HTMLMediaElement\n    safeAttrs.rr_mediaState = mediaElement.paused ? 'paused' : 'played'\n  }\n\n  /**\n   * Serialize the scroll state for each element only for full snapshot\n   */\n  let scrollTop: number | undefined\n  let scrollLeft: number | undefined\n  const serializationContext = options.serializationContext\n  switch (serializationContext.status) {\n    case 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 SerializationContextStatus.SUBSEQUENT_FULL_SNAPSHOT:\n      if (serializationContext.elementsScrollPositions.has(element)) {\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\n  return safeAttrs\n}\n\nexport function getCssRulesString(cssStyleSheet: CSSStyleSheet | undefined | null): string | null {\n  if (!cssStyleSheet) {\n    return null\n  }\n  let rules: CSSRuleList | undefined\n  try {\n    rules = cssStyleSheet.rules || cssStyleSheet.cssRules\n  } catch {\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}\n\nfunction getCssRuleStringForSafari(rule: CSSRule): string {\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\n  return getCssRuleString(rule)\n}\n\nfunction getCssRuleString(rule: CSSRule): string {\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}\n\nfunction isCSSImportRule(rule: CSSRule): rule is CSSImportRule {\n  return 'styleSheet' in rule\n}\n\nfunction isCSSStyleRule(rule: CSSRule): rule is CSSStyleRule {\n  return 'selectorText' in rule\n}\n","import {\n  reducePrivacyLevel,\n  getNodeSelfPrivacyLevel,\n  getTextContent,\n  isNodeShadowRoot,\n  hasChildNodes,\n  forEachChildNodes,\n  NodePrivacyLevel,\n  PRIVACY_ATTR_NAME,\n  PRIVACY_ATTR_VALUE_HIDDEN,\n} from '@datadog/browser-rum-core'\nimport { assign } from '@datadog/browser-core'\nimport type {\n  DocumentFragmentNode,\n  DocumentNode,\n  SerializedNode,\n  SerializedNodeWithId,\n  CDataNode,\n  DocumentTypeNode,\n  ElementNode,\n  TextNode,\n} from '../../../types'\nimport { NodeType } from '../../../types'\nimport { getSerializedNodeId, getValidTagName, setSerializedNodeId } from './serializationUtils'\nimport type { SerializeOptions } from './serialization.types'\nimport { serializeStyleSheets } from './serializeStyleSheets'\nimport { serializeAttributes } from './serializeAttributes'\n\nexport function serializeNodeWithId(node: Node, options: SerializeOptions): SerializedNodeWithId | null {\n  const serializedNode = serializeNode(node, options)\n  if (!serializedNode) {\n    return null\n  }\n\n  // Try to reuse the previous id\n  const id = getSerializedNodeId(node) || generateNextId()\n  const serializedNodeWithId = serializedNode as SerializedNodeWithId\n  serializedNodeWithId.id = id\n  setSerializedNodeId(node, id)\n  if (options.serializedNodeIds) {\n    options.serializedNodeIds.add(id)\n  }\n  return serializedNodeWithId\n}\n\nlet _nextId = 1\nexport function generateNextId(): number {\n  return _nextId++\n}\n\nexport function serializeChildNodes(node: Node, options: SerializeOptions): SerializedNodeWithId[] {\n  const result: SerializedNodeWithId[] = []\n  forEachChildNodes(node, (childNode) => {\n    const serializedChildNode = serializeNodeWithId(childNode, options)\n    if (serializedChildNode) {\n      result.push(serializedChildNode)\n    }\n  })\n  return result\n}\n\nfunction serializeNode(node: Node, options: SerializeOptions): SerializedNode | undefined {\n  switch (node.nodeType) {\n    case node.DOCUMENT_NODE:\n      return serializeDocumentNode(node as Document, options)\n    case node.DOCUMENT_FRAGMENT_NODE:\n      return serializeDocumentFragmentNode(node as DocumentFragment, options)\n    case node.DOCUMENT_TYPE_NODE:\n      return serializeDocumentTypeNode(node as DocumentType)\n    case node.ELEMENT_NODE:\n      return serializeElementNode(node as Element, options)\n    case node.TEXT_NODE:\n      return serializeTextNode(node as Text, options)\n    case node.CDATA_SECTION_NODE:\n      return serializeCDataNode()\n  }\n}\n\nexport function serializeDocumentNode(document: Document, options: SerializeOptions): DocumentNode {\n  return {\n    type: NodeType.Document,\n    childNodes: serializeChildNodes(document, options),\n    adoptedStyleSheets: serializeStyleSheets(document.adoptedStyleSheets),\n  }\n}\n\nfunction serializeDocumentFragmentNode(\n  element: DocumentFragment,\n  options: SerializeOptions\n): DocumentFragmentNode | undefined {\n  const isShadowRoot = isNodeShadowRoot(element)\n  if (isShadowRoot) {\n    options.serializationContext.shadowRootsController.addShadowRoot(element)\n  }\n\n  return {\n    type: NodeType.DocumentFragment,\n    childNodes: serializeChildNodes(element, options),\n    isShadowRoot,\n    adoptedStyleSheets: isShadowRoot ? serializeStyleSheets(element.adoptedStyleSheets) : undefined,\n  }\n}\n\nfunction serializeDocumentTypeNode(documentType: DocumentType): DocumentTypeNode {\n  return {\n    type: NodeType.DocumentType,\n    name: documentType.name,\n    publicId: documentType.publicId,\n    systemId: documentType.systemId,\n  }\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 */\n\nfunction serializeElementNode(element: Element, options: SerializeOptions): ElementNode | undefined {\n  const tagName = getValidTagName(element.tagName)\n  const isSVG = isSVGElement(element) || undefined\n\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\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\n  // Ignore Elements like Script and some Link, Metas\n  if (nodePrivacyLevel === NodePrivacyLevel.IGNORE) {\n    return\n  }\n\n  const attributes = serializeAttributes(element, nodePrivacyLevel, options)\n\n  let childNodes: SerializedNodeWithId[] = []\n  if (\n    hasChildNodes(element) &&\n    // Do not serialize style children as the css rules are already in the _cssText attribute\n    tagName !== 'style'\n  ) {\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    } else {\n      childNodesSerializationOptions = assign({}, options, {\n        parentNodePrivacyLevel: nodePrivacyLevel,\n        ignoreWhiteSpace: tagName === 'head',\n      })\n    }\n    childNodes = serializeChildNodes(element, childNodesSerializationOptions)\n  }\n\n  return {\n    type: NodeType.Element,\n    tagName,\n    attributes,\n    childNodes,\n    isSVG,\n  }\n}\n\nfunction isSVGElement(el: Element): boolean {\n  return el.tagName === 'svg' || el instanceof SVGElement\n}\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 */\n\nfunction serializeTextNode(textNode: Text, options: SerializeOptions): TextNode | undefined {\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}\n\nfunction serializeCDataNode(): CDataNode {\n  return {\n    type: NodeType.CDATA,\n    textContent: '',\n  }\n}\n","import type { RumConfiguration } from '@datadog/browser-rum-core'\nimport type { SerializedNodeWithId } from '../../../types'\nimport type { SerializationContext } from './serialization.types'\nimport { serializeNodeWithId } from './serializeNode'\n\nexport function serializeDocument(\n  document: Document,\n  configuration: RumConfiguration,\n  serializationContext: SerializationContext\n): SerializedNodeWithId {\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","import { isNodeShadowHost } from '@datadog/browser-rum-core'\n\nexport function isTouchEvent(event: MouseEvent | TouchEvent): event is TouchEvent {\n  return Boolean((event as TouchEvent).changedTouches)\n}\n\nexport function getEventTarget(event: Event): Node {\n  if (event.composed === true && isNodeShadowHost(event.target as Node)) {\n    return event.composedPath()[0] as Node\n  }\n  return event.target as Node\n}\n","/**\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\nimport type { VisualViewportRecord } from '../../types'\n\n// Scrollbar widths vary across properties on different devices and browsers\nconst TOLERANCE = 25\n\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: VisualViewport) {\n  return (\n    Math.abs(visualViewport.pageTop - visualViewport.offsetTop - window.scrollY) > TOLERANCE ||\n    Math.abs(visualViewport.pageLeft - visualViewport.offsetLeft - window.scrollX) > TOLERANCE\n  )\n}\n\ninterface LayoutCoordinates {\n  layoutViewportX: number\n  layoutViewportY: number\n  visualViewportX: number\n  visualViewportY: number\n}\n\nexport const convertMouseEventToLayoutCoordinates = (clientX: number, clientY: number): LayoutCoordinates => {\n  const visualViewport = window.visualViewport\n  const normalized: LayoutCoordinates = {\n    layoutViewportX: clientX,\n    layoutViewportY: clientY,\n    visualViewportX: clientX,\n    visualViewportY: clientY,\n  }\n\n  if (!visualViewport) {\n    // On old browsers, we cannot normalize, so fallback to clientX/Y\n    return normalized\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  } 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}\n\nexport const getVisualViewport = (visualViewport: VisualViewport): VisualViewportRecord['data'] => ({\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","import { assign, timeStampNow } from '@datadog/browser-core'\nimport type { BrowserIncrementalData, BrowserIncrementalSnapshotRecord } from '../../types'\nimport { RecordType } from '../../types'\n\nexport function assembleIncrementalSnapshot<Data extends BrowserIncrementalData>(\n  source: Data['source'],\n  data: Omit<Data, 'source'>\n): BrowserIncrementalSnapshotRecord {\n  return {\n    data: assign(\n      {\n        source,\n      },\n      data\n    ) as Data,\n    type: RecordType.IncrementalSnapshot,\n    timestamp: timeStampNow(),\n  }\n}\n","import { addEventListeners, addTelemetryDebug, DOM_EVENT, throttle } from '@datadog/browser-core'\nimport type { RumConfiguration } from '@datadog/browser-rum-core'\nimport { getSerializedNodeId, hasSerializedNode } from '../serialization'\nimport type { BrowserIncrementalSnapshotRecord, MousemoveData, MousePosition } from '../../../types'\nimport { IncrementalSource } from '../../../types'\nimport { getEventTarget, isTouchEvent } from '../eventsUtils'\nimport { convertMouseEventToLayoutCoordinates } from '../viewports'\nimport { assembleIncrementalSnapshot } from '../assembly'\nimport type { Tracker } from './tracker.types'\n\nconst MOUSE_MOVE_OBSERVER_THRESHOLD = 50\n\nexport type MousemoveCallBack = (incrementalSnapshotRecord: BrowserIncrementalSnapshotRecord) => void\n\nexport function trackMove(configuration: RumConfiguration, moveCb: MousemoveCallBack): Tracker {\n  const { throttled: updatePosition, cancel: cancelThrottle } = throttle(\n    (event: MouseEvent | TouchEvent) => {\n      const target = getEventTarget(event)\n      if (hasSerializedNode(target)) {\n        const coordinates = tryToComputeCoordinates(event)\n        if (!coordinates) {\n          return\n        }\n        const position: MousePosition = {\n          id: getSerializedNodeId(target),\n          timeOffset: 0,\n          x: coordinates.x,\n          y: coordinates.y,\n        }\n\n        moveCb(\n          assembleIncrementalSnapshot<MousemoveData>(\n            isTouchEvent(event) ? IncrementalSource.TouchMove : IncrementalSource.MouseMove,\n            { positions: [position] }\n          )\n        )\n      }\n    },\n    MOUSE_MOVE_OBSERVER_THRESHOLD,\n    {\n      trailing: false,\n    }\n  )\n\n  const { stop: removeListener } = addEventListeners(\n    configuration,\n    document,\n    [DOM_EVENT.MOUSE_MOVE, DOM_EVENT.TOUCH_MOVE],\n    updatePosition,\n    {\n      capture: true,\n      passive: true,\n    }\n  )\n\n  return {\n    stop: () => {\n      removeListener()\n      cancelThrottle()\n    },\n  }\n}\n\nexport function tryToComputeCoordinates(event: MouseEvent | TouchEvent) {\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","import { assign, addEventListeners, DOM_EVENT } from '@datadog/browser-core'\nimport { getNodePrivacyLevel, NodePrivacyLevel } from '@datadog/browser-rum-core'\nimport type { RumConfiguration } from '@datadog/browser-rum-core'\nimport type { MouseInteraction, MouseInteractionData, BrowserIncrementalSnapshotRecord } from '../../../types'\nimport { IncrementalSource, MouseInteractionType } from '../../../types'\nimport { assembleIncrementalSnapshot } from '../assembly'\nimport { getEventTarget } from '../eventsUtils'\nimport { getSerializedNodeId, hasSerializedNode } from '../serialization'\nimport type { RecordIds } from '../recordIds'\nimport { tryToComputeCoordinates } from './trackMove'\nimport type { Tracker } from './tracker.types'\n\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  [DOM_EVENT.POINTER_UP]: MouseInteractionType.MouseUp,\n\n  [DOM_EVENT.MOUSE_DOWN]: MouseInteractionType.MouseDown,\n  [DOM_EVENT.CLICK]: MouseInteractionType.Click,\n  [DOM_EVENT.CONTEXT_MENU]: MouseInteractionType.ContextMenu,\n  [DOM_EVENT.DBL_CLICK]: MouseInteractionType.DblClick,\n  [DOM_EVENT.FOCUS]: MouseInteractionType.Focus,\n  [DOM_EVENT.BLUR]: MouseInteractionType.Blur,\n  [DOM_EVENT.TOUCH_START]: MouseInteractionType.TouchStart,\n  [DOM_EVENT.TOUCH_END]: MouseInteractionType.TouchEnd,\n}\n\nexport type MouseInteractionCallback = (record: BrowserIncrementalSnapshotRecord) => void\n\nexport function trackMouseInteraction(\n  configuration: RumConfiguration,\n  mouseInteractionCb: MouseInteractionCallback,\n  recordIds: RecordIds\n): Tracker {\n  const handler = (event: MouseEvent | TouchEvent | FocusEvent) => {\n    const target = getEventTarget(event)\n    if (\n      getNodePrivacyLevel(target, configuration.defaultPrivacyLevel) === NodePrivacyLevel.HIDDEN ||\n      !hasSerializedNode(target)\n    ) {\n      return\n    }\n    const id = getSerializedNodeId(target)\n    const type = eventTypeToMouseInteraction[event.type as keyof typeof eventTypeToMouseInteraction]\n\n    let interaction: MouseInteraction\n    if (type !== MouseInteractionType.Blur && type !== MouseInteractionType.Focus) {\n      const coordinates = tryToComputeCoordinates(event as MouseEvent | TouchEvent)\n      if (!coordinates) {\n        return\n      }\n      interaction = { id, type, x: coordinates.x, y: coordinates.y }\n    } else {\n      interaction = { id, type }\n    }\n\n    const record = assign(\n      { id: recordIds.getIdForEvent(event) },\n      assembleIncrementalSnapshot<MouseInteractionData>(IncrementalSource.MouseInteraction, interaction)\n    )\n    mouseInteractionCb(record)\n  }\n  return addEventListeners(\n    configuration,\n    document,\n    Object.keys(eventTypeToMouseInteraction) as Array<keyof typeof eventTypeToMouseInteraction>,\n    handler,\n    {\n      capture: true,\n      passive: true,\n    }\n  )\n}\n","import { DOM_EVENT, throttle, addEventListener } from '@datadog/browser-core'\nimport type { RumConfiguration } from '@datadog/browser-rum-core'\nimport { getScrollX, getScrollY, getNodePrivacyLevel, NodePrivacyLevel } from '@datadog/browser-rum-core'\nimport type { ElementsScrollPositions } from '../elementsScrollPositions'\nimport { getEventTarget } from '../eventsUtils'\nimport { getSerializedNodeId, hasSerializedNode } from '../serialization'\nimport { IncrementalSource } from '../../../types'\nimport type { BrowserIncrementalSnapshotRecord, ScrollData } from '../../../types'\nimport { assembleIncrementalSnapshot } from '../assembly'\nimport type { Tracker } from './tracker.types'\n\nconst SCROLL_OBSERVER_THRESHOLD = 100\n\nexport type ScrollCallback = (incrementalSnapshotRecord: BrowserIncrementalSnapshotRecord) => void\n\nexport function trackScroll(\n  configuration: RumConfiguration,\n  scrollCb: ScrollCallback,\n  elementsScrollPositions: ElementsScrollPositions,\n  target: Document | ShadowRoot = document\n): Tracker {\n  const { throttled: updatePosition, cancel: cancelThrottle } = throttle((event: Event) => {\n    const target = getEventTarget(event) as HTMLElement | Document\n    if (\n      !target ||\n      getNodePrivacyLevel(target, configuration.defaultPrivacyLevel) === NodePrivacyLevel.HIDDEN ||\n      !hasSerializedNode(target)\n    ) {\n      return\n    }\n    const id = getSerializedNodeId(target)\n    const scrollPositions =\n      target === document\n        ? {\n            scrollTop: getScrollY(),\n            scrollLeft: getScrollX(),\n          }\n        : {\n            scrollTop: Math.round((target as HTMLElement).scrollTop),\n            scrollLeft: Math.round((target as HTMLElement).scrollLeft),\n          }\n    elementsScrollPositions.set(target, scrollPositions)\n    scrollCb(\n      assembleIncrementalSnapshot<ScrollData>(IncrementalSource.Scroll, {\n        id,\n        x: scrollPositions.scrollLeft,\n        y: scrollPositions.scrollTop,\n      })\n    )\n  }, SCROLL_OBSERVER_THRESHOLD)\n\n  const { stop: removeListener } = addEventListener(configuration, target, DOM_EVENT.SCROLL, updatePosition, {\n    capture: true,\n    passive: true,\n  })\n\n  return {\n    stop: () => {\n      removeListener()\n      cancelThrottle()\n    },\n  }\n}\n","import { throttle, DOM_EVENT, addEventListeners, timeStampNow, noop } from '@datadog/browser-core'\nimport type { RumConfiguration, ViewportDimension } from '@datadog/browser-rum-core'\nimport { initViewportObservable } from '@datadog/browser-rum-core'\nimport { IncrementalSource, RecordType } from '../../../types'\nimport type { BrowserIncrementalSnapshotRecord, ViewportResizeData, VisualViewportRecord } from '../../../types'\nimport { getVisualViewport } from '../viewports'\nimport { assembleIncrementalSnapshot } from '../assembly'\nimport type { Tracker } from './tracker.types'\n\nconst VISUAL_VIEWPORT_OBSERVER_THRESHOLD = 200\n\nexport type ViewportResizeCallback = (incrementalSnapshotRecord: BrowserIncrementalSnapshotRecord) => void\n\nexport type VisualViewportResizeCallback = (visualViewportRecord: VisualViewportRecord) => void\n\nexport function trackViewportResize(\n  configuration: RumConfiguration,\n  viewportResizeCb: ViewportResizeCallback\n): Tracker {\n  const viewportResizeSubscription = initViewportObservable(configuration).subscribe((data: ViewportDimension) => {\n    viewportResizeCb(assembleIncrementalSnapshot<ViewportResizeData>(IncrementalSource.ViewportResize, data))\n  })\n\n  return {\n    stop: () => {\n      viewportResizeSubscription.unsubscribe()\n    },\n  }\n}\n\nexport function trackVisualViewportResize(\n  configuration: RumConfiguration,\n  visualViewportResizeCb: VisualViewportResizeCallback\n): Tracker {\n  const visualViewport = window.visualViewport\n  if (!visualViewport) {\n    return { stop: noop }\n  }\n  const { throttled: updateDimension, cancel: cancelThrottle } = throttle(\n    () => {\n      visualViewportResizeCb({\n        data: getVisualViewport(visualViewport),\n        type: RecordType.VisualViewport,\n        timestamp: timeStampNow(),\n      })\n    },\n    VISUAL_VIEWPORT_OBSERVER_THRESHOLD,\n    {\n      trailing: false,\n    }\n  )\n  const { stop: removeListener } = addEventListeners(\n    configuration,\n    visualViewport,\n    [DOM_EVENT.RESIZE, DOM_EVENT.SCROLL],\n    updateDimension,\n    {\n      capture: true,\n      passive: true,\n    }\n  )\n\n  return {\n    stop: () => {\n      removeListener()\n      cancelThrottle()\n    },\n  }\n}\n","import { DOM_EVENT, addEventListeners } from '@datadog/browser-core'\nimport type { RumConfiguration } from '@datadog/browser-rum-core'\nimport { NodePrivacyLevel, getNodePrivacyLevel } from '@datadog/browser-rum-core'\nimport type { BrowserIncrementalSnapshotRecord, MediaInteractionData } from '../../../types'\nimport { IncrementalSource, MediaInteractionType } from '../../../types'\nimport { getEventTarget } from '../eventsUtils'\nimport { getSerializedNodeId, hasSerializedNode } from '../serialization'\nimport { assembleIncrementalSnapshot } from '../assembly'\nimport type { Tracker } from './tracker.types'\n\nexport type MediaInteractionCallback = (incrementalSnapshotRecord: BrowserIncrementalSnapshotRecord) => void\n\nexport function trackMediaInteraction(\n  configuration: RumConfiguration,\n  mediaInteractionCb: MediaInteractionCallback\n): Tracker {\n  return addEventListeners(\n    configuration,\n    document,\n    [DOM_EVENT.PLAY, DOM_EVENT.PAUSE],\n    (event) => {\n      const target = getEventTarget(event)\n      if (\n        !target ||\n        getNodePrivacyLevel(target, configuration.defaultPrivacyLevel) === NodePrivacyLevel.HIDDEN ||\n        !hasSerializedNode(target)\n      ) {\n        return\n      }\n      mediaInteractionCb(\n        assembleIncrementalSnapshot<MediaInteractionData>(IncrementalSource.MediaInteraction, {\n          id: getSerializedNodeId(target),\n          type: event.type === DOM_EVENT.PLAY ? MediaInteractionType.Play : MediaInteractionType.Pause,\n        })\n      )\n    },\n    {\n      capture: true,\n      passive: true,\n    }\n  )\n}\n","import { instrumentMethod } from '@datadog/browser-core'\nimport { IncrementalSource } from '../../../types'\nimport type { StyleSheetRuleData, BrowserIncrementalSnapshotRecord } from '../../../types'\nimport { getSerializedNodeId, hasSerializedNode } from '../serialization'\nimport { assembleIncrementalSnapshot } from '../assembly'\nimport type { Tracker } from './tracker.types'\n\ntype GroupingCSSRuleTypes = typeof CSSGroupingRule | typeof CSSMediaRule | typeof CSSSupportsRule\n\nexport type StyleSheetCallback = (incrementalSnapshotRecord: BrowserIncrementalSnapshotRecord) => void\n\nexport function trackStyleSheet(styleSheetCb: StyleSheetCallback): Tracker {\n  function checkStyleSheetAndCallback(styleSheet: CSSStyleSheet | null, callback: (id: number) => void): void {\n    if (styleSheet && hasSerializedNode(styleSheet.ownerNode!)) {\n      callback(getSerializedNodeId(styleSheet.ownerNode))\n    }\n  }\n\n  const instrumentationStoppers = [\n    instrumentMethod(CSSStyleSheet.prototype, 'insertRule', ({ target: styleSheet, parameters: [rule, index] }) => {\n      checkStyleSheetAndCallback(styleSheet, (id) =>\n        styleSheetCb(\n          assembleIncrementalSnapshot<StyleSheetRuleData>(IncrementalSource.StyleSheetRule, {\n            id,\n            adds: [{ rule, index }],\n          })\n        )\n      )\n    }),\n\n    instrumentMethod(CSSStyleSheet.prototype, 'deleteRule', ({ target: styleSheet, parameters: [index] }) => {\n      checkStyleSheetAndCallback(styleSheet, (id) =>\n        styleSheetCb(\n          assembleIncrementalSnapshot<StyleSheetRuleData>(IncrementalSource.StyleSheetRule, {\n            id,\n            removes: [{ index }],\n          })\n        )\n      )\n    }),\n  ]\n\n  if (typeof CSSGroupingRule !== 'undefined') {\n    instrumentGroupingCSSRuleClass(CSSGroupingRule)\n  } else {\n    instrumentGroupingCSSRuleClass(CSSMediaRule)\n    instrumentGroupingCSSRuleClass(CSSSupportsRule)\n  }\n\n  function instrumentGroupingCSSRuleClass(cls: GroupingCSSRuleTypes) {\n    instrumentationStoppers.push(\n      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(\n              assembleIncrementalSnapshot<StyleSheetRuleData>(IncrementalSource.StyleSheetRule, {\n                id,\n                adds: [{ rule, index: path }],\n              })\n            )\n          }\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(\n              assembleIncrementalSnapshot<StyleSheetRuleData>(IncrementalSource.StyleSheetRule, {\n                id,\n                removes: [{ index: path }],\n              })\n            )\n          }\n        })\n      })\n    )\n  }\n\n  return {\n    stop: () => {\n      instrumentationStoppers.forEach((stopper) => stopper.stop())\n    },\n  }\n}\n\nexport function getPathToNestedCSSRule(rule: CSSRule): number[] | undefined {\n  const path: number[] = []\n  let currentRule = rule\n  while (currentRule.parentRule) {\n    const rules = Array.from((currentRule.parentRule as CSSGroupingRule).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\n  const rules = Array.from(currentRule.parentStyleSheet.cssRules)\n  const index = rules.indexOf(currentRule)\n  path.unshift(index)\n\n  return path\n}\n","import { DOM_EVENT, addEventListeners, timeStampNow } from '@datadog/browser-core'\nimport type { RumConfiguration } from '@datadog/browser-rum-core'\nimport { RecordType, type FocusRecord } from '../../../types'\nimport type { Tracker } from './tracker.types'\n\nexport type FocusCallback = (data: FocusRecord) => void\n\nexport function trackFocus(configuration: RumConfiguration, focusCb: FocusCallback): Tracker {\n  return addEventListeners(configuration, window, [DOM_EVENT.FOCUS, DOM_EVENT.BLUR], () => {\n    focusCb({\n      data: { has_focus: document.hasFocus() },\n      type: RecordType.Focus,\n      timestamp: timeStampNow(),\n    })\n  })\n}\n","import type { LifeCycle } from '@datadog/browser-rum-core'\nimport { ActionType, RumEventType, LifeCycleEventType } from '@datadog/browser-rum-core'\nimport type { FrustrationRecord } from '../../../types'\nimport { RecordType } from '../../../types'\nimport type { RecordIds } from '../recordIds'\nimport type { Tracker } from './tracker.types'\n\nexport type FrustrationCallback = (record: FrustrationRecord) => void\n\nexport function trackFrustration(\n  lifeCycle: LifeCycle,\n  frustrationCb: FrustrationCallback,\n  recordIds: RecordIds\n): Tracker {\n  const frustrationSubscription = lifeCycle.subscribe(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, (data) => {\n    if (\n      data.rawRumEvent.type === RumEventType.ACTION &&\n      data.rawRumEvent.action.type === ActionType.CLICK &&\n      data.rawRumEvent.action.frustration?.type?.length &&\n      'events' in data.domainContext &&\n      data.domainContext.events &&\n      data.domainContext.events.length\n    ) {\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\n  return {\n    stop: () => {\n      frustrationSubscription.unsubscribe()\n    },\n  }\n}\n","import { timeStampNow } from '@datadog/browser-core'\nimport type { LifeCycle } from '@datadog/browser-rum-core'\nimport { LifeCycleEventType } from '@datadog/browser-rum-core'\nimport type { ViewEndRecord } from '../../../types'\nimport { RecordType } from '../../../types'\nimport type { Tracker } from './tracker.types'\n\nexport type ViewEndCallback = (record: ViewEndRecord) => void\n\nexport function trackViewEnd(lifeCycle: LifeCycle, viewEndCb: ViewEndCallback): Tracker {\n  const viewEndSubscription = lifeCycle.subscribe(LifeCycleEventType.VIEW_ENDED, () => {\n    viewEndCb({\n      timestamp: timeStampNow(),\n      type: RecordType.ViewEnd,\n    })\n  })\n\n  return {\n    stop: () => {\n      viewEndSubscription.unsubscribe()\n    },\n  }\n}\n","import { instrumentSetter, assign, DOM_EVENT, addEventListeners, forEach, noop } from '@datadog/browser-core'\nimport { NodePrivacyLevel, getNodePrivacyLevel, shouldMaskNode, cssEscape } from '@datadog/browser-rum-core'\nimport type { RumConfiguration } from '@datadog/browser-rum-core'\nimport { IncrementalSource } from '../../../types'\nimport type { BrowserIncrementalSnapshotRecord, InputData, InputState } from '../../../types'\nimport { getEventTarget } from '../eventsUtils'\nimport { getElementInputValue, getSerializedNodeId, hasSerializedNode } from '../serialization'\nimport { assembleIncrementalSnapshot } from '../assembly'\nimport type { Tracker } from './tracker.types'\n\nexport type InputCallback = (incrementalSnapshotRecord: BrowserIncrementalSnapshotRecord) => void\n\nexport function trackInput(\n  configuration: RumConfiguration,\n  inputCb: InputCallback,\n  target: Document | ShadowRoot = document\n): Tracker {\n  const defaultPrivacyLevel = configuration.defaultPrivacyLevel\n  const lastInputStateMap: WeakMap<Node, InputState> = new WeakMap()\n\n  const isShadowRoot = target !== document\n\n  const { stop: stopEventListeners } = addEventListeners(\n    configuration,\n    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 ? [DOM_EVENT.CHANGE] : [DOM_EVENT.INPUT, DOM_EVENT.CHANGE],\n    (event) => {\n      const target = getEventTarget(event)\n      if (\n        target instanceof HTMLInputElement ||\n        target instanceof HTMLTextAreaElement ||\n        target instanceof HTMLSelectElement\n      ) {\n        onElementChange(target)\n      }\n    },\n    {\n      capture: true,\n      passive: true,\n    }\n  )\n\n  let stopPropertySetterInstrumentation: () => void\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  } else {\n    stopPropertySetterInstrumentation = noop\n  }\n\n  return {\n    stop: () => {\n      stopPropertySetterInstrumentation()\n      stopEventListeners()\n    },\n  }\n\n  function onElementChange(target: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement) {\n    const nodePrivacyLevel = getNodePrivacyLevel(target, defaultPrivacyLevel)\n    if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n      return\n    }\n\n    const type = target.type\n\n    let inputState: InputState\n    if (type === 'radio' || type === 'checkbox') {\n      if (shouldMaskNode(target, nodePrivacyLevel)) {\n        return\n      }\n      inputState = { isChecked: (target as HTMLInputElement).checked }\n    } else {\n      const value = getElementInputValue(target, nodePrivacyLevel)\n      if (value === undefined) {\n        return\n      }\n      inputState = { text: value }\n    }\n\n    // Can be multiple changes on the same node within the same batched mutation observation.\n    cbWithDedup(target, inputState)\n\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 as HTMLInputElement).checked) {\n      forEach(document.querySelectorAll(`input[type=\"radio\"][name=\"${cssEscape(name)}\"]`), (el: Element) => {\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  /**\n   * There can be multiple changes on the same node within the same batched mutation observation.\n   */\n  function cbWithDedup(target: Node, inputState: InputState) {\n    if (!hasSerializedNode(target)) {\n      return\n    }\n    const lastInputState = lastInputStateMap.get(target)\n    if (\n      !lastInputState ||\n      (lastInputState as { text?: string }).text !== (inputState as { text?: string }).text ||\n      (lastInputState as { isChecked?: boolean }).isChecked !== (inputState as { isChecked?: boolean }).isChecked\n    ) {\n      lastInputStateMap.set(target, inputState)\n      inputCb(\n        assembleIncrementalSnapshot<InputData>(\n          IncrementalSource.Input,\n          assign(\n            {\n              id: getSerializedNodeId(target),\n            },\n            inputState\n          )\n        )\n      )\n    }\n  }\n}\n","import { noop, monitor, throttle } from '@datadog/browser-core'\nimport type { RumMutationRecord } from './trackers'\n\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\n\nexport function createMutationBatch(processMutationBatch: (mutations: RumMutationRecord[]) => void) {\n  let cancelScheduledFlush = noop\n  let pendingMutations: RumMutationRecord[] = []\n\n  function flush() {\n    cancelScheduledFlush()\n    processMutationBatch(pendingMutations)\n    pendingMutations = []\n  }\n\n  const { throttled: throttledFlush, cancel: cancelThrottle } = throttle(flush, MUTATION_PROCESS_MIN_DELAY, {\n    leading: false,\n  })\n\n  return {\n    addMutations: (mutations: RumMutationRecord[]) => {\n      if (pendingMutations.length === 0) {\n        cancelScheduledFlush = requestIdleCallback(throttledFlush, { timeout: MUTATION_PROCESS_MAX_DELAY })\n      }\n      pendingMutations.push(...mutations)\n    },\n\n    flush,\n\n    stop: () => {\n      cancelScheduledFlush()\n      cancelThrottle()\n    },\n  }\n}\n\n/**\n * Use 'requestIdleCallback' when available: it will throttle the mutation processing if the\n * browser is busy rendering frames (ex: when frames are below 60fps). When not available, the\n * fallback on 'requestAnimationFrame' will still ensure the mutations are processed after any\n * browser rendering process (Layout, Recalculate Style, etc.), so we can serialize DOM nodes efficiently.\n *\n * Note: check both 'requestIdleCallback' and 'cancelIdleCallback' existence because some polyfills only implement 'requestIdleCallback'.\n */\nfunction requestIdleCallback(callback: () => void, opts?: { timeout?: number }) {\n  if (window.requestIdleCallback && window.cancelIdleCallback) {\n    const id = window.requestIdleCallback(monitor(callback), opts)\n    return () => window.cancelIdleCallback(id)\n  }\n  const id = window.requestAnimationFrame(monitor(callback))\n  return () => window.cancelAnimationFrame(id)\n}\n","import { monitor, noop } from '@datadog/browser-core'\nimport type { RumConfiguration, NodePrivacyLevelCache } from '@datadog/browser-rum-core'\nimport {\n  isNodeShadowHost,\n  getMutationObserverConstructor,\n  getParentNode,\n  forEachChildNodes,\n  getNodePrivacyLevel,\n  getTextContent,\n  NodePrivacyLevel,\n} from '@datadog/browser-rum-core'\nimport { IncrementalSource } from '../../../types'\nimport type {\n  BrowserMutationData,\n  AddedNodeMutation,\n  AttributeMutation,\n  RemovedNodeMutation,\n  TextMutation,\n  BrowserIncrementalSnapshotRecord,\n} from '../../../types'\nimport type { NodeWithSerializedNode } from '../serialization'\nimport {\n  getElementInputValue,\n  getSerializedNodeId,\n  hasSerializedNode,\n  nodeAndAncestorsHaveSerializedNode,\n  serializeNodeWithId,\n  SerializationContextStatus,\n  serializeAttribute,\n} from '../serialization'\nimport { createMutationBatch } from '../mutationBatch'\nimport type { ShadowRootCallBack, ShadowRootsController } from '../shadowRootsController'\nimport { assembleIncrementalSnapshot } from '../assembly'\nimport type { Tracker } from './tracker.types'\n\nexport type MutationCallBack = (incrementalSnapshotRecord: BrowserIncrementalSnapshotRecord) => void\n\ntype WithSerializedTarget<T> = T & { target: NodeWithSerializedNode }\n\n// https://dom.spec.whatwg.org/#interface-mutationrecord\ninterface RumCharacterDataMutationRecord {\n  type: 'characterData'\n  target: Node\n  oldValue: string | null\n}\n\ninterface RumAttributesMutationRecord {\n  type: 'attributes'\n  target: Element\n  oldValue: string | null\n  attributeName: string | null\n}\n\ninterface RumChildListMutationRecord {\n  type: 'childList'\n  target: Node\n  addedNodes: NodeList\n  removedNodes: NodeList\n}\n\nexport type RumMutationRecord =\n  | RumCharacterDataMutationRecord\n  | RumAttributesMutationRecord\n  | RumChildListMutationRecord\n\nexport type MutationTracker = Tracker & { flush: () => void }\n\n/**\n * Buffers and aggregate mutations generated by a MutationObserver into MutationPayload\n */\nexport function trackMutation(\n  mutationCallback: MutationCallBack,\n  configuration: RumConfiguration,\n  shadowRootsController: ShadowRootsController,\n  target: Node\n): MutationTracker {\n  const MutationObserver = getMutationObserverConstructor()\n  if (!MutationObserver) {\n    return { stop: noop, flush: noop }\n  }\n\n  const mutationBatch = createMutationBatch((mutations) => {\n    processMutations(\n      mutations.concat(observer.takeRecords() as RumMutationRecord[]),\n      mutationCallback,\n      configuration,\n      shadowRootsController\n    )\n  })\n\n  const observer = new MutationObserver(monitor(mutationBatch.addMutations) as (callback: MutationRecord[]) => void)\n\n  observer.observe(target, {\n    attributeOldValue: true,\n    attributes: true,\n    characterData: true,\n    characterDataOldValue: true,\n    childList: true,\n    subtree: true,\n  })\n\n  return {\n    stop: () => {\n      observer.disconnect()\n      mutationBatch.stop()\n    },\n    flush: () => {\n      mutationBatch.flush()\n    },\n  }\n}\n\nfunction processMutations(\n  mutations: RumMutationRecord[],\n  mutationCallback: MutationCallBack,\n  configuration: RumConfiguration,\n  shadowRootsController: ShadowRootsController\n) {\n  const nodePrivacyLevelCache: NodePrivacyLevelCache = new Map()\n\n  mutations\n    .filter((mutation): mutation is RumChildListMutationRecord => mutation.type === 'childList')\n    .forEach((mutation) => {\n      mutation.removedNodes.forEach((removedNode) => {\n        traverseRemovedShadowDom(removedNode, shadowRootsController.removeShadowRoot)\n      })\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(\n    (mutation): mutation is WithSerializedTarget<RumMutationRecord> =>\n      mutation.target.isConnected &&\n      nodeAndAncestorsHaveSerializedNode(mutation.target) &&\n      getNodePrivacyLevel(mutation.target, configuration.defaultPrivacyLevel, nodePrivacyLevelCache) !==\n        NodePrivacyLevel.HIDDEN\n  )\n\n  const { adds, removes, hasBeenSerialized } = processChildListMutations(\n    filteredMutations.filter(\n      (mutation): mutation is WithSerializedTarget<RumChildListMutationRecord> => mutation.type === 'childList'\n    ),\n    configuration,\n    shadowRootsController,\n    nodePrivacyLevelCache\n  )\n\n  const texts = processCharacterDataMutations(\n    filteredMutations.filter(\n      (mutation): mutation is WithSerializedTarget<RumCharacterDataMutationRecord> =>\n        mutation.type === 'characterData' && !hasBeenSerialized(mutation.target)\n    ),\n    configuration,\n    nodePrivacyLevelCache\n  )\n\n  const attributes = processAttributesMutations(\n    filteredMutations.filter(\n      (mutation): mutation is WithSerializedTarget<RumAttributesMutationRecord> =>\n        mutation.type === 'attributes' && !hasBeenSerialized(mutation.target)\n    ),\n    configuration,\n    nodePrivacyLevelCache\n  )\n\n  if (!texts.length && !attributes.length && !removes.length && !adds.length) {\n    return\n  }\n\n  mutationCallback(\n    assembleIncrementalSnapshot<BrowserMutationData>(IncrementalSource.Mutation, { adds, removes, texts, attributes })\n  )\n}\n\nfunction processChildListMutations(\n  mutations: Array<WithSerializedTarget<RumChildListMutationRecord>>,\n  configuration: RumConfiguration,\n  shadowRootsController: ShadowRootsController,\n  nodePrivacyLevelCache: NodePrivacyLevelCache\n) {\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<Node>()\n  const removedNodes = new Map<Node, NodeWithSerializedNode>()\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\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\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<number>()\n\n  const addedNodeMutations: AddedNodeMutation[] = []\n  for (const node of sortedAddedAndMovedNodes) {\n    if (hasBeenSerialized(node)) {\n      continue\n    }\n\n    const parentNodePrivacyLevel = getNodePrivacyLevel(\n      node.parentNode!,\n      configuration.defaultPrivacyLevel,\n      nodePrivacyLevelCache\n    )\n    if (parentNodePrivacyLevel === NodePrivacyLevel.HIDDEN || parentNodePrivacyLevel === NodePrivacyLevel.IGNORE) {\n      continue\n    }\n\n    const serializedNode = serializeNodeWithId(node, {\n      serializedNodeIds,\n      parentNodePrivacyLevel,\n      serializationContext: { status: SerializationContextStatus.MUTATION, shadowRootsController },\n      configuration,\n    })\n    if (!serializedNode) {\n      continue\n    }\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: RemovedNodeMutation[] = []\n  removedNodes.forEach((parent, node) => {\n    if (hasSerializedNode(node)) {\n      removedNodeMutations.push({\n        parentId: getSerializedNodeId(parent),\n        id: getSerializedNodeId(node),\n      })\n    }\n  })\n\n  return { adds: addedNodeMutations, removes: removedNodeMutations, hasBeenSerialized }\n\n  function hasBeenSerialized(node: Node) {\n    return hasSerializedNode(node) && serializedNodeIds.has(getSerializedNodeId(node))\n  }\n\n  function getNextSibling(node: Node): null | number {\n    let nextSibling = node.nextSibling\n    while (nextSibling) {\n      if (hasSerializedNode(nextSibling)) {\n        return getSerializedNodeId(nextSibling)\n      }\n      nextSibling = nextSibling.nextSibling\n    }\n\n    return null\n  }\n}\n\nfunction processCharacterDataMutations(\n  mutations: Array<WithSerializedTarget<RumCharacterDataMutationRecord>>,\n  configuration: RumConfiguration,\n  nodePrivacyLevelCache: NodePrivacyLevelCache\n) {\n  const textMutations: TextMutation[] = []\n\n  // Deduplicate mutations based on their target node\n  const handledNodes = new Set<Node>()\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\n  // Emit mutations\n  for (const mutation of filteredMutations) {\n    const value = mutation.target.textContent\n    if (value === mutation.oldValue) {\n      continue\n    }\n\n    const parentNodePrivacyLevel = getNodePrivacyLevel(\n      getParentNode(mutation.target)!,\n      configuration.defaultPrivacyLevel,\n      nodePrivacyLevelCache\n    )\n    if (parentNodePrivacyLevel === NodePrivacyLevel.HIDDEN || parentNodePrivacyLevel === NodePrivacyLevel.IGNORE) {\n      continue\n    }\n\n    textMutations.push({\n      id: getSerializedNodeId(mutation.target),\n      // TODO: pass a valid \"ignoreWhiteSpace\" argument\n      value: getTextContent(mutation.target, false, parentNodePrivacyLevel) ?? null,\n    })\n  }\n\n  return textMutations\n}\n\nfunction processAttributesMutations(\n  mutations: Array<WithSerializedTarget<RumAttributesMutationRecord>>,\n  configuration: RumConfiguration,\n  nodePrivacyLevelCache: NodePrivacyLevelCache\n) {\n  const attributeMutations: AttributeMutation[] = []\n\n  // Deduplicate mutations based on their target node and changed attribute\n  const handledElements = new Map<Element, Set<string>>()\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    } else {\n      handledAttributes.add(mutation.attributeName!)\n    }\n    return true\n  })\n\n  // Emit mutations\n  const emittedMutations = new Map<Element, AttributeMutation>()\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\n    let transformedValue: string | null\n    if (mutation.attributeName === 'value') {\n      const inputValue = getElementInputValue(mutation.target, privacyLevel)\n      if (inputValue === undefined) {\n        continue\n      }\n      transformedValue = inputValue\n    } else if (typeof attributeValue === 'string') {\n      transformedValue = attributeValue\n    } else {\n      transformedValue = null\n    }\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\n    emittedMutation.attributes[mutation.attributeName!] = transformedValue\n  }\n\n  return attributeMutations\n}\n\nexport function sortAddedAndMovedNodes(nodes: Node[]) {\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    } else if (position & Node.DOCUMENT_POSITION_CONTAINS) {\n      return 1\n    } else if (position & Node.DOCUMENT_POSITION_FOLLOWING) {\n      return 1\n    } else if (position & Node.DOCUMENT_POSITION_PRECEDING) {\n      return -1\n    }\n    /* eslint-enable no-bitwise */\n    return 0\n  })\n}\n\nfunction traverseRemovedShadowDom(removedNode: Node, shadowDomRemovedCallback: ShadowRootCallBack) {\n  if (isNodeShadowHost(removedNode)) {\n    shadowDomRemovedCallback(removedNode.shadowRoot)\n  }\n  forEachChildNodes(removedNode, (childNode) => traverseRemovedShadowDom(childNode, shadowDomRemovedCallback))\n}\n","import { sendToExtension } from '@datadog/browser-core'\nimport type { LifeCycle, RumConfiguration, ViewHistory } from '@datadog/browser-rum-core'\nimport type { BrowserRecord } from '../../types'\nimport * as replayStats from '../replayStats'\nimport type { Tracker } from './trackers'\nimport {\n  trackFocus,\n  trackFrustration,\n  trackInput,\n  trackMediaInteraction,\n  trackMouseInteraction,\n  trackMove,\n  trackMutation,\n  trackScroll,\n  trackStyleSheet,\n  trackViewEnd,\n  trackViewportResize,\n  trackVisualViewportResize,\n} from './trackers'\nimport { createElementsScrollPositions } from './elementsScrollPositions'\nimport type { ShadowRootsController } from './shadowRootsController'\nimport { initShadowRootsController } from './shadowRootsController'\nimport { startFullSnapshots } from './startFullSnapshots'\nimport { initRecordIds } from './recordIds'\n\nexport interface RecordOptions {\n  emit?: (record: BrowserRecord) => void\n  configuration: RumConfiguration\n  lifeCycle: LifeCycle\n  viewHistory: ViewHistory\n}\n\nexport interface RecordAPI {\n  stop: () => void\n  flushMutations: () => void\n  shadowRootsController: ShadowRootsController\n}\n\nexport function record(options: RecordOptions): RecordAPI {\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\n  const emitAndComputeStats = (record: BrowserRecord) => {\n    emit(record)\n    sendToExtension('record', { record })\n    const view = options.viewHistory.findView()!\n    replayStats.addRecord(view.id)\n  }\n\n  const elementsScrollPositions = createElementsScrollPositions()\n\n  const shadowRootsController = initShadowRootsController(configuration, emitAndComputeStats, elementsScrollPositions)\n\n  const { stop: stopFullSnapshots } = startFullSnapshots(\n    elementsScrollPositions,\n    shadowRootsController,\n    lifeCycle,\n    configuration,\n    flushMutations,\n    (records) => records.forEach((record) => emitAndComputeStats(record))\n  )\n\n  function flushMutations() {\n    shadowRootsController.flush()\n    mutationTracker.flush()\n  }\n\n  const recordIds = initRecordIds()\n  const mutationTracker = trackMutation(emitAndComputeStats, configuration, shadowRootsController, document)\n  const trackers: Tracker[] = [\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\n  return {\n    stop: () => {\n      shadowRootsController.stop()\n      trackers.forEach((tracker) => tracker.stop())\n      stopFullSnapshots()\n    },\n    flushMutations,\n    shadowRootsController,\n  }\n}\n","export type ElementsScrollPositions = ReturnType<typeof createElementsScrollPositions>\nexport type ScrollPositions = { scrollLeft: number; scrollTop: number }\n\nexport function createElementsScrollPositions() {\n  const scrollPositionsByElement = new WeakMap<Element, ScrollPositions>()\n  return {\n    set(element: Element | Document, scrollPositions: 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(\n        element === document ? document.scrollingElement! : (element as Element),\n        scrollPositions\n      )\n    },\n    get(element: Element) {\n      return scrollPositionsByElement.get(element)\n    },\n    has(element: Element) {\n      return scrollPositionsByElement.has(element)\n    },\n  }\n}\n","import type { RumConfiguration } from '@datadog/browser-rum-core'\nimport type { BrowserIncrementalSnapshotRecord } from '../../types'\nimport { trackInput, trackMutation, trackScroll } from './trackers'\nimport type { ElementsScrollPositions } from './elementsScrollPositions'\n\ninterface ShadowRootController {\n  stop: () => void\n  flush: () => void\n}\n\nexport type ShadowRootCallBack = (shadowRoot: ShadowRoot) => void\n\nexport interface ShadowRootsController {\n  addShadowRoot: ShadowRootCallBack\n  removeShadowRoot: ShadowRootCallBack\n  stop: () => void\n  flush: () => void\n}\n\nexport const initShadowRootsController = (\n  configuration: RumConfiguration,\n  callback: (record: BrowserIncrementalSnapshotRecord) => void,\n  elementsScrollPositions: ElementsScrollPositions\n): ShadowRootsController => {\n  const controllerByShadowRoot = new Map<ShadowRoot, ShadowRootController>()\n\n  const shadowRootsController: ShadowRootsController = {\n    addShadowRoot: (shadowRoot: 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: 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","import { LifeCycleEventType, getScrollX, getScrollY, getViewportDimension } from '@datadog/browser-rum-core'\nimport type { RumConfiguration, LifeCycle } from '@datadog/browser-rum-core'\nimport { timeStampNow } from '@datadog/browser-core'\nimport type { BrowserRecord } from '../../types'\nimport { RecordType } from '../../types'\nimport type { ElementsScrollPositions } from './elementsScrollPositions'\nimport type { ShadowRootsController } from './shadowRootsController'\nimport { SerializationContextStatus, serializeDocument } from './serialization'\nimport { getVisualViewport } from './viewports'\n\nexport function startFullSnapshots(\n  elementsScrollPositions: ElementsScrollPositions,\n  shadowRootsController: ShadowRootsController,\n  lifeCycle: LifeCycle,\n  configuration: RumConfiguration,\n  flushMutations: () => void,\n  fullSnapshotCallback: (records: BrowserRecord[]) => void\n) {\n  const takeFullSnapshot = (\n    timestamp = timeStampNow(),\n    serializationContext = {\n      status: SerializationContextStatus.INITIAL_FULL_SNAPSHOT,\n      elementsScrollPositions,\n      shadowRootsController,\n    }\n  ) => {\n    const { width, height } = getViewportDimension()\n    const records: BrowserRecord[] = [\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\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\n  fullSnapshotCallback(takeFullSnapshot())\n\n  const { unsubscribe } = lifeCycle.subscribe(LifeCycleEventType.VIEW_CREATED, (view) => {\n    flushMutations()\n    fullSnapshotCallback(\n      takeFullSnapshot(view.startClocks.timeStamp, {\n        shadowRootsController,\n        status: SerializationContextStatus.SUBSEQUENT_FULL_SNAPSHOT,\n        elementsScrollPositions,\n      })\n    )\n  })\n\n  return {\n    stop: unsubscribe,\n  }\n}\n","export type RecordIds = ReturnType<typeof initRecordIds>\n\nexport function initRecordIds() {\n  const recordIds = new WeakMap<Event, number>()\n  let nextId = 1\n\n  return {\n    getIdForEvent(event: Event): number {\n      if (!recordIds.has(event)) {\n        recordIds.set(event, nextId++)\n      }\n      return recordIds.get(event)!\n    },\n  }\n}\n","import type { Encoder, EncoderResult } from '@datadog/browser-core'\nimport { assign } from '@datadog/browser-core'\nimport type { BrowserRecord, BrowserSegmentMetadata, CreationReason, SegmentContext } from '../../types'\nimport { RecordType } from '../../types'\nimport * as replayStats from '../replayStats'\n\nexport type FlushReason = Exclude<CreationReason, 'init'> | 'stop'\nexport type FlushCallback = (metadata: BrowserSegmentMetadata, encoderResult: EncoderResult<Uint8Array>) => void\nexport type AddRecordCallback = (encodedBytesCount: number) => void\n\nexport interface Segment {\n  addRecord: (record: BrowserRecord, callback: AddRecordCallback) => void\n  flush: (callback: FlushCallback) => void\n}\n\nexport function createSegment({\n  context,\n  creationReason,\n  encoder,\n}: {\n  context: SegmentContext\n  creationReason: CreationReason\n  encoder: Encoder<Uint8Array>\n}): Segment {\n  let encodedBytesCount = 0\n  const viewId = context.view.id\n  const metadata: BrowserSegmentMetadata = assign(\n    {\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' as const,\n    },\n    context\n  )\n  replayStats.addSegment(viewId)\n\n  function addRecord(record: BrowserRecord, callback: AddRecordCallback): void {\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 ||= record.type === RecordType.FullSnapshot\n\n    const prefix = encoder.isEmpty ? '{\"records\":[' : ','\n    encoder.write(prefix + JSON.stringify(record), (additionalEncodedBytesCount) => {\n      encodedBytesCount += additionalEncodedBytesCount\n      callback(encodedBytesCount)\n    })\n  }\n\n  function flush(callback: FlushCallback) {\n    if (encoder.isEmpty) {\n      throw new Error('Empty segment flushed')\n    }\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\n  return { addRecord, flush }\n}\n","import type { DeflateEncoder, HttpRequest, TimeoutId } from '@datadog/browser-core'\nimport {\n  isPageExitReason,\n  ONE_SECOND,\n  clearTimeout,\n  setTimeout,\n  isExperimentalFeatureEnabled,\n  ExperimentalFeature,\n} from '@datadog/browser-core'\nimport type { LifeCycle, ViewHistory, RumSessionManager, RumConfiguration } from '@datadog/browser-rum-core'\nimport { LifeCycleEventType } from '@datadog/browser-rum-core'\nimport type { BrowserRecord, CreationReason, SegmentContext } from '../../types'\nimport { buildReplayPayload } from './buildReplayPayload'\nimport type { FlushReason, Segment } from './segment'\nimport { createSegment } from './segment'\n\nexport function getSegmentDurationLimit() {\n  return isExperimentalFeatureEnabled(ExperimentalFeature.REDUCE_SEGMENT_LIMIT_BATCH_TIME)\n    ? 5 * ONE_SECOND\n    : 30 * ONE_SECOND\n}\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 = 60_000\n\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.\n\nexport function startSegmentCollection(\n  lifeCycle: LifeCycle,\n  configuration: RumConfiguration,\n  sessionManager: RumSessionManager,\n  viewHistory: ViewHistory,\n  httpRequest: HttpRequest,\n  encoder: DeflateEncoder\n) {\n  return doStartSegmentCollection(\n    lifeCycle,\n    () => computeSegmentContext(configuration.applicationId, sessionManager, viewHistory),\n    httpRequest,\n    encoder\n  )\n}\n\nconst enum SegmentCollectionStatus {\n  WaitingForInitialRecord,\n  SegmentPending,\n  Stopped,\n}\ntype SegmentCollectionState =\n  | {\n      status: SegmentCollectionStatus.WaitingForInitialRecord\n      nextSegmentCreationReason: CreationReason\n    }\n  | {\n      status: SegmentCollectionStatus.SegmentPending\n      segment: Segment\n      expirationTimeoutId: TimeoutId\n    }\n  | {\n      status: SegmentCollectionStatus.Stopped\n    }\n\nexport function doStartSegmentCollection(\n  lifeCycle: LifeCycle,\n  getSegmentContext: () => SegmentContext | undefined,\n  httpRequest: HttpRequest,\n  encoder: DeflateEncoder\n) {\n  let state: SegmentCollectionState = {\n    status: SegmentCollectionStatus.WaitingForInitialRecord,\n    nextSegmentCreationReason: 'init',\n  }\n\n  const { unsubscribe: unsubscribeViewCreated } = lifeCycle.subscribe(LifeCycleEventType.VIEW_CREATED, () => {\n    flushSegment('view_change')\n  })\n\n  const { unsubscribe: unsubscribePageExited } = lifeCycle.subscribe(\n    LifeCycleEventType.PAGE_EXITED,\n    (pageExitEvent) => {\n      flushSegment(pageExitEvent.reason as FlushReason)\n    }\n  )\n\n  function flushSegment(flushReason: FlushReason) {\n    if (state.status === SegmentCollectionStatus.SegmentPending) {\n      state.segment.flush((metadata, encoderResult) => {\n        const payload = buildReplayPayload(encoderResult.output, metadata, encoderResult.rawBytesCount)\n\n        if (isPageExitReason(flushReason)) {\n          httpRequest.sendOnExit(payload)\n        } else {\n          httpRequest.send(payload)\n        }\n      })\n      clearTimeout(state.expirationTimeoutId)\n    }\n\n    if (flushReason !== 'stop') {\n      state = {\n        status: SegmentCollectionStatus.WaitingForInitialRecord,\n        nextSegmentCreationReason: flushReason,\n      }\n    } else {\n      state = {\n        status: SegmentCollectionStatus.Stopped,\n      }\n    }\n  }\n\n  return {\n    addRecord: (record: BrowserRecord) => {\n      if (state.status === SegmentCollectionStatus.Stopped) {\n        return\n      }\n\n      if (state.status === SegmentCollectionStatus.WaitingForInitialRecord) {\n        const context = getSegmentContext()\n        if (!context) {\n          return\n        }\n\n        state = {\n          status: SegmentCollectionStatus.SegmentPending,\n          segment: createSegment({ encoder, context, creationReason: state.nextSegmentCreationReason }),\n          expirationTimeoutId: setTimeout(() => {\n            flushSegment('segment_duration_limit')\n          }, getSegmentDurationLimit()),\n        }\n      }\n\n      state.segment.addRecord(record, (encodedBytesCount) => {\n        if (encodedBytesCount > SEGMENT_BYTES_LIMIT) {\n          flushSegment('segment_bytes_limit')\n        }\n      })\n    },\n\n    stop: () => {\n      flushSegment('stop')\n      unsubscribeViewCreated()\n      unsubscribePageExited()\n    },\n  }\n}\n\nexport function computeSegmentContext(\n  applicationId: string,\n  sessionManager: RumSessionManager,\n  viewHistory: ViewHistory\n) {\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}\n\nexport function setSegmentBytesLimit(newSegmentBytesLimit = 60_000) {\n  SEGMENT_BYTES_LIMIT = newSegmentBytesLimit\n}\n","import type { Payload } from '@datadog/browser-core'\nimport { assign } from '@datadog/browser-core'\nimport type { BrowserSegmentMetadata } from '../../types'\n\nexport type BrowserSegmentMetadataAndSegmentSizes = BrowserSegmentMetadata & {\n  raw_segment_size: number\n  compressed_segment_size: number\n}\n\nexport function buildReplayPayload(\n  data: Uint8Array,\n  metadata: BrowserSegmentMetadata,\n  rawSegmentBytesCount: number\n): Payload {\n  const formData = new FormData()\n\n  formData.append(\n    'segment',\n    new Blob([data], {\n      type: 'application/octet-stream',\n    }),\n    `${metadata.session.id}-${metadata.start}`\n  )\n\n  const metadataAndSegmentSizes: BrowserSegmentMetadataAndSegmentSizes = assign(\n    {\n      raw_segment_size: rawSegmentBytesCount,\n      compressed_segment_size: data.byteLength,\n    },\n    metadata\n  )\n  const serializedMetadataAndSegmentSizes = JSON.stringify(metadataAndSegmentSizes)\n  formData.append('event', new Blob([serializedMetadataAndSegmentSizes], { type: 'application/json' }))\n\n  return { data: formData, bytesCount: data.byteLength }\n}\n","/**\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}\n","import type { RumConfiguration, RumSessionManager, ViewHistory, RumSession } from '@datadog/browser-rum-core'\nimport { getSessionReplayUrl, SessionReplayState } from '@datadog/browser-rum-core'\nimport { isBrowserSupported } from '../boot/isBrowserSupported'\n\nexport function getSessionReplayLink(\n  configuration: RumConfiguration,\n  sessionManager: RumSessionManager,\n  viewHistory: ViewHistory,\n  isRecordingStarted: boolean\n): string | undefined {\n  const session = sessionManager.findTrackedSession()\n  const errorType = getErrorType(session, isRecordingStarted)\n  const viewContext = viewHistory.findView()\n\n  return getSessionReplayUrl(configuration, {\n    viewContext,\n    errorType,\n    session,\n  })\n}\n\nfunction getErrorType(session: RumSession | undefined, isRecordingStarted: boolean) {\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 === 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","import { INTAKE_SITE_STAGING, INTAKE_SITE_US1, INTAKE_SITE_EU1 } from '@datadog/browser-core'\nimport type { RumConfiguration } from './configuration'\nimport type { ViewHistoryEntry } from './contexts/viewHistory'\nimport type { RumSession } from './rumSessionManager'\n\nexport function getSessionReplayUrl(\n  configuration: RumConfiguration,\n  {\n    session,\n    viewContext,\n    errorType,\n  }: {\n    session?: RumSession\n    viewContext?: ViewHistoryEntry\n    errorType?: string\n  }\n): string {\n  const sessionId = session ? session.id : 'no-session-id'\n  const parameters: string[] = []\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\n  const origin = getDatadogSiteUrl(configuration)\n  const path = `/rum/replay/sessions/${sessionId}`\n  return `${origin}${path}?${parameters.join('&')}`\n}\n\nexport function getDatadogSiteUrl(rumConfiguration: RumConfiguration) {\n  const site = rumConfiguration.site\n  const subdomain = rumConfiguration.subdomain || getSiteDefaultSubdomain(rumConfiguration)\n  return `https://${subdomain ? `${subdomain}.` : ''}${site}`\n}\n\nfunction getSiteDefaultSubdomain(configuration: RumConfiguration): string | undefined {\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","import type {\n  DeflateWorkerResponse,\n  DeflateEncoder,\n  DeflateEncoderStreamId,\n  DeflateWorker,\n  EncoderResult,\n} from '@datadog/browser-core'\nimport type { RumConfiguration } from '@datadog/browser-rum-core'\nimport { addEventListener, addTelemetryDebug, assign, concatBuffers } from '@datadog/browser-core'\n\nexport function createDeflateEncoder(\n  configuration: RumConfiguration,\n  worker: DeflateWorker,\n  streamId: DeflateEncoderStreamId\n): DeflateEncoder {\n  let rawBytesCount = 0\n  let compressedData: Uint8Array[] = []\n  let compressedDataTrailer: Uint8Array\n\n  let nextWriteActionId = 0\n  const pendingWriteActions: Array<{\n    writeCallback?: (additionalEncodedBytesCount: number) => void\n    finishCallback?: () => void\n    id: number\n    data: string\n  }> = []\n\n  const { stop: removeMessageListener } = addEventListener(\n    configuration,\n    worker,\n    'message',\n    ({ data: workerResponse }: MessageEvent<DeflateWorkerResponse>) => {\n      if (workerResponse.type !== 'wrote' || (workerResponse.streamId as DeflateEncoderStreamId) !== streamId) {\n        return\n      }\n\n      rawBytesCount += workerResponse.additionalBytesCount\n      compressedData.push(workerResponse.result)\n      compressedDataTrailer = workerResponse.trailer\n\n      const nextPendingAction = pendingWriteActions.shift()\n      if (nextPendingAction && nextPendingAction.id === workerResponse.id) {\n        if (nextPendingAction.writeCallback) {\n          nextPendingAction.writeCallback(workerResponse.result.byteLength)\n        } else if (nextPendingAction.finishCallback) {\n          nextPendingAction.finishCallback()\n        }\n      } else {\n        removeMessageListener()\n        addTelemetryDebug('Worker responses received out of order.')\n      }\n    }\n  )\n\n  function consumeResult(): EncoderResult<Uint8Array> {\n    const output =\n      compressedData.length === 0 ? new Uint8Array(0) : concatBuffers(compressedData.concat(compressedDataTrailer))\n    const result: EncoderResult<Uint8Array> = {\n      rawBytesCount,\n      output,\n      outputBytesCount: output.byteLength,\n      encoding: 'deflate',\n    }\n    rawBytesCount = 0\n    compressedData = []\n    return result\n  }\n\n  function sendResetIfNeeded() {\n    if (nextWriteActionId > 0) {\n      worker.postMessage({\n        action: 'reset',\n        streamId,\n      })\n      nextWriteActionId = 0\n    }\n  }\n\n  return {\n    isAsync: true,\n\n    get isEmpty() {\n      return nextWriteActionId === 0\n    },\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\n    finish(callback) {\n      sendResetIfNeeded()\n\n      if (!pendingWriteActions.length) {\n        callback(consumeResult())\n      } else {\n        // Make sure we do not call any write callback\n        pendingWriteActions.forEach((pendingWriteAction) => {\n          delete pendingWriteAction.writeCallback\n        })\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\n    finishSync() {\n      sendResetIfNeeded()\n\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\n      return assign(consumeResult(), {\n        pendingData,\n      })\n    },\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\n    stop() {\n      removeMessageListener()\n    },\n  }\n}\n","import type { DeflateWorker, DeflateWorkerResponse } from '@datadog/browser-core'\nimport {\n  addTelemetryError,\n  display,\n  includes,\n  addEventListener,\n  setTimeout,\n  ONE_SECOND,\n  DOCS_ORIGIN,\n} from '@datadog/browser-core'\nimport type { RumConfiguration } from '@datadog/browser-rum-core'\n\nexport const INITIALIZATION_TIME_OUT_DELAY = 30 * ONE_SECOND\n\ndeclare const __BUILD_ENV__WORKER_STRING__: string\n\n/**\n * In order to be sure that the worker is correctly working, we need a round trip of\n * initialization messages, making the creation asynchronous.\n * These worker lifecycle states handle this case.\n */\nexport const enum DeflateWorkerStatus {\n  Nil,\n  Loading,\n  Error,\n  Initialized,\n}\n\ntype DeflateWorkerState =\n  | {\n      status: DeflateWorkerStatus.Nil\n    }\n  | {\n      status: DeflateWorkerStatus.Loading\n      worker: DeflateWorker\n      stop: () => void\n      initializationFailureCallbacks: Array<() => void>\n    }\n  | {\n      status: DeflateWorkerStatus.Error\n    }\n  | {\n      status: DeflateWorkerStatus.Initialized\n      worker: DeflateWorker\n      stop: () => void\n      version: string\n    }\n\nexport type CreateDeflateWorker = typeof createDeflateWorker\n\nfunction createDeflateWorker(configuration: RumConfiguration): DeflateWorker {\n  return new Worker(configuration.workerUrl || URL.createObjectURL(new Blob([__BUILD_ENV__WORKER_STRING__])))\n}\n\nlet state: DeflateWorkerState = { status: DeflateWorkerStatus.Nil }\n\nexport function startDeflateWorker(\n  configuration: RumConfiguration,\n  source: string,\n  onInitializationFailure: () => void,\n  createDeflateWorkerImpl = createDeflateWorker\n) {\n  if (state.status === DeflateWorkerStatus.Nil) {\n    // doStartDeflateWorker updates the state to \"loading\" or \"error\"\n    doStartDeflateWorker(configuration, source, createDeflateWorkerImpl)\n  }\n\n  switch (state.status) {\n    case DeflateWorkerStatus.Loading:\n      state.initializationFailureCallbacks.push(onInitializationFailure)\n      return state.worker\n    case DeflateWorkerStatus.Initialized:\n      return state.worker\n  }\n}\n\nexport function resetDeflateWorkerState() {\n  if (state.status === DeflateWorkerStatus.Initialized || state.status === DeflateWorkerStatus.Loading) {\n    state.stop()\n  }\n  state = { status: DeflateWorkerStatus.Nil }\n}\n\nexport function getDeflateWorkerStatus() {\n  return state.status\n}\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(\n  configuration: RumConfiguration,\n  source: string,\n  createDeflateWorkerImpl = createDeflateWorker\n) {\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(\n      configuration,\n      worker,\n      'message',\n      ({ data }: MessageEvent<DeflateWorkerResponse>) => {\n        if (data.type === 'errored') {\n          onError(configuration, source, data.error, data.streamId)\n        } else if (data.type === 'initialized') {\n          onInitialized(data.version)\n        }\n      }\n    )\n    worker.postMessage({ action: 'init' })\n    setTimeout(() => onTimeout(source), INITIALIZATION_TIME_OUT_DELAY)\n    const stop = () => {\n      removeErrorListener()\n      removeMessageListener()\n    }\n\n    state = { status: DeflateWorkerStatus.Loading, worker, stop, initializationFailureCallbacks: [] }\n  } catch (error) {\n    onError(configuration, source, error)\n  }\n}\n\nfunction onTimeout(source: string) {\n  if (state.status === 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: DeflateWorkerStatus.Error }\n  }\n}\n\nfunction onInitialized(version: string) {\n  if (state.status === DeflateWorkerStatus.Loading) {\n    state = { status: DeflateWorkerStatus.Initialized, worker: state.worker, stop: state.stop, version }\n  }\n}\n\nfunction onError(configuration: RumConfiguration, source: string, error: unknown, streamId?: number) {\n  if (state.status === DeflateWorkerStatus.Loading || state.status === 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      } else {\n        baseMessage = 'Please make sure CSP is correctly configured.'\n      }\n      display.error(\n        `${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 === DeflateWorkerStatus.Loading) {\n      state.initializationFailureCallbacks.forEach((callback) => callback())\n    }\n    state = { status: DeflateWorkerStatus.Error }\n  } else {\n    addTelemetryError(error, {\n      worker_version: state.status === DeflateWorkerStatus.Initialized && state.version,\n      stream_id: streamId,\n    })\n  }\n}\n\nfunction isMessageCspRelated(message: string) {\n  return (\n    includes(message, '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    includes(message, \"requires 'TrustedScriptURL'\")\n  )\n}\n","// Keep the following in sync with packages/rum-slim/src/entries/main.ts\nimport { defineGlobal, getGlobalObject } from '@datadog/browser-core'\nimport type { RumPublicApi } from '@datadog/browser-rum-core'\nimport { makeRumPublicApi, startRum } from '@datadog/browser-rum-core'\n\nimport { startRecording } from '../boot/startRecording'\nimport { makeRecorderApi } from '../boot/recorderApi'\nimport { createDeflateEncoder, startDeflateWorker } from '../domain/deflate'\n\nexport {\n  CommonProperties,\n  RumPublicApi as RumGlobal,\n  RumInitConfiguration,\n  // Events\n  RumEvent,\n  RumActionEvent,\n  RumErrorEvent,\n  RumLongTaskEvent,\n  RumResourceEvent,\n  RumViewEvent,\n  RumVitalEvent,\n  // Events context\n  RumEventDomainContext,\n  RumViewEventDomainContext,\n  RumErrorEventDomainContext,\n  RumActionEventDomainContext,\n  RumFetchResourceEventDomainContext,\n  RumXhrResourceEventDomainContext,\n  RumOtherResourceEventDomainContext,\n  RumLongTaskEventDomainContext,\n} from '@datadog/browser-rum-core'\nexport { DefaultPrivacyLevel } from '@datadog/browser-core'\n\nconst recorderApi = makeRecorderApi(startRecording)\nexport const datadogRum = makeRumPublicApi(startRum, recorderApi, { startDeflateWorker, createDeflateEncoder })\n\ninterface BrowserWindow extends Window {\n  DD_RUM?: RumPublicApi\n}\ndefineGlobal(getGlobalObject<BrowserWindow>(), 'DD_RUM', datadogRum)\n","import { catchUserErrors } from '../tools/catchUserErrors'\nimport { setDebugMode } from '../tools/monitor'\nimport { assign } from '../tools/utils/polyfills'\nimport { display } from '../tools/display'\n\n// replaced at build time\ndeclare const __BUILD_ENV__SDK_VERSION__: string\n\nexport interface PublicApi {\n  /**\n   * Version of the Logs browser SDK\n   */\n  version: string\n\n  /**\n   * [For CDN async setup] Early RUM API calls must be wrapped in the `window.DD_RUM.onReady()` callback. This ensures the code only gets executed once the SDK is properly loaded.\n   *\n   * See [CDN async setup](https://docs.datadoghq.com/real_user_monitoring/browser/#cdn-async) for further information.\n   */\n  onReady: (callback: () => void) => void\n}\n\nexport function makePublicApi<T extends PublicApi>(stub: Omit<T, keyof PublicApi>): T {\n  const publicApi = assign(\n    {\n      version: __BUILD_ENV__SDK_VERSION__,\n\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: () => void) {\n        callback()\n      },\n    },\n    stub\n  )\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\n  return publicApi as T\n}\n\nexport function defineGlobal<Global, Name extends keyof Global>(global: Global, name: Name, api: Global[Name]) {\n  const existingGlobalVariable = global[name] as { q?: Array<() => void>; version?: string } | undefined\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","import type { DeflateEncoder } from '@datadog/browser-core'\nimport {\n  DeflateEncoderStreamId,\n  canUseEventBridge,\n  noop,\n  runOnReadyState,\n  PageExitReason,\n  BridgeCapability,\n  bridgeSupports,\n} from '@datadog/browser-core'\nimport type {\n  LifeCycle,\n  ViewHistory,\n  RumSessionManager,\n  RecorderApi,\n  RumConfiguration,\n  StartRecordingOptions,\n} from '@datadog/browser-rum-core'\nimport { LifeCycleEventType, SessionReplayState } from '@datadog/browser-rum-core'\nimport { getReplayStats as getReplayStatsImpl } from '../domain/replayStats'\nimport { getSessionReplayLink } from '../domain/getSessionReplayLink'\nimport type { CreateDeflateWorker } from '../domain/deflate'\nimport {\n  createDeflateEncoder,\n  startDeflateWorker,\n  DeflateWorkerStatus,\n  getDeflateWorkerStatus,\n} from '../domain/deflate'\n\nimport type { startRecording } from './startRecording'\nimport { isBrowserSupported } from './isBrowserSupported'\n\nexport type StartRecording = typeof startRecording\n\nconst enum RecorderStatus {\n  // The recorder is stopped.\n  Stopped,\n  // The user started the recording while it wasn't possible yet. The recorder should start as soon\n  // as possible.\n  IntentToStart,\n  // The recorder is starting. It does not record anything yet.\n  Starting,\n  // The recorder is started, it records the session.\n  Started,\n}\ntype RecorderState =\n  | {\n      status: RecorderStatus.Stopped\n    }\n  | {\n      status: RecorderStatus.IntentToStart\n    }\n  | {\n      status: RecorderStatus.Starting\n    }\n  | {\n      status: RecorderStatus.Started\n      stopRecording: () => void\n    }\n\ntype StartStrategyFn = (options?: StartRecordingOptions) => void\n\nexport function makeRecorderApi(\n  startRecordingImpl: StartRecording,\n  createDeflateWorkerImpl?: CreateDeflateWorker\n): RecorderApi {\n  if ((canUseEventBridge() && !bridgeSupports(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\n  let state: RecorderState = {\n    status: RecorderStatus.IntentToStart,\n  }\n\n  let startStrategy: StartStrategyFn = () => {\n    state = { status: RecorderStatus.IntentToStart }\n  }\n  let stopStrategy = () => {\n    state = { status: RecorderStatus.Stopped }\n  }\n  let getSessionReplayLinkStrategy = noop as () => string | undefined\n\n  return {\n    start: (options?: StartRecordingOptions) => startStrategy(options),\n    stop: () => stopStrategy(),\n    getSessionReplayLink: () => getSessionReplayLinkStrategy(),\n    onRumStart: (\n      lifeCycle: LifeCycle,\n      configuration: RumConfiguration,\n      sessionManager: RumSessionManager,\n      viewHistory: ViewHistory,\n      worker\n    ) => {\n      if (configuration.startSessionReplayRecordingManually) {\n        state = { status: RecorderStatus.Stopped }\n      }\n      lifeCycle.subscribe(LifeCycleEventType.SESSION_EXPIRED, () => {\n        if (state.status === RecorderStatus.Starting || state.status === RecorderStatus.Started) {\n          stopStrategy()\n          state = { status: RecorderStatus.IntentToStart }\n        }\n      })\n\n      // Stop the recorder on page unload to avoid sending records after the page is ended.\n      lifeCycle.subscribe(LifeCycleEventType.PAGE_EXITED, (pageExitEvent) => {\n        if (pageExitEvent.reason === PageExitReason.UNLOADING) {\n          stopStrategy()\n        }\n      })\n\n      lifeCycle.subscribe(LifeCycleEventType.SESSION_RENEWED, () => {\n        if (state.status === RecorderStatus.IntentToStart) {\n          startStrategy()\n        }\n      })\n\n      let cachedDeflateEncoder: DeflateEncoder | undefined\n\n      function getOrCreateDeflateEncoder() {\n        if (!cachedDeflateEncoder) {\n          if (!worker) {\n            worker = startDeflateWorker(\n              configuration,\n              'Datadog Session Replay',\n              () => {\n                stopStrategy()\n              },\n              createDeflateWorkerImpl\n            )\n          }\n          if (worker) {\n            cachedDeflateEncoder = createDeflateEncoder(configuration, worker, DeflateEncoderStreamId.REPLAY)\n          }\n        }\n        return cachedDeflateEncoder\n      }\n\n      startStrategy = (options?: StartRecordingOptions) => {\n        const session = sessionManager.findTrackedSession()\n        if (!session || (session.sessionReplay === SessionReplayState.OFF && (!options || !options.force))) {\n          state = { status: RecorderStatus.IntentToStart }\n          return\n        }\n\n        if (state.status === RecorderStatus.Starting || state.status === RecorderStatus.Started) {\n          return\n        }\n\n        state = { status: RecorderStatus.Starting }\n\n        runOnReadyState(configuration, 'interactive', () => {\n          if (state.status !== RecorderStatus.Starting) {\n            return\n          }\n\n          const deflateEncoder = getOrCreateDeflateEncoder()\n          if (!deflateEncoder) {\n            state = {\n              status: RecorderStatus.Stopped,\n            }\n            return\n          }\n\n          const { stop: stopRecording } = startRecordingImpl(\n            lifeCycle,\n            configuration,\n            sessionManager,\n            viewHistory,\n            deflateEncoder\n          )\n          state = {\n            status: RecorderStatus.Started,\n            stopRecording,\n          }\n        })\n\n        if (options && options.force && session.sessionReplay === SessionReplayState.OFF) {\n          sessionManager.setForcedReplay()\n        }\n      }\n\n      stopStrategy = () => {\n        if (state.status === RecorderStatus.Stopped) {\n          return\n        }\n\n        if (state.status === RecorderStatus.Started) {\n          state.stopRecording()\n        }\n\n        state = {\n          status: RecorderStatus.Stopped,\n        }\n      }\n\n      getSessionReplayLinkStrategy = () =>\n        getSessionReplayLink(configuration, sessionManager, viewHistory, state.status !== RecorderStatus.Stopped)\n\n      if (state.status === RecorderStatus.IntentToStart) {\n        startStrategy()\n      }\n    },\n\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() === DeflateWorkerStatus.Initialized && state.status === RecorderStatus.Started,\n\n    getReplayStats: (viewId) =>\n      getDeflateWorkerStatus() === DeflateWorkerStatus.Initialized ? getReplayStatsImpl(viewId) : undefined,\n  }\n}\n","import type { RawError, HttpRequest, DeflateEncoder } from '@datadog/browser-core'\nimport { createHttpRequest, addTelemetryDebug, canUseEventBridge } from '@datadog/browser-core'\nimport type { LifeCycle, ViewHistory, RumConfiguration, RumSessionManager } from '@datadog/browser-rum-core'\nimport { LifeCycleEventType } from '@datadog/browser-rum-core'\n\nimport { record } from '../domain/record'\nimport { startSegmentCollection, SEGMENT_BYTES_LIMIT } from '../domain/segmentCollection'\nimport type { BrowserRecord } from '../types'\nimport { startRecordBridge } from '../domain/startRecordBridge'\n\nexport function startRecording(\n  lifeCycle: LifeCycle,\n  configuration: RumConfiguration,\n  sessionManager: RumSessionManager,\n  viewHistory: ViewHistory,\n  encoder: DeflateEncoder,\n  httpRequest?: HttpRequest\n) {\n  const cleanupTasks: Array<() => void> = []\n\n  const reportError = (error: RawError) => {\n    lifeCycle.notify(LifeCycleEventType.RAW_ERROR_COLLECTED, { error })\n    addTelemetryDebug('Error reported to customer', { 'error.message': error.message })\n  }\n\n  const replayRequest =\n    httpRequest ||\n    createHttpRequest(configuration, configuration.sessionReplayEndpointBuilder, SEGMENT_BYTES_LIMIT, reportError)\n\n  let addRecord: (record: BrowserRecord) => void\n\n  if (!canUseEventBridge()) {\n    const segmentCollection = startSegmentCollection(\n      lifeCycle,\n      configuration,\n      sessionManager,\n      viewHistory,\n      replayRequest,\n      encoder\n    )\n    addRecord = segmentCollection.addRecord\n    cleanupTasks.push(segmentCollection.stop)\n  } else {\n    ;({ addRecord } = startRecordBridge(viewHistory))\n  }\n\n  const { stop: stopRecording } = record({\n    emit: addRecord,\n    configuration,\n    lifeCycle,\n    viewHistory,\n  })\n  cleanupTasks.push(stopRecording)\n\n  return {\n    stop: () => {\n      cleanupTasks.forEach((task) => task())\n    },\n  }\n}\n","import { getEventBridge } from '@datadog/browser-core'\nimport type { ViewHistory } from '@datadog/browser-rum-core'\nimport type { BrowserRecord } from '../types'\n\nexport function startRecordBridge(viewHistory: ViewHistory) {\n  const bridge = getEventBridge<'record', BrowserRecord>()!\n\n  return {\n    addRecord: (record: BrowserRecord) => {\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","import type {\n  Context,\n  TimeStamp,\n  RelativeTime,\n  User,\n  DeflateWorker,\n  DeflateEncoderStreamId,\n  DeflateEncoder,\n  TrackingConsent,\n  PublicApi,\n  Duration,\n} from '@datadog/browser-core'\nimport {\n  addTelemetryUsage,\n  isExperimentalFeatureEnabled,\n  ExperimentalFeature,\n  CustomerDataType,\n  assign,\n  createContextManager,\n  deepClone,\n  makePublicApi,\n  monitor,\n  clocksNow,\n  callMonitored,\n  createHandlingStack,\n  checkUser,\n  sanitizeUser,\n  sanitize,\n  createIdentityEncoder,\n  CustomerDataCompressionStatus,\n  createCustomerDataTrackerManager,\n  storeContextManager,\n  displayAlreadyInitializedError,\n  createTrackingConsentState,\n  timeStampToClocks,\n} from '@datadog/browser-core'\nimport type { LifeCycle } from '../domain/lifeCycle'\nimport type { ViewHistory } from '../domain/contexts/viewHistory'\nimport type { RumSessionManager } from '../domain/rumSessionManager'\nimport type { ReplayStats } from '../rawRumEvent.types'\nimport { ActionType, VitalType } from '../rawRumEvent.types'\nimport type { RumConfiguration, RumInitConfiguration } from '../domain/configuration'\nimport type { ViewOptions } from '../domain/view/trackViews'\nimport { buildCommonContext } from '../domain/contexts/commonContext'\nimport type { InternalContext } from '../domain/contexts/internalContext'\nimport type { DurationVitalReference } from '../domain/vital/vitalCollection'\nimport { createCustomVitalsState } from '../domain/vital/vitalCollection'\nimport { createPreStartStrategy } from './preStartRum'\nimport type { StartRum, StartRumResult } from './startRum'\n\nexport interface StartRecordingOptions {\n  force: boolean\n}\nexport interface RumPublicApi extends PublicApi {\n  /**\n   * Init the RUM browser SDK.\n   * @param initConfiguration Configuration options of the SDK\n   *\n   * See [RUM Browser Monitoring Setup](https://docs.datadoghq.com/real_user_monitoring/browser) for further information.\n   */\n  init: (initConfiguration: RumInitConfiguration) => void\n\n  /**\n   * Set the tracking consent of the current user.\n   *\n   * @param {\"granted\" | \"not-granted\"} trackingConsent The user tracking consent\n   *\n   * Data will be sent only if it is set to \"granted\". This value won't be stored by the library\n   * across page loads: you will need to call this method or set the appropriate `trackingConsent`\n   * field in the init() method at each page load.\n   *\n   * If this method is called before the init() method, the provided value will take precedence\n   * over the one provided as initialization parameter.\n   *\n   * See [User tracking consent](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#user-tracking-consent) for further information.\n   */\n  setTrackingConsent: (trackingConsent: TrackingConsent) => void\n\n  /**\n   * Set View Context.\n   *\n   * Enable to manually set the context of the current view.\n   * @param context context of the view\n   */\n  setViewContext: (context: Context) => void\n  /**\n   * Set View Context Property.\n   *\n   * Enable to manually set a property of the context of the current view.\n   * @param key key of the property\n   * @param value value of the property\n   */\n  setViewContextProperty: (key: string, value: any) => void\n  /**\n   * Set the global context information to all events, stored in `@context`\n   *\n   * @param context Global context\n   *\n   * See [Global context](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#global-context) for further information.\n   */\n  setGlobalContext: (context: any) => void\n\n  /**\n   * Get the global Context\n   *\n   * See [Global context](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#global-context) for further information.\n   */\n  getGlobalContext: () => Context\n\n  /**\n   * Set or update a global context property, stored in `@context.<key>`\n   *\n   * @param key Key of the property\n   * @param property Value of the property\n   *\n   * See [Global context](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#global-context) for further information.\n   */\n  setGlobalContextProperty: (key: any, value: any) => void\n\n  /**\n   * Remove a global context property\n   *\n   * See [Global context](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#global-context) for further information.\n   */\n  removeGlobalContextProperty: (key: any) => void\n\n  /**\n   * Clear the global context\n   *\n   * See [Global context](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#global-context) for further information.\n   */\n  clearGlobalContext: () => void\n\n  /**\n   * [Internal API] Get the internal SDK context\n   */\n  getInternalContext: (startTime?: number) => InternalContext | undefined\n\n  /**\n   * Get the init configuration\n   */\n  getInitConfiguration: () => RumInitConfiguration | undefined\n\n  /**\n   * Add a custom action, stored in `@action`\n   * @param name Name of the action\n   * @param context Context of the action\n   *\n   * See [Send RUM Custom Actions](https://docs.datadoghq.com/real_user_monitoring/guide/send-rum-custom-actions) for further information.\n   */\n  addAction: (name: string, context?: object) => void\n\n  /**\n   * Add a custom error, stored in `@error`.\n   * @param error Error. Favor sending a [Javascript Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) to have a stack trace attached to the error event.\n   * @param context Context of the error\n   *\n   * See [Send RUM Custom Actions](https://docs.datadoghq.com/real_user_monitoring/guide/send-rum-custom-actions) for further information.\n   */\n  addError: (error: unknown, context?: object) => void\n\n  /**\n   * Add a custom timing relative to the start of the current view,\n   * stored in `@view.custom_timings.<timing_name>`\n   *\n   * @param name Name of the custom timing\n   * @param [time] Epoch timestamp of the custom timing (if not set, will use current time)\n   *\n   * Note: passing a relative time is discouraged since it is actually used as-is but displayed relative to the view start.\n   * We currently don't provide a way to retrieve the view start time, so it can be challenging to provide a timing relative to the view start.\n   * see https://github.com/DataDog/browser-sdk/issues/2552\n   */\n  addTiming: (name: string, time?: number) => void\n\n  /**\n   * Set user information to all events, stored in `@usr`\n   *\n   * See [User session](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#user-session) for further information.\n   */\n  setUser: (newUser: User) => void\n\n  /**\n   * Get user information\n   *\n   * See [User session](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#user-session) for further information.\n   */\n  getUser: () => Context\n\n  /**\n   * Set or update the user property, stored in `@usr.<key>`\n   *\n   * @param key Key of the property\n   * @param property Value of the property\n   *\n   * See [User session](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#user-session) for further information.\n   */\n  setUserProperty: (key: any, property: any) => void\n\n  /**\n   * Remove a user property\n   *\n   * See [User session](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#user-session) for further information.\n   */\n  removeUserProperty: (key: any) => void\n\n  /**\n   * Clear all user information\n   *\n   * See [User session](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#user-session) for further information.\n   */\n  clearUser: () => void\n\n  /**\n   * Start a view manually.\n   * Enable to manual start a view, use `trackViewManually: true` init parameter and call `startView()` to create RUM views and be aligned with how you’ve defined them in your SPA application routing.\n   *\n   * @param options.name name of the view\n   * @param options.service service of the view\n   * @param options.version version of the view\n   *\n   * See [Override default RUM view names](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#override-default-rum-view-names) for further information.\n   */\n  startView: {\n    (name?: string): void\n    (options: ViewOptions): void\n  }\n\n  /**\n   * Stop the session. A new session will start at the next user interaction with the page.\n   */\n  stopSession: () => void\n\n  /**\n   * Add a feature flag evaluation,\n   * stored in `@feature_flags.<feature_flag_key>`\n   *\n   * @param {string} key The key of the feature flag.\n   * @param {any} value The value of the feature flag.\n   *\n   * We recommend enabling the intake request compression when using feature flags `compressIntakeRequests: true`.\n   *\n   * See [Feature Flag Tracking](https://docs.datadoghq.com/real_user_monitoring/feature_flag_tracking/) for further information.\n   */\n  addFeatureFlagEvaluation: (key: string, value: any) => void\n\n  /**\n   * Get the Session Replay Link.\n   *\n   * See [Connect Session Replay To Your Third-Party Tools](https://docs.datadoghq.com/real_user_monitoring/guide/connect-session-replay-to-your-third-party-tools) for further information.\n   */\n  getSessionReplayLink: () => string | undefined\n\n  /**\n   * Start Session Replay recording.\n   * Enable to conditionally start the recording, use the `startSessionReplayRecordingManually:true` init parameter and call `startSessionReplayRecording()`\n   *\n   * See [Browser Session Replay](https://docs.datadoghq.com/real_user_monitoring/session_replay/browser) for further information.\n   */\n  startSessionReplayRecording: (options?: StartRecordingOptions) => void\n\n  /**\n   * Stop Session Replay recording.\n   *\n   * See [Browser Session Replay](https://docs.datadoghq.com/real_user_monitoring/session_replay/browser) for further information.\n   */\n  stopSessionReplayRecording: () => void\n\n  /**\n   * Add a custom duration vital\n   *\n   * @param name name of the custom vital\n   * @param options.startTime epoch timestamp of the start of the custom vital\n   * @param options.duration duration of the custom vital in millisecond\n   * @param options.context custom context attached to the vital\n   * @param options.description  Description of the vital\n   */\n  addDurationVital: (\n    name: string,\n    options: { startTime: number; duration: number; context?: object; description?: string }\n  ) => void\n\n  /**\n   * Start a custom duration vital.\n   *\n   * If you plan to have multiple durations for the same vital, you should use the reference returned by this method.\n   *\n   * @param name name of the custom vital\n   * @param options.context custom context attached to the vital\n   * @param options.description Description of the vital\n   * @returns reference to the custom vital\n   */\n  startDurationVital: (name: string, options?: { context?: object; description?: string }) => DurationVitalReference\n\n  /**\n   * Stop a custom duration vital\n   *\n   * @param nameOrRef name of the custom vital or the reference to it\n   * @param options.context custom context attached to the vital\n   * @param options.description Description of the vital\n   */\n  stopDurationVital: (\n    nameOrRef: string | DurationVitalReference,\n    options?: { context?: object; description?: string }\n  ) => void\n}\n\nexport interface RecorderApi {\n  start: (options?: StartRecordingOptions) => void\n  stop: () => void\n  onRumStart: (\n    lifeCycle: LifeCycle,\n    configuration: RumConfiguration,\n    sessionManager: RumSessionManager,\n    viewHistory: ViewHistory,\n    deflateWorker: DeflateWorker | undefined\n  ) => void\n  isRecording: () => boolean\n  getReplayStats: (viewId: string) => ReplayStats | undefined\n  getSessionReplayLink: () => string | undefined\n}\n\nexport interface RumPublicApiOptions {\n  ignoreInitIfSyntheticsWillInjectRum?: boolean\n  startDeflateWorker?: (\n    configuration: RumConfiguration,\n    source: string,\n    onInitializationFailure: () => void\n  ) => DeflateWorker | undefined\n  createDeflateEncoder?: (\n    configuration: RumConfiguration,\n    worker: DeflateWorker,\n    streamId: DeflateEncoderStreamId\n  ) => DeflateEncoder\n}\n\nconst RUM_STORAGE_KEY = 'rum'\n\nexport interface Strategy {\n  init: (initConfiguration: RumInitConfiguration, publicApi: RumPublicApi) => void\n  initConfiguration: RumInitConfiguration | undefined\n  getInternalContext: StartRumResult['getInternalContext']\n  stopSession: StartRumResult['stopSession']\n  addTiming: StartRumResult['addTiming']\n  startView: StartRumResult['startView']\n  updateViewName: StartRumResult['updateViewName']\n  setViewContext: StartRumResult['setViewContext']\n  setViewContextProperty: StartRumResult['setViewContextProperty']\n  addAction: StartRumResult['addAction']\n  addError: StartRumResult['addError']\n  addFeatureFlagEvaluation: StartRumResult['addFeatureFlagEvaluation']\n  startDurationVital: StartRumResult['startDurationVital']\n  stopDurationVital: StartRumResult['stopDurationVital']\n  addDurationVital: StartRumResult['addDurationVital']\n}\n\nexport function makeRumPublicApi(\n  startRumImpl: StartRum,\n  recorderApi: RecorderApi,\n  options: RumPublicApiOptions = {}\n): RumPublicApi {\n  const customerDataTrackerManager = createCustomerDataTrackerManager(CustomerDataCompressionStatus.Unknown)\n  const globalContextManager = createContextManager(\n    customerDataTrackerManager.getOrCreateTracker(CustomerDataType.GlobalContext)\n  )\n  const userContextManager = createContextManager(customerDataTrackerManager.getOrCreateTracker(CustomerDataType.User))\n  const trackingConsentState = createTrackingConsentState()\n  const customVitalsState = createCustomVitalsState()\n\n  function getCommonContext() {\n    return buildCommonContext(globalContextManager, userContextManager, recorderApi)\n  }\n\n  let strategy = createPreStartStrategy(\n    options,\n    getCommonContext,\n    trackingConsentState,\n    customVitalsState,\n    (configuration, deflateWorker, initialViewOptions) => {\n      if (configuration.storeContextsAcrossPages) {\n        storeContextManager(configuration, globalContextManager, RUM_STORAGE_KEY, CustomerDataType.GlobalContext)\n        storeContextManager(configuration, userContextManager, RUM_STORAGE_KEY, CustomerDataType.User)\n      }\n\n      customerDataTrackerManager.setCompressionStatus(\n        deflateWorker ? CustomerDataCompressionStatus.Enabled : CustomerDataCompressionStatus.Disabled\n      )\n\n      const startRumResult = startRumImpl(\n        configuration,\n        recorderApi,\n        customerDataTrackerManager,\n        getCommonContext,\n        initialViewOptions,\n        deflateWorker && options.createDeflateEncoder\n          ? (streamId) => options.createDeflateEncoder!(configuration, deflateWorker, streamId)\n          : createIdentityEncoder,\n        trackingConsentState,\n        customVitalsState\n      )\n\n      recorderApi.onRumStart(\n        startRumResult.lifeCycle,\n        configuration,\n        startRumResult.session,\n        startRumResult.viewHistory,\n        deflateWorker\n      )\n\n      strategy = createPostStartStrategy(strategy, startRumResult)\n\n      return startRumResult\n    }\n  )\n\n  const startView: {\n    (name?: string): void\n    (options: ViewOptions): void\n  } = monitor((options?: string | ViewOptions) => {\n    const sanitizedOptions = typeof options === 'object' ? options : { name: options }\n    if (sanitizedOptions.context) {\n      customerDataTrackerManager.getOrCreateTracker(CustomerDataType.View).updateCustomerData(sanitizedOptions.context)\n    }\n    strategy.startView(sanitizedOptions)\n    addTelemetryUsage({ feature: 'start-view' })\n  })\n\n  const rumPublicApi: RumPublicApi = makePublicApi<RumPublicApi>({\n    init: monitor((initConfiguration) => {\n      strategy.init(initConfiguration, rumPublicApi)\n\n      // Add experimental features here\n      if (isExperimentalFeatureEnabled(ExperimentalFeature.UPDATE_VIEW_NAME)) {\n        /**\n         * Update View Name.\n         *\n         * Enable to manually change the name of the current view.\n         * @param name name of the view\n         * See [Override default RUM view names](https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/#override-default-rum-view-names) for further information.\n         */\n        ;(rumPublicApi as any).updateViewName = monitor((name: string) => {\n          strategy.updateViewName(name)\n        })\n      }\n    }),\n\n    setTrackingConsent: monitor((trackingConsent) => {\n      trackingConsentState.update(trackingConsent)\n      addTelemetryUsage({ feature: 'set-tracking-consent', tracking_consent: trackingConsent })\n    }),\n\n    setViewContext: monitor((context: Context) => {\n      strategy.setViewContext(context)\n    }),\n\n    setViewContextProperty: monitor((key: string, value: any) => {\n      strategy.setViewContextProperty(key, value)\n    }),\n\n    setGlobalContext: monitor((context) => {\n      globalContextManager.setContext(context)\n      addTelemetryUsage({ feature: 'set-global-context' })\n    }),\n\n    getGlobalContext: monitor(() => globalContextManager.getContext()),\n\n    setGlobalContextProperty: monitor((key, value) => {\n      globalContextManager.setContextProperty(key, value)\n      addTelemetryUsage({ feature: 'set-global-context' })\n    }),\n\n    removeGlobalContextProperty: monitor((key) => globalContextManager.removeContextProperty(key)),\n\n    clearGlobalContext: monitor(() => globalContextManager.clearContext()),\n\n    getInternalContext: monitor((startTime) => strategy.getInternalContext(startTime)),\n\n    getInitConfiguration: monitor(() => deepClone(strategy.initConfiguration)),\n\n    addAction: (name, context) => {\n      const handlingStack = createHandlingStack()\n\n      callMonitored(() => {\n        strategy.addAction({\n          name: sanitize(name)!,\n          context: sanitize(context) as Context,\n          startClocks: clocksNow(),\n          type: ActionType.CUSTOM,\n          handlingStack,\n        })\n        addTelemetryUsage({ feature: 'add-action' })\n      })\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) as Context,\n          startClocks: clocksNow(),\n        })\n        addTelemetryUsage({ feature: 'add-error' })\n      })\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 as RelativeTime | TimeStamp | undefined)\n    }),\n\n    setUser: monitor((newUser) => {\n      if (checkUser(newUser)) {\n        userContextManager.setContext(sanitizeUser(newUser as Context))\n      }\n      addTelemetryUsage({ feature: 'set-user' })\n    }),\n\n    getUser: monitor(() => userContextManager.getContext()),\n\n    setUserProperty: monitor((key, property) => {\n      const sanitizedProperty = sanitizeUser({ [key]: property })[key]\n      userContextManager.setContextProperty(key, sanitizedProperty)\n      addTelemetryUsage({ feature: 'set-user' })\n    }),\n\n    removeUserProperty: monitor((key) => userContextManager.removeContextProperty(key)),\n\n    clearUser: monitor(() => userContextManager.clearContext()),\n\n    startView,\n\n    stopSession: monitor(() => {\n      strategy.stopSession()\n      addTelemetryUsage({ feature: 'stop-session' })\n    }),\n\n    addFeatureFlagEvaluation: monitor((key, value) => {\n      strategy.addFeatureFlagEvaluation(sanitize(key)!, sanitize(value))\n      addTelemetryUsage({ feature: 'add-feature-flag-evaluation' })\n    }),\n\n    getSessionReplayLink: monitor(() => recorderApi.getSessionReplayLink()),\n    startSessionReplayRecording: monitor((options?: StartRecordingOptions) => {\n      recorderApi.start(options)\n      addTelemetryUsage({ feature: 'start-session-replay-recording', force: options && options.force })\n    }),\n\n    stopSessionReplayRecording: monitor(() => recorderApi.stop()),\n\n    addDurationVital: monitor((name, options) => {\n      addTelemetryUsage({ feature: 'add-duration-vital' })\n      strategy.addDurationVital({\n        name: sanitize(name)!,\n        type: VitalType.DURATION,\n        startClocks: timeStampToClocks(options.startTime as TimeStamp),\n        duration: options.duration as Duration,\n        context: sanitize(options && options.context) as Context,\n        description: sanitize(options && options.description) as string | undefined,\n      })\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) as Context,\n        description: sanitize(options && options.description) as string | undefined,\n      })\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) as Context,\n        description: sanitize(options && options.description) as string | undefined,\n      })\n    }),\n  })\n\n  return rumPublicApi\n}\n\nfunction createPostStartStrategy(preStartStrategy: Strategy, startRumResult: StartRumResult): Strategy {\n  return assign(\n    {\n      init: (initConfiguration: RumInitConfiguration) => {\n        displayAlreadyInitializedError('DD_RUM', initConfiguration)\n      },\n      initConfiguration: preStartStrategy.initConfiguration,\n    },\n    startRumResult\n  )\n}\n","import type { Context, ContextManager, User } from '@datadog/browser-core'\nimport type { RecorderApi } from '../../boot/rumPublicApi'\n\nexport interface CommonContext {\n  user: User\n  context: Context\n  hasReplay: true | undefined\n}\n\nexport function buildCommonContext(\n  globalContextManager: ContextManager,\n  userContextManager: ContextManager,\n  recorderApi: RecorderApi\n): CommonContext {\n  return {\n    context: globalContextManager.getContext(),\n    user: userContextManager.getContext(),\n    hasReplay: recorderApi.isRecording() ? true : undefined,\n  }\n}\n","import type {\n  Observable,\n  TelemetryEvent,\n  RawError,\n  DeflateEncoderStreamId,\n  Encoder,\n  CustomerDataTrackerManager,\n  TrackingConsentState,\n} from '@datadog/browser-core'\nimport {\n  sendToExtension,\n  createPageExitObservable,\n  TelemetryService,\n  startTelemetry,\n  canUseEventBridge,\n  getEventBridge,\n  addTelemetryDebug,\n  CustomerDataType,\n  drainPreStartTelemetry,\n  isExperimentalFeatureEnabled,\n  ExperimentalFeature,\n} from '@datadog/browser-core'\nimport { createDOMMutationObservable } from '../browser/domMutationObservable'\nimport { startRumAssembly } from '../domain/assembly'\nimport { startInternalContext } from '../domain/contexts/internalContext'\nimport { LifeCycle, LifeCycleEventType } 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 { startLongTaskCollection } from '../domain/longTask/longTaskCollection'\nimport { startResourceCollection } from '../domain/resource/resourceCollection'\nimport { startViewCollection } from '../domain/view/viewCollection'\nimport type { RumSessionManager } from '../domain/rumSessionManager'\nimport { startRumSessionManager, startRumSessionManagerStub } from '../domain/rumSessionManager'\nimport { startRumBatch } from '../transport/startRumBatch'\nimport { startRumEventBridge } from '../transport/startRumEventBridge'\nimport { startUrlContexts } from '../domain/contexts/urlContexts'\nimport type { LocationChange } from '../browser/locationChangeObservable'\nimport { createLocationChangeObservable } from '../browser/locationChangeObservable'\nimport type { RumConfiguration } from '../domain/configuration'\nimport type { ViewOptions } from '../domain/view/trackViews'\nimport { startFeatureFlagContexts } from '../domain/contexts/featureFlagContext'\nimport { startCustomerDataTelemetry } from '../domain/startCustomerDataTelemetry'\nimport type { PageStateHistory } from '../domain/contexts/pageStateHistory'\nimport { startPageStateHistory } from '../domain/contexts/pageStateHistory'\nimport type { CommonContext } from '../domain/contexts/commonContext'\nimport { startDisplayContext } from '../domain/contexts/displayContext'\nimport type { CustomVitalsState } from '../domain/vital/vitalCollection'\nimport { startVitalCollection } from '../domain/vital/vitalCollection'\nimport { startCiVisibilityContext } from '../domain/contexts/ciVisibilityContext'\nimport { startLongAnimationFrameCollection } from '../domain/longAnimationFrame/longAnimationFrameCollection'\nimport type { RecorderApi } from './rumPublicApi'\n\nexport type StartRum = typeof startRum\nexport type StartRumResult = ReturnType<StartRum>\n\nexport function startRum(\n  configuration: RumConfiguration,\n  recorderApi: RecorderApi,\n  customerDataTrackerManager: CustomerDataTrackerManager,\n  getCommonContext: () => CommonContext,\n  initialViewOptions: ViewOptions | undefined,\n  createEncoder: (streamId: DeflateEncoderStreamId) => Encoder,\n\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\".\n  trackingConsentState: TrackingConsentState,\n  customVitalsState: CustomVitalsState\n) {\n  const cleanupTasks: Array<() => void> = []\n  const lifeCycle = new LifeCycle()\n\n  lifeCycle.subscribe(LifeCycleEventType.RUM_EVENT_COLLECTED, (event) => sendToExtension('rum', event))\n\n  const telemetry = startRumTelemetry(configuration)\n  telemetry.setContextProvider(() => ({\n    application: {\n      id: configuration.applicationId,\n    },\n    session: {\n      id: session.findTrackedSession()?.id,\n    },\n    view: {\n      id: viewHistory.findView()?.id,\n    },\n    action: {\n      id: actionContexts.findActionId(),\n    },\n  }))\n\n  const reportError = (error: RawError) => {\n    lifeCycle.notify(LifeCycleEventType.RAW_ERROR_COLLECTED, { error })\n    addTelemetryDebug('Error reported to customer', { 'error.message': error.message })\n  }\n  const featureFlagContexts = startFeatureFlagContexts(\n    lifeCycle,\n    customerDataTrackerManager.getOrCreateTracker(CustomerDataType.FeatureFlag)\n  )\n\n  const pageExitObservable = createPageExitObservable(configuration)\n  const pageExitSubscription = pageExitObservable.subscribe((event) => {\n    lifeCycle.notify(LifeCycleEventType.PAGE_EXITED, event)\n  })\n  cleanupTasks.push(() => pageExitSubscription.unsubscribe())\n\n  const session = !canUseEventBridge()\n    ? startRumSessionManager(configuration, lifeCycle, trackingConsentState)\n    : startRumSessionManagerStub()\n  if (!canUseEventBridge()) {\n    const batch = startRumBatch(\n      configuration,\n      lifeCycle,\n      telemetry.observable,\n      reportError,\n      pageExitObservable,\n      session.expireObservable,\n      createEncoder\n    )\n    cleanupTasks.push(() => batch.stop())\n    startCustomerDataTelemetry(configuration, telemetry, lifeCycle, customerDataTrackerManager, batch.flushObservable)\n  } else {\n    startRumEventBridge(lifeCycle)\n  }\n\n  const domMutationObservable = createDOMMutationObservable()\n  const locationChangeObservable = createLocationChangeObservable(configuration, location)\n  const pageStateHistory = startPageStateHistory(configuration)\n  const {\n    viewHistory,\n    urlContexts,\n    actionContexts,\n    addAction,\n    stop: stopRumEventCollection,\n  } = startRumEventCollection(\n    lifeCycle,\n    configuration,\n    location,\n    session,\n    pageStateHistory,\n    locationChangeObservable,\n    domMutationObservable,\n    getCommonContext,\n    reportError\n  )\n  cleanupTasks.push(stopRumEventCollection)\n\n  drainPreStartTelemetry()\n\n  const {\n    addTiming,\n    startView,\n    updateViewName,\n    setViewContext,\n    setViewContextProperty,\n    stop: stopViewCollection,\n  } = startViewCollection(\n    lifeCycle,\n    configuration,\n    location,\n    domMutationObservable,\n    locationChangeObservable,\n    featureFlagContexts,\n    pageStateHistory,\n    recorderApi,\n    initialViewOptions\n  )\n  cleanupTasks.push(stopViewCollection)\n\n  const { stop: stopResourceCollection } = startResourceCollection(lifeCycle, configuration, pageStateHistory)\n  cleanupTasks.push(stopResourceCollection)\n\n  if (isExperimentalFeatureEnabled(ExperimentalFeature.LONG_ANIMATION_FRAME)) {\n    if (configuration.trackLongTasks) {\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, featureFlagContexts)\n\n  startRequestCollection(lifeCycle, configuration, session)\n\n  const vitalCollection = startVitalCollection(lifeCycle, pageStateHistory, customVitalsState)\n  const internalContext = startInternalContext(\n    configuration.applicationId,\n    session,\n    viewHistory,\n    actionContexts,\n    urlContexts\n  )\n\n  return {\n    addAction,\n    addError,\n    addTiming,\n    addFeatureFlagEvaluation: featureFlagContexts.addFeatureFlagEvaluation,\n    startView,\n    setViewContext,\n    setViewContextProperty,\n    updateViewName,\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}\n\nfunction startRumTelemetry(configuration: RumConfiguration) {\n  const telemetry = startTelemetry(TelemetryService.RUM, configuration)\n  if (canUseEventBridge()) {\n    const bridge = getEventBridge<'internal_telemetry', TelemetryEvent>()!\n    telemetry.observable.subscribe((event) => bridge.send('internal_telemetry', event))\n  }\n  return telemetry\n}\n\nexport function startRumEventCollection(\n  lifeCycle: LifeCycle,\n  configuration: RumConfiguration,\n  location: Location,\n  sessionManager: RumSessionManager,\n  pageStateHistory: PageStateHistory,\n  locationChangeObservable: Observable<LocationChange>,\n  domMutationObservable: Observable<void>,\n  getCommonContext: () => CommonContext,\n  reportError: (error: RawError) => void\n) {\n  const viewHistory = startViewHistory(lifeCycle)\n  const urlContexts = startUrlContexts(lifeCycle, locationChangeObservable, location)\n\n  const { addAction, actionContexts } = startActionCollection(\n    lifeCycle,\n    domMutationObservable,\n    configuration,\n    pageStateHistory\n  )\n\n  const displayContext = startDisplayContext(configuration)\n  const ciVisibilityContext = startCiVisibilityContext(configuration)\n\n  startRumAssembly(\n    configuration,\n    lifeCycle,\n    sessionManager,\n    viewHistory,\n    urlContexts,\n    actionContexts,\n    displayContext,\n    ciVisibilityContext,\n    getCommonContext,\n    reportError\n  )\n\n  return {\n    viewHistory,\n    pageStateHistory,\n    urlContexts,\n    addAction,\n    actionContexts,\n    stop: () => {\n      ciVisibilityContext.stop()\n      displayContext.stop()\n      urlContexts.stop()\n      viewHistory.stop()\n      pageStateHistory.stop()\n    },\n  }\n}\n","import type { Context } from '@datadog/browser-core'\nimport { getEventBridge } from '@datadog/browser-core'\nimport type { LifeCycle } from '../domain/lifeCycle'\nimport { LifeCycleEventType } from '../domain/lifeCycle'\nimport type { RumEvent } from '../rumEvent.types'\n\nexport function startRumEventBridge(lifeCycle: LifeCycle) {\n  const bridge = getEventBridge<'rum', RumEvent>()!\n\n  lifeCycle.subscribe(LifeCycleEventType.RUM_EVENT_COLLECTED, (serverRumEvent: RumEvent & Context) => {\n    bridge.send('rum', serverRumEvent)\n  })\n}\n","import type { Context, TelemetryEvent, Observable, RawError, PageExitEvent, Encoder } from '@datadog/browser-core'\nimport {\n  DeflateEncoderStreamId,\n  combine,\n  isTelemetryReplicationAllowed,\n  startBatchWithReplica,\n} from '@datadog/browser-core'\nimport type { RumConfiguration } from '../domain/configuration'\nimport type { LifeCycle } from '../domain/lifeCycle'\nimport { LifeCycleEventType } from '../domain/lifeCycle'\nimport { RumEventType } from '../rawRumEvent.types'\nimport type { RumEvent } from '../rumEvent.types'\n\nexport function startRumBatch(\n  configuration: RumConfiguration,\n  lifeCycle: LifeCycle,\n  telemetryEventObservable: Observable<TelemetryEvent & Context>,\n  reportError: (error: RawError) => void,\n  pageExitObservable: Observable<PageExitEvent>,\n  sessionExpireObservable: Observable<void>,\n  createEncoder: (streamId: DeflateEncoderStreamId) => Encoder\n) {\n  const replica = configuration.replica\n\n  const batch = startBatchWithReplica(\n    configuration,\n    {\n      endpoint: configuration.rumEndpointBuilder,\n      encoder: createEncoder(DeflateEncoderStreamId.RUM),\n    },\n    replica && {\n      endpoint: replica.rumEndpointBuilder,\n      transformMessage: (message) => combine(message, { application: { id: replica.applicationId } }),\n      encoder: createEncoder(DeflateEncoderStreamId.RUM_REPLICA),\n    },\n    reportError,\n    pageExitObservable,\n    sessionExpireObservable\n  )\n\n  lifeCycle.subscribe(LifeCycleEventType.RUM_EVENT_COLLECTED, (serverRumEvent: RumEvent & Context) => {\n    if (serverRumEvent.type === RumEventType.VIEW) {\n      batch.upsert(serverRumEvent, serverRumEvent.view.id)\n    } else {\n      batch.add(serverRumEvent)\n    }\n  })\n\n  telemetryEventObservable.subscribe((event) => batch.add(event, isTelemetryReplicationAllowed(configuration)))\n\n  return batch\n}\n","import type { Configuration, EndpointBuilder } from '../domain/configuration'\nimport type { Context } from '../tools/serialisation/context'\nimport type { Observable } from '../tools/observable'\nimport type { PageExitEvent } from '../browser/pageExitObservable'\nimport type { RawError } from '../domain/error/error.types'\nimport type { Encoder } from '../tools/encoder'\nimport { createBatch } from './batch'\nimport { createHttpRequest } from './httpRequest'\nimport { createFlushController } from './flushController'\n\nexport interface BatchConfiguration {\n  endpoint: EndpointBuilder\n  encoder: Encoder\n}\n\ninterface ReplicaBatchConfiguration<T> extends BatchConfiguration {\n  transformMessage?: (message: T) => T\n}\n\nexport function startBatchWithReplica<T extends Context>(\n  configuration: Configuration,\n  primary: BatchConfiguration,\n  replica: ReplicaBatchConfiguration<T> | undefined,\n  reportError: (error: RawError) => void,\n  pageExitObservable: Observable<PageExitEvent>,\n  sessionExpireObservable: Observable<void>,\n  batchFactoryImp = createBatch\n) {\n  const primaryBatch = createBatchFromConfig(configuration, primary)\n  const replicaBatch = replica && createBatchFromConfig(configuration, replica)\n\n  function createBatchFromConfig(configuration: Configuration, { endpoint, encoder }: BatchConfiguration) {\n    return batchFactoryImp({\n      encoder,\n      request: createHttpRequest(configuration, 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\n  return {\n    flushObservable: primaryBatch.flushController.flushObservable,\n\n    add(message: T, replicated = true) {\n      primaryBatch.add(message)\n      if (replicaBatch && replicated) {\n        replicaBatch.add(replica.transformMessage ? replica.transformMessage(message) : message)\n      }\n    },\n\n    upsert: (message: T, key: string) => {\n      primaryBatch.upsert(message, key)\n      if (replicaBatch) {\n        replicaBatch.upsert(replica.transformMessage ? replica.transformMessage(message) : message, key)\n      }\n    },\n\n    stop: () => {\n      primaryBatch.stop()\n      if (replicaBatch) {\n        replicaBatch.stop()\n      }\n    },\n  }\n}\n","import type { RumConfiguration } from '../configuration'\nimport { getViewportDimension, initViewportObservable } from '../../browser/viewportObservable'\n\nexport type DisplayContext = ReturnType<typeof startDisplayContext>\n\nexport function startDisplayContext(configuration: RumConfiguration) {\n  let viewport = getViewportDimension()\n  const unsubscribeViewport = initViewportObservable(configuration).subscribe((viewportDimension) => {\n    viewport = viewportDimension\n  }).unsubscribe\n\n  return {\n    get: () => ({ viewport }),\n    stop: unsubscribeViewport,\n  }\n}\n","import { toServerDuration, relativeToClocks, generateUUID } from '@datadog/browser-core'\nimport type { RawRumLongAnimationFrameEvent } from '../../rawRumEvent.types'\nimport { RumEventType, RumLongTaskEntryType } from '../../rawRumEvent.types'\nimport type { LifeCycle } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../../browser/performanceObservable'\nimport type { RumConfiguration } from '../configuration'\n\nexport function startLongAnimationFrameCollection(lifeCycle: LifeCycle, configuration: RumConfiguration) {\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\n      const rawRumEvent: RawRumLongAnimationFrameEvent = {\n        date: startClocks.timeStamp,\n        long_task: {\n          id: generateUUID(),\n          entry_type: 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: RumEventType.LONG_TASK,\n        _dd: {\n          discarded: false,\n        },\n      }\n\n      lifeCycle.notify(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, {\n        rawRumEvent,\n        startTime: startClocks.relative,\n        domainContext: { performanceEntry: entry },\n      })\n    }\n  })\n\n  return {\n    stop: () => performanceResourceSubscription.unsubscribe(),\n  }\n}\n","import { toServerDuration, relativeToClocks, generateUUID } from '@datadog/browser-core'\nimport type { RawRumLongTaskEvent } from '../../rawRumEvent.types'\nimport { RumEventType, RumLongTaskEntryType } from '../../rawRumEvent.types'\nimport type { LifeCycle } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../../browser/performanceObservable'\nimport type { RumConfiguration } from '../configuration'\nexport function startLongTaskCollection(lifeCycle: LifeCycle, configuration: RumConfiguration) {\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: RawRumLongTaskEvent = {\n        date: startClocks.timeStamp,\n        long_task: {\n          id: generateUUID(),\n          entry_type: RumLongTaskEntryType.LONG_TASK,\n          duration: toServerDuration(entry.duration),\n        },\n        type: RumEventType.LONG_TASK,\n        _dd: {\n          discarded: false,\n        },\n      }\n      lifeCycle.notify(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, {\n        rawRumEvent,\n        startTime: startClocks.relative,\n        domainContext: { performanceEntry: entry },\n      })\n    }\n  })\n\n  return {\n    stop() {\n      performanceLongTaskSubscription.unsubscribe()\n    },\n  }\n}\n","import type { RelativeTime } from '@datadog/browser-core'\nimport type { ActionContexts } from '../action/actionCollection'\nimport type { RumSessionManager } from '../rumSessionManager'\nimport type { ViewHistory } from './viewHistory'\nimport type { UrlContexts } from './urlContexts'\n\nexport interface InternalContext {\n  application_id: string\n  session_id: string | undefined\n  view?: {\n    id: string\n    url: string\n    referrer: string\n    name?: string\n  }\n  user_action?: {\n    id: string | string[]\n  }\n}\n\n/**\n * Internal context keep returning v1 format\n * to not break compatibility with logs data format\n */\nexport function startInternalContext(\n  applicationId: string,\n  sessionManager: RumSessionManager,\n  viewHistory: ViewHistory,\n  actionContexts: ActionContexts,\n  urlContexts: UrlContexts\n) {\n  return {\n    get: (startTime?: number): InternalContext | undefined => {\n      const viewContext = viewHistory.findView(startTime as RelativeTime)\n      const urlContext = urlContexts.findUrl(startTime as RelativeTime)\n      const session = sessionManager.findTrackedSession(startTime as RelativeTime)\n      if (session && viewContext && urlContext) {\n        const actionId = actionContexts.findActionId(startTime as RelativeTime)\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","var moduleMap = {\n\t\"./adobe\": () => {\n\t\treturn __webpack_require__.e(6814).then(() => (() => ((__webpack_require__(16814)))));\n\t},\n\t\"./auth\": () => {\n\t\treturn Promise.all([__webpack_require__.e(3122), __webpack_require__.e(7000), __webpack_require__.e(8812), __webpack_require__.e(8412), __webpack_require__.e(5850), __webpack_require__.e(8019), __webpack_require__.e(85), __webpack_require__.e(1849), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(5929), __webpack_require__.e(4118), __webpack_require__.e(2019), __webpack_require__.e(9309), __webpack_require__.e(9925), __webpack_require__.e(1422), __webpack_require__.e(7431), __webpack_require__.e(5459), __webpack_require__.e(1740), __webpack_require__.e(1644)]).then(() => (() => ((__webpack_require__(1644)))));\n\t},\n\t\"./config\": () => {\n\t\treturn Promise.all([__webpack_require__.e(1527), __webpack_require__.e(2019), __webpack_require__.e(9925), __webpack_require__.e(7276)]).then(() => (() => ((__webpack_require__(47276)))));\n\t},\n\t\"./dialog\": () => {\n\t\treturn Promise.all([__webpack_require__.e(3122), __webpack_require__.e(7000), __webpack_require__.e(8812), __webpack_require__.e(8412), __webpack_require__.e(5850), __webpack_require__.e(8019), __webpack_require__.e(85), __webpack_require__.e(1849), __webpack_require__.e(4871), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(5929), __webpack_require__.e(4118), __webpack_require__.e(2019), __webpack_require__.e(9309), __webpack_require__.e(9925), __webpack_require__.e(1422), __webpack_require__.e(7431), __webpack_require__.e(5459), __webpack_require__.e(1740), __webpack_require__.e(1644), __webpack_require__.e(4256), __webpack_require__.e(7162), __webpack_require__.e(2847)]).then(() => (() => ((__webpack_require__(97162)))));\n\t},\n\t\"./logout\": () => {\n\t\treturn Promise.all([__webpack_require__.e(3122), __webpack_require__.e(7000), __webpack_require__.e(8812), __webpack_require__.e(8412), __webpack_require__.e(5850), __webpack_require__.e(8019), __webpack_require__.e(85), __webpack_require__.e(1849), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(5929), __webpack_require__.e(4118), __webpack_require__.e(2019), __webpack_require__.e(9309), __webpack_require__.e(9925), __webpack_require__.e(1422), __webpack_require__.e(7431), __webpack_require__.e(5459), __webpack_require__.e(1740), __webpack_require__.e(1644), __webpack_require__.e(1988)]).then(() => (() => ((__webpack_require__(51988)))));\n\t},\n\t\"./content\": () => {\n\t\treturn Promise.all([__webpack_require__.e(3122), __webpack_require__.e(7000), __webpack_require__.e(8812), __webpack_require__.e(8412), __webpack_require__.e(8019), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(4118), __webpack_require__.e(2019), __webpack_require__.e(9309), __webpack_require__.e(9925), __webpack_require__.e(1422), __webpack_require__.e(7431), __webpack_require__.e(1740), __webpack_require__.e(1072)]).then(() => (() => ((__webpack_require__(20559)))));\n\t},\n\t\"./mf-tester\": () => {\n\t\treturn Promise.all([__webpack_require__.e(3122), __webpack_require__.e(7000), __webpack_require__.e(8812), __webpack_require__.e(8412), __webpack_require__.e(5850), __webpack_require__.e(8019), __webpack_require__.e(85), __webpack_require__.e(1849), __webpack_require__.e(4871), __webpack_require__.e(456), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(5929), __webpack_require__.e(4118), __webpack_require__.e(2019), __webpack_require__.e(9309), __webpack_require__.e(9925), __webpack_require__.e(1422), __webpack_require__.e(7431), __webpack_require__.e(5459), __webpack_require__.e(1740), __webpack_require__.e(1644), __webpack_require__.e(4256), __webpack_require__.e(7162), __webpack_require__.e(708)]).then(() => (() => ((__webpack_require__(30708)))));\n\t},\n\t\"./provider\": () => {\n\t\treturn Promise.all([__webpack_require__.e(3122), __webpack_require__.e(7000), __webpack_require__.e(8812), __webpack_require__.e(8412), __webpack_require__.e(5850), __webpack_require__.e(8019), __webpack_require__.e(85), __webpack_require__.e(1849), __webpack_require__.e(4871), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(5929), __webpack_require__.e(4118), __webpack_require__.e(2019), __webpack_require__.e(9309), __webpack_require__.e(9925), __webpack_require__.e(1422), __webpack_require__.e(7431), __webpack_require__.e(5459), __webpack_require__.e(1740), __webpack_require__.e(1644), __webpack_require__.e(4256), __webpack_require__.e(3823)]).then(() => (() => ((__webpack_require__(83823)))));\n\t},\n\t\"./query\": () => {\n\t\treturn Promise.all([__webpack_require__.e(8812), __webpack_require__.e(8019), __webpack_require__.e(1527), __webpack_require__.e(2019), __webpack_require__.e(9925), __webpack_require__.e(1422), __webpack_require__.e(7431)]).then(() => (() => ((__webpack_require__(93282)))));\n\t},\n\t\"./routing\": () => {\n\t\treturn Promise.all([__webpack_require__.e(3122), __webpack_require__.e(7000), __webpack_require__.e(8812), __webpack_require__.e(8412), __webpack_require__.e(5850), __webpack_require__.e(8019), __webpack_require__.e(85), __webpack_require__.e(1849), __webpack_require__.e(4871), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(5929), __webpack_require__.e(4118), __webpack_require__.e(2019), __webpack_require__.e(9309), __webpack_require__.e(9925), __webpack_require__.e(1422), __webpack_require__.e(7431), __webpack_require__.e(5459), __webpack_require__.e(1740), __webpack_require__.e(1644), __webpack_require__.e(9059)]).then(() => (() => ((__webpack_require__(99059)))));\n\t},\n\t\"./state\": () => {\n\t\treturn Promise.all([__webpack_require__.e(5459), __webpack_require__.e(8011)]).then(() => (() => ((__webpack_require__(98011)))));\n\t},\n\t\"./widget\": () => {\n\t\treturn Promise.all([__webpack_require__.e(1527), __webpack_require__.e(5113)]).then(() => (() => ((__webpack_require__(65113)))));\n\t},\n\t\"./feature-flag\": () => {\n\t\treturn Promise.all([__webpack_require__.e(8812), __webpack_require__.e(8019), __webpack_require__.e(1527), __webpack_require__.e(2019), __webpack_require__.e(9925), __webpack_require__.e(1422), __webpack_require__.e(7431), __webpack_require__.e(133)]).then(() => (() => ((__webpack_require__(30133)))));\n\t}\n};\nvar get = (module, getScope) => {\n\t__webpack_require__.R = getScope;\n\tgetScope = (\n\t\t__webpack_require__.o(moduleMap, module)\n\t\t\t? moduleMap[module]()\n\t\t\t: Promise.resolve().then(() => {\n\t\t\t\tthrow new Error('Module \"' + module + '\" does not exist in container.');\n\t\t\t})\n\t);\n\t__webpack_require__.R = undefined;\n\treturn getScope;\n};\nvar init = (shareScope, initScope) => {\n\tif (!__webpack_require__.S) return;\n\tvar name = \"default\"\n\tvar oldScope = __webpack_require__.S[name];\n\tif(oldScope && oldScope !== shareScope) throw new Error(\"Container initialization failed as it has already been initialized with a different share scope\");\n\t__webpack_require__.S[name] = shareScope;\n\treturn __webpack_require__.I(name, initScope);\n};\n\n// This exports getters to disallow modifications\n__webpack_require__.d(exports, {\n\tget: () => (get),\n\tinit: () => (init)\n});","// 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\tid: moduleId,\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n// expose the module cache\n__webpack_require__.c = __webpack_module_cache__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\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__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"static/js/\" + chunkId + \".\" + {\"85\":\"9da8f9a9\",\"133\":\"d0eb9dbc\",\"300\":\"18e23a0d\",\"360\":\"4dab196f\",\"394\":\"383c64ad\",\"456\":\"33133832\",\"708\":\"e0345c31\",\"900\":\"cef8852a\",\"1072\":\"d17eff4b\",\"1342\":\"7bff409c\",\"1422\":\"902e9cfb\",\"1527\":\"5c2de637\",\"1534\":\"2b49295b\",\"1644\":\"a7b50c57\",\"1740\":\"6fb6555e\",\"1844\":\"79ba2692\",\"1849\":\"3b01f745\",\"1874\":\"dd34de15\",\"1988\":\"3e38934a\",\"2019\":\"c0f85ab0\",\"2031\":\"6ae35126\",\"2197\":\"e26f6894\",\"2483\":\"54f25233\",\"2503\":\"ba81b7c2\",\"2661\":\"6422912b\",\"2780\":\"e25396eb\",\"2847\":\"a60d5737\",\"2960\":\"b30e19a8\",\"3122\":\"3cc59559\",\"3487\":\"3ecef672\",\"3489\":\"2af78515\",\"3610\":\"59dd96aa\",\"3823\":\"01178be4\",\"4118\":\"bd317fe5\",\"4180\":\"29c77df1\",\"4243\":\"ed2af5cb\",\"4245\":\"6ff19012\",\"4256\":\"bc709e99\",\"4433\":\"94645f55\",\"4578\":\"6f6f949f\",\"4687\":\"97a98eb1\",\"4825\":\"ead96449\",\"4871\":\"78da67ee\",\"4922\":\"76d10d17\",\"5037\":\"57169486\",\"5113\":\"684f914a\",\"5459\":\"b8579134\",\"5531\":\"45fa570b\",\"5563\":\"bd45d97e\",\"5720\":\"869ad7fa\",\"5836\":\"54bbc40c\",\"5843\":\"d1848d61\",\"5850\":\"f08ab430\",\"5870\":\"119b3833\",\"5929\":\"c969ee85\",\"6146\":\"cdc56be6\",\"6311\":\"69f39a63\",\"6624\":\"ffb4b5c1\",\"6814\":\"7ee32e19\",\"7000\":\"9ea6beac\",\"7006\":\"89ce94a3\",\"7162\":\"d854b3fd\",\"7276\":\"3c8f4017\",\"7431\":\"d86bc67f\",\"7810\":\"273dbfcb\",\"8011\":\"d5dc88ce\",\"8019\":\"8f75fc6b\",\"8177\":\"24a5ef9b\",\"8412\":\"1547da52\",\"8598\":\"ee04498d\",\"8689\":\"8f5e25f5\",\"8771\":\"2021614a\",\"8812\":\"edd48c89\",\"9059\":\"2dd34e8f\",\"9303\":\"b2d16914\",\"9309\":\"d8152fee\",\"9925\":\"4916b931\"}[chunkId] + \".chunk.js\";\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\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};","__webpack_require__.S = {};\nvar initPromises = {};\nvar initTokens = {};\n__webpack_require__.I = (name, initScope) => {\n\tif(!initScope) initScope = [];\n\t// handling circular init calls\n\tvar initToken = initTokens[name];\n\tif(!initToken) initToken = initTokens[name] = {};\n\tif(initScope.indexOf(initToken) >= 0) return;\n\tinitScope.push(initToken);\n\t// only runs once\n\tif(initPromises[name]) return initPromises[name];\n\t// creates a new share scope if needed\n\tif(!__webpack_require__.o(__webpack_require__.S, name)) __webpack_require__.S[name] = {};\n\t// runs all init snippets from all modules reachable\n\tvar scope = __webpack_require__.S[name];\n\tvar warn = (msg) => {\n\t\tif (typeof console !== \"undefined\" && console.warn) console.warn(msg);\n\t};\n\tvar uniqueName = \"mf_core\";\n\tvar register = (name, version, factory, eager) => {\n\t\tvar versions = scope[name] = scope[name] || {};\n\t\tvar activeVersion = versions[version];\n\t\tif(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager };\n\t};\n\tvar initExternal = (id) => {\n\t\tvar handleError = (err) => (warn(\"Initialization of sharing external failed: \" + err));\n\t\ttry {\n\t\t\tvar module = __webpack_require__(id);\n\t\t\tif(!module) return;\n\t\t\tvar initFn = (module) => (module && module.init && module.init(__webpack_require__.S[name], initScope))\n\t\t\tif(module.then) return promises.push(module.then(initFn, handleError));\n\t\t\tvar initResult = initFn(module);\n\t\t\tif(initResult && initResult.then) return promises.push(initResult['catch'](handleError));\n\t\t} catch(err) { handleError(err); }\n\t}\n\tvar promises = [];\n\tswitch(name) {\n\t\tcase \"default\": {\n\t\t\tregister(\"@datadog/browser-rum\", \"5.29.0\", () => (() => (__webpack_require__(82702))), 1);\n\t\t\tregister(\"@emotion/cache\", \"11.11.0\", () => (__webpack_require__.e(2661).then(() => (() => (__webpack_require__(92661))))));\n\t\t\tregister(\"@emotion/react\", \"11.11.4\", () => (Promise.all([__webpack_require__.e(9303), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(4180)]).then(() => (() => (__webpack_require__(29303))))));\n\t\t\tregister(\"@emotion/styled\", \"11.11.5\", () => (Promise.all([__webpack_require__.e(1527), __webpack_require__.e(1874), __webpack_require__.e(2197)]).then(() => (() => (__webpack_require__(24578))))));\n\t\t\tregister(\"@fullstory/browser\", \"1.7.1\", () => (__webpack_require__.e(4825).then(() => (() => (__webpack_require__(64825))))));\n\t\t\tregister(\"@im/im-theme\", \"2.0.883\", () => (Promise.all([__webpack_require__.e(3122), __webpack_require__.e(7000), __webpack_require__.e(8598), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(4118), __webpack_require__.e(9309), __webpack_require__.e(4433)]).then(() => (() => (__webpack_require__(58598))))));\n\t\t\tregister(\"@im/react-localization\", \"1.0.349\", () => (Promise.all([__webpack_require__.e(3122), __webpack_require__.e(7000), __webpack_require__.e(8412), __webpack_require__.e(5850), __webpack_require__.e(394), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(5929), __webpack_require__.e(4118), __webpack_require__.e(9309), __webpack_require__.e(360), __webpack_require__.e(8177)]).then(() => (() => (__webpack_require__(80394))))));\n\t\t\tregister(\"@mui/system\", \"5.15.15\", () => (Promise.all([__webpack_require__.e(3122), __webpack_require__.e(4245), __webpack_require__.e(1527), __webpack_require__.e(2031), __webpack_require__.e(1874), __webpack_require__.e(4118), __webpack_require__.e(4922)]).then(() => (() => (__webpack_require__(84245))))));\n\t\t\tregister(\"@mui/x-license-pro\", \"6.10.2\", () => (Promise.all([__webpack_require__.e(1527), __webpack_require__.e(6624)]).then(() => (() => (__webpack_require__(14243))))));\n\t\t\tregister(\"@okta/okta-auth-js\", \"7.0.2\", () => (Promise.all([__webpack_require__.e(6146), __webpack_require__.e(5843), __webpack_require__.e(2780)]).then(() => (() => (__webpack_require__(95843))))));\n\t\t\tregister(\"@okta/okta-auth-js\", \"7.4.3\", () => (Promise.all([__webpack_require__.e(6146), __webpack_require__.e(3610), __webpack_require__.e(5870)]).then(() => (() => (__webpack_require__(13610))))));\n\t\t\tregister(\"@okta/okta-react\", \"6.7.0\", () => (Promise.all([__webpack_require__.e(1844), __webpack_require__.e(1527), __webpack_require__.e(5720), __webpack_require__.e(2503)]).then(() => (() => (__webpack_require__(41844))))));\n\t\t\tregister(\"@okta/okta-signin-widget\", \"7.11.2\", () => (Promise.all([__webpack_require__.e(4687), __webpack_require__.e(8771)]).then(() => (() => (__webpack_require__(64687))))));\n\t\t\tregister(\"@tanstack/react-query\", \"5.32.1\", () => (Promise.all([__webpack_require__.e(6311), __webpack_require__.e(1527)]).then(() => (() => (__webpack_require__(86311))))));\n\t\t\tregister(\"date-fns\", \"2.30.0\", () => (Promise.all([__webpack_require__.e(5531), __webpack_require__.e(5037)]).then(() => (() => (__webpack_require__(75531))))));\n\t\t\tregister(\"html-react-parser\", \"5.1.10\", () => (Promise.all([__webpack_require__.e(900), __webpack_require__.e(1527)]).then(() => (() => (__webpack_require__(10900))))));\n\t\t\tregister(\"jwt-decode\", \"3.1.2\", () => (__webpack_require__.e(3487).then(() => (() => (__webpack_require__(43487))))));\n\t\t\tregister(\"react-dom\", \"18.2.0\", () => (Promise.all([__webpack_require__.e(2483), __webpack_require__.e(1527)]).then(() => (() => (__webpack_require__(22483))))));\n\t\t\tregister(\"react-helmet-async\", \"2.0.4\", () => (Promise.all([__webpack_require__.e(300), __webpack_require__.e(1527)]).then(() => (() => (__webpack_require__(70300))))));\n\t\t\tregister(\"react-router-dom\", \"6.22.2\", () => (Promise.all([__webpack_require__.e(1534), __webpack_require__.e(1342), __webpack_require__.e(1527), __webpack_require__.e(5929), __webpack_require__.e(5563)]).then(() => (() => (__webpack_require__(81342))))));\n\t\t\tregister(\"react-router\", \"6.22.2\", () => (Promise.all([__webpack_require__.e(1534), __webpack_require__.e(8689), __webpack_require__.e(1527)]).then(() => (() => (__webpack_require__(28689))))));\n\t\t\tregister(\"react\", \"18.2.0\", () => (__webpack_require__.e(7810).then(() => (() => (__webpack_require__(77810))))));\n\t\t\tregister(\"recoil\", \"0.7.7\", () => (Promise.all([__webpack_require__.e(7006), __webpack_require__.e(1527), __webpack_require__.e(5929)]).then(() => (() => (__webpack_require__(27006))))));\n\t\t\tregister(\"uuid\", \"8.3.2\", () => (__webpack_require__.e(5836).then(() => (() => (__webpack_require__(35836))))));\n\t\t\tregister(\"wretch\", \"1.7.6\", () => (__webpack_require__.e(2960).then(() => (() => (__webpack_require__(12960))))));\n\t\t}\n\t\tbreak;\n\t}\n\tif(!promises.length) return initPromises[name] = 1;\n\treturn initPromises[name] = Promise.all(promises).then(() => (initPromises[name] = 1));\n};","__webpack_require__.p = \"/cep/mf_core/\";","__webpack_require__.b = document.baseURI || self.location.href;\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t556: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(!/^(1(422|527|740|874)|2(019|031|503)|5(459|563|720|929)|360|4118|4256|8177|8771|9309|9925)$/.test(chunkId)) {\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t} else installedChunks[chunkId] = 0;\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkmf_core\"] = self[\"webpackChunkmf_core\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","__webpack_require__.nc = undefined;","// module cache are used so entry inlining is disabled\n// startup\n// Load entry module and return exports\nvar __webpack_exports__ = __webpack_require__(87861);\n"],"names":["inProgress","dataWebpackPrefix","parseVersion","versionLt","rangeToString","satisfy","findSingletonVersionKey","getInvalidSingletonVersionMessage","getSingletonVersion","findValidVersion","warn","get","init","loadSingletonVersionCheckFallback","loadStrictVersionCheckFallback","installedModules","moduleToHandlerMapping","chunkMapping","startedInstallModules","ConsoleApiName","log","debug","info","error","globalConsole","console","originalConsoleMethods","Object","keys","forEach","name","PREFIX","display","bind","DOCS_ORIGIN","DOCS_TROUBLESHOOTING","MORE_DETAILS","catchUserErrors","fn","errorMsg","args","err","onMonitorErrorCollected","debugMode","setDebugMode","newDebugMode","monitor","callMonitored","this","arguments","context","apply","e","displayIfDebugEnabled","includes","candidate","search","indexOf","arrayLike","Array","from","array","Set","item","push","i","length","find","predicate","objectValues","object","map","key","objectEntries","startsWith","slice","target","toAssign","source","prototype","hasOwnProperty","call","getGlobalObject","globalThis","defineProperty","configurable","globalObject","_dd_temp_","self","window","ONE_KIBI_BYTE","ONE_MEBI_BYTE","HAS_MULTI_BYTES_CHARACTERS","computeBytesCount","test","undefined","TextEncoder","encode","Blob","size","getZoneJsOriginalValue","original","browserWindow","Zone","__symbol__","callback","delay","timeoutId","throttle","wait","options","pendingExecutionWithParameters","pendingTimeoutId","needLeadingExecution","leading","needTrailingExecution","trailing","inWaitPeriod","throttled","parameters","cancel","noop","jsonStringify","value","replacer","space","JSON","stringify","restoreObjectPrototypeToJson","detachToJsonMethod","restoreArrayPrototypeToJson","restoreValuePrototypeToJson","getPrototypeOf","restoreValueToJson","objectToJson","toJSON","shallowClone","objectHasValue","some","isEmptyObject","CUSTOMER_DATA_BYTES_LIMIT","CUSTOMER_COMPRESSED_DATA_BYTES_LIMIT","BYTES_COMPUTATION_THROTTLING_DELAY","createCustomerDataTracker","checkCustomerDataLimit","bytesCountCache","computeBytesCountThrottled","cancelComputeBytesCount","resetBytesCount","updateCustomerData","resetCustomerData","getBytesCount","stop","getType","isArray","mergeInto","destination","circularReferenceChecker","WeakSet","hasAlreadyBeenSeen","has","add","createCircularReferenceChecker","Date","getTime","RegExp","flags","global","ignoreCase","multiline","sticky","unicode","join","merged","deepClone","combine","sources","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","toString","description","sanitizedSource","Event","isTrusted","match","sanitizeObjects","sourceAsObject","currentPath","set","changeType","onFirstSubscribe","observers","subscribe","f","onLastUnsubscribe","unsubscribe","filter","other","notify","data","observer","mergeObservables","Observable","globalObservable","subscriptions","observables","observable","subscription","createContextManager","customerDataTracker","changeObservable","contextManager","getContext","setContext","newContext","clearContext","setContextProperty","property","removeContextProperty","TrackingConsent","GRANTED","NOT_GRANTED","addEventListener","configuration","eventTarget","eventName","listener","addEventListeners","eventNames","once","capture","passive","listenerWithMonitor","event","__ddIsTrusted","allowUntrustedEvents","remove","storageListeners","storeContextManager","productKey","customerDataType","storageKey","buildStorageKey","getFromStorage","rawContext","localStorage","getItem","parse","setItem","createIdentityEncoder","output","outputBytesCount","isAsync","isEmpty","write","additionalEncodedBytesCount","finish","finishSync","result","rawBytesCount","pendingData","estimateEncodedBytesCount","UNKNOWN_FUNCTION","computeStackTrace","ex","stack","stackProperty","tryToGetString","exString","String","split","line","stackFrame","parts","CHROME_LINE_RE","exec","isNative","isEval","submatch","CHROME_EVAL_RE","column","func","url","parseChromeLine","CHROME_ANONYMOUS_FUNCTION_RE","parseChromeAnonymousLine","WINJS_LINE_RE","parseWinLine","GECKO_LINE_RE","GECKO_EVAL_RE","parseGeckoLine","message","fileUrl","filePosition","ERROR_TYPES_RE","createHandlingStack","formattedStack","Error","stackTrace","toStackTraceString","formatErrorMessage","frame","ExperimentalFeature","NO_ERROR_STACK_PRESENT_MESSAGE","computeRawError","originalError","handlingStack","startClocks","nonErrorPrefix","handling","isErrorInstance","computeMessage","hasUsableStack","causes","flattenErrorCauses","type","fingerprint","tryToGetFingerprint","dd_fingerprint","parentSource","currentError","cause","enabledExperimentalFeatures","isExperimentalFeatureEnabled","featureName","INTAKE_SITE_STAGING","INTAKE_SITE_FED_STAGING","INTAKE_SITE_US1","INTAKE_SITE_EU1","PCI_INTAKE_HOST_US1","performDraw","threshold","Math","random","round","num","decimals","toFixed","isNumber","navigationStart","ONE_SECOND","ONE_MINUTE","ONE_HOUR","ONE_YEAR","relativeToClocks","relative","timeStamp","relativeTime","correctedOrigin","dateNow","performance","now","getNavigationStart","addDuration","getTimeStamp","toServerDuration","duration","timeStampNow","relativeNow","clocksNow","clocksOrigin","elapsed","start","end","a","b","getRelativeTime","timestamp","timing","sendToExtension","payload","__ddBrowserSdkExtensionCallback","getConnectivity","navigator","status","onLine","interfaces","connection","effective_type","effectiveType","removeItem","index","splice","BUFFER_LIMIT","buffer","drain","arg","TelemetryType","usage","ALLOWED_FRAME_URLS","TELEMETRY_EXCLUDED_SITES","preStartTelemetryBuffer","onRawTelemetryEventCollected","addTelemetryDebug","addTelemetryError","kind","scrubCustomerFrames","formatError","addTelemetryUsage","allowedFrameUrl","sanitizeUser","newUser","user","displayAlreadyInitializedError","sdkName","initConfiguration","silentMultipleInit","generateUUID","placeholder","parseInt","replace","COMMA_SEPARATED_KEY_VALUE","findCommaSeparatedValue","rawString","lastIndex","safeTruncate","suffix","lastChar","charCodeAt","correctedLength","startDurationVital","vitalsByName","vitalsByReference","vital","reference","__dd_vital_reference","stopDurationVital","stopCallback","nameOrRef","vitalStart","stopOptions","stopClocks","buildDurationVital","delete","getEventBridge","eventBridgeGlobal","DatadogEventBridge","getCapabilities","getPrivacyLevel","getAllowedWebViewHosts","send","eventType","viewId","view","id","bridgeSupports","capability","bridge","canUseEventBridge","currentHost","location","hostname","allowedHost","instrumentMethod","targetPrototype","method","onPreCall","computeHandlingStack","stopped","instrumentation","postCallCallback","onPostCall","instrumentSetter","after","originalDescriptor","getOwnPropertyDescriptor","stoppedInstrumentation","instrumentationWrapper","normalizeUrl","buildUrl","href","base","supportedURL","isURLSupported","originalURL","getSupportedUrl","doc","document","anchorElement","createElement","baseElement","implementation","createHTMLDocument","head","appendChild","body","fetchObservable","initCookieParsed","getCurrentSiteCache","URL","initFetchObservable","fetch","input","methodFromParams","Request","toUpperCase","state","responsePromise","startContext","reportFetch","partialContext","then","response","responseType","isAborted","signal","aborted","DOMException","code","ABORT_ERR","afterSend","beforeSend","setCookie","expireDelay","date","setTime","expires","toUTCString","sameSite","crossSite","domain","secure","partitioned","cookie","getCookie","getInitCookie","Map","findCommaSeparatedValues","deleteCookie","browserCache","SYNTHETICS_TEST_ID_COOKIE_NAME","SYNTHETICS_RESULT_ID_COOKIE_NAME","SYNTHETICS_INJECTS_RUM_COOKIE_NAME","willSyntheticsInjectRum","Boolean","_DATADOG_SYNTHETICS_INJECTS_RUM","detectBrowserCached","userAgent","chrome","vendor","documentMode","detectBrowser","SESSION_STORE_KEY","SESSION_TIME_OUT_DELAY","SESSION_EXPIRATION_DELAY","SESSION_ENTRY_REGEXP","SESSION_ENTRY_SEPARATOR","EXPIRED","getExpiredSessionState","isExpired","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","retrieveSessionCookie","LOCAL_STORAGE_TEST_KEY","persistInLocalStorage","retrieveSessionFromLocalStorage","expireSessionFromLocalStorage","ongoingOperations","LOCK_RETRY_DELAY","LOCK_MAX_TRIES","bufferedOperations","processSessionStoreOperations","operations","sessionStoreStrategy","numberOfRetries","isLockEnabled","persistSession","expireSession","persistWithLock","lock","currentLock","retrieveStore","retrieveSession","next","currentStore","retryLater","processedSession","process","sessionStore","currentNumberOfRetries","nextOperations","STORAGE_POLL_DELAY","selectSessionStoreStrategyType","sessionStoreStrategyType","cookieOptions","useSecureSessionCookie","usePartitionedCrossSiteSessionCookie","useCrossSiteSessionCookie","trackSessionAcrossSubdomains","testCookieName","domainLevels","candidateDomain","pop","getCurrentSite","buildCookieOptions","testCookieValue","isCookieCorrectlySet","areCookiesAuthorized","selectCookieStrategy","allowFallbackToLocalStorage","testKey","retrievedId","selectLocalStorageStrategy","startSessionStore","computeSessionState","sessionCache","cookieStore","renewObservable","expireObservable","sessionStateUpdateObservable","cookieStoreStrategy","oldSessionId","oldRumType","oldLogsType","tryOldCookiesMigration","expireSessionCookie","watchSessionTimeoutId","synchronizeSession","startSession","synchronizedSession","trackingType","isTracked","expandOrRenewSessionState","hasSessionInCache","renewSessionInCache","throttledExpandOrRenewSession","cancelExpandOrRenewSession","isSessionInCacheOutdated","previousState","newState","expandOrRenewSession","expandSession","getSession","restartSession","updateSessionState","partialSessionState","createEndpointBuilder","trackType","configurationTags","buildUrlWithParameters","proxy","encodeURIComponent","host","site","internalAnalyticsSubdomain","usePciIntake","domainParts","extension","buildEndpointHost","createEndpointUrlWithParametersBuilder","build","api","clientToken","retry","encoding","tags","count","lastFailureStatus","reverse","buildEndpointParameters","urlPrefix","TAG_SIZE_LIMIT","buildTag","rawValue","valueSizeLimit","supportUnicodePropertyEscapes","hasForbiddenCharacters","sanitizedValue","DefaultPrivacyLevel","ALLOW","MASK","MASK_USER_INPUT","TraceContextInjection","ALL","SAMPLED","isString","tag","tagName","isSampleRate","sampleRate","validateAndBuildConfiguration","sessionSampleRate","telemetrySampleRate","telemetryConfigurationSampleRate","telemetryUsageSampleRate","version","env","service","trackingConsent","storeContextsAcrossPages","batchBytesLimit","eventRateLimiterThreshold","maxTelemetryEventsPerPage","flushTimeout","batchMessagesLimit","messageBytesLimit","datacenter","buildTags","endpointBuilders","logsEndpointBuilder","rumEndpointBuilder","sessionReplayEndpointBuilder","computeEndpointBuilders","intakeUrlPrefixes","builder","computeIntakeUrlPrefixes","replicaConfiguration","replica","replicaEndpointBuilders","applicationId","computeReplicaConfiguration","isIntakeUrl","intakeEndpoint","computeTransportConfiguration","isMatchOption","itemType","matchList","list","useStartsWith","clearTracingIfNeeded","traceId","spanId","traceSampled","injectHeadersIfTracingAllowed","sessionManager","inject","getCrypto","findTrackedSession","propagatorTypes","tracingHeaders","tracingOption","allowedTracingUrls","traceSampleRate","traceContextInjection","createTraceIdentifier","propagatorType","toDecimalString","traceparent","toPaddedHexadecimalString","b3","crypto","msCrypto","Uint8Array","readInt32","offset","radix","high","low","str","mod","floor","getRandomValues","DEFAULT_PROPAGATOR_TYPES","getSelectedTracingPropagators","usedTracingPropagators","option","REMOTE_CONFIGURATION_URL","displayRemoteConfigurationFetchingError","createPreStartStrategy","getCommonContext","trackingConsentState","customVitalsState","doStartRum","firstStartViewCall","deflateWorker","cachedInitConfiguration","cachedConfiguration","ignoreInitIfSyntheticsWillInjectRum","startDeflateWorker","bufferApiCalls","trackingConsentStateSubscription","tryStartRum","isGranted","initialViewOptions","trackViewsManually","startRumResult","doInit","eventBridgeAvailable","defaultPrivacyLevel","overrideInitConfigurationForBridge","addTelemetryConfiguration","baseSerializedConfiguration","session_sample_rate","telemetry_sample_rate","telemetry_configuration_sample_rate","telemetry_usage_sample_rate","use_before_send","use_cross_site_session_cookie","use_partitioned_cross_site_session_cookie","use_secure_session_cookie","use_proxy","silent_multiple_init","track_session_across_subdomains","allow_fallback_to_local_storage","store_contexts_across_pages","allow_untrusted_events","tracking_consent","session_replay_sample_rate","sessionReplaySampleRate","start_session_replay_recording_manually","startSessionReplayRecordingManually","trace_sample_rate","trace_context_injection","action_name_attribute","actionNameAttribute","use_allowed_tracing_urls","selected_tracing_propagators","default_privacy_level","enable_privacy_for_action_name","enablePrivacyForActionName","use_excluded_activity_urls","excludedActivityUrls","use_worker_url","workerUrl","compress_intake_requests","compressIntakeRequests","track_views_manually","track_user_interactions","trackUserInteractions","track_resources","trackResources","track_long_task","trackLongTasks","plugins","betaPlugins","plugin","getConfigurationTelemetry","serializeRumConfiguration","tracingOptions","expectedItem","validateAndBuildTracingOptions","baseConfiguration","subdomain","customerDataTelemetrySampleRate","validateAndBuildRumConfiguration","tryToInit","addDurationVital","publicApi","enableExperimentalFeatures","flag","methodName","parameter","callPluginsMethod","remoteConfigurationId","REMOTE_CONFIGURATION","xhr","XMLHttpRequest","responseText","open","fetchRemoteConfiguration","remoteInitConfiguration","applyRemoteConfiguration","fetchAndApplyRemoteConfiguration","getInternalContext","stopSession","addTiming","time","startView","updateViewName","setViewContext","setViewContextProperty","addAction","action","commonContext","addError","providedError","addFeatureFlagEvaluation","PageExitReason","HIDDEN","UNLOADING","PAGEHIDE","FROZEN","isPageExitReason","reason","getMutationObserverConstructor","constructor","MutationObserver","originalInstance","ErrorSource","AGENT","CONSOLE","CUSTOM","LOGGER","NETWORK","SOURCE","REPORT","createEventRateLimiter","limit","onLimitReached","eventCount","allowNextEvent","isLimitReached","current","fields","field","isValidObject","isValidObjectContaining","modifiableFieldPathsByEvent","VIEW_MODIFIABLE_FIELD_PATHS","USER_CUSTOMIZABLE_FIELD_PATHS","ROOT_MODIFIABLE_FIELD_PATHS","startRumAssembly","lifeCycle","viewHistory","urlContexts","actionContexts","displayContext","ciVisibilityContext","reportError","WRITABLE_RESOURCE_GRAPHQL","eventRateLimiters","syntheticsContext","testId","_DATADOG_SYNTHETICS_PUBLIC_ID","resultId","_DATADOG_SYNTHETICS_RESULT_ID","getSyntheticsResultId","test_id","result_id","injected","getSyntheticsContext","startTime","rawRumEvent","domainContext","savedCommonContext","customerContext","viewHistoryEntry","findView","urlContext","findUrl","actionId","findActionId","serverRumEvent","_dd","format_version","drift","browser_sdk_version","application","referrer","synthetics","ci_test","connectivity","has_replay","hasReplay","sampled_for_replay","sessionReplay","usr","modifiableFieldPaths","modifier","clone","fieldPath","fieldType","newValue","newType","limitModification","shouldSend","LifeCycle","callbacks","eventCallbacks","END_OF_TIMES","Infinity","CLEAR_OLD_VALUES_INTERVAL","createValueHistory","maxEntries","entries","clearOldValuesInterval","oldTimeThreshold","endTime","clearOldValues","close","unshift","returnInactive","closeActive","latestEntry","findAll","reset","xhrObservable","VIEW_CONTEXT_TIME_OUT_DELAY","xhrContexts","openXhr","abortXhr","FAKE_INITIAL_DOCUMENT","RESOURCE_TYPES","initiatorType","_","areInOrder","numbers","isResourceEntryRequestType","computeResourceEntryDuration","responseEnd","computeResourceEntryDetails","hasValidResourceEntryTimings","fetchStart","redirectStart","redirectEnd","domainLookupStart","domainLookupEnd","connectStart","secureConnectionStart","connectEnd","requestStart","responseStart","details","download","formatTiming","first_byte","connect","ssl","dns","redirect","hasValidResourceEntryDuration","areCommonTimingsInOrder","areRedirectionTimingsInOrder","hasRedirection","origin","computeResourceEntrySize","encodedBodySize","decodedBodySize","encoded_body_size","decoded_body_size","transfer_size","isAllowedRequestUrl","DATA_URL_REGEX","MAX_ATTRIBUTE_VALUE_CHAR_LENGTH","isLongDataUrl","substring","sanitizeDataUrl","RumPerformanceEntryType","resourceTimingBufferFullListener","nextRequestIndex","startRequestCollection","tracer","traceFetch","headers","append","Headers","header","concat","traceXhr","setRequestHeader","startTracer","stopInstrumentingStart","stopInstrumentingSend","hasBeenReported","stopInstrumentingOnReadyStateChange","readyState","DONE","onEnd","unsubscribeLoadEndListener","completeContext","sendXhr","stopInstrumentingAbort","createXhrObservable","initXhrObservable","requestIndex","getNextRequestIndex","trackXhr","clonedResponse","tryToClone","stream","reader","getReader","chunks","readBytesCount","onDone","catch","collectStreamBody","chunk","bytesLimit","readMore","read","done","readBytesFromStream","POSITIVE_INFINITY","waitForResponseToComplete","trackFetch","discardNegativeDuration","trackEventCounts","isChildEvent","onChange","eventCounts","errorCount","longTaskCount","resourceCount","actionCount","frustrationCount","frustration","discarded","createPerformanceObservable","PerformanceObserver","stopFirstInputTiming","handlePerformanceEntries","rumPerformanceEntries","entryType","RESOURCE","isForbiddenResource","filterRumPerformanceEntries","isObserverInitializing","getEntries","observe","NAVIGATION","LONG_TASK","PAINT","buffered","getEntriesByType","entryTypes","clearResourceTimings","manageResourceTimingBufferFull","supportPerformanceTimingEvent","FIRST_INPUT","startTimeStamp","timingSent","removeEventListeners","evt","cancelable","processingStart","processingEnd","sendTiming","sendTimingIfPointerIsNotCancelled","retrieveFirstInputTiming","disconnect","supportedEntryTypes","PAGE_ACTIVITY_VALIDATION_DELAY","PAGE_ACTIVITY_END_DELAY","waitPageActivityEnd","domMutationObservable","pageActivityEndCallback","maxDuration","pageActivityObservable","firstRequestIndex","pendingRequestsCount","notifyPageActivity","isExcludedUrl","startEvent","request","stopTrackingWindowOpen","s","isBusy","createPageActivityObservable","pageActivityEndTimeoutId","hasCompleted","validationTimeoutId","complete","hadActivity","maxDurationTimeoutId","pageActivitySubscription","lastChangeTime","doWaitPageActivityEnd","requestUrl","cssEscape","CSS","escape","ch","asCodePoint","elementMatches","element","selector","msMatchesSelector","getParentElement","node","parentElement","parentNode","nodeType","Node","ELEMENT_NODE","initialValues","isTextNode","TEXT_NODE","isElementNode","isNodeShadowHost","shadowRoot","isNodeShadowRoot","DOCUMENT_FRAGMENT_NODE","forEachChildNodes","child","firstChild","nextSibling","getParentNode","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","nodeName","relAttribute","getLowerCaseAttribute","nameAttribute","propertyAttribute","hasAttribute","toLowerCase","shouldIgnoreElement","shouldMaskNode","privacyLevel","isFormElement","censorText","text","getTextContent","textNode","ignoreWhiteSpace","parentTagName","textContent","trim","DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE","ACTION_NAME_PLACEHOLDER","getActionNameFromElement","userProgrammaticAttribute","defaultActionName","getActionNameFromElementProgrammatically","getActionNameFromElementForStrategies","priorityStrategies","fallbackStrategies","targetElement","programmaticAttribute","elementWithAttribute","supportsElementClosestResult","HTMLElement","closest","truncate","normalizeWhitespace","supportsLabelPropertyResult","privacy","HTMLInputElement","labels","getTextualContent","label","ownerDocument","querySelectorAll","htmlFor","privacyEnabledActionName","labelledByAttribute","refElement","getElementById","MAX_PARENTS_TO_CONSIDER","strategies","recursionCounter","strategy","trimmedName","isContentEditable","innerText","removeTextFromElements","query","textToReplace","supportScopeSelectorCache","STABLE_ATTRIBUTES","GLOBALLY_UNIQUE_SELECTOR_GETTERS","getStableAttributeSelector","isGeneratedValue","UNIQUE_AMONG_CHILDREN_SELECTOR_GETTERS","classList","classes","getClassList","className","getSelectorFromElement","isConnected","documentElement","contains","targetElementSelector","currentElement","globallyUniqueSelector","findSelector","isSelectorUniqueGlobally","isSelectorUniqueAmongSiblings","combineSelector","getPositionSelector","getAttributeSelector","attributeName","sibling","firstElementChild","elementIndex","nextElementSibling","selectorGetters","childSelector","elementSelector","selectorGetter","currentElementSelector","isSiblingMatching","querySelector","supportScopeSelector","parent","MAX_DURATION_BETWEEN_CLICKS","MAX_DISTANCE_BETWEEN_CLICKS","isSelectionEmpty","selection","getSelection","isCollapsed","isValidPointerEvent","Element","isPrimary","MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE","DEAD_CLICK_EXCLUDE_SELECTOR","isDead","click","hasPageActivity","getUserActivity","scroll","CLICK_ACTION_MAX_DURATION","interactionSelectorCache","updateInteractionSelector","relativeTimestamp","ACTION_CONTEXT_TIME_OUT_DELAY","trackClickActions","currentClickChain","history","stopObservable","stopClickChain","stopActionEventsListener","selectionEmptyAtPointerDown","clickContext","onPointerDown","onPointerUp","userActivity","listeners","listenActionEvents","pointerDownEvent","clickActionBase","rect","getBoundingClientRect","width","height","position","x","clientX","left","y","clientY","top","computeClickActionBase","hadActivityOnPointerDown","pageActivityEndEvent","processPointerDown","appendClickToClickChain","newClick","stopWaitPageActivityEnd","discard","viewEndedSubscription","endClocks","stopSubscription","startClickAction","tryAppend","firstClick","onFinalize","maxDurationBetweenClicksTimeoutId","bufferedClicks","appendClick","tryFinalize","dontAcceptMoreClick","every","isStopped","first","second","sqrt","pow","createClickChain","clicks","rageClick","isRage","addFrustration","hasError","hasSelectionChanged","computeFrustration","validate","finalizeClicks","activityEndTime","historyEntry","eventCountsSubscription","frustrationTypes","newActivityEndTime","frustrationType","domEvents","clickAction","counts","events","processAction","pageStateHistory","autoActionProperties","isAutoAction","loading_time","long_task","resource","actionEvent","in_foreground","wasInPageStateAt","trackRuntimeError","errorObservable","handleRuntimeError","rawError","stopInstrumentingOnError","messageObj","errorObj","tryToParseMessage","computeStackTraceFromOnErrorMessage","stopInstrumentingOnUnhandledRejection","instrumentUnhandledRejection","consoleObservablesByApi","RawReportType","intervention","deprecation","cspViolation","buildRawReportError","partial","buildStack","sourceFile","lineNumber","columnNumber","startErrorCollection","featureFlagContexts","apis","consoleObservables","originalConsoleApi","params","param","formatConsoleParameters","firstErrorParam","buildConsoleLog","createConsoleObservable","consoleLog","trackConsoleError","blockedURI","effectiveDirective","csp","disposition","originalPolicy","buildRawReportErrorFromCspViolation","createCspViolationReportObservable","reportTypes","ReportingObserver","handleReports","reports","report","buildRawReportErrorFromReport","types","createReportObservable","initReportObservable","trackReportError","handling_stack","source_type","featureFlagContext","findFeatureFlagEvaluations","feature_flags","processError","doStartErrorCollection","alreadyMatchedEntries","runOnReadyState","expectedReadyState","INITIAL_DOCUMENT_OUTDATED_TRACE_ID_THRESHOLD","getDocumentTraceId","traceIdMeta","traceTimeMeta","createDocumentTraceData","content","getDocumentTraceDataFromMeta","comment","childNodes","getTraceCommentFromNode","findTraceComment","getDocumentTraceDataFromComment","traceTime","rawTraceTime","COMMENT_NODE","isCommentNode","getNavigationEntry","navigationEntry","timings","numberKey","timingElement","computeTimingsFromDeprecatedPerformanceTiming","transferSize","retrieveInitialDocumentResourceTiming","startResourceCollection","retrieveInitialDocumentResourceTimingImpl","rawEvent","matchingTiming","sameNameEntries","getEntriesByName","candidates","matchRequestResourceEntry","tracingInfo","span_id","trace_id","rule_psr","getRulePsr","computeRequestTracingInfo","correspondingTimingOverrides","computeResourceEntryMetrics","wasInPageStateDuringPeriod","computeRequestDuration","resourceEvent","status_code","performanceEntry","requestInput","requestInit","processRequest","performanceResourceSubscription","processResourceEntry","computeResourceEntryTracingInfo","statusCode","isValidUrl","pathname","getPathName","isType","computeResourceEntryType","entryMetrics","responseStatus","renderBlockingStatus","render_blocking_status","FCP_MAXIMUM_DELAY","LCP_MAXIMUM_DELAY","trackFirstHidden","stopListeners","visibilityState","trackInitialViewMetrics","setLoadEvent","scheduleViewUpdate","initialViewMetrics","stopNavigationTracking","getNavigationEntryImpl","stopOnReadyState","waitAfterLoadEvent","loadEventEnd","isIncompleteNavigation","domComplete","domContentLoaded","domContentLoadedEventEnd","domInteractive","loadEvent","firstByte","processNavigationEntry","trackNavigationTimings","navigationTimings","firstHidden","stopFCPTracking","firstContentfulPaint","fcpEntry","trackFirstContentfulPaint","stopLCPTracking","firstInteractionTimestamp","stopEventListener","biggestLcpSize","performanceLcpSubscription","LARGEST_CONTENTFUL_PAINT","largestContentfulPaint","lcpEntry","findLast","lcpTargetSelector","targetSelector","trackLargestContentfulPaint","stopFIDTracking","performanceFirstInputSubscription","firstInput","firstInputEntry","firstInputDelay","firstInputTargetSelector","trackFirstInput","getTargetFromSource","MAX_WINDOW_DURATION","MAX_UPDATE_GAP","isLayoutShiftSupported","LAYOUT_SHIFT","viewportObservable","interactionCountEstimate","minKnownInteractionId","maxKnownInteractionId","getInteractionCount","interactionCount","MAX_INTERACTION_ENTRIES","MAX_INP_VALUE","getScrollX","scrollX","visual","visualViewport","pageLeft","offsetLeft","pageXOffset","getScrollY","scrollY","pageTop","offsetTop","pageYOffset","initViewportObservable","updateDimension","getViewportDimension","createViewportObservable","scale","innerWidth","innerHeight","THROTTLE_SCROLL_DURATION","trackCommonViewMetrics","loadingType","viewStart","commonViewMetrics","loadType","isWaitingForLoadEvent","isWaitingForActivityLoadingTime","loadingTimeCandidates","invokeCallbackIfAllCandidatesAreReceived","loadingTime","max","newLoadingTime","trackLoadingTime","stopLoadingTimeTracking","stopScrollMetricsTracking","scrollValues","throttleDuration","ResizeObserver","scrollTop","scrollHeight","scrollingElement","scrollDepth","unobserve","createScrollValuesObservable","maxScrollDepth","maxScrollHeight","maxScrollHeightTime","shouldUpdate","maxDepth","min","maxDepthScrollTop","trackScrollMetrics","newScrollMetrics","stopCLSTracking","maxClsTarget","maxClsStartTime","maxClsValue","cumulatedValue","maxValue","update","isMaxValue","slidingSessionWindow","performanceSubscription","hadRecentInput","WeakRef","deref","trackCumulativeLayoutShift","cumulativeLayoutShift","viewLoadingType","EVENT","PerformanceEventTiming","getInteractionToNextPaint","setViewEnd","interactionToNextPaintTargetSelector","interactionToNextPaintStartTime","interactionId","durationThreshold","previousInteractionCount","computeViewInteractionCount","getViewInteractionCount","stopViewInteractionCount","trackViewInteractionCount","viewEnd","longestInteractions","sortAndTrimLongestInteractions","sort","interactionIndex","findIndex","interaction","minLongestInteraction","estimateP98Interaction","trackLongestInteractions","interactionToNextPaint","handleEntries","newInteraction","firstInputSubscription","eventSubscription","viewEndTime","trackInteractionToNextPaint","stopINPTracking","getCommonViewMetrics","THROTTLE_VIEW_UPDATE_PERIOD","SESSION_KEEP_ALIVE_INTERVAL","KEEP_TRACKING_AFTER_VIEW_DELAY","getPathFromHash","hash","startViewCollection","locationChangeObservable","recorderApi","replayStats","getReplayStats","pageStates","viewEvent","document_version","documentVersion","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","isActive","largest_contentful_paint","largest_contentful_paint_target_selector","load_event","loading_type","time_spent","max_depth","max_depth_scroll_top","max_scroll_height","max_scroll_height_time","sessionIsActive","replay_level","customTimings","custom_timings","newObject","mapValues","processViewUpdate","areViewsTrackedAutomatically","locationChangeSubscription","activeViews","currentView","startNewView","viewOptions","newlyCreatedView","initialLocation","viewCreatedEvent","triggerViewUpdate","cancelScheduleViewUpdate","stopCommonViewMetricsTracking","stopInitialViewMetricsTracking","trackViewEventCounts","stopEventCountsTracking","keepAliveIntervalId","currentEnd","looksLikeRelativeTime","sanitized","sanitizeTiming","updatedName","UPDATE_VIEW_NAME","newView","pageExitEvent","currentLocation","otherLocation","correspondingId","oldLocation","renewViewOnLocationChange","trackViews","VISIBILITY_CHECK_DELAY","SESSION_CONTEXT_TIMEOUT_DELAY","stopCallbacks","startSessionManager","sessionContextHistory","buildSessionContext","isReplayForced","forcedReplay","trackActivity","expandSessionWhenVisible","visibilityCheckInterval","trackVisibility","cb","trackResume","findSession","isTypeTracked","rumSessionType","createBatch","encoder","flushController","upsertBuffer","flushSubscription","flushObservable","upsertMessages","isPageExit","sendOnExit","encoderResult","formatPayloadFromEncoder","pendingMessages","bytesCount","flush","addOrUpdate","serializedMessage","estimatedMessageBytesCount","hasMessageFor","removedMessage","messageBytesCount","notifyAfterRemoveMessage","notifyBeforeAddMessage","notifyAfterAddMessage","realMessageBytesCount","upsert","MAX_ONGOING_BYTES_COUNT","MAX_ONGOING_REQUESTS","MAX_QUEUE_BYTES_COUNT","MAX_BACKOFF_TIME","INITIAL_BACKOFF_TIME","sendWithRetryStrategy","sendStrategy","transportStatus","queuedPayloads","bandwidthMonitor","canHandle","onSuccess","retryQueuedPayloads","onFailure","enqueue","scheduleRetry","dequeue","currentBackoffTime","shouldRetryRequest","ongoingRequestCount","isFull","queueFullReported","previousQueue","newPayloadQueue","createHttpRequest","endpointBuilder","retryState","ongoingByteCount","sendStrategyForRetry","onResponse","isKeepAliveSupported","fetchUrl","keepalive","mode","xhrUrl","sendXHR","fetchKeepAliveStrategy","sendBeacon","beaconUrl","hasReportedBeaconError","reportBeaconError","sendBeaconStrategy","createFlushController","durationLimitTimeoutId","messagesLimit","durationLimit","pageExitObservable","sessionExpireObservable","pageExitSubscription","sessionExpireSubscription","currentBytesCount","currentMessagesCount","flushReason","messagesCount","cancelDurationLimitTimeout","messageBytesCountDiff","URL_CONTEXT_TIME_OUT_DELAY","getHistoryInstrumentationTarget","History","currentPeriodMeasures","currentBatchMeasures","batchHasRumEvent","FEATURE_FLAG_CONTEXT_TIME_OUT_DELAY","MEASURES_PERIOD_DURATION","sendCurrentPeriodMeasures","batchCount","initCurrentPeriodMeasures","updateMeasure","measure","sum","mergeMeasure","batchBytesCount","batchMessagesCount","globalContextBytes","userContextBytes","featureFlagBytes","initCurrentBatchMeasures","PAGE_STATE_CONTEXT_TIME_OUT_DELAY","getPageState","hasFocus","WATCH_COOKIE_INTERVAL_DELAY","watchCookieFallback","cookieName","previousCookieValue","watchCookieIntervalId","cookieValue","CI_VISIBILITY_TEST_ID_COOKIE_NAME","statsPerView","MAX_STATS_HISTORY","getSegmentsCount","getOrCreateReplayStats","segments_count","records_count","segments_total_raw_size","toDelete","_value","deleteOldestStats","serializedNodeIds","hasSerializedNode","getSerializedNodeId","getElementInputValue","URL_IN_CSS_REF","ABSOLUTE_URL","DATA_URI","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","cssText","disabled","media","serializeAttribute","attributeValue","image","naturalWidth","naturalHeight","getCssRulesString","cssHref","getCssRuleStringForSafari","getCssRuleString","matchingSubstring","singleQuote","urlWrappedInSingleQuotes","doubleQuote","urlWrappedInDoubleQuotes","urlNotWrappedInQuotes","quote","baseUrl","makeUrlAbsolute","rule","isCSSStyleRule","selectorText","isCSSImportRule","styleSheet","serializeNodeWithId","serializedNode","DOCUMENT_NODE","serializeChildNodes","adoptedStyleSheets","serializeDocumentNode","isShadowRoot","serializationContext","shadowRootsController","addShadowRoot","serializeDocumentFragmentNode","DOCUMENT_TYPE_NODE","documentType","publicId","systemId","el","isSVG","SVGElement","attributes","rr_width","rr_height","safeAttrs","formValue","optionElement","selected","stylesheet","styleSheets","_cssText","sheet","scrollLeft","checked","mediaElement","rr_mediaState","paused","elementsScrollPositions","rr_scrollLeft","rr_scrollTop","serializeAttributes","hasChildNodes","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","coordinates","tryToComputeCoordinates","timeOffset","positions","updatePosition","cancelThrottle","removeListener","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","cls","parentStyleSheet","getPathToNestedCSSRule","CSSGroupingRule","CSSMediaRule","CSSSupportsRule","stopper","currentRule","parentRule","trackFocus","focusCb","has_focus","trackFrustration","frustrationCb","frustrationSubscription","trackViewEnd","viewEndCb","viewEndSubscription","trackInput","inputCb","stopPropertySetterInstrumentation","lastInputStateMap","stopEventListeners","HTMLTextAreaElement","HTMLSelectElement","onElementChange","inputState","isChecked","cbWithDedup","lastInputState","MUTATION_PROCESS_MAX_DELAY","MUTATION_PROCESS_MIN_DELAY","trackMutation","mutationCallback","mutationBatch","processMutationBatch","cancelScheduledFlush","pendingMutations","throttledFlush","addMutations","mutations","opts","requestIdleCallback","cancelIdleCallback","requestAnimationFrame","cancelAnimationFrame","timeout","createMutationBatch","nodePrivacyLevelCache","mutation","removedNodes","removedNode","traverseRemovedShadowDom","removeShadowRoot","filteredMutations","nodeAndAncestorsHaveSerializedNode","addedAndMovedNodes","addedNodes","sortedAddedAndMovedNodes","compareDocumentPosition","DOCUMENT_POSITION_CONTAINED_BY","DOCUMENT_POSITION_CONTAINS","DOCUMENT_POSITION_FOLLOWING","DOCUMENT_POSITION_PRECEDING","addedNodeMutations","hasBeenSerialized","nextId","getNextSibling","parentId","removedNodeMutations","processChildListMutations","texts","textMutations","handledNodes","oldValue","processCharacterDataMutations","attributeMutations","handledElements","handledAttributes","emittedMutations","transformedValue","inputValue","emittedMutation","processAttributesMutations","processMutations","takeRecords","attributeOldValue","characterData","characterDataOldValue","childList","subtree","shadowDomRemovedCallback","emit","scrollPositionsByElement","emitAndComputeStats","controllerByShadowRoot","mutationTracker","inputTracker","scrollTracker","initShadowRootsController","stopFullSnapshots","flushMutations","fullSnapshotCallback","takeFullSnapshot","records","initialOffset","startFullSnapshots","initRecordIds","trackers","viewEndRecord","tracker","createSegment","creationReason","encodedBytesCount","metadata","creation_reason","has_full_snapshot","index_in_view","addRecord","prefix","additionalBytesCount","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","viewContext","computeSegmentContext","REDUCE_SEGMENT_LIMIT_BATCH_TIME","doStartSegmentCollection","isBrowserSupported","createObjectURL","NodeList","getSessionReplayLink","isRecordingStarted","errorType","getErrorType","sessionId","rumConfiguration","getSiteDefaultSubdomain","getSessionReplayUrl","createDeflateEncoder","worker","streamId","compressedDataTrailer","compressedData","nextWriteActionId","pendingWriteActions","removeMessageListener","workerResponse","trailer","nextPendingAction","writeCallback","finishCallback","consumeResult","buffers","reduce","total","concatBuffers","sendResetIfNeeded","postMessage","pendingWriteAction","INITIALIZATION_TIME_OUT_DELAY","createDeflateWorker","Worker","onInitializationFailure","createDeflateWorkerImpl","onError","initializationFailureCallbacks","onTimeout","doStartDeflateWorker","getDeflateWorkerStatus","baseMessage","worker_version","stream_id","existingGlobalVariable","startRecordingImpl","onRumStart","isRecording","startStrategy","stopStrategy","getSessionReplayLinkStrategy","cachedDeflateEncoder","force","deflateEncoder","makeRecorderApi","stopRecording","cleanupTasks","replayRequest","startRecordBridge","segmentCollection","task","setForcedReplay","datadogRum","startRumImpl","currentConsent","customerDataTrackerManager","compressionStatus","customerDataTrackers","alreadyWarned","initialBytesCount","bytesCountLimit","displayCustomerDataLimitReachedWarning","createDetachedTracker","getOrCreateTracker","setCompressionStatus","newCompressionStatus","getCompressionStatus","clear","createCustomerDataTrackerManager","globalContextManager","userContextManager","buildCommonContext","stub","createEncoder","telemetry","telemetryService","contextProvider","alreadySentEvents","telemetryEnabled","telemetryEnabledPerType","runtimeEnvInfo","is_local_file","protocol","is_worker","stringifiedEvent","runtime_env","sdk_setup","experimental_features","toTelemetryEvent","setContextProvider","provider","enabled","startTelemetry","startRumTelemetry","currentContext","startFeatureFlagContexts","stopBeforeUnloadListener","createPageExitObservable","startRumSessionManagerStub","rawTrackingType","hasValidRumSession","sessionEntity","startRumSessionManager","startRumEventBridge","telemetryEventObservable","batch","primary","batchFactoryImp","primaryBatch","createBatchFromConfig","replicaBatch","endpoint","replicated","transformMessage","startBatchWithReplica","isTelemetryReplicationAllowed","startRumBatch","batchFlushObservable","startCustomerDataTelemetry","stopHistoryTracking","onHistoryChange","stopInstrumentingPushState","stopInstrumentingReplaceState","trackHistory","onLocationChange","stopHashTracking","onHashChange","trackHash","newLocation","createLocationChangeObservable","maxPageStateEntriesSelectable","currentPageState","pageStateEntryHistory","addPageState","persisted","computePageState","nextPageState","eventStartTime","pageStateEntries","pageStateServerEntries","pageState","relativeStartTime","startPageStateHistory","viewValueHistory","buildViewHistoryEntry","viewUpdate","startViewHistory","previousViewUrl","urlContextHistory","viewUrl","buildUrlContext","changeTime","startUrlContexts","startActionCollection","viewport","viewportDimension","startDisplayContext","cookieObservable","detectCookieChangeStrategy","changeEvent","changed","deleted","listenToCookieStoreChange","createCookieObservable","testExecutionId","Cypress","cookieObservableSubscription","test_execution_id","startCiVisibilityContext","startRumEventCollection","stopRumEventCollection","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","startLongTaskCollection","vitalCollection","isValid","valueComputedBySdk","computed_value","processVital","startVitalCollection","internalContext","application_id","session_id","user_action","startInternalContext","preStartStrategy","createPostStartStrategy","sanitizedOptions","feature","rumPublicApi","setTrackingConsent","setGlobalContext","getGlobalContext","setGlobalContextProperty","removeGlobalContextProperty","clearGlobalContext","getInitConfiguration","setUser","checkUser","getUser","setUserProperty","sanitizedProperty","removeUserProperty","clearUser","startSessionReplayRecording","stopSessionReplayRecording","onReady","enumerable","makeRumPublicApi","q","moduleMap","__webpack_require__","Promise","all","module","getScope","R","o","resolve","shareScope","initScope","S","oldScope","I","d","exports","__webpack_module_cache__","moduleId","cachedModule","__webpack_modules__","m","c","n","getter","__esModule","definition","chunkId","promises","u","g","Function","obj","prop","l","needAttach","getElementsByTagName","charset","nc","setAttribute","src","onScriptComplete","prev","onerror","onload","clearTimeout","doneFns","removeChild","setTimeout","r","Symbol","toStringTag","initPromises","initTokens","initToken","scope","uniqueName","register","factory","eager","versions","activeVersion","loaded","p","t","range","requiredVersion","scopeName","msg","promise","fallback","consumes","onFactory","baseURI","installedChunks","j","installedChunkData","reject","realSrc","webpackJsonpCallback","parentChunkLoadingFunction","chunkIds","moreModules","runtime","chunkLoadingGlobal","__webpack_exports__"],"sourceRoot":""}