{ "version": 3, "sources": ["../../../node_modules/@citizensadvice/design-system/lib/header/header.js", "../../../node_modules/@citizensadvice/design-system/lib/header/index.js", "../../../node_modules/@citizensadvice/design-system/lib/navigation/navigation.js", "../../../node_modules/@citizensadvice/design-system/lib/navigation/index.js", "../../../node_modules/@citizensadvice/design-system/lib/greedy-nav/GreedyNav.js", "../../../node_modules/@citizensadvice/design-system/lib/greedy-nav/index.js", "../../javascript/application.js", "../../javascript/modules/greedy-nav.js", "../../javascript/modules/supplier-table.js", "../../../node_modules/@datadog/browser-core/src/tools/display.ts", "../../../node_modules/@datadog/browser-core/src/tools/catchUserErrors.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/numberUtils.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/timeUtils.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/byteUtils.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/objectUtils.ts", "../../../node_modules/@datadog/browser-core/src/tools/getGlobalObject.ts", "../../../node_modules/@datadog/browser-core/src/tools/getZoneJsOriginalValue.ts", "../../../node_modules/@datadog/browser-core/src/tools/monitor.ts", "../../../node_modules/@datadog/browser-core/src/tools/timer.ts", "../../../node_modules/@datadog/browser-core/src/tools/observable.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/functionUtils.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/stringUtils.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/browserDetection.ts", "../../../node_modules/@datadog/browser-core/src/browser/cookie.ts", "../../../node_modules/@datadog/browser-core/src/domain/session/storeStrategies/sessionStoreStrategy.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/polyfills.ts", "../../../node_modules/@datadog/browser-core/src/domain/session/sessionConstants.ts", "../../../node_modules/@datadog/browser-core/src/domain/session/sessionStateValidation.ts", "../../../node_modules/@datadog/browser-core/src/domain/session/sessionState.ts", "../../../node_modules/@datadog/browser-core/src/domain/session/oldCookiesMigration.ts", "../../../node_modules/@datadog/browser-core/src/domain/session/storeStrategies/sessionInCookie.ts", "../../../node_modules/@datadog/browser-core/src/domain/session/storeStrategies/sessionInLocalStorage.ts", "../../../node_modules/@datadog/browser-core/src/domain/session/sessionStoreOperations.ts", "../../../node_modules/@datadog/browser-core/src/domain/session/sessionStore.ts", "../../../node_modules/@datadog/browser-core/src/domain/trackingConsent.ts", "../../../node_modules/@datadog/browser-core/src/tools/serialisation/jsonStringify.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/urlPolyfill.ts", "../../../node_modules/@datadog/browser-core/src/domain/configuration/intakeSites.ts", "../../../node_modules/@datadog/browser-core/src/domain/configuration/endpointBuilder.ts", "../../../node_modules/@datadog/browser-core/src/domain/configuration/tags.ts", "../../../node_modules/@datadog/browser-core/src/domain/configuration/transportConfiguration.ts", "../../../node_modules/@datadog/browser-core/src/domain/configuration/configuration.ts", "../../../node_modules/@datadog/browser-core/src/tools/experimentalFeatures.ts", "../../../node_modules/@datadog/browser-core/src/tools/stackTrace/computeStackTrace.ts", "../../../node_modules/@datadog/browser-core/src/tools/stackTrace/handlingStack.ts", "../../../node_modules/@datadog/browser-core/src/tools/instrumentMethod.ts", "../../../node_modules/@datadog/browser-core/src/tools/serialisation/sanitize.ts", "../../../node_modules/@datadog/browser-core/src/domain/error/error.ts", "../../../node_modules/@datadog/browser-core/src/domain/error/error.types.ts", "../../../node_modules/@datadog/browser-core/src/domain/error/trackRuntimeError.ts", "../../../node_modules/@datadog/browser-core/src/boot/init.ts", "../../../node_modules/@datadog/browser-core/src/boot/displayAlreadyInitializedError.ts", "../../../node_modules/@datadog/browser-core/src/browser/addEventListener.ts", "../../../node_modules/@datadog/browser-core/src/domain/report/reportObservable.ts", "../../../node_modules/@datadog/browser-core/src/tools/sendToExtension.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/typeUtils.ts", "../../../node_modules/@datadog/browser-core/src/tools/mergeInto.ts", "../../../node_modules/@datadog/browser-core/src/domain/connectivity/connectivity.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/arrayUtils.ts", "../../../node_modules/@datadog/browser-core/src/tools/boundedBuffer.ts", "../../../node_modules/@datadog/browser-core/src/domain/telemetry/rawTelemetryEvent.types.ts", "../../../node_modules/@datadog/browser-core/src/domain/telemetry/telemetry.ts", "../../../node_modules/@datadog/browser-core/src/tools/valueHistory.ts", "../../../node_modules/@datadog/browser-core/src/domain/session/sessionManager.ts", "../../../node_modules/@datadog/browser-core/src/tools/utils/responseUtils.ts", "../../../node_modules/@datadog/browser-core/src/transport/sendWithRetryStrategy.ts", "../../../node_modules/@datadog/browser-core/src/transport/httpRequest.ts", "../../../node_modules/@datadog/browser-core/src/transport/eventBridge.ts", "../../../node_modules/@datadog/browser-core/src/browser/pageExitObservable.ts", "../../../node_modules/@datadog/browser-core/src/transport/batch.ts", "../../../node_modules/@datadog/browser-core/src/transport/flushController.ts", "../../../node_modules/@datadog/browser-core/src/transport/startBatchWithReplica.ts", "../../../node_modules/@datadog/browser-core/src/tools/encoder.ts", "../../../node_modules/@datadog/browser-core/src/tools/abstractLifeCycle.ts", "../../../node_modules/@datadog/browser-core/src/domain/eventRateLimiter/createEventRateLimiter.ts", "../../../node_modules/@datadog/browser-core/src/browser/xhrObservable.ts", "../../../node_modules/@datadog/browser-core/src/browser/fetchObservable.ts", "../../../node_modules/@datadog/browser-core/src/domain/console/consoleObservable.ts", "../../../node_modules/@datadog/browser-core/src/domain/context/contextManager.ts", "../../../node_modules/@datadog/browser-core/src/domain/context/storeContextManager.ts", "../../../node_modules/@datadog/browser-core/src/domain/context/customerDataTracker.ts", "../../../node_modules/@datadog/browser-core/src/tools/readBytesFromStream.ts", "../../../node_modules/@datadog/browser-core/src/domain/synthetics/syntheticsWorkerValues.ts", "../../../node_modules/@datadog/browser-core/src/domain/user/user.ts", "../../../node_modules/@datadog/browser-logs/src/domain/logger/isAuthorized.ts", "../../../node_modules/@datadog/browser-logs/src/domain/createErrorFieldFromRawError.ts", "../../../node_modules/@datadog/browser-logs/src/domain/logger.ts", "../../../node_modules/@datadog/browser-logs/src/domain/contexts/commonContext.ts", "../../../node_modules/@datadog/browser-logs/src/domain/configuration.ts", "../../../node_modules/@datadog/browser-logs/src/boot/preStartLogs.ts", "../../../node_modules/@datadog/browser-logs/src/boot/logsPublicApi.ts", "../../../node_modules/@datadog/browser-logs/src/domain/logsSessionManager.ts", "../../../node_modules/@datadog/browser-logs/src/domain/contexts/rumInternalContext.ts", "../../../node_modules/@datadog/browser-logs/src/domain/assembly.ts", "../../../node_modules/@datadog/browser-logs/src/domain/console/consoleCollection.ts", "../../../node_modules/@datadog/browser-logs/src/domain/report/reportCollection.ts", "../../../node_modules/@datadog/browser-logs/src/domain/networkError/networkErrorCollection.ts", "../../../node_modules/@datadog/browser-logs/src/domain/runtimeError/runtimeErrorCollection.ts", "../../../node_modules/@datadog/browser-logs/src/domain/lifeCycle.ts", "../../../node_modules/@datadog/browser-logs/src/domain/logger/loggerCollection.ts", "../../../node_modules/@datadog/browser-logs/src/transport/startLogsBatch.ts", "../../../node_modules/@datadog/browser-logs/src/transport/startLogsBridge.ts", "../../../node_modules/@datadog/browser-logs/src/domain/contexts/internalContext.ts", "../../../node_modules/@datadog/browser-logs/src/domain/reportError.ts", "../../../node_modules/@datadog/browser-logs/src/domain/logsTelemetry.ts", "../../../node_modules/@datadog/browser-logs/src/boot/startLogs.ts", "../../../node_modules/@datadog/browser-logs/src/entries/main.ts", "../../javascript/modules/datadog.js"], "sourcesContent": ["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar initHeader = function () {\n var SELECTOR = '.js-cads-search-reveal';\n var SHOW_SEARCH_CLASS_NAME = 'cads-header--show-search';\n var header = document.querySelector('.cads-header');\n var controlButton = header && header.querySelector(SELECTOR);\n if (controlButton) {\n var setClosed_1 = function () {\n header.classList.remove(SHOW_SEARCH_CLASS_NAME);\n controlButton.setAttribute('aria-expanded', 'false');\n var showLabel = controlButton.getAttribute('data-descriptive-label-show');\n if (showLabel) {\n controlButton.setAttribute('aria-label', showLabel);\n }\n };\n var setOpen_1 = function () {\n header.classList.add(SHOW_SEARCH_CLASS_NAME);\n controlButton.setAttribute('aria-expanded', 'true');\n var hideLabel = controlButton.getAttribute('data-descriptive-label-hide');\n if (hideLabel) {\n controlButton.setAttribute('aria-label', hideLabel);\n }\n };\n // Set initial control state on init\n setClosed_1();\n controlButton.addEventListener('click', function () {\n if (header.classList.contains(SHOW_SEARCH_CLASS_NAME)) {\n setClosed_1();\n }\n else {\n setOpen_1();\n }\n });\n }\n};\nexports.default = initHeader;\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.initHeader = void 0;\nvar header_1 = __importDefault(require(\"./header\"));\nexports.initHeader = header_1.default;\nexports.default = header_1.default;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = initNavigation;\n/**\n * The global navigation uses a \"greedy\" navigation pattern to allow as many\n * links to be visible as possible. As the width of the viewport is restricted,\n * navigation links fall into a collapsible section. On smaller viewports any links\n * that appear in the header links section in the header are also copied into the navigation.\n *\n * import { initNavigation } from '@citizensadvice/design-system/lib';\n * initNavigation();\n *\n * There is no configuration for the component. Labels are translated through\n * data attributes on the the container element. Translations are provided by\n * the ViewComponent and bundled as part of the Rails engine.\n *\n * This component uses an inline SVG icon for the toggle icon which a\n * version of the ArrowDown component HTML. The icon is rotated in CSS when\n * active rather than inlining two dedicated icons.\n */\nfunction isExpanded(toggle) {\n var ariaExpanded = toggle.getAttribute('aria-expanded');\n return ariaExpanded === 'true';\n}\nfunction getToggleEl(containerEl) {\n return containerEl.querySelector(\"button[aria-controls='cads-greedy-nav-dropdown']\");\n}\nfunction getWrapperEl(containerEl) {\n return containerEl.querySelector('.cads-greedy-nav');\n}\nfunction getDropdownEl(containerEl) {\n // The dropdown has a unique ID but query against the container for consistency\n return containerEl.querySelector('#cads-greedy-nav-dropdown');\n}\nfunction getMainNavEl(containerEl) {\n // The menu is just the first element child of the container\n return containerEl.firstElementChild;\n}\nfunction extractDataAttributes(containerEl) {\n var getData = function (name) {\n return containerEl.getAttribute(\"data-dropdown-\".concat(name));\n };\n return {\n label: getData('label') || 'More',\n labelClose: getData('label-close') || 'Close',\n ariaLabel: getData('aria-label') || 'More navigation options',\n ariaLabelClose: getData('aria-label-close') || 'Close navigation',\n };\n}\nfunction buildToggle(containerEl, dropdownId) {\n var data = extractDataAttributes(containerEl);\n var toggleId = 'cads-greedy-nav-toggle';\n return \"\");\n}\nfunction buildNavDropdown(dropdownId) {\n var navDropdown = document.createElement('ul');\n navDropdown.setAttribute('id', dropdownId);\n navDropdown.setAttribute('data-testid', dropdownId);\n navDropdown.classList.add('cads-greedy-nav__dropdown');\n var headerLinks = document.querySelector('.js-cads-copy-into-nav');\n if (headerLinks) {\n // Clone header links into navigation\n var headerLinksClone = headerLinks.cloneNode(true);\n var headerLinksContainer = document.createElement('li');\n headerLinksContainer.className = 'cads-greedy-nav__header-links';\n headerLinksContainer.appendChild(headerLinksClone);\n navDropdown.appendChild(headerLinksContainer);\n }\n return navDropdown;\n}\nfunction prepareHtml(containerEl) {\n var mainNavEl = getMainNavEl(containerEl);\n var toggleWrapper = document.createElement('div');\n toggleWrapper.classList.add('cads-greedy-nav');\n var dropdownId = 'cads-greedy-nav-dropdown';\n toggleWrapper.insertAdjacentHTML('beforeend', buildToggle(containerEl, dropdownId));\n toggleWrapper.appendChild(buildNavDropdown(dropdownId));\n mainNavEl.insertAdjacentElement('afterend', toggleWrapper);\n}\nfunction setToggleVisibility(containerEl, breaks) {\n var _a, _b;\n var toggleEl = getToggleEl(containerEl);\n if (breaks.length < 1) {\n (_a = toggleEl.parentElement) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-haspopup', 'false');\n }\n else {\n (_b = toggleEl.parentElement) === null || _b === void 0 ? void 0 : _b.setAttribute('aria-haspopup', 'true');\n }\n}\nfunction openDropDown(containerEl) {\n var data = extractDataAttributes(containerEl);\n var toggleEl = getToggleEl(containerEl);\n var dropdownEl = getDropdownEl(containerEl);\n toggleEl.setAttribute('aria-expanded', 'true');\n dropdownEl.setAttribute('aria-hidden', 'false');\n toggleEl.firstElementChild.textContent = data.labelClose;\n toggleEl.setAttribute('aria-label', data.ariaLabelClose);\n}\nfunction closeDropDown(containerEl) {\n var data = extractDataAttributes(containerEl);\n var toggleEl = getToggleEl(containerEl);\n var dropdownEl = getDropdownEl(containerEl);\n toggleEl.setAttribute('aria-expanded', 'false');\n dropdownEl.setAttribute('aria-hidden', 'true');\n toggleEl.firstElementChild.textContent = data.label;\n toggleEl.setAttribute('aria-label', data.ariaLabel);\n}\nfunction toDropdown(containerEl) {\n var navDropdown = getDropdownEl(containerEl);\n var mainNav = getMainNavEl(containerEl);\n if (mainNav && mainNav.children.length > 0 && mainNav.lastElementChild) {\n if (navDropdown.firstChild) {\n navDropdown.insertBefore(mainNav.lastElementChild, navDropdown.firstChild);\n }\n else {\n navDropdown.appendChild(mainNav.lastElementChild);\n }\n }\n}\nfunction toMenu(containerEl) {\n var navDropdown = getDropdownEl(containerEl);\n var mainNav = getMainNavEl(containerEl);\n if (mainNav &&\n navDropdown &&\n navDropdown.children.length > 0 &&\n navDropdown.firstElementChild) {\n mainNav.appendChild(navDropdown.firstElementChild);\n }\n}\nfunction computeContentWidth(containerEl) {\n var styles = window.getComputedStyle(containerEl);\n var padding = parseFloat(styles.paddingLeft) + parseFloat(styles.paddingRight);\n return containerEl.clientWidth - padding;\n}\nfunction computeChildrenOffsetWidth(containerEl) {\n var children = containerEl.childNodes;\n var sum = 0;\n for (var i = 0; i < children.length; i++) {\n var child = children[i];\n if (child.nodeType !== 3 && !Number.isNaN(child.offsetWidth)) {\n sum += child.offsetWidth;\n }\n }\n return sum;\n}\nfunction doesItFit(containerEl, breaks) {\n var mainNav = getMainNavEl(containerEl);\n var currentContentWidth = computeContentWidth(containerEl);\n var currentChildrenOffsetWidth = computeChildrenOffsetWidth(containerEl);\n while (currentContentWidth <= currentChildrenOffsetWidth &&\n mainNav.children.length > 0) {\n toDropdown(containerEl);\n breaks.push(currentChildrenOffsetWidth);\n setToggleVisibility(containerEl, breaks);\n currentContentWidth = computeContentWidth(containerEl);\n currentChildrenOffsetWidth = computeChildrenOffsetWidth(containerEl);\n }\n while (currentContentWidth >= breaks[breaks.length - 1]) {\n toMenu(containerEl);\n breaks.pop();\n setToggleVisibility(containerEl, breaks);\n }\n setToggleVisibility(containerEl, breaks);\n}\nfunction addResizeObserver(containerEl) {\n var isInitialised = false;\n var breaks = [];\n var timer;\n var observer = new ResizeObserver(function () {\n clearTimeout(timer);\n timer = window.setTimeout(function () {\n doesItFit(containerEl, breaks);\n // Only add initialised class once we've actually\n // moved some items into the navigation for the\n // first time.\n if (!isInitialised) {\n document.body.classList.add('cads-has-greedy-nav');\n isInitialised = true;\n }\n }, 50);\n });\n // This will fire when observed, which is desirable.\n // Use this to set up the initial state of the dropdown.\n observer.observe(containerEl);\n}\nfunction addToggleHandler(containerEl) {\n var toggleEl = getToggleEl(containerEl);\n toggleEl.addEventListener('click', function (event) {\n if (isExpanded(toggleEl)) {\n closeDropDown(containerEl);\n }\n else {\n openDropDown(containerEl);\n }\n });\n}\nfunction addFocusHandler(containerEl) {\n var wrapperEl = getWrapperEl(containerEl);\n wrapperEl.addEventListener('focusout', function (event) {\n var target = event.relatedTarget || document.activeElement;\n if (wrapperEl.contains(target)) {\n return;\n }\n closeDropDown(containerEl);\n });\n}\nfunction addClickOutsideHandler(containerEl) {\n var toggleEl = getToggleEl(containerEl);\n var navDropdownEl = getDropdownEl(containerEl);\n document.addEventListener('click', function (event) {\n if ('composedPath' in event) {\n var withinBoundaries = event.composedPath().includes(toggleEl) ||\n event.composedPath().includes(navDropdownEl);\n if (!withinBoundaries) {\n closeDropDown(containerEl);\n }\n }\n });\n}\nfunction addEscapeKeyHandler(containerEl) {\n document.addEventListener('keydown', function (event) {\n if (event.key === 'Escape') {\n closeDropDown(containerEl);\n }\n });\n}\nfunction initNavigation() {\n var containerEl = document.querySelector('.js-cads-greedy-nav');\n if (containerEl) {\n prepareHtml(containerEl);\n addResizeObserver(containerEl);\n addToggleHandler(containerEl);\n addFocusHandler(containerEl);\n addClickOutsideHandler(containerEl);\n addEscapeKeyHandler(containerEl);\n }\n}\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.initNavigation = void 0;\nvar navigation_1 = __importDefault(require(\"./navigation\"));\nexports.initNavigation = navigation_1.default;\nexports.default = navigation_1.default;\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar navigation_1 = __importDefault(require(\"../navigation\"));\n// Delegate to new navigation script for backwards compatibility\nvar GreedyNav = {\n init: function (_options) {\n if (_options === void 0) { _options = {}; }\n console.warn('Deprecated: use initNavigation instead');\n (0, navigation_1.default)();\n },\n};\nexports.default = GreedyNav;\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GreedyNav = void 0;\nexports.initGreedyNav = initGreedyNav;\nvar GreedyNav_1 = __importDefault(require(\"./GreedyNav\"));\nexports.GreedyNav = GreedyNav_1.default;\n// Delegate to old init script for backwards compatibility\nfunction initGreedyNav(options) {\n if (options === void 0) { options = {}; }\n GreedyNav_1.default.init(options);\n}\nexports.default = GreedyNav_1.default;\n", "// Entry point for the build script in your package.json\nimport initHeader from '@citizensadvice/design-system/lib/header';\nimport initGreedyNav from \"./modules/greedy-nav\";\nimport initSupplierTableButton from \"./modules/supplier-table\";\nimport initDatadog from \"./modules/datadog\";\n\ntry {\n // Initialise datadog monitoring\n initDatadog();\n\n // Initialise design-system modules\n initHeader();\n initGreedyNav();\n\n // Initialise application modules\n initSupplierTableButton();\n} catch (error) {\n document.querySelector(\"html\").classList.add(\"no-js\");\n throw error;\n}\n", "import greedyNav from '@citizensadvice/design-system/lib/greedy-nav';\n\nexport default function initGreedyNav() {\n greedyNav.init({\n mainNavWrapper: '.cads-navigation',\n initClass: 'cads-greedy-nav-init',\n });\n}\n", "const selectors = {\n table: \".js-supplier-table\",\n allRows: \".js-supplier-table tbody tr\",\n rowSixUp: \".js-supplier-table tbody tr:nth-child(n + 6)\",\n showMoreButton: \".js-show-more-suppliers\",\n showFewerButton: \".js-show-fewer-suppliers\",\n countText: \".js-supplier-table-count-text\",\n};\n\nconst totalRows = document.querySelectorAll(selectors.allRows).length;\n\nconst hideRows = () => {\n document.querySelectorAll(selectors.rowSixUp).forEach((row) => {\n row.classList.add(\"supplier-table__row--hidden\");\n });\n};\n\nconst showRows = () => {\n document.querySelectorAll(selectors.rowSixUp).forEach((row) => {\n row.classList.remove(\"supplier-table__row--hidden\");\n });\n};\n\nconst updateCountText = (showing) => {\n const countText = document.querySelector(selectors.countText);\n countText.innerHTML = `Showing ${showing} of ${totalRows} suppliers`;\n};\n\nconst showMoreSuppliers = () => {\n const tableContainer = document.querySelector(\".supplier-table--show-more\");\n tableContainer.classList.remove(\"supplier-table--show-more\");\n tableContainer.classList.add(\"supplier-table--show-fewer\");\n\n updateCountText(totalRows);\n showRows();\n const showFewer = document.querySelector(selectors.showFewerButton);\n showFewer.focus({ focusVisible: true });\n};\n\nconst showFewerSuppliers = () => {\n const tableContainer = document.querySelector(\".supplier-table--show-fewer\");\n tableContainer.classList.remove(\"supplier-table--show-fewer\");\n tableContainer.classList.add(\"supplier-table--show-more\");\n\n updateCountText(5);\n hideRows();\n const showMore = document.querySelector(selectors.showMoreButton);\n showMore.focus({ focusVisible: true });\n};\n\nconst addButtonEventHandlers = () => {\n document\n .querySelector(selectors.showMoreButton)\n .addEventListener(\"click\", showMoreSuppliers);\n\n document\n .querySelector(selectors.showFewerButton)\n .addEventListener(\"click\", showFewerSuppliers);\n};\n\nexport default () => {\n hideRows();\n addButtonEventHandlers();\n};\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(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", "/**\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// Get the time since the navigation was started.\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\n/**\n * Notes: this does not use `performance.timeOrigin` because:\n * - It doesn't seem to reflect the actual time on which the navigation has started: it may be much farther in the past,\n * at least in Firefox 71. (see: https://bugzilla.mozilla.org/show_bug.cgi?id=1429926)\n * - It is not supported in Safari <15\n */\nfunction getNavigationStart() {\n if (navigationStart === undefined) {\n navigationStart = performance.timing.navigationStart as TimeStamp\n }\n return navigationStart\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[]): Uint8Array {\n const length = buffers.reduce((total, buffer) => total + buffer.length, 0)\n const result: Uint8Array = 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", "export function shallowClone(object: T): T & Record {\n return { ...object } as T & Record\n}\n\nexport function objectHasValue(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(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", "/**\n * inspired by https://mathiasbynens.be/notes/globalthis\n */\n\nexport function getGlobalObject(): 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", "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(\n target: Target,\n name: Name\n): Target[Name] {\n const browserWindow = getGlobalObject()\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 { 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 unknown>(\n _: any,\n __: string,\n descriptor: TypedPropertyDescriptor\n) {\n const originalMethod = descriptor.value!\n descriptor.value = function (this: any, ...args: Parameters) {\n const decorated = onMonitorErrorCollected ? monitor(originalMethod) : originalMethod\n return decorated.apply(this, args) as ReturnType\n } as T\n}\n\nexport function monitor 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)\n } as unknown as T // consider output type has input type\n}\n\nexport function callMonitored any>(\n fn: T,\n context: ThisParameterType,\n args: Parameters\n): ReturnType | undefined\nexport function callMonitored any>(fn: T): ReturnType | undefined\nexport function callMonitored any>(\n fn: T,\n context?: any,\n args?: any\n): ReturnType | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return fn.apply(context, args)\n } catch (e) {\n monitorError(e)\n }\n}\n\nexport function monitorError(e: unknown) {\n displayIfDebugEnabled(e)\n if (onMonitorErrorCollected) {\n try {\n onMonitorErrorCollected(e)\n } catch (e) {\n displayIfDebugEnabled(e)\n }\n }\n}\n\nexport function displayIfDebugEnabled(...args: any[]) {\n if (debugMode) {\n display.error('[MONITOR]', ...args)\n }\n}\n", "import { getZoneJsOriginalValue } from './getZoneJsOriginalValue'\nimport { monitor } from './monitor'\nimport { getGlobalObject } from './getGlobalObject'\n\nexport type TimeoutId = ReturnType\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", "export interface Subscription {\n unsubscribe: () => void\n}\n\n// eslint-disable-next-line no-restricted-syntax\nexport class Observable {\n private observers: Array<(data: T) => void> = []\n private onLastUnsubscribe?: () => void\n\n constructor(private onFirstSubscribe?: (observable: Observable) => (() => 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(...observables: Array>) {\n return new Observable((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 type { TimeoutId } from '../timer'\nimport { setTimeout, clearTimeout } from '../timer'\n\n// use lodash API\nexport function throttle 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 | undefined\n let pendingTimeoutId: TimeoutId\n\n return {\n throttled: (...parameters: Parameters) => {\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", "/**\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 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 {\n const result = new Map()\n COMMA_SEPARATED_KEY_VALUE.lastIndex = 0\n while (true) {\n const match = COMMA_SEPARATED_KEY_VALUE.exec(rawString)\n if (match) {\n result.set(match[1], match[2])\n } 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", "// Exported only for tests\nexport const enum Browser {\n CHROMIUM,\n SAFARI,\n OTHER,\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 return Browser.OTHER\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 = 0, 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 | 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 type { CookieOptions } from '../../../browser/cookie'\nimport type { SessionPersistence } from '../sessionConstants'\nimport type { SessionState } from '../sessionState'\n\nexport const SESSION_STORE_KEY = '_dd_s'\n\nexport type SessionStoreStrategyType =\n | { type: typeof SessionPersistence.COOKIE; cookieOptions: CookieOptions }\n | { type: typeof SessionPersistence.LOCAL_STORAGE }\n\nexport interface SessionStoreStrategy {\n isLockEnabled: boolean\n persistSession: (session: SessionState) => void\n retrieveSession: () => SessionState\n expireSession: (previousSessionState: SessionState) => void\n}\n", "export function findLast(\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\n// Keep the following wrapper functions as it can be mangled and will result in smaller bundle size that using\n// the native Object.values and Object.entries directly\n\nexport function objectValues(object: { [key: string]: T }) {\n return Object.values(object)\n}\n\nexport function objectEntries(object: { [key: string]: T }): Array<[string, T]> {\n return Object.entries(object)\n}\n", "import { ONE_HOUR, ONE_MINUTE, ONE_YEAR } from '../../tools/utils/timeUtils'\n\nexport const SESSION_TIME_OUT_DELAY = 4 * ONE_HOUR\nexport const SESSION_EXPIRATION_DELAY = 15 * ONE_MINUTE\nexport const SESSION_COOKIE_EXPIRATION_DELAY = ONE_YEAR\n\nexport const SessionPersistence = {\n COOKIE: 'cookie',\n LOCAL_STORAGE: 'local-storage',\n} as const\nexport type SessionPersistence = (typeof SessionPersistence)[keyof typeof SessionPersistence]\n", "export const SESSION_ENTRY_REGEXP = /^([a-zA-Z]+)=([a-z0-9-]+)$/\nexport const SESSION_ENTRY_SEPARATOR = '&'\n\nexport function 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 { isEmptyObject } from '../../tools/utils/objectUtils'\nimport { objectEntries } from '../../tools/utils/polyfills'\nimport { dateNow } from '../../tools/utils/timeUtils'\nimport { generateUUID } from '../../tools/utils/stringUtils'\nimport type { Configuration } from '../configuration'\nimport { SESSION_EXPIRATION_DELAY, SESSION_TIME_OUT_DELAY } from './sessionConstants'\nimport { isValidSessionString, SESSION_ENTRY_REGEXP, SESSION_ENTRY_SEPARATOR } from './sessionStateValidation'\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(\n previousSessionState: SessionState | undefined,\n configuration: Configuration\n): SessionState {\n const expiredSessionState: SessionState = {\n isExpired: EXPIRED,\n }\n if (configuration.trackAnonymousUser) {\n if (previousSessionState?.anonymousId) {\n expiredSessionState.anonymousId = previousSessionState?.anonymousId\n } else {\n expiredSessionState.anonymousId = generateUUID()\n }\n }\n return expiredSessionState\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 (\n objectEntries(session)\n // we use `aid` as a key for anonymousId\n .map(([key, value]) => (key === 'anonymousId' ? `aid=${value}` : `${key}=${value}`))\n .join(SESSION_ENTRY_SEPARATOR)\n )\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 if (key === 'aid') {\n // we use `aid` as a key for anonymousId\n session.anonymousId = value\n } else {\n session[key] = value\n }\n }\n })\n }\n return session\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, Configuration } from '../../configuration'\nimport { tryOldCookiesMigration } from '../oldCookiesMigration'\nimport {\n SESSION_COOKIE_EXPIRATION_DELAY,\n SESSION_EXPIRATION_DELAY,\n SESSION_TIME_OUT_DELAY,\n SessionPersistence,\n} 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: SessionPersistence.COOKIE, cookieOptions } : undefined\n}\n\nexport function initCookieStrategy(configuration: Configuration, 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: (sessionState: SessionState) => expireSessionCookie(cookieOptions, sessionState, configuration),\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, sessionState: SessionState, configuration: Configuration) {\n const expiredSessionState = getExpiredSessionState(sessionState, configuration)\n // we do not extend cookie expiration date\n setCookie(\n SESSION_STORE_KEY,\n toSessionString(expiredSessionState),\n configuration.trackAnonymousUser ? SESSION_COOKIE_EXPIRATION_DELAY : SESSION_TIME_OUT_DELAY,\n options\n )\n}\n\nfunction retrieveSessionCookie(): SessionState {\n const sessionString = getCookie(SESSION_STORE_KEY)\n const sessionState = toSessionState(sessionString)\n return sessionState\n}\n\nexport function buildCookieOptions(initConfiguration: InitConfiguration) {\n const cookieOptions: CookieOptions = {}\n\n cookieOptions.secure =\n !!initConfiguration.useSecureSessionCookie || !!initConfiguration.usePartitionedCrossSiteSessionCookie\n cookieOptions.crossSite = !!initConfiguration.usePartitionedCrossSiteSessionCookie\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 { Configuration } from '../../configuration'\nimport { SessionPersistence } 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\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: SessionPersistence.LOCAL_STORAGE } : undefined\n } catch {\n return undefined\n }\n}\n\nexport function initLocalStorageStrategy(configuration: Configuration): SessionStoreStrategy {\n return {\n isLockEnabled: false,\n persistSession: persistInLocalStorage,\n retrieveSession: retrieveSessionFromLocalStorage,\n expireSession: (sessionState: SessionState) => expireSessionFromLocalStorage(sessionState, configuration),\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(previousSessionState: SessionState, configuration: Configuration) {\n persistInLocalStorage(getExpiredSessionState(previousSessionState, configuration))\n}\n", "import { setTimeout } from '../../tools/timer'\nimport { generateUUID } from '../../tools/utils/stringUtils'\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({ ...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(processedSession)\n } else {\n expandSessionState(processedSession)\n if (isLockEnabled) {\n persistWithLock(processedSession)\n } else {\n persistSession(processedSession)\n }\n }\n }\n if (isLockEnabled) {\n // correctly handle lock around expiration would require to handle this case properly at several levels\n // since we don't have evidence of lock issues around expiration, let's just not do the corruption check for it\n if (!(processedSession && isSessionInExpiredState(processedSession))) {\n // if lock corrupted after persist, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock!) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n persistSession(currentStore.session)\n processedSession = currentStore.session\n }\n }\n // call after even if session is not persisted in order to perform operations on\n // up-to-date session state value => the value could have been modified by another tab\n 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, Configuration } from '../configuration'\nimport { display } from '../../tools/display'\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'\nimport { SessionPersistence } from './sessionConstants'\n\nexport interface SessionStore {\n expandOrRenewSession: () => void\n expandSession: () => void\n getSession: () => SessionState\n restartSession: () => void\n renewObservable: Observable\n expireObservable: Observable\n sessionStateUpdateObservable: Observable<{ previousState: SessionState; newState: SessionState }>\n expire: () => void\n stop: () => void\n updateSessionState: (state: Partial) => 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 * Selects the correct session store strategy type based on the configuration and storage\n * availability.\n */\nexport function selectSessionStoreStrategyType(\n initConfiguration: InitConfiguration\n): SessionStoreStrategyType | undefined {\n switch (initConfiguration.sessionPersistence) {\n case SessionPersistence.COOKIE:\n return selectCookieStrategy(initConfiguration)\n\n case SessionPersistence.LOCAL_STORAGE:\n return selectLocalStorageStrategy()\n\n case undefined: {\n let sessionStoreStrategyType = selectCookieStrategy(initConfiguration)\n if (!sessionStoreStrategyType && initConfiguration.allowFallbackToLocalStorage) {\n sessionStoreStrategyType = selectLocalStorageStrategy()\n }\n return sessionStoreStrategyType\n }\n\n default:\n display.error(`Invalid session persistence '${String(initConfiguration.sessionPersistence)}'`)\n }\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(\n sessionStoreStrategyType: SessionStoreStrategyType,\n configuration: Configuration,\n productKey: string,\n computeSessionState: (rawTrackingType?: string) => { trackingType: TrackingType; isTracked: boolean }\n): SessionStore {\n const renewObservable = new Observable()\n const expireObservable = new Observable()\n const sessionStateUpdateObservable = new Observable<{ previousState: SessionState; newState: SessionState }>()\n\n const sessionStoreStrategy =\n sessionStoreStrategyType.type === SessionPersistence.COOKIE\n ? initCookieStrategy(configuration, sessionStoreStrategyType.cookieOptions)\n : initLocalStorageStrategy(configuration)\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) =>\n isSessionInExpiredState(sessionState) ? getExpiredSessionState(sessionState, configuration) : undefined,\n after: synchronizeSession,\n },\n sessionStoreStrategy\n )\n }\n\n function synchronizeSession(sessionState: SessionState) {\n if (isSessionInExpiredState(sessionState)) {\n sessionState = getExpiredSessionState(sessionState, configuration)\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(sessionState, configuration)\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(sessionCache, configuration)\n expireObservable.notify()\n }\n\n function renewSessionInCache(sessionState: SessionState) {\n sessionCache = sessionState\n renewObservable.notify()\n }\n\n function updateSessionState(partialSessionState: Partial) {\n processSessionStoreOperations(\n {\n process: (sessionState) => ({ ...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(sessionCache)\n synchronizeSession(getExpiredSessionState(sessionCache, configuration))\n },\n stop: () => {\n clearInterval(watchSessionTimeoutId)\n },\n updateSessionState,\n }\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\n}\n\nexport function createTrackingConsentState(currentConsent?: TrackingConsent): TrackingConsentState {\n const observable = new Observable()\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 { 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,\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 ''\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 { 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", "export type Site =\n | 'datadoghq.com'\n | 'us3.datadoghq.com'\n | 'us5.datadoghq.com'\n | 'datadoghq.eu'\n | 'ddog-gov.com'\n | 'ap1.datadoghq.com'\n\nexport const INTAKE_SITE_STAGING: Site = 'datad0g.com' as Site\nexport const INTAKE_SITE_FED_STAGING: Site = 'dd0g-gov.com' as Site\nexport const INTAKE_SITE_US1: Site = 'datadoghq.com'\nexport const INTAKE_SITE_EU1: Site = 'datadoghq.eu'\nexport const INTAKE_SITE_US1_FED: Site = 'ddog-gov.com'\n\nexport const PCI_INTAKE_HOST_US1 = 'pci.browser-intake-datadoghq.com'\nexport const INTAKE_URL_PARAMETERS = ['ddsource', 'ddtags']\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\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\nexport function buildEndpointHost(\n trackType: TrackType,\n initConfiguration: InitConfiguration & { usePciIntake?: boolean }\n) {\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 support for Chrome 63 and Firefox 67\n // see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape#browser_compatibility\n if (!supportUnicodePropertyEscapes()) {\n return false\n }\n\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 type { InitConfiguration } from './configuration'\nimport type { EndpointBuilder } from './endpointBuilder'\nimport { createEndpointBuilder } from './endpointBuilder'\nimport { buildTags } from './tags'\nimport type { Site } from './intakeSites'\nimport { INTAKE_SITE_US1, INTAKE_URL_PARAMETERS } from './intakeSites'\n\nexport interface TransportConfiguration {\n logsEndpointBuilder: EndpointBuilder\n rumEndpointBuilder: EndpointBuilder\n sessionReplayEndpointBuilder: EndpointBuilder\n replica?: ReplicaConfiguration\n site: Site\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 replicaConfiguration = computeReplicaConfiguration(initConfiguration, tags)\n\n return {\n replica: replicaConfiguration,\n site,\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 tags: string[]\n): ReplicaConfiguration | undefined {\n if (!initConfiguration.replica) {\n return\n }\n\n const replicaConfiguration: InitConfiguration = {\n ...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 return { applicationId: initConfiguration.replica.applicationId, ...replicaEndpointBuilders }\n}\n\nexport function isIntakeUrl(url: string): boolean {\n // check if tags is present in the query string\n return INTAKE_URL_PARAMETERS.every((param) => url.includes(param))\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 { selectSessionStoreStrategyType } from '../session/sessionStore'\nimport type { SessionStoreStrategyType } from '../session/storeStrategies/sessionStoreStrategy'\nimport { TrackingConsent } from '../trackingConsent'\nimport type { SessionPersistence } from '../session/sessionConstants'\nimport type { TransportConfiguration } from './transportConfiguration'\nimport { computeTransportConfiguration } from './transportConfiguration'\nimport type { Site } from './intakeSites'\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 /**\n * Which storage strategy to use for persisting sessions. Can be either 'cookie' or 'local-storage'.\n * @default \"cookie\"\n */\n sessionPersistence?: SessionPersistence | undefined\n\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 * @deprecated use `sessionPersistence: local-storage` where you want to use localStorage instead\n */\n allowFallbackToLocalStorage?: boolean | undefined\n\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?: Site | 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\u2019s 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\u2019s 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 * 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 * Track anonymous user for the same site and extend cookie expiration date\n * @default true\n */\n trackAnonymousUser?: boolean | undefined\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\nexport interface 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 trackAnonymousUser?: 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 {\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 trackAnonymousUser: initConfiguration.trackAnonymousUser ?? true,\n storeContextsAcrossPages: !!initConfiguration.storeContextsAcrossPages,\n /**\n * beacon payload max queue size implementation is 64kb\n * ensure that we leave room for logs, rum and potential other users\n */\n batchBytesLimit: 16 * ONE_KIBI_BYTE,\n\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 ...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_partitioned_cross_site_session_cookie: initConfiguration.usePartitionedCrossSiteSessionCookie,\n use_secure_session_cookie: initConfiguration.useSecureSessionCookie,\n use_proxy: !!initConfiguration.proxy,\n silent_multiple_init: initConfiguration.silentMultipleInit,\n track_session_across_subdomains: initConfiguration.trackSessionAcrossSubdomains,\n track_anonymous_user: initConfiguration.trackAnonymousUser,\n session_persistence: initConfiguration.sessionPersistence,\n allow_fallback_to_local_storage: !!initConfiguration.allowFallbackToLocalStorage,\n store_contexts_across_pages: !!initConfiguration.storeContextsAcrossPages,\n allow_untrusted_events: !!initConfiguration.allowUntrustedEvents,\n tracking_consent: initConfiguration.trackingConsent,\n } satisfies RawTelemetryConfiguration\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 CONSISTENT_TRACE_SAMPLING = 'consistent_trace_sampling',\n MISSING_URL_CONTEXT_TELEMETRY = 'missing_url_context_telemetry',\n}\n\nconst enabledExperimentalFeatures: Set = 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 {\n return enabledExperimentalFeatures\n}\n", "/**\n * Cross-browser stack trace computation.\n *\n * Reference implementation: https://github.com/csnover/TraceKit/blob/04530298073c3823de72deb0b97e7b38ca7bcb59/tracekit.js\n */\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 && stackProperty.startsWith(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 =\n '((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet||\\\\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 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 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 === '?' ? '' : 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 { setTimeout } from './timer'\nimport { callMonitored } from './monitor'\nimport { noop } from './utils/functionUtils'\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 = {\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\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) => void\n\n /**\n * The stack trace of the method call.\n */\n handlingStack?: string\n}\n\ntype PostCallCallback = (\n result: ReturnType\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(\n targetPrototype: TARGET,\n method: METHOD,\n onPreCall: (this: null, callInfos: InstrumentedMethodCall) => void,\n { computeHandlingStack }: { computeHandlingStack?: boolean } = {}\n) {\n let original = targetPrototype[method]\n\n if (typeof original !== 'function') {\n if (method in targetPrototype && method.startsWith('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 | 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)\n }\n\n const parameters = Array.from(arguments) as Parameters\n\n let postCallCallback: PostCallCallback | 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(\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 { 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/no-unsafe-function-type\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\ntype SanitizedEvent = {\n type: string\n isTrusted: boolean\n currentTarget: string | null | undefined\n target: string | null | undefined\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()\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\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 */\nfunction sanitizeObjects(value: object): string | SanitizedEvent {\n try {\n if (value instanceof Event) {\n return sanitizeEvent(value)\n }\n\n if (value instanceof RegExp) {\n return `[RegExp] ${value.toString()}`\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\nfunction sanitizeEvent(event: Event): SanitizedEvent {\n return {\n type: event.type,\n isTrusted: event.isTrusted,\n currentTarget: event.currentTarget ? (sanitizeObjects(event.currentTarget) as string) : null,\n target: event.target ? (sanitizeObjects(event.target) as string) : null,\n }\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", "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 componentStack?: 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 componentStack,\n startClocks,\n nonErrorPrefix,\n source,\n handling,\n}: RawErrorParams): RawError {\n const isErrorInstance = isError(originalError)\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 componentStack,\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 isError(originalError) && 'dd_fingerprint' in originalError ? String(originalError.dd_fingerprint) : undefined\n}\n\nexport function getFileFromStackTraceString(stack: string) {\n return /@ (.+)/.exec(stack)?.[1]\n}\n\nexport function isError(error: unknown): error is Error {\n return error instanceof Error || Object.prototype.toString.call(error) === '[object Error]'\n}\n\nexport function flattenErrorCauses(error: ErrorWithCause, parentSource: ErrorSource): RawErrorCause[] | undefined {\n let currentError = error\n const causes: RawErrorCause[] = []\n while (isError(currentError?.cause) && causes.length < 10) {\n const stackTrace = computeStackTrace(currentError.cause)\n causes.push({\n message: currentError.cause.message,\n source: parentSource,\n type: stackTrace?.name,\n stack: stackTrace && toStackTraceString(stackTrace),\n })\n currentError = currentError.cause\n }\n return causes.length ? causes : undefined\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 {\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 componentStack?: 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 { 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, isError } 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) {\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 (isError(errorObj)) {\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 { catchUserErrors } from '../tools/catchUserErrors'\nimport { setDebugMode } from '../tools/monitor'\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(stub: Omit): T {\n const publicApi = {\n version: __BUILD_ENV__SDK_VERSION__,\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 ...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: 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 { 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", "import { monitor } from '../tools/monitor'\nimport { getZoneJsOriginalValue } from '../tools/getZoneJsOriginalValue'\nimport type { CookieStore, CookieStoreEventMap, VisualViewport, VisualViewportEventMap } from './browser.types'\n\nexport type TrustableEvent = 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 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\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 & string>(\n configuration: { allowUntrustedEvents?: boolean | undefined },\n eventTarget: Target,\n eventName: EventName,\n listener: (event: EventMapFor[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 & string>(\n configuration: { allowUntrustedEvents?: boolean | undefined },\n eventTarget: Target,\n eventNames: EventName[],\n listener: (event: EventMapFor[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[EventName] & { type: EventName })\n })\n\n const options = passive ? { capture, passive } : capture\n\n // Use the window.EventTarget.prototype when possible to avoid wrong overrides (e.g: https://github.com/salesforce/lwc/issues/1824)\n const listenerTarget =\n window.EventTarget && eventTarget instanceof EventTarget ? window.EventTarget.prototype : eventTarget\n\n const add = getZoneJsOriginalValue(listenerTarget, 'addEventListener')\n eventNames.forEach((eventName) => add.call(eventTarget, eventName, listenerWithMonitor, options))\n\n function stop() {\n const remove = getZoneJsOriginalValue(listenerTarget, 'removeEventListener')\n eventNames.forEach((eventName) => remove.call(eventTarget, eventName, listenerWithMonitor, options))\n }\n\n return {\n stop,\n }\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 { 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> = []\n\n if (apis.includes(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((observable) => {\n if (!window.ReportingObserver) {\n return\n }\n\n const handleReports = monitor((reports: Array, _: 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((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 {\n return {\n startClocks: clocksNow(),\n source: ErrorSource.REPORT,\n handling: ErrorHandling.UNHANDLED,\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", "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", "/**\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 =\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(\n destination: D,\n source: S,\n circularReferenceChecker = createCircularReferenceChecker()\n): Merged {\n // ignore the source if it is undefined\n if (source === undefined) {\n return destination as Merged\n }\n\n if (typeof source !== 'object' || source === null) {\n // primitive values - just return source\n return source as Merged\n } else if (source instanceof Date) {\n return new Date(source.getTime()) as unknown as Merged\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\n }\n\n if (circularReferenceChecker.hasAlreadyBeenSeen(source)) {\n // remove circular references\n return undefined as unknown as Merged\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\n }\n\n const merged = getType(destination) === 'object' ? (destination as Record) : {}\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\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(value: T): T {\n return mergeInto(undefined, value) as T\n}\n\ntype Combined = A extends null ? B : B extends null ? A : Merged\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: A, b: B): Combined\nexport function combine(a: A, b: B, c: C): Combined, C>\nexport function combine(a: A, b: B, c: C, d: D): Combined, C>, D>\nexport function combine(\n a: A,\n b: B,\n c: C,\n d: D,\n e: E\n): Combined, C>, D>, E>\nexport function combine(\n a: A,\n b: B,\n c: C,\n d: D,\n e: E,\n f: F\n): Combined, C>, D>, E>, F>\nexport function combine(\n a: A,\n b: B,\n c: C,\n d: D,\n e: E,\n f: F,\n g: G\n): Combined, C>, D>, E>, F>, G>\nexport function combine(\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, 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 = 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", "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", "export function removeDuplicates(array: T[]) {\n const set = new Set()\n array.forEach((item) => set.add(item))\n return Array.from(set)\n}\n\nexport function removeItem(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 {\n add: (callback: (arg: T) => void) => void\n remove: (callback: (arg: T) => void) => void\n drain: (arg: T) => void\n}\n\nexport function createBoundedBuffer(): BoundedBuffer {\n const buffer: Array<(arg: T) => void> = []\n\n const add: BoundedBuffer['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['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, isError } 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 { 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 '',\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\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()\n const alreadySentEvents = new Set()\n\n const telemetryEnabled =\n !TELEMETRY_EXCLUDED_SITES.includes(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: Array.from(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 type: TelemetryType.log,\n message,\n status: StatusType.debug,\n ...context,\n })\n}\n\nexport function addTelemetryError(e: unknown, context?: Context) {\n onRawTelemetryEventCollected({\n type: TelemetryType.log,\n status: StatusType.error,\n ...formatError(e),\n ...context,\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 (isError(e)) {\n const stackTrace = computeStackTrace(e)\n return {\n error: {\n kind: stackTrace.name,\n stack: toStackTraceString(scrubCustomerFrames(stackTrace)),\n },\n message: stackTrace.message!,\n }\n }\n return {\n error: {\n stack: NO_ERROR_STACK_PRESENT_MESSAGE,\n },\n message: `${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) => frame.url!.startsWith(allowedFrameUrl))\n )\n return stackTrace\n}\n", "import type { Context } from './serialisation/context'\nimport { 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 {\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 {\n add: (value: Value, startTime: RelativeTime) => ValueHistoryEntry\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 getAllEntries: () => Context[]\n getDeletedEntries: () => RelativeTime[]\n}\n\nlet cleanupHistoriesInterval: TimeoutId | null = null\n\nconst cleanupTasks: Set<() => void> = new Set()\n\nfunction cleanupHistories() {\n cleanupTasks.forEach((task) => task())\n}\n\nexport function createValueHistory({\n expireDelay,\n maxEntries,\n}: {\n expireDelay: number\n maxEntries?: number\n}): ValueHistory {\n let entries: Array> = []\n const deletedEntries: RelativeTime[] = []\n\n if (!cleanupHistoriesInterval) {\n cleanupHistoriesInterval = setInterval(() => cleanupHistories(), CLEAR_OLD_VALUES_INTERVAL)\n }\n\n const clearExpiredValues = () => {\n const oldTimeThreshold = relativeNow() - expireDelay\n while (entries.length > 0 && entries[entries.length - 1].endTime < oldTimeThreshold) {\n const entry = entries.pop()\n if (entry) {\n deletedEntries.push(entry.startTime)\n }\n }\n }\n\n cleanupTasks.add(clearExpiredValues)\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 {\n const entry: ValueHistoryEntry = {\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 function getAllEntries() {\n return entries.map(({ startTime, endTime, value }) => ({\n startTime,\n endTime: endTime === END_OF_TIMES ? 'Infinity' : endTime,\n value,\n })) as Context[]\n }\n\n function getDeletedEntries() {\n return deletedEntries\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 cleanupTasks.delete(clearExpiredValues)\n if (cleanupTasks.size === 0 && cleanupHistoriesInterval) {\n clearInterval(cleanupHistoriesInterval)\n cleanupHistoriesInterval = null\n }\n }\n\n return { add, find, closeActive, findAll, reset, stop, getAllEntries, getDeletedEntries }\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 {\n findSession: (\n startTime?: RelativeTime,\n options?: { returnInactive: boolean }\n ) => SessionContext | undefined\n renewObservable: Observable\n expireObservable: Observable\n sessionStateUpdateObservable: Observable<{ previousState: SessionState; newState: SessionState }>\n expire: () => void\n updateSessionState: (state: Partial) => void\n}\n\nexport interface SessionContext extends Context {\n id: string\n trackingType: TrackingType\n isReplayForced: boolean\n anonymousId: string | undefined\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(\n configuration: Configuration,\n productKey: string,\n computeSessionState: (rawTrackingType?: string) => { trackingType: TrackingType; isTracked: boolean },\n trackingConsentState: TrackingConsentState\n): SessionManager {\n const renewObservable = new Observable()\n const expireObservable = new Observable()\n\n // TODO - Improve configuration type and remove assertion\n const sessionStore = startSessionStore(\n configuration.sessionStoreStrategyType!,\n configuration,\n productKey,\n computeSessionState\n )\n stopCallbacks.push(() => sessionStore.stop())\n\n const sessionContextHistory = createValueHistory>({\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 anonymousId: sessionStore.getSession().anonymousId,\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", "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 {\n // clone can throw if the response has already been used by another instrumentation or is disturbed\n return\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\n queuedPayloads: ReturnType\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 } 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\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 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(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(endpointBuilder, bytesLimit, payload)\n },\n }\n}\n\nfunction sendBeaconStrategy(endpointBuilder: EndpointBuilder, bytesLimit: number, payload: Payload) {\n const canUseBeacon = !!navigator.sendBeacon && payload.bytesCount < bytesLimit\n if (canUseBeacon) {\n try {\n const beaconUrl = endpointBuilder.build('beacon', payload)\n const isQueued = navigator.sendBeacon(beaconUrl, payload.data)\n\n if (isQueued) {\n return\n }\n } catch (e) {\n reportBeaconError(e)\n }\n }\n\n const xhrUrl = endpointBuilder.build('xhr', payload)\n sendXHR(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 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(xhrUrl, payload.data, onResponse)\n })\n )\n } else {\n const xhrUrl = endpointBuilder.build('xhr', payload)\n sendXHR(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(url: string, data: Payload['data'], onResponse?: (r: HttpResponse) => void) {\n const request = new XMLHttpRequest()\n request.open('POST', url, true)\n if (data instanceof Blob) {\n // When using a Blob instance, IE does not use its 'type' to define the 'Content-Type' header\n // automatically, so the intake request ends up being rejected with an HTTP status 415\n // Defining the header manually fixes this issue.\n request.setRequestHeader('Content-Type', data.type)\n }\n addEventListener(\n // allow untrusted event to acount for synthetic event dispatched by third party xhr wrapper\n { allowUntrustedEvents: true },\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 { 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() {\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 && bridge.getCapabilities().includes(capability)\n}\n\nexport function canUseEventBridge(currentHost = getGlobalObject().location?.hostname): boolean {\n const bridge = getEventBridge()\n return (\n !!bridge &&\n bridge\n .getAllowedWebViewHosts()\n .some((allowedHost) => currentHost === allowedHost || currentHost.endsWith(`.${allowedHost}`))\n )\n}\n\nfunction getEventBridgeGlobal() {\n return getGlobalObject().DatadogEventBridge\n}\n", "import { Observable } from '../tools/observable'\nimport { objectValues } 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 {\n return new Observable((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): reason is PageExitReason {\n return objectValues(PageExitReason).includes(reason as PageExitReason)\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 { 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\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\n sessionExpireObservable: Observable\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(() => () => {\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 { 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 extends BatchConfiguration {\n transformMessage?: (message: T) => T\n}\n\nexport function startBatchWithReplica(\n configuration: Configuration,\n primary: BatchConfiguration,\n replica: ReplicaBatchConfiguration | undefined,\n reportError: (error: RawError) => void,\n pageExitObservable: Observable,\n sessionExpireObservable: Observable,\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(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 { computeBytesCount } from './utils/byteUtils'\n\nexport interface Encoder {\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) => 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 & { 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 {\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 {\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", "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\n * new LifeCycle().notify('foo')\n * ```\n */\ntype EventTypesWithoutData = {\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 {\n private callbacks: { [key in keyof EventMap]?: Array<(data: any) => void> } = {}\n\n notify>(eventType: EventType): void\n notify(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(\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 { 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\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 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 {\n state: 'start'\n startClocks: ClocksState\n isAborted: boolean\n xhr: XMLHttpRequest\n handlingStack?: string\n}\n\nexport interface XhrCompleteContext extends Omit {\n state: 'complete'\n duration: Duration\n status: number\n}\n\nexport type XhrContext = XhrOpenContext | XhrStartContext | XhrCompleteContext\n\nlet xhrObservable: Observable | undefined\nconst xhrContexts = new WeakMap()\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((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) {\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,\n configuration: Configuration,\n observable: Observable\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) {\n const context = xhrContexts.get(xhr) as XhrStartContext | undefined\n if (context) {\n context.isAborted = true\n }\n}\n", "import type { InstrumentedMethodCall } from '../tools/instrumentMethod'\nimport { instrumentMethod } from '../tools/instrumentMethod'\nimport { monitor } from '../tools/monitor'\nimport { Observable } from '../tools/observable'\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 | 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((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,\n observable: Observable\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,\n responsePromise: Promise,\n startContext: FetchStartContext\n) {\n const context = startContext as unknown as FetchResolveContext\n\n function reportFetch(partialContext: Partial) {\n context.state = 'resolve'\n Object.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 { flattenErrorCauses, isError, tryToGetFingerprint } from '../error/error'\nimport { mergeObservables, Observable } from '../../tools/observable'\nimport { ConsoleApiName, globalConsole } from '../../tools/display'\nimport { callMonitored } from '../../tools/monitor'\nimport { sanitize } from '../../tools/serialisation/sanitize'\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify'\nimport 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\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 typeof ConsoleApiName.error\n ? ErrorConsoleLog\n : NonErrorConsoleLog\n\nlet consoleObservablesByApi: { [K in ConsoleApiName]?: Observable> } = {}\n\nexport function initConsoleObservable(apis: T): Observable> {\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>\n })\n\n return mergeObservables(...consoleObservables)\n}\n\nexport function resetConsoleObservable() {\n consoleObservablesByApi = {}\n}\n\nfunction createConsoleObservable(api: ConsoleApiName) {\n return new Observable((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 = params.find(isError)\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 (isError(param)) {\n return formatErrorMessage(computeStackTrace(param))\n }\n return jsonStringify(sanitize(param), undefined, 2)\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 { display } from '../../tools/display'\nimport type { CustomerDataTracker } from './customerDataTracker'\n\nexport type ContextManager = ReturnType\n\nexport type PropertiesConfig = {\n [key: string]: {\n required?: boolean\n type?: 'string'\n }\n}\n\nfunction ensureProperties(context: Context, propertiesConfig: PropertiesConfig, name: string) {\n const newContext = { ...context }\n\n for (const [key, { required, type }] of Object.entries(propertiesConfig)) {\n /**\n * Ensure specified properties are strings as defined here:\n * https://docs.datadoghq.com/logs/log_configuration/attributes_naming_convention/#user-related-attributes\n */\n if (type === 'string' && key in newContext) {\n /* eslint-disable @typescript-eslint/no-base-to-string */\n newContext[key] = String(newContext[key])\n }\n\n if (required && !(key in context)) {\n display.warn(`The property ${key} of ${name} context is required; context will not be sent to the intake.`)\n }\n }\n\n return newContext\n}\n\nexport function createContextManager(\n name: string = '',\n {\n customerDataTracker,\n propertiesConfig = {},\n }: {\n customerDataTracker?: CustomerDataTracker\n propertiesConfig?: PropertiesConfig\n } = {}\n) {\n let context: Context = {}\n const changeObservable = new Observable()\n\n const contextManager = {\n getContext: () => deepClone(context),\n\n setContext: (newContext: Context) => {\n if (getType(newContext) === 'object') {\n context = sanitize(ensureProperties(newContext, propertiesConfig, name))\n customerDataTracker?.updateCustomerData(context)\n } else {\n contextManager.clearContext()\n }\n changeObservable.notify()\n },\n\n setContextProperty: (key: string, property: any) => {\n context[key] = sanitize(ensureProperties({ [key]: property }, propertiesConfig, name)[key])\n customerDataTracker?.updateCustomerData(context)\n changeObservable.notify()\n },\n\n removeContextProperty: (key: string) => {\n delete context[key]\n customerDataTracker?.updateCustomerData(context)\n ensureProperties(context, propertiesConfig, name)\n changeObservable.notify()\n },\n\n clearContext: () => {\n context = {}\n customerDataTracker?.resetCustomerData()\n changeObservable.notify()\n },\n\n changeObservable,\n }\n return contextManager\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 { 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\nexport type CustomerDataTrackerManager = ReturnType\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()\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", "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,\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) => {\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 { 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", "import { display } from '../../tools/display'\nimport { getType } from '../../tools/utils/typeUtils'\nimport type { User } from './user.types'\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 { Logger, HandlerType } from '../logger'\n\nexport function isAuthorized(status: StatusType, handlerType: HandlerType, logger: Logger) {\n const loggerHandler = logger.getHandler()\n const sanitizedHandlerType = Array.isArray(loggerHandler) ? loggerHandler : [loggerHandler]\n return STATUS_PRIORITIES[status] >= STATUS_PRIORITIES[logger.getLevel()] && sanitizedHandlerType.includes(handlerType)\n}\n\nexport const StatusType = {\n ok: 'ok',\n debug: 'debug',\n info: 'info',\n notice: 'notice',\n warn: 'warn',\n error: 'error',\n critical: 'critical',\n alert: 'alert',\n emerg: 'emerg',\n} as const\n\nexport const STATUS_PRIORITIES: { [key in StatusType]: number } = {\n [StatusType.ok]: 0,\n [StatusType.debug]: 1,\n [StatusType.info]: 2,\n [StatusType.notice]: 4,\n [StatusType.warn]: 5,\n [StatusType.error]: 6,\n [StatusType.critical]: 7,\n [StatusType.alert]: 8,\n [StatusType.emerg]: 9,\n}\n\nexport type StatusType = (typeof StatusType)[keyof typeof StatusType]\n", "import type { RawError } from '@datadog/browser-core'\nimport type { RawLoggerLogsEvent } from '../rawLogsEvent.types'\n\nexport function createErrorFieldFromRawError(\n rawError: RawError,\n {\n /**\n * Set this to `true` to include the error message in the error field. In most cases, the error\n * message is already included in the log message, so we don't need to include it again.\n */\n includeMessage = false,\n } = {}\n): NonNullable {\n return {\n stack: rawError.stack,\n kind: rawError.type,\n message: includeMessage ? rawError.message : undefined,\n causes: rawError.causes,\n fingerprint: rawError.fingerprint,\n handling: rawError.handling,\n }\n}\n", "import type { Context, ContextManager, CustomerDataTracker } from '@datadog/browser-core'\nimport {\n clocksNow,\n computeRawError,\n ErrorHandling,\n computeStackTrace,\n combine,\n createContextManager,\n ErrorSource,\n monitored,\n sanitize,\n NonErrorPrefix,\n createHandlingStack,\n isError,\n} from '@datadog/browser-core'\n\nimport { isAuthorized, StatusType } from './logger/isAuthorized'\nimport { createErrorFieldFromRawError } from './createErrorFieldFromRawError'\n\nexport interface LogsMessage {\n message: string\n status: StatusType\n context?: Context\n}\n\nexport const HandlerType = {\n console: 'console',\n http: 'http',\n silent: 'silent',\n} as const\n\nexport type HandlerType = (typeof HandlerType)[keyof typeof HandlerType]\nexport const STATUSES = Object.keys(StatusType) as StatusType[]\n\n// note: it is safe to merge declarations as long as the methods are actually defined on the prototype\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging, no-restricted-syntax\nexport class Logger {\n private contextManager: ContextManager\n\n constructor(\n private handleLogStrategy: (logsMessage: LogsMessage, logger: Logger, handlingStack?: string) => void,\n customerDataTracker: CustomerDataTracker,\n name?: string,\n private handlerType: HandlerType | HandlerType[] = HandlerType.http,\n private level: StatusType = StatusType.debug,\n loggerContext: object = {}\n ) {\n this.contextManager = createContextManager('logger', { customerDataTracker })\n this.contextManager.setContext(loggerContext as Context)\n if (name) {\n this.contextManager.setContextProperty('logger', { name })\n }\n }\n\n @monitored\n logImplementation(\n message: string,\n messageContext?: object,\n status: StatusType = StatusType.info,\n error?: Error,\n handlingStack?: string\n ) {\n const sanitizedMessageContext = sanitize(messageContext) as Context\n let context: Context\n\n if (error !== undefined && error !== null) {\n const rawError = computeRawError({\n stackTrace: isError(error) ? computeStackTrace(error) : undefined,\n originalError: error,\n nonErrorPrefix: NonErrorPrefix.PROVIDED,\n source: ErrorSource.LOGGER,\n handling: ErrorHandling.HANDLED,\n startClocks: clocksNow(),\n })\n\n context = combine(\n {\n error: createErrorFieldFromRawError(rawError, { includeMessage: true }),\n },\n sanitizedMessageContext\n )\n } else {\n context = sanitizedMessageContext\n }\n\n this.handleLogStrategy(\n {\n message: sanitize(message)!,\n context,\n status,\n },\n this,\n handlingStack\n )\n }\n\n log(message: string, messageContext?: object, status: StatusType = StatusType.info, error?: Error) {\n let handlingStack: string | undefined\n\n if (isAuthorized(status, HandlerType.http, this)) {\n handlingStack = createHandlingStack()\n }\n\n this.logImplementation(message, messageContext, status, error, handlingStack)\n }\n\n setContext(context: object) {\n this.contextManager.setContext(context as Context)\n }\n\n getContext() {\n return this.contextManager.getContext()\n }\n\n setContextProperty(key: string, value: any) {\n this.contextManager.setContextProperty(key, value)\n }\n\n removeContextProperty(key: string) {\n this.contextManager.removeContextProperty(key)\n }\n\n clearContext() {\n this.contextManager.clearContext()\n }\n\n setHandler(handler: HandlerType | HandlerType[]) {\n this.handlerType = handler\n }\n\n getHandler() {\n return this.handlerType\n }\n\n setLevel(level: StatusType) {\n this.level = level\n }\n\n getLevel() {\n return this.level\n }\n}\n\n/* eslint-disable local-rules/disallow-side-effects */\nLogger.prototype.ok = createLoggerMethod(StatusType.ok)\nLogger.prototype.debug = createLoggerMethod(StatusType.debug)\nLogger.prototype.info = createLoggerMethod(StatusType.info)\nLogger.prototype.notice = createLoggerMethod(StatusType.notice)\nLogger.prototype.warn = createLoggerMethod(StatusType.warn)\nLogger.prototype.error = createLoggerMethod(StatusType.error)\nLogger.prototype.critical = createLoggerMethod(StatusType.critical)\nLogger.prototype.alert = createLoggerMethod(StatusType.alert)\nLogger.prototype.emerg = createLoggerMethod(StatusType.emerg)\n/* eslint-enable local-rules/disallow-side-effects */\n\n// note: it is safe to merge declarations as long as the methods are actually defined on the prototype\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport interface Logger {\n ok(message: string, messageContext?: object, error?: Error): void\n debug(message: string, messageContext?: object, error?: Error): void\n info(message: string, messageContext?: object, error?: Error): void\n notice(message: string, messageContext?: object, error?: Error): void\n warn(message: string, messageContext?: object, error?: Error): void\n error(message: string, messageContext?: object, error?: Error): void\n critical(message: string, messageContext?: object, error?: Error): void\n alert(message: string, messageContext?: object, error?: Error): void\n emerg(message: string, messageContext?: object, error?: Error): void\n}\n\nfunction createLoggerMethod(status: StatusType) {\n return function (this: Logger, message: string, messageContext?: object, error?: Error) {\n let handlingStack: string | undefined\n\n if (isAuthorized(status, HandlerType.http, this)) {\n handlingStack = createHandlingStack()\n }\n\n this.logImplementation(message, messageContext, status, error, handlingStack)\n }\n}\n", "import type { ContextManager } from '@datadog/browser-core'\nimport type { CommonContext } from '../../rawLogsEvent.types'\n\nexport function buildCommonContext(\n globalContextManager: ContextManager,\n userContextManager: ContextManager\n): CommonContext {\n return {\n view: {\n referrer: document.referrer,\n url: window.location.href,\n },\n context: globalContextManager.getContext(),\n user: userContextManager.getContext(),\n }\n}\n", "import type { Configuration, InitConfiguration, RawTelemetryConfiguration } from '@datadog/browser-core'\nimport {\n serializeConfiguration,\n ONE_KIBI_BYTE,\n validateAndBuildConfiguration,\n display,\n removeDuplicates,\n ConsoleApiName,\n RawReportType,\n objectValues,\n} from '@datadog/browser-core'\nimport type { LogsEvent } from '../logsEvent.types'\nimport type { LogsEventDomainContext } from '../domainContext.types'\n\nexport interface LogsInitConfiguration extends InitConfiguration {\n /**\n * Access to every logs collected by the Logs SDK before they are sent to Datadog.\n * It allows:\n * - Enrich your logs with additional context attributes\n * - Modify your logs to modify their content, or redact sensitive sequences (see the list of editable properties)\n * - Discard selected logs\n */\n beforeSend?: ((event: LogsEvent, context: LogsEventDomainContext) => boolean) | undefined\n /**\n * Forward console.error logs, uncaught exceptions and network errors to Datadog.\n * @default true\n */\n forwardErrorsToLogs?: boolean | undefined\n /**\n * Forward logs from console.* to Datadog. Use \"all\" to forward everything or an array of console API names to forward only a subset.\n */\n forwardConsoleLogs?: ConsoleApiName[] | 'all' | undefined\n /**\n * Forward reports from the [Reporting API](https://developer.mozilla.org/en-US/docs/Web/API/Reporting_API) to Datadog. Use \"all\" to forward everything or an array of report types to forward only a subset.\n */\n forwardReports?: RawReportType[] | 'all' | undefined\n /**\n * Use PCI-compliant intake. See [PCI DSS Compliance](https://docs.datadoghq.com/data_security/pci_compliance/?tab=logmanagement) for further information.\n * @default false\n */\n usePciIntake?: boolean\n}\n\nexport type HybridInitConfiguration = Omit\n\nexport interface LogsConfiguration extends Configuration {\n forwardErrorsToLogs: boolean\n forwardConsoleLogs: ConsoleApiName[]\n forwardReports: RawReportType[]\n requestErrorResponseLengthLimit: number\n}\n\n/**\n * arbitrary value, byte precision not needed\n */\nexport const DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT = 32 * ONE_KIBI_BYTE\n\nexport function validateAndBuildLogsConfiguration(\n initConfiguration: LogsInitConfiguration\n): LogsConfiguration | undefined {\n if (initConfiguration.usePciIntake === true && initConfiguration.site && initConfiguration.site !== 'datadoghq.com') {\n display.warn(\n 'PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.'\n )\n }\n\n const baseConfiguration = validateAndBuildConfiguration(initConfiguration)\n\n const forwardConsoleLogs = validateAndBuildForwardOption(\n initConfiguration.forwardConsoleLogs,\n objectValues(ConsoleApiName),\n 'Forward Console Logs'\n )\n\n const forwardReports = validateAndBuildForwardOption(\n initConfiguration.forwardReports,\n objectValues(RawReportType),\n 'Forward Reports'\n )\n\n if (!baseConfiguration || !forwardConsoleLogs || !forwardReports) {\n return\n }\n\n if (initConfiguration.forwardErrorsToLogs && !forwardConsoleLogs.includes(ConsoleApiName.error)) {\n forwardConsoleLogs.push(ConsoleApiName.error)\n }\n\n return {\n forwardErrorsToLogs: initConfiguration.forwardErrorsToLogs !== false,\n forwardConsoleLogs,\n forwardReports,\n requestErrorResponseLengthLimit: DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT,\n ...baseConfiguration,\n }\n}\n\nexport function validateAndBuildForwardOption(\n option: readonly T[] | 'all' | undefined,\n allowedValues: T[],\n label: string\n): T[] | undefined {\n if (option === undefined) {\n return []\n }\n\n if (!(option === 'all' || (Array.isArray(option) && option.every((api) => allowedValues.includes(api))))) {\n display.error(`${label} should be \"all\" or an array with allowed values \"${allowedValues.join('\", \"')}\"`)\n return\n }\n\n return option === 'all' ? allowedValues : removeDuplicates(option)\n}\n\nexport function serializeLogsConfiguration(configuration: LogsInitConfiguration) {\n const baseSerializedInitConfiguration = serializeConfiguration(configuration)\n\n return {\n forward_errors_to_logs: configuration.forwardErrorsToLogs,\n forward_console_logs: configuration.forwardConsoleLogs,\n forward_reports: configuration.forwardReports,\n use_pci_intake: configuration.usePciIntake,\n ...baseSerializedInitConfiguration,\n } satisfies RawTelemetryConfiguration\n}\n", "import type { TrackingConsentState } from '@datadog/browser-core'\nimport {\n createBoundedBuffer,\n canUseEventBridge,\n display,\n displayAlreadyInitializedError,\n initFeatureFlags,\n initFetchObservable,\n noop,\n timeStampNow,\n} from '@datadog/browser-core'\nimport {\n validateAndBuildLogsConfiguration,\n type LogsConfiguration,\n type LogsInitConfiguration,\n} from '../domain/configuration'\nimport type { CommonContext } from '../rawLogsEvent.types'\nimport type { Strategy } from './logsPublicApi'\nimport type { StartLogsResult } from './startLogs'\n\nexport function createPreStartStrategy(\n getCommonContext: () => CommonContext,\n trackingConsentState: TrackingConsentState,\n doStartLogs: (initConfiguration: LogsInitConfiguration, configuration: LogsConfiguration) => StartLogsResult\n): Strategy {\n const bufferApiCalls = createBoundedBuffer()\n let cachedInitConfiguration: LogsInitConfiguration | undefined\n let cachedConfiguration: LogsConfiguration | undefined\n const trackingConsentStateSubscription = trackingConsentState.observable.subscribe(tryStartLogs)\n\n function tryStartLogs() {\n if (!cachedConfiguration || !cachedInitConfiguration || !trackingConsentState.isGranted()) {\n return\n }\n\n trackingConsentStateSubscription.unsubscribe()\n const startLogsResult = doStartLogs(cachedInitConfiguration, cachedConfiguration)\n\n bufferApiCalls.drain(startLogsResult)\n }\n\n return {\n init(initConfiguration) {\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 if (canUseEventBridge()) {\n initConfiguration = overrideInitConfigurationForBridge(initConfiguration)\n }\n\n // Expose the initial configuration regardless of initialization success.\n cachedInitConfiguration = initConfiguration\n\n if (cachedConfiguration) {\n displayAlreadyInitializedError('DD_LOGS', initConfiguration)\n return\n }\n\n const configuration = validateAndBuildLogsConfiguration(initConfiguration)\n if (!configuration) {\n return\n }\n\n cachedConfiguration = configuration\n // Instrumuent fetch to track network requests\n // This is needed in case the consent is not granted and some cutsomer\n // library (Apollo Client) is storing uninstrumented fetch to be used later\n // The subscrption is needed so that the instrumentation process is completed\n initFetchObservable().subscribe(noop)\n\n trackingConsentState.tryToInit(configuration.trackingConsent)\n tryStartLogs()\n },\n\n get initConfiguration() {\n return cachedInitConfiguration\n },\n\n getInternalContext: noop as () => undefined,\n\n handleLog(message, statusType, handlingStack, context = getCommonContext(), date = timeStampNow()) {\n bufferApiCalls.add((startLogsResult) =>\n startLogsResult.handleLog(message, statusType, handlingStack, context, date)\n )\n },\n }\n}\n\nfunction overrideInitConfigurationForBridge(initConfiguration: LogsInitConfiguration): LogsInitConfiguration {\n return { ...initConfiguration, clientToken: 'empty' }\n}\n", "import type { Context, TrackingConsent, User, PublicApi } from '@datadog/browser-core'\nimport {\n addTelemetryUsage,\n CustomerDataType,\n createContextManager,\n makePublicApi,\n monitor,\n checkUser,\n sanitize,\n createCustomerDataTrackerManager,\n storeContextManager,\n displayAlreadyInitializedError,\n deepClone,\n createTrackingConsentState,\n} from '@datadog/browser-core'\nimport type { LogsInitConfiguration } from '../domain/configuration'\nimport type { HandlerType } from '../domain/logger'\nimport type { StatusType } from '../domain/logger/isAuthorized'\nimport { Logger } from '../domain/logger'\nimport { buildCommonContext } from '../domain/contexts/commonContext'\nimport type { InternalContext } from '../domain/contexts/internalContext'\nimport type { StartLogs, StartLogsResult } from './startLogs'\nimport { createPreStartStrategy } from './preStartLogs'\n\nexport interface LoggerConfiguration {\n level?: StatusType\n handler?: HandlerType | HandlerType[]\n context?: object\n}\n\nexport interface LogsPublicApi extends PublicApi {\n logger: Logger\n\n /**\n * Init the Logs browser SDK.\n * @param initConfiguration Configuration options of the SDK\n *\n * See [Browser Log Collection](https://docs.datadoghq.com/logs/log_collection/javascript) for further information.\n */\n init: (initConfiguration: LogsInitConfiguration) => 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 * Logs 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 setTrackingConsent: (trackingConsent: TrackingConsent) => void\n\n /**\n * Get the global Context\n *\n * See [Overwrite context](https://docs.datadoghq.com/logs/log_collection/javascript/#overwrite-context) for further information.\n */\n getGlobalContext: () => Context\n\n /**\n * Set the global context information to all logs, stored in `@context`\n *\n * @param context Global context\n *\n * See [Overwrite context](https://docs.datadoghq.com/logs/log_collection/javascript/#overwrite-context) for further information.\n */\n setGlobalContext: (context: any) => void\n\n /**\n * Set or update a global context property, stored in `@context.`\n *\n * @param key Key of the property\n * @param property Value of the property\n *\n * See [Overwrite context](https://docs.datadoghq.com/logs/log_collection/javascript/#overwrite-context) for further information.\n */\n setGlobalContextProperty: (key: any, value: any) => void\n\n /**\n * Remove a global context property\n *\n * See [Overwrite context](https://docs.datadoghq.com/logs/log_collection/javascript/#overwrite-context) for further information.\n */\n removeGlobalContextProperty: (key: any) => void\n\n /**\n * Clear the global context\n *\n * See [Overwrite context](https://docs.datadoghq.com/logs/log_collection/javascript/#overwrite-context) for further information.\n */\n clearGlobalContext: () => void\n\n /**\n * The Datadog browser logs SDK contains a default logger `DD_LOGS.logger`, but this API allows to create different ones.\n *\n * See [Define multiple loggers](https://docs.datadoghq.com/logs/log_collection/javascript/#define-multiple-loggers) for further information.\n */\n createLogger: (name: string, conf?: LoggerConfiguration) => Logger\n\n /**\n * Get a logger\n *\n * See [Define multiple loggers](https://docs.datadoghq.com/logs/log_collection/javascript/#define-multiple-loggers) for further information.\n */\n getLogger: (name: string) => Logger | undefined\n\n /**\n * Get the init configuration\n */\n getInitConfiguration: () => LogsInitConfiguration | undefined\n\n /**\n * [Internal API] Get the internal SDK context\n *\n * See [Access internal context](https://docs.datadoghq.com/logs/log_collection/javascript/#access-internal-context) for further information.\n */\n getInternalContext: (startTime?: number) => InternalContext | undefined\n\n /**\n * Set user information to all events, stored in `@usr`\n *\n * See [User context](https://docs.datadoghq.com/logs/log_collection/javascript/#user-context) for further information.\n */\n setUser: (newUser: User) => void\n\n /**\n * Get user information\n *\n * See [User context](https://docs.datadoghq.com/logs/log_collection/javascript/#user-context) for further information.\n */\n getUser: () => Context\n\n /**\n * Set or update the user property, stored in `@usr.`\n *\n * @param key Key of the property\n * @param property Value of the property\n *\n * See [User context](https://docs.datadoghq.com/logs/log_collection/javascript/#user-context) for further information.\n */\n setUserProperty: (key: any, property: any) => void\n\n /**\n * Remove a user property\n *\n * See [User context](https://docs.datadoghq.com/logs/log_collection/javascript/#user-context) for further information.\n */\n removeUserProperty: (key: any) => void\n\n /**\n * Clear all user information\n *\n * See [User context](https://docs.datadoghq.com/logs/log_collection/javascript/#user-context) for further information.\n */\n clearUser: () => void\n}\n\nconst LOGS_STORAGE_KEY = 'logs'\n\nexport interface Strategy {\n init: (initConfiguration: LogsInitConfiguration) => void\n initConfiguration: LogsInitConfiguration | undefined\n getInternalContext: StartLogsResult['getInternalContext']\n handleLog: StartLogsResult['handleLog']\n}\n\nexport function makeLogsPublicApi(startLogsImpl: StartLogs): LogsPublicApi {\n const customerDataTrackerManager = createCustomerDataTrackerManager()\n const globalContextManager = createContextManager('global', {\n customerDataTracker: customerDataTrackerManager.getOrCreateTracker(CustomerDataType.GlobalContext),\n })\n const userContextManager = createContextManager('user', {\n customerDataTracker: customerDataTrackerManager.getOrCreateTracker(CustomerDataType.User),\n propertiesConfig: {\n id: { type: 'string' },\n name: { type: 'string' },\n email: { type: 'string' },\n },\n })\n const trackingConsentState = createTrackingConsentState()\n\n function getCommonContext() {\n return buildCommonContext(globalContextManager, userContextManager)\n }\n\n let strategy = createPreStartStrategy(getCommonContext, trackingConsentState, (initConfiguration, configuration) => {\n if (initConfiguration.storeContextsAcrossPages) {\n storeContextManager(configuration, globalContextManager, LOGS_STORAGE_KEY, CustomerDataType.GlobalContext)\n storeContextManager(configuration, userContextManager, LOGS_STORAGE_KEY, CustomerDataType.User)\n }\n\n const startLogsResult = startLogsImpl(initConfiguration, configuration, getCommonContext, trackingConsentState)\n\n strategy = createPostStartStrategy(initConfiguration, startLogsResult)\n return startLogsResult\n })\n\n const customLoggers: { [name: string]: Logger | undefined } = {}\n\n const mainLogger = new Logger(\n (...params) => strategy.handleLog(...params),\n customerDataTrackerManager.createDetachedTracker()\n )\n\n return makePublicApi({\n logger: mainLogger,\n\n init: monitor((initConfiguration) => strategy.init(initConfiguration)),\n\n setTrackingConsent: monitor((trackingConsent) => {\n trackingConsentState.update(trackingConsent)\n addTelemetryUsage({ feature: 'set-tracking-consent', tracking_consent: trackingConsent })\n }),\n\n getGlobalContext: monitor(() => globalContextManager.getContext()),\n\n setGlobalContext: monitor((context) => globalContextManager.setContext(context)),\n\n setGlobalContextProperty: monitor((key, value) => globalContextManager.setContextProperty(key, value)),\n\n removeGlobalContextProperty: monitor((key) => globalContextManager.removeContextProperty(key)),\n\n clearGlobalContext: monitor(() => globalContextManager.clearContext()),\n\n createLogger: monitor((name, conf = {}) => {\n customLoggers[name] = new Logger(\n (...params) => strategy.handleLog(...params),\n customerDataTrackerManager.createDetachedTracker(),\n sanitize(name),\n conf.handler,\n conf.level,\n sanitize(conf.context) as object\n )\n\n return customLoggers[name]\n }),\n\n getLogger: monitor((name) => customLoggers[name]),\n\n getInitConfiguration: monitor(() => deepClone(strategy.initConfiguration)),\n\n getInternalContext: monitor((startTime) => strategy.getInternalContext(startTime)),\n\n setUser: monitor((newUser) => {\n if (checkUser(newUser)) {\n userContextManager.setContext(newUser as Context)\n }\n }),\n\n getUser: monitor(() => userContextManager.getContext()),\n\n setUserProperty: monitor((key, property) => {\n userContextManager.setContextProperty(key, property)\n }),\n\n removeUserProperty: monitor((key) => userContextManager.removeContextProperty(key)),\n\n clearUser: monitor(() => userContextManager.clearContext()),\n })\n}\n\nfunction createPostStartStrategy(initConfiguration: LogsInitConfiguration, startLogsResult: StartLogsResult): Strategy {\n return {\n init: (initConfiguration: LogsInitConfiguration) => {\n displayAlreadyInitializedError('DD_LOGS', initConfiguration)\n },\n initConfiguration,\n ...startLogsResult,\n }\n}\n", "import type { RelativeTime, TrackingConsentState } from '@datadog/browser-core'\nimport { Observable, performDraw, startSessionManager } from '@datadog/browser-core'\nimport type { LogsConfiguration } from './configuration'\n\nexport const LOGS_SESSION_KEY = 'logs'\n\nexport interface LogsSessionManager {\n findTrackedSession: (startTime?: RelativeTime, options?: { returnInactive: boolean }) => LogsSession | undefined\n expireObservable: Observable\n}\n\nexport type LogsSession = {\n id?: string // session can be tracked without id\n anonymousId?: string // device id lasts across session\n}\n\nexport const enum LoggerTrackingType {\n NOT_TRACKED = '0',\n TRACKED = '1',\n}\n\nexport function startLogsSessionManager(\n configuration: LogsConfiguration,\n trackingConsentState: TrackingConsentState\n): LogsSessionManager {\n const sessionManager = startSessionManager(\n configuration,\n LOGS_SESSION_KEY,\n (rawTrackingType) => computeSessionState(configuration, rawTrackingType),\n trackingConsentState\n )\n return {\n findTrackedSession: (startTime?: RelativeTime, options = { returnInactive: false }) => {\n const session = sessionManager.findSession(startTime, options)\n return session && session.trackingType === LoggerTrackingType.TRACKED\n ? {\n id: session.id,\n anonymousId: session.anonymousId,\n }\n : undefined\n },\n expireObservable: sessionManager.expireObservable,\n }\n}\n\nexport function startLogsSessionManagerStub(configuration: LogsConfiguration): LogsSessionManager {\n const isTracked = computeTrackingType(configuration) === LoggerTrackingType.TRACKED\n const session = isTracked ? {} : undefined\n return {\n findTrackedSession: () => session,\n expireObservable: new Observable(),\n }\n}\n\nfunction computeTrackingType(configuration: LogsConfiguration) {\n if (!performDraw(configuration.sessionSampleRate)) {\n return LoggerTrackingType.NOT_TRACKED\n }\n return LoggerTrackingType.TRACKED\n}\n\nfunction computeSessionState(configuration: LogsConfiguration, rawSessionType?: string) {\n const trackingType = hasValidLoggerSession(rawSessionType) ? rawSessionType : computeTrackingType(configuration)\n return {\n trackingType,\n isTracked: trackingType === LoggerTrackingType.TRACKED,\n }\n}\n\nfunction hasValidLoggerSession(trackingType?: string): trackingType is LoggerTrackingType {\n return trackingType === LoggerTrackingType.NOT_TRACKED || trackingType === LoggerTrackingType.TRACKED\n}\n", "import type { RelativeTime, Context } from '@datadog/browser-core'\nimport {\n willSyntheticsInjectRum,\n addTelemetryDebug,\n getSyntheticsTestId,\n getSyntheticsResultId,\n} from '@datadog/browser-core'\n\ninterface Rum {\n getInternalContext?: (startTime?: RelativeTime) => Context | undefined\n}\n\ninterface BrowserWindow {\n DD_RUM?: Rum\n DD_RUM_SYNTHETICS?: Rum\n}\n\nlet logsSentBeforeRumInjectionTelemetryAdded = false\n\nexport function getRUMInternalContext(startTime?: RelativeTime): Context | undefined {\n const browserWindow = window as BrowserWindow\n\n if (willSyntheticsInjectRum()) {\n const context = getInternalContextFromRumGlobal(browserWindow.DD_RUM_SYNTHETICS)\n if (!context && !logsSentBeforeRumInjectionTelemetryAdded) {\n logsSentBeforeRumInjectionTelemetryAdded = true\n addTelemetryDebug('Logs sent before RUM is injected by the synthetics worker', {\n testId: getSyntheticsTestId(),\n resultId: getSyntheticsResultId(),\n })\n }\n return context\n }\n\n return getInternalContextFromRumGlobal(browserWindow.DD_RUM)\n\n function getInternalContextFromRumGlobal(rumGlobal?: Rum): Context | undefined {\n if (rumGlobal && rumGlobal.getInternalContext) {\n return rumGlobal.getInternalContext(startTime)\n }\n }\n}\n\nexport function resetRUMInternalContext() {\n logsSentBeforeRumInjectionTelemetryAdded = false\n}\n", "import type { EventRateLimiter, RawError } from '@datadog/browser-core'\nimport { ErrorSource, combine, createEventRateLimiter, getRelativeTime, isEmptyObject } from '@datadog/browser-core'\nimport type { CommonContext } from '../rawLogsEvent.types'\nimport type { LogsConfiguration } from './configuration'\nimport type { LifeCycle } from './lifeCycle'\nimport { LifeCycleEventType } from './lifeCycle'\nimport { STATUSES } from './logger'\nimport type { LogsSessionManager } from './logsSessionManager'\nimport { getRUMInternalContext } from './contexts/rumInternalContext'\n\nexport function startLogsAssembly(\n sessionManager: LogsSessionManager,\n configuration: LogsConfiguration,\n lifeCycle: LifeCycle,\n getCommonContext: () => CommonContext,\n reportError: (error: RawError) => void\n) {\n const statusWithCustom = (STATUSES as string[]).concat(['custom'])\n const logRateLimiters: { [key: string]: EventRateLimiter } = {}\n statusWithCustom.forEach((status) => {\n logRateLimiters[status] = createEventRateLimiter(status, configuration.eventRateLimiterThreshold, reportError)\n })\n\n lifeCycle.subscribe(\n LifeCycleEventType.RAW_LOG_COLLECTED,\n ({ rawLogsEvent, messageContext = undefined, savedCommonContext = undefined, domainContext }) => {\n const startTime = getRelativeTime(rawLogsEvent.date)\n const session = sessionManager.findTrackedSession(startTime)\n const shouldSendLog = sessionManager.findTrackedSession(startTime, { returnInactive: true })\n\n if (!shouldSendLog) {\n return\n }\n\n const commonContext = savedCommonContext || getCommonContext()\n if (session && session.anonymousId && !commonContext.user.anonymous_id) {\n commonContext.user.anonymous_id = session.anonymousId\n }\n const log = combine(\n {\n service: configuration.service,\n session_id: session ? session.id : undefined,\n session: session ? { id: session.id } : undefined,\n // Insert user first to allow overrides from global context\n usr: !isEmptyObject(commonContext.user) ? commonContext.user : undefined,\n view: commonContext.view,\n },\n commonContext.context,\n getRUMInternalContext(startTime),\n rawLogsEvent,\n messageContext\n )\n\n if (\n configuration.beforeSend?.(log, domainContext) === false ||\n (log.origin !== ErrorSource.AGENT &&\n (logRateLimiters[log.status] ?? logRateLimiters['custom']).isLimitReached())\n ) {\n return\n }\n\n lifeCycle.notify(LifeCycleEventType.LOG_COLLECTED, log)\n }\n )\n}\n", "import type { Context, ClocksState, ConsoleLog } from '@datadog/browser-core'\nimport { timeStampNow, ConsoleApiName, ErrorSource, initConsoleObservable } from '@datadog/browser-core'\nimport type { LogsConfiguration } from '../configuration'\nimport type { LifeCycle, RawLogsEventCollectedData } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport { StatusType } from '../logger/isAuthorized'\nimport type { RawLogsEvent } from '../../rawLogsEvent.types'\nimport { createErrorFieldFromRawError } from '../createErrorFieldFromRawError'\n\nexport interface ProvidedError {\n startClocks: ClocksState\n error: unknown\n context?: Context\n handlingStack: string\n}\n\nexport const LogStatusForApi = {\n [ConsoleApiName.log]: StatusType.info,\n [ConsoleApiName.debug]: StatusType.debug,\n [ConsoleApiName.info]: StatusType.info,\n [ConsoleApiName.warn]: StatusType.warn,\n [ConsoleApiName.error]: StatusType.error,\n}\nexport function startConsoleCollection(configuration: LogsConfiguration, lifeCycle: LifeCycle) {\n const consoleSubscription = initConsoleObservable(configuration.forwardConsoleLogs).subscribe((log: ConsoleLog) => {\n const collectedData: RawLogsEventCollectedData = {\n rawLogsEvent: {\n date: timeStampNow(),\n message: log.message,\n origin: ErrorSource.CONSOLE,\n error: log.error && createErrorFieldFromRawError(log.error),\n status: LogStatusForApi[log.api],\n },\n domainContext: {\n handlingStack: log.handlingStack,\n },\n }\n\n lifeCycle.notify(LifeCycleEventType.RAW_LOG_COLLECTED, collectedData)\n })\n\n return {\n stop: () => {\n consoleSubscription.unsubscribe()\n },\n }\n}\n", "import type { Context, ClocksState } from '@datadog/browser-core'\nimport { timeStampNow, ErrorSource, getFileFromStackTraceString, initReportObservable } from '@datadog/browser-core'\nimport type { LogsConfiguration } from '../configuration'\nimport type { LifeCycle } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport { StatusType } from '../logger/isAuthorized'\nimport { createErrorFieldFromRawError } from '../createErrorFieldFromRawError'\n\nexport interface ProvidedError {\n startClocks: ClocksState\n error: unknown\n context?: Context\n handlingStack: string\n}\n\nexport function startReportCollection(configuration: LogsConfiguration, lifeCycle: LifeCycle) {\n const reportSubscription = initReportObservable(configuration, configuration.forwardReports).subscribe((rawError) => {\n let message = rawError.message\n let error\n const status = rawError.originalError.type === 'deprecation' ? StatusType.warn : StatusType.error\n\n if (status === StatusType.error) {\n error = createErrorFieldFromRawError(rawError)\n } else if (rawError.stack) {\n message += ` Found in ${getFileFromStackTraceString(rawError.stack)!}`\n }\n\n lifeCycle.notify(LifeCycleEventType.RAW_LOG_COLLECTED, {\n rawLogsEvent: {\n date: timeStampNow(),\n message,\n origin: ErrorSource.REPORT,\n error,\n status,\n },\n })\n })\n\n return {\n stop: () => {\n reportSubscription.unsubscribe()\n },\n }\n}\n", "import type { FetchResolveContext, XhrCompleteContext } from '@datadog/browser-core'\nimport {\n ErrorSource,\n initXhrObservable,\n RequestType,\n initFetchObservable,\n computeStackTrace,\n toStackTraceString,\n monitor,\n noop,\n readBytesFromStream,\n tryToClone,\n isServerError,\n isIntakeUrl,\n} from '@datadog/browser-core'\nimport type { LogsConfiguration } from '../configuration'\nimport type { LifeCycle } from '../lifeCycle'\nimport type { LogsEventDomainContext } from '../../domainContext.types'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport { StatusType } from '../logger/isAuthorized'\n\nexport function startNetworkErrorCollection(configuration: LogsConfiguration, lifeCycle: LifeCycle) {\n if (!configuration.forwardErrorsToLogs) {\n return { stop: noop }\n }\n\n const xhrSubscription = initXhrObservable(configuration).subscribe((context) => {\n if (context.state === 'complete') {\n handleResponse(RequestType.XHR, context)\n }\n })\n const fetchSubscription = initFetchObservable().subscribe((context) => {\n if (context.state === 'resolve') {\n handleResponse(RequestType.FETCH, context)\n }\n })\n\n function handleResponse(type: RequestType, request: XhrCompleteContext | FetchResolveContext) {\n if (!isIntakeUrl(request.url) && (isRejected(request) || isServerError(request.status))) {\n if ('xhr' in request) {\n computeXhrResponseData(request.xhr, configuration, onResponseDataAvailable)\n } else if (request.response) {\n computeFetchResponseText(request.response, configuration, onResponseDataAvailable)\n } else if (request.error) {\n computeFetchErrorText(request.error, configuration, onResponseDataAvailable)\n }\n }\n\n function onResponseDataAvailable(responseData: unknown) {\n const domainContext: LogsEventDomainContext = {\n isAborted: request.isAborted,\n handlingStack: request.handlingStack,\n }\n\n lifeCycle.notify(LifeCycleEventType.RAW_LOG_COLLECTED, {\n rawLogsEvent: {\n message: `${format(type)} error ${request.method} ${request.url}`,\n date: request.startClocks.timeStamp,\n error: {\n stack: (responseData as string) || 'Failed to load',\n // We don't know if the error was handled or not, so we set it to undefined\n handling: undefined,\n },\n http: {\n method: request.method as any, // Cast resource method because of case mismatch cf issue RUMF-1152\n status_code: request.status,\n url: request.url,\n },\n status: StatusType.error,\n origin: ErrorSource.NETWORK,\n },\n domainContext,\n })\n }\n }\n\n return {\n stop: () => {\n xhrSubscription.unsubscribe()\n fetchSubscription.unsubscribe()\n },\n }\n}\n\n// TODO: ideally, computeXhrResponseData should always call the callback with a string instead of\n// `unknown`. But to keep backward compatibility, in the case of XHR with a `responseType` different\n// than \"text\", the response data should be whatever `xhr.response` is. This is a bit confusing as\n// Logs event 'stack' is expected to be a string. This should be changed in a future major version\n// as it could be a breaking change.\nexport function computeXhrResponseData(\n xhr: XMLHttpRequest,\n configuration: LogsConfiguration,\n callback: (responseData: unknown) => void\n) {\n if (typeof xhr.response === 'string') {\n callback(truncateResponseText(xhr.response, configuration))\n } else {\n callback(xhr.response)\n }\n}\n\nexport function computeFetchErrorText(\n error: Error,\n configuration: LogsConfiguration,\n callback: (errorText: string) => void\n) {\n callback(truncateResponseText(toStackTraceString(computeStackTrace(error)), configuration))\n}\n\nexport function computeFetchResponseText(\n response: Response,\n configuration: LogsConfiguration,\n callback: (responseText?: string) => void\n) {\n const clonedResponse = tryToClone(response)\n if (!clonedResponse || !clonedResponse.body) {\n // if the clone failed or if the body is null, let's not try to read it.\n callback()\n } else if (!window.TextDecoder) {\n // If the browser doesn't support TextDecoder, let's read the whole response then truncate it.\n //\n // This should only be the case on early versions of Edge (before they migrated to Chromium).\n // Even if it could be possible to implement a workaround for the missing TextDecoder API (using\n // a Blob and FileReader), we found another issue preventing us from reading only the first\n // bytes from the response: contrary to other browsers, when reading from the cloned response,\n // if the original response gets canceled, the cloned response is also canceled and we can't\n // know about it. In the following illustration, the promise returned by `reader.read()` may\n // never be fulfilled:\n //\n // fetch('/').then((response) => {\n // const reader = response.clone().body.getReader()\n // readMore()\n // function readMore() {\n // reader.read().then(\n // (result) => {\n // if (result.done) {\n // console.log('done')\n // } else {\n // readMore()\n // }\n // },\n // () => console.log('error')\n // )\n // }\n // response.body.getReader().cancel()\n // })\n clonedResponse.text().then(\n monitor((text) => callback(truncateResponseText(text, configuration))),\n monitor((error) => callback(`Unable to retrieve response: ${error as string}`))\n )\n } else {\n truncateResponseStream(\n clonedResponse.body,\n configuration.requestErrorResponseLengthLimit,\n (error, responseText) => {\n if (error) {\n callback(`Unable to retrieve response: ${error as unknown as string}`)\n } else {\n callback(responseText)\n }\n }\n )\n }\n}\n\nfunction isRejected(request: { status: number; responseType?: string }) {\n return request.status === 0 && request.responseType !== 'opaque'\n}\n\nfunction truncateResponseText(responseText: string, configuration: LogsConfiguration) {\n if (responseText.length > configuration.requestErrorResponseLengthLimit) {\n return `${responseText.substring(0, configuration.requestErrorResponseLengthLimit)}...`\n }\n return responseText\n}\n\nfunction format(type: RequestType) {\n if (RequestType.XHR === type) {\n return 'XHR'\n }\n return 'Fetch'\n}\n\nfunction truncateResponseStream(\n stream: ReadableStream,\n bytesLimit: number,\n callback: (error?: Error, responseText?: string) => void\n) {\n readBytesFromStream(\n stream,\n (error, bytes, limitExceeded) => {\n if (error) {\n callback(error)\n } else {\n let responseText = new TextDecoder().decode(bytes)\n if (limitExceeded) {\n responseText += '...'\n }\n callback(undefined, responseText)\n }\n },\n {\n bytesLimit,\n collectStreamBody: true,\n }\n )\n}\n", "import type { Context, RawError, ClocksState } from '@datadog/browser-core'\nimport { noop, ErrorSource, trackRuntimeError, Observable } from '@datadog/browser-core'\nimport type { LogsConfiguration } from '../configuration'\nimport type { LifeCycle } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport { StatusType } from '../logger/isAuthorized'\nimport { createErrorFieldFromRawError } from '../createErrorFieldFromRawError'\n\nexport interface ProvidedError {\n startClocks: ClocksState\n error: unknown\n context?: Context\n handlingStack: string\n}\n\nexport function startRuntimeErrorCollection(configuration: LogsConfiguration, lifeCycle: LifeCycle) {\n if (!configuration.forwardErrorsToLogs) {\n return { stop: noop }\n }\n\n const rawErrorObservable = new Observable()\n\n const { stop: stopRuntimeErrorTracking } = trackRuntimeError(rawErrorObservable)\n\n const rawErrorSubscription = rawErrorObservable.subscribe((rawError) => {\n lifeCycle.notify(LifeCycleEventType.RAW_LOG_COLLECTED, {\n rawLogsEvent: {\n message: rawError.message,\n date: rawError.startClocks.timeStamp,\n error: createErrorFieldFromRawError(rawError),\n origin: ErrorSource.SOURCE,\n status: StatusType.error,\n },\n })\n })\n\n return {\n stop: () => {\n stopRuntimeErrorTracking()\n rawErrorSubscription.unsubscribe()\n },\n }\n}\n", "import { AbstractLifeCycle } from '@datadog/browser-core'\nimport type { Context } from '@datadog/browser-core'\nimport type { LogsEvent } from '../logsEvent.types'\nimport type { CommonContext, RawLogsEvent } from '../rawLogsEvent.types'\nimport type { LogsEventDomainContext } from '../domainContext.types'\n\nexport const enum LifeCycleEventType {\n RAW_LOG_COLLECTED,\n LOG_COLLECTED,\n}\n\ninterface LifeCycleEventMap {\n [LifeCycleEventType.RAW_LOG_COLLECTED]: RawLogsEventCollectedData\n [LifeCycleEventType.LOG_COLLECTED]: LogsEvent & Context\n}\n\nexport const LifeCycle = AbstractLifeCycle\nexport type LifeCycle = AbstractLifeCycle\n\nexport interface RawLogsEventCollectedData {\n rawLogsEvent: E\n messageContext?: object\n savedCommonContext?: CommonContext\n domainContext?: LogsEventDomainContext\n}\n", "import type { Context, TimeStamp } from '@datadog/browser-core'\nimport {\n combine,\n ErrorSource,\n timeStampNow,\n originalConsoleMethods,\n globalConsole,\n ConsoleApiName,\n} from '@datadog/browser-core'\nimport type { CommonContext, RawLogsEvent } from '../../rawLogsEvent.types'\nimport type { LifeCycle, RawLogsEventCollectedData } from '../lifeCycle'\nimport { LifeCycleEventType } from '../lifeCycle'\nimport type { Logger, LogsMessage } from '../logger'\nimport { HandlerType } from '../logger'\nimport { isAuthorized, StatusType } from './isAuthorized'\n\nexport function startLoggerCollection(lifeCycle: LifeCycle) {\n function handleLog(\n logsMessage: LogsMessage,\n logger: Logger,\n handlingStack?: string,\n savedCommonContext?: CommonContext,\n savedDate?: TimeStamp\n ) {\n const messageContext = combine(logger.getContext(), logsMessage.context)\n\n if (isAuthorized(logsMessage.status, HandlerType.console, logger)) {\n displayInConsole(logsMessage, messageContext)\n }\n\n if (isAuthorized(logsMessage.status, HandlerType.http, logger)) {\n const rawLogEventData: RawLogsEventCollectedData = {\n rawLogsEvent: {\n date: savedDate || timeStampNow(),\n message: logsMessage.message,\n status: logsMessage.status,\n origin: ErrorSource.LOGGER,\n },\n messageContext,\n savedCommonContext,\n }\n\n if (handlingStack) {\n rawLogEventData.domainContext = { handlingStack }\n }\n\n lifeCycle.notify(LifeCycleEventType.RAW_LOG_COLLECTED, rawLogEventData)\n }\n }\n\n return {\n handleLog,\n }\n}\nconst loggerToConsoleApiName: { [key in StatusType]: ConsoleApiName } = {\n [StatusType.ok]: ConsoleApiName.debug,\n [StatusType.debug]: ConsoleApiName.debug,\n [StatusType.info]: ConsoleApiName.info,\n [StatusType.notice]: ConsoleApiName.info,\n [StatusType.warn]: ConsoleApiName.warn,\n [StatusType.error]: ConsoleApiName.error,\n [StatusType.critical]: ConsoleApiName.error,\n [StatusType.alert]: ConsoleApiName.error,\n [StatusType.emerg]: ConsoleApiName.error,\n}\n\nfunction displayInConsole({ status, message }: LogsMessage, messageContext: Context | undefined) {\n originalConsoleMethods[loggerToConsoleApiName[status]].call(globalConsole, message, messageContext)\n}\n", "import type { Context, Observable, PageExitEvent, RawError } from '@datadog/browser-core'\nimport { createIdentityEncoder, startBatchWithReplica } from '@datadog/browser-core'\nimport type { LogsConfiguration } from '../domain/configuration'\nimport type { LifeCycle } from '../domain/lifeCycle'\nimport { LifeCycleEventType } from '../domain/lifeCycle'\nimport type { LogsEvent } from '../logsEvent.types'\nimport type { LogsSessionManager } from '../domain/logsSessionManager'\n\nexport function startLogsBatch(\n configuration: LogsConfiguration,\n lifeCycle: LifeCycle,\n reportError: (error: RawError) => void,\n pageExitObservable: Observable,\n session: LogsSessionManager\n) {\n const batch = startBatchWithReplica(\n configuration,\n {\n endpoint: configuration.logsEndpointBuilder,\n encoder: createIdentityEncoder(),\n },\n configuration.replica && {\n endpoint: configuration.replica.logsEndpointBuilder,\n encoder: createIdentityEncoder(),\n },\n reportError,\n pageExitObservable,\n session.expireObservable\n )\n\n lifeCycle.subscribe(LifeCycleEventType.LOG_COLLECTED, (serverLogsEvent: LogsEvent & Context) => {\n batch.add(serverLogsEvent)\n })\n\n return batch\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 { LogsEvent } from '../logsEvent.types'\n\nexport function startLogsBridge(lifeCycle: LifeCycle) {\n const bridge = getEventBridge<'log', LogsEvent>()!\n\n lifeCycle.subscribe(LifeCycleEventType.LOG_COLLECTED, (serverLogsEvent: LogsEvent & Context) => {\n bridge.send('log', serverLogsEvent)\n })\n}\n", "import type { RelativeTime } from '@datadog/browser-core'\nimport type { LogsSessionManager } from '../logsSessionManager'\n\nexport interface InternalContext {\n session_id: string | undefined\n}\n\nexport function startInternalContext(sessionManager: LogsSessionManager) {\n return {\n get: (startTime?: number): InternalContext | undefined => {\n const trackedSession = sessionManager.findTrackedSession(startTime as RelativeTime)\n if (trackedSession) {\n return {\n session_id: trackedSession.id,\n }\n }\n },\n }\n}\n", "import type { RawError } from '@datadog/browser-core'\nimport { ErrorSource, addTelemetryDebug } from '@datadog/browser-core'\nimport type { LifeCycle } from './lifeCycle'\nimport { LifeCycleEventType } from './lifeCycle'\nimport { StatusType } from './logger/isAuthorized'\n\nexport function startReportError(lifeCycle: LifeCycle) {\n return (error: RawError) => {\n lifeCycle.notify(LifeCycleEventType.RAW_LOG_COLLECTED, {\n rawLogsEvent: {\n message: error.message,\n date: error.startClocks.timeStamp,\n origin: ErrorSource.AGENT,\n status: StatusType.error,\n },\n })\n addTelemetryDebug('Error reported to customer', { 'error.message': error.message })\n }\n}\n", "import type { RawError, Observable, PageExitEvent, TelemetryEvent, Context } from '@datadog/browser-core'\nimport {\n startTelemetry,\n TelemetryService,\n canUseEventBridge,\n getEventBridge,\n startBatchWithReplica,\n createIdentityEncoder,\n isTelemetryReplicationAllowed,\n addTelemetryConfiguration,\n drainPreStartTelemetry,\n} from '@datadog/browser-core'\nimport type { LogsConfiguration, LogsInitConfiguration } from './configuration'\nimport { getRUMInternalContext } from './contexts/rumInternalContext'\nimport type { LogsSessionManager } from './logsSessionManager'\nimport { serializeLogsConfiguration } from './configuration'\n\nexport function startLogsTelemetry(\n initConfiguration: LogsInitConfiguration,\n configuration: LogsConfiguration,\n reportError: (error: RawError) => void,\n pageExitObservable: Observable,\n session: LogsSessionManager\n) {\n const telemetry = startTelemetry(TelemetryService.LOGS, configuration)\n telemetry.setContextProvider(() => ({\n application: {\n id: getRUMInternalContext()?.application_id,\n },\n session: {\n id: session.findTrackedSession()?.id,\n },\n view: {\n id: (getRUMInternalContext()?.view as Context)?.id,\n },\n action: {\n id: (getRUMInternalContext()?.user_action as Context)?.id,\n },\n }))\n const cleanupTasks: Array<() => void> = []\n if (canUseEventBridge()) {\n const bridge = getEventBridge<'internal_telemetry', TelemetryEvent>()!\n const telemetrySubscription = telemetry.observable.subscribe((event) => bridge.send('internal_telemetry', event))\n cleanupTasks.push(() => telemetrySubscription.unsubscribe())\n } else {\n const telemetryBatch = startBatchWithReplica(\n configuration,\n {\n endpoint: configuration.rumEndpointBuilder,\n encoder: createIdentityEncoder(),\n },\n configuration.replica && {\n endpoint: configuration.replica.rumEndpointBuilder,\n encoder: createIdentityEncoder(),\n },\n reportError,\n pageExitObservable,\n session.expireObservable\n )\n cleanupTasks.push(() => telemetryBatch.stop())\n const telemetrySubscription = telemetry.observable.subscribe((event) =>\n telemetryBatch.add(event, isTelemetryReplicationAllowed(configuration))\n )\n cleanupTasks.push(() => telemetrySubscription.unsubscribe())\n }\n drainPreStartTelemetry()\n addTelemetryConfiguration(serializeLogsConfiguration(initConfiguration))\n return {\n telemetry,\n stop: () => {\n cleanupTasks.forEach((task) => task())\n },\n }\n}\n", "import type { TrackingConsentState } from '@datadog/browser-core'\nimport {\n sendToExtension,\n createPageExitObservable,\n willSyntheticsInjectRum,\n canUseEventBridge,\n} from '@datadog/browser-core'\nimport { startLogsSessionManager, startLogsSessionManagerStub } from '../domain/logsSessionManager'\nimport type { LogsConfiguration, LogsInitConfiguration } from '../domain/configuration'\nimport { startLogsAssembly } from '../domain/assembly'\nimport { startConsoleCollection } from '../domain/console/consoleCollection'\nimport { startReportCollection } from '../domain/report/reportCollection'\nimport { startNetworkErrorCollection } from '../domain/networkError/networkErrorCollection'\nimport { startRuntimeErrorCollection } from '../domain/runtimeError/runtimeErrorCollection'\nimport { LifeCycle, LifeCycleEventType } from '../domain/lifeCycle'\nimport { startLoggerCollection } from '../domain/logger/loggerCollection'\nimport { startLogsBatch } from '../transport/startLogsBatch'\nimport { startLogsBridge } from '../transport/startLogsBridge'\nimport { startInternalContext } from '../domain/contexts/internalContext'\nimport { startReportError } from '../domain/reportError'\nimport { startLogsTelemetry } from '../domain/logsTelemetry'\nimport type { CommonContext } from '../rawLogsEvent.types'\n\nexport type StartLogs = typeof startLogs\nexport type StartLogsResult = ReturnType\n\nexport function startLogs(\n initConfiguration: LogsInitConfiguration,\n configuration: LogsConfiguration,\n getCommonContext: () => CommonContext,\n\n // `startLogs` and its subcomponents assume tracking consent is granted initially and starts\n // collecting logs unconditionally. As such, `startLogs` should be called with a\n // `trackingConsentState` set to \"granted\".\n trackingConsentState: TrackingConsentState\n) {\n const lifeCycle = new LifeCycle()\n const cleanupTasks: Array<() => void> = []\n\n lifeCycle.subscribe(LifeCycleEventType.LOG_COLLECTED, (log) => sendToExtension('logs', log))\n\n const reportError = startReportError(lifeCycle)\n const pageExitObservable = createPageExitObservable(configuration)\n\n const session =\n configuration.sessionStoreStrategyType && !canUseEventBridge() && !willSyntheticsInjectRum()\n ? startLogsSessionManager(configuration, trackingConsentState)\n : startLogsSessionManagerStub(configuration)\n\n const { stop: stopLogsTelemetry } = startLogsTelemetry(\n initConfiguration,\n configuration,\n reportError,\n pageExitObservable,\n session\n )\n cleanupTasks.push(() => stopLogsTelemetry())\n\n startNetworkErrorCollection(configuration, lifeCycle)\n startRuntimeErrorCollection(configuration, lifeCycle)\n startConsoleCollection(configuration, lifeCycle)\n startReportCollection(configuration, lifeCycle)\n const { handleLog } = startLoggerCollection(lifeCycle)\n\n startLogsAssembly(session, configuration, lifeCycle, getCommonContext, reportError)\n\n if (!canUseEventBridge()) {\n const { stop: stopLogsBatch } = startLogsBatch(configuration, lifeCycle, reportError, pageExitObservable, session)\n cleanupTasks.push(() => stopLogsBatch())\n } else {\n startLogsBridge(lifeCycle)\n }\n\n const internalContext = startInternalContext(session)\n\n return {\n handleLog,\n getInternalContext: internalContext.get,\n stop: () => {\n cleanupTasks.forEach((task) => task())\n },\n }\n}\n", "import { defineGlobal, getGlobalObject } from '@datadog/browser-core'\nimport type { LogsPublicApi } from '../boot/logsPublicApi'\nimport { makeLogsPublicApi } from '../boot/logsPublicApi'\nimport { startLogs } from '../boot/startLogs'\n\nexport type { LogsMessage } from '../domain/logger'\nexport { Logger, HandlerType } from '../domain/logger'\nexport { StatusType } from '../domain/logger/isAuthorized'\nexport type { LoggerConfiguration, LogsPublicApi as LogsGlobal } from '../boot/logsPublicApi'\nexport type { LogsInitConfiguration } from '../domain/configuration'\nexport type { LogsEvent } from '../logsEvent.types'\nexport type { LogsEventDomainContext } from '../domainContext.types'\n\nexport const datadogLogs = makeLogsPublicApi(startLogs)\n\ninterface BrowserWindow extends Window {\n DD_LOGS?: LogsPublicApi\n}\ndefineGlobal(getGlobalObject(), 'DD_LOGS', datadogLogs)\n", "import { datadogLogs } from '@datadog/browser-logs'\n\nconst initDatadog = () => {\n const ddEnv = window.location.hostname === 'www.citizensadvice.org.uk' ? \"prod\" : \"dev\";\n const appVersion = document.querySelector('meta[name=\"app-version\"]').getAttribute('content');\n\n if (ddEnv && appVersion) {\n datadogLogs.init({\n clientToken: 'pub32a7538113d7910e4304b8aa13ff4521', // this is a public token designed to be used in client side js\n site: 'datadoghq.eu',\n forwardErrorsToLogs: true,\n sessionSampleRate: 100,\n service: 'energy-apps',\n env: ddEnv,\n version: appVersion\n });\n }\n}\n\nexport default initDatadog;\n"], "mappings": "giBAAA,IAAAA,GAAAC,GAAAC,IAAA,cACA,OAAO,eAAeA,GAAS,aAAc,CAAE,MAAO,EAAK,CAAC,EAC5D,IAAIC,GAAa,UAAY,CACzB,IAAIC,EAAW,yBACXC,EAAyB,2BACzBC,EAAS,SAAS,cAAc,cAAc,EAC9CC,EAAgBD,GAAUA,EAAO,cAAcF,CAAQ,EAC3D,GAAIG,EAAe,CACf,IAAIC,EAAc,UAAY,CAC1BF,EAAO,UAAU,OAAOD,CAAsB,EAC9CE,EAAc,aAAa,gBAAiB,OAAO,EACnD,IAAIE,EAAYF,EAAc,aAAa,6BAA6B,EACpEE,GACAF,EAAc,aAAa,aAAcE,CAAS,CAE1D,EACIC,EAAY,UAAY,CACxBJ,EAAO,UAAU,IAAID,CAAsB,EAC3CE,EAAc,aAAa,gBAAiB,MAAM,EAClD,IAAII,EAAYJ,EAAc,aAAa,6BAA6B,EACpEI,GACAJ,EAAc,aAAa,aAAcI,CAAS,CAE1D,EAEAH,EAAY,EACZD,EAAc,iBAAiB,Q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AE,EACAE,CAAO,EAETP,EAAa,KAAK,IAAMY,EAAiB,CAAE,EAE3CE,GAA4BnB,EAAeG,CAAS,EACpDiB,GAA4BpB,EAAeG,CAAS,EACpDkB,GAAuBrB,EAAeG,CAAS,EAC/CmB,GAAsBtB,EAAeG,CAAS,EAC9C,GAAM,CAAE,UAAAoB,CAAS,EAAKC,GAAsBrB,CAAS,EAIrD,GAFAsB,GAAkBb,EAASZ,EAAeG,EAAWF,EAAkBO,CAAW,EAE7EK,EAAiB,EAIpBa,GAAgBvB,CAAS,MAJD,CACxB,GAAM,CAAE,KAAMwB,CAAa,EAAKC,GAAe5B,EAAeG,EAAWK,EAAaE,EAAoBE,CAAO,EACjHP,EAAa,KAAK,IAAMsB,EAAa,CAAE,CACzC,CAIA,IAAME,EAAkBC,GAAqBlB,CAAO,EAEpD,MAAO,CACL,UAAAW,EACA,mBAAoBM,EAAgB,IACpC,KAAM,IAAK,CACTxB,EAAa,QAAS0B,GAASA,EAAI,CAAE,CACvC,EAEJ,CCrEO,IAAMC,GAAcC,GAAkBC,EAAS,EAKtDC,GAAaC,EAAe,EAAmB,UAAWJ,EAAW,EChBrE,IAAMK,GAAc,IAAM,CACtB,IAAMC,EAAQ,OAAO,SAAS,WAAa,4BAA8B,OAAS,MAC5EC,EAAa,SAAS,cAAc,0BAA0B,EAAE,aAAa,SAAS,EAExFD,GAASC,GACTC,GAAY,KAAK,CACb,YAAa,sCACb,KAAM,eACN,oBAAqB,GACrB,kBAAmB,IACnB,QAAS,cACT,IAAKF,EACL,QAASC,CACb,CAAC,CAET,EAEOE,GAAQJ,GrGbf,GAAI,CAEFK,GAAY,KAGZ,GAAAC,SAAW,EACXC,GAAc,EAGdC,GAAwB,CAC1B,OAASC,EAAO,CACd,eAAS,cAAc,MAAM,EAAE,UAAU,IAAI,OAAO,EAC9CA,CACR", "names": ["require_header", "__commonJSMin", "exports", "initHeader", "SELECTOR", "SHOW_SEARCH_CLASS_NAME", "header", "controlButton", "setClosed_1", "showLabel", "setOpen_1", "hideLabel", "require_header", "__commonJSMin", "exports", "__importDefault", "mod", "header_1", "require_navigation", "__commonJSMin", "exports", "initNavigation", "isExpanded", "toggle", "ariaExpanded", "getToggleEl", "containerEl", "getWrapperEl", "getDropdownEl", "getMainNavEl", "extractDataAttributes", "getData", "name", "buildToggle", "dropdownId", "data", "toggleId", "buildNavDropdown", "navDropdown", "headerLinks", "headerLinksClone", "headerLinksContainer", "prepareHtml", "mainNavEl", "toggleWrapper", "setToggleVisibility", "breaks", "_a", "_b", "toggleEl", "openDropDown", "dropdownEl", "closeDropDown", "toDropdown", "mainNav", "toMenu", "computeContentWidth", "styles", "padding", "computeChildrenOffsetWidth", "children", "sum", "i", "child", "doesItFit", "currentContentWidth", "currentChildrenOffsetWidth", "addResizeObserver", "isInitialised", "timer", "observer", "addToggleHandler", "event", "addFocusHandler", "wrapperEl", "target", "addClickOutsideHandler", "navDropdownEl", "withinBoundaries", "addEscapeKeyHandler", "require_navigation", "__commonJSMin", "exports", "__importDefault", "mod", "navigation_1", "require_GreedyNav", "__commonJSMin", "exports", "__importDefault", "mod", "navigation_1", "GreedyNav", "_options", "require_greedy_nav", "__commonJSMin", "exports", "__importDefault", "mod", "initGreedyNav", "GreedyNav_1", "options", "import_header", "import_greedy_nav", "initGreedyNav", "greedyNav", "selectors", "totalRows", "hideRows", "row", "showRows", "updateCountText", "showing", "countText", "showMoreSuppliers", "tableContainer", "showFewerSuppliers", "addButtonEventHandlers", "supplier_table_default", "ConsoleApiName", "globalConsole", "originalConsoleMethods", "name", "PREFIX", "display", "DOCS_ORIGIN", "DOCS_TROUBLESHOOTING", "MORE_DETAILS", "catchUserErrors", "fn", "errorMsg", "args", "err", "display", "performDraw", "threshold", "isPercentage", "value", "isNumber", "ONE_SECOND", "ONE_MINUTE", "ONE_HOUR", "ONE_DAY", "ONE_YEAR", "dateNow", "timeStampNow", "relativeNow", "clocksNow", "clocksOrigin", "getNavigationStart", "elapsed", "start", "end", "addDuration", "a", "b", "getRelativeTime", "timestamp", "navigationStart", "getNavigationStart", "HAS_MULTI_BYTES_CHARACTERS", "computeBytesCount", "candidate", "shallowClone", "object", "objectHasValue", "value", "key", "isEmptyObject", "getGlobalObject", "globalObject", "getZoneJsOriginalValue", "target", "name", "browserWindow", "getGlobalObject", "original", "onMonitorErrorCollected", "debugMode", "startMonitorErrorCollection", "newOnMonitorErrorCollected", "setDebugMode", "newDebugMode", "monitored", "_", "__", "descriptor", "originalMethod", "args", "onMonitorErrorCollected", "monitor", "fn", "callMonitored", "context", "e", "monitorError", "displayIfDebugEnabled", "debugMode", "display", "setTimeout", "callback", "delay", "getZoneJsOriginalValue", "getGlobalObject", "monitor", "clearTimeout", "timeoutId", "setInterval", "clearInterval", "Observable", "onFirstSubscribe", "f", "other", "data", "observer", "mergeObservables", "observables", "globalObservable", "subscriptions", "observable", "subscription", "throttle", "fn", "wait", "options", "needLeadingExecution", "needTrailingExecution", "inWaitPeriod", "pendingExecutionWithParameters", "pendingTimeoutId", "parameters", "setTimeout", "clearTimeout", "noop", "generateUUID", "placeholder", "COMMA_SEPARATED_KEY_VALUE", "findCommaSeparatedValue", "rawString", "name", "match", "findCommaSeparatedValues", "result", "safeTruncate", "candidate", "length", "suffix", "lastChar", "correctedLength", "isChromium", "detectBrowserCached", "browserCache", "detectBrowserCached", "detectBrowser", "browserWindow", "userAgent", "_a", "setCookie", "name", "value", "expireDelay", "options", "date", "expires", "sameSite", "domain", "secure", "partitioned", "getCookie", "findCommaSeparatedValue", "initCookieParsed", "getInitCookie", "findCommaSeparatedValues", "deleteCookie", "name", "options", "setCookie", "areCookiesAuthorized", "testCookieName", "generateUUID", "testCookieValue", "ONE_MINUTE", "isCookieCorrectlySet", "getCookie", "error", "display", "getCurrentSiteCache", "getCurrentSite", "domainLevels", "candidateDomain", "ONE_SECOND", "SESSION_STORE_KEY", "objectValues", "object", "objectEntries", "SESSION_TIME_OUT_DELAY", "ONE_HOUR", "SESSION_EXPIRATION_DELAY", "ONE_MINUTE", "SESSION_COOKIE_EXPIRATION_DELAY", "ONE_YEAR", "SessionPersistence", "SESSION_ENTRY_REGEXP", "SESSION_ENTRY_SEPARATOR", "isValidSessionString", "sessionString", "EXPIRED", "getExpiredSessionState", "previousSessionState", "configuration", "expiredSessionState", "generateUUID", "isSessionInNotStartedState", "session", "isEmptyObject", "isSessionStarted", "isSessionInExpiredState", "isActiveSession", "sessionState", "dateNow", "SESSION_TIME_OUT_DELAY", "expandSessionState", "SESSION_EXPIRATION_DELAY", "toSessionString", "objectEntries", "key", "value", "SESSION_ENTRY_SEPARATOR", "toSessionState", "sessionString", "isValidSessionString", "entry", "matches", "SESSION_ENTRY_REGEXP", "OLD_SESSION_COOKIE_NAME", "OLD_RUM_COOKIE_NAME", "OLD_LOGS_COOKIE_NAME", "RUM_SESSION_KEY", "LOGS_SESSION_KEY", "tryOldCookiesMigration", "cookieStoreStrategy", "getInitCookie", "SESSION_STORE_KEY", "oldSessionId", "oldRumType", "oldLogsType", "session", "isSessionStarted", "expandSessionState", "selectCookieStrategy", "initConfiguration", "cookieOptions", "buildCookieOptions", "areCookiesAuthorized", "SessionPersistence", "initCookieStrategy", "configuration", "cookieStore", "isChromium", "persistSessionCookie", "retrieveSessionCookie", "sessionState", "expireSessionCookie", "tryOldCookiesMigration", "options", "session", "setCookie", "SESSION_STORE_KEY", "toSessionString", "SESSION_EXPIRATION_DELAY", "expiredSessionState", "getExpiredSessionState", "SESSION_COOKIE_EXPIRATION_DELAY", "SESSION_TIME_OUT_DELAY", "sessionString", "getCookie", "toSessionState", "getCurrentSite", "LOCAL_STORAGE_TEST_KEY", "selectLocalStorageStrategy", "id", "generateUUID", "testKey", "retrievedId", "SessionPersistence", "initLocalStorageStrategy", "configuration", "persistInLocalStorage", "retrieveSessionFromLocalStorage", "sessionState", "expireSessionFromLocalStorage", "SESSION_STORE_KEY", "toSessionString", "sessionString", "toSessionState", "previousSessionState", "getExpiredSessionState", "LOCK_RETRY_DELAY", "LOCK_MAX_TRIES", "bufferedOperations", "ongoingOperations", "processSessionStoreOperations", "operations", "sessionStoreStrategy", "numberOfRetries", "isLockEnabled", "persistSession", "expireSession", "persistWithLock", "session", "currentLock", "retrieveStore", "lock", "next", "currentStore", "retryLater", "generateUUID", "processedSession", "isSessionInExpiredState", "expandSessionState", "_a", "sessionStore", "currentNumberOfRetries", "setTimeout", "nextOperations", "STORAGE_POLL_DELAY", "ONE_SECOND", "selectSessionStoreStrategyType", "initConfiguration", "SessionPersistence", "selectCookieStrategy", "selectLocalStorageStrategy", "sessionStoreStrategyType", "display", "startSessionStore", "configuration", "productKey", "computeSessionState", "renewObservable", "Observable", "expireObservable", "sessionStateUpdateObservable", "sessionStoreStrategy", "initCookieStrategy", "initLocalStorageStrategy", "expireSession", "watchSessionTimeoutId", "setInterval", "watchSession", "sessionCache", "startSession", "throttledExpandOrRenewSession", "cancelExpandOrRenewSession", "throttle", "processSessionStoreOperations", "sessionState", "isSessionInNotStartedState", "synchronizedSession", "synchronizeSession", "expandOrRenewSessionState", "isSessionStarted", "hasSessionInCache", "renewSessionInCache", "expandSession", "isSessionInExpiredState", "getExpiredSessionState", "isSessionInCacheOutdated", "expireSessionInCache", "trackingType", "isTracked", "generateUUID", "dateNow", "updateSessionState", "partialSessionState", "clearInterval", "TrackingConsent", "createTrackingConsentState", "currentConsent", "observable", "Observable", "trackingConsent", "jsonStringify", "value", "replacer", "space", "restoreObjectPrototypeToJson", "detachToJsonMethod", "restoreArrayPrototypeToJson", "restoreValuePrototypeToJson", "restoreValueToJson", "object", "objectToJson", "noop", "normalizeUrl", "url", "buildUrl", "buildUrl", "url", "base", "supportedURL", "getSupportedUrl", "error", "jsonStringify", "doc", "anchorElement", "baseElement", "originalURL", "isURLSupported", "INTAKE_SITE_STAGING", "INTAKE_SITE_FED_STAGING", "INTAKE_SITE_US1", "INTAKE_SITE_US1_FED", "PCI_INTAKE_HOST_US1", "INTAKE_URL_PARAMETERS", "createEndpointBuilder", "initConfiguration", "trackType", "configurationTags", "buildUrlWithParameters", "createEndpointUrlWithParametersBuilder", "api", "payload", "parameters", "buildEndpointParameters", "path", "proxy", "normalizedProxyUrl", "normalizeUrl", "host", "buildEndpointHost", "site", "INTAKE_SITE_US1", "internalAnalyticsSubdomain", "PCI_INTAKE_HOST_US1", "INTAKE_SITE_FED_STAGING", "domainParts", "extension", "clientToken", "retry", "encoding", "tags", "generateUUID", "timeStampNow", "TAG_SIZE_LIMIT", "buildTags", "configuration", "env", "service", "version", "datacenter", "tags", "buildTag", "key", "rawValue", "valueSizeLimit", "hasForbiddenCharacters", "display", "MORE_DETAILS", "DOCS_ORIGIN", "sanitizedValue", "supportUnicodePropertyEscapes", "computeTransportConfiguration", "initConfiguration", "site", "INTAKE_SITE_US1", "tags", "buildTags", "endpointBuilders", "computeEndpointBuilders", "computeReplicaConfiguration", "createEndpointBuilder", "replicaConfiguration", "replicaEndpointBuilders", "isIntakeUrl", "url", "INTAKE_URL_PARAMETERS", "param", "isString", "tag", "tagName", "display", "isDatadogSite", "site", "MORE_DETAILS", "DOCS_ORIGIN", "isSampleRate", "sampleRate", "name", "isPercentage", "validateAndBuildConfiguration", "initConfiguration", "objectHasValue", "TrackingConsent", "catchUserErrors", "selectSessionStoreStrategyType", "_a", "_b", "_c", "_d", "_e", "_f", "ONE_SECOND", "computeTransportConfiguration", "serializeConfiguration", "ExperimentalFeature", "enabledExperimentalFeatures", "initFeatureFlags", "enableExperimentalFeatures", "addExperimentalFeatures", "flag", "objectHasValue", "enabledFeatures", "getExperimentalFeatures", "enabledExperimentalFeatures", "UNKNOWN_FUNCTION", "computeStackTrace", "ex", "stack", "stackProperty", "tryToGetString", "exString", "line", "stackFrame", "parseChromeLine", "parseChromeAnonymousLine", "parseWinLine", "parseGeckoLine", "fileUrl", "filePosition", "CHROME_LINE_RE", "CHROME_EVAL_RE", "parts", "isNative", "isEval", "submatch", "CHROME_ANONYMOUS_FUNCTION_RE", "WINJS_LINE_RE", "GECKO_LINE_RE", "GECKO_EVAL_RE", "candidate", "property", "value", "computeStackTraceFromOnErrorMessage", "messageObj", "url", "column", "name", "message", "tryToParseMessage", "ERROR_TYPES_RE", "createHandlingStack", "error", "formattedStack", "callMonitored", "stackTrace", "computeStackTrace", "toStackTraceString", "stack", "result", "formatErrorMessage", "frame", "func", "args", "line", "column", "instrumentMethod", "targetPrototype", "method", "onPreCall", "computeHandlingStack", "original", "noop", "stopped", "instrumentation", "parameters", "postCallCallback", "callMonitored", "callback", "createHandlingStack", "result", "SANITIZE_DEFAULT_MAX_CHARACTER_COUNT", "JSON_PATH_ROOT_ELEMENT", "KEY_DECORATION_LENGTH", "sanitize", "source", "maxCharacterCount", "restoreObjectPrototypeToJson", "detachToJsonMethod", "restoreArrayPrototypeToJson", "containerQueue", "visitedObjectsWithPath", "sanitizedData", "sanitizeProcessor", "serializedSanitizedData", "accumulatedCharacterCount", "warnOverCharacterLimit", "containerToProcess", "separatorLength", "key", "targetData", "parentPath", "queue", "sourceToSanitize", "tryToApplyToJSON", "sanitizePrimitivesAndFunctions", "sanitizedSource", "sanitizeObjects", "sourceAsObject", "currentPath", "target", "value", "sanitizeEvent", "match", "event", "object", "changeType", "display", "NO_ERROR_STACK_PRESENT_MESSAGE", "computeRawError", "stackTrace", "originalError", "handlingStack", "componentStack", "startClocks", "nonErrorPrefix", "source", "handling", "isErrorInstance", "isError", "message", "computeMessage", "stack", "hasUsableStack", "toStackTraceString", "causes", "flattenErrorCauses", "type", "fingerprint", "tryToGetFingerprint", "jsonStringify", "sanitize", "getFileFromStackTraceString", "_a", "error", "parentSource", "currentError", "computeStackTrace", "ErrorSource", "trackRuntimeError", "errorObservable", "handleRuntimeError", "stackTrace", "originalError", "rawError", "computeRawError", "clocksNow", "ErrorSource", "stopInstrumentingOnError", "instrumentOnError", "stopInstrumentingOnUnhandledRejection", "instrumentUnhandledRejection", "callback", "instrumentMethod", "messageObj", "url", "line", "column", "errorObj", "isError", "computeStackTrace", "computeStackTraceFromOnErrorMessage", "e", "reason", "stack", "makePublicApi", "stub", "publicApi", "callback", "setDebugMode", "defineGlobal", "global", "name", "api", "existingGlobalVariable", "display", "fn", "catchUserErrors", "displayAlreadyInitializedError", "sdkName", "initConfiguration", "display", "addEventListener", "configuration", "eventTarget", "eventName", "listener", "options", "addEventListeners", "eventNames", "once", "capture", "passive", "listenerWithMonitor", "monitor", "event", "stop", "listenerTarget", "add", "getZoneJsOriginalValue", "remove", "RawReportType", "initReportObservable", "configuration", "apis", "observables", "createCspViolationReportObservable", "reportTypes", "api", "createReportObservable", "mergeObservables", "Observable", "observable", "handleReports", "monitor", "reports", "_", "report", "buildRawReportErrorFromReport", "observer", "stop", "addEventListener", "event", "buildRawReportErrorFromCspViolation", "type", "body", "buildRawReportError", "buildStack", "message", "safeTruncate", "partial", "clocksNow", "ErrorSource", "name", "sourceFile", "lineNumber", "columnNumber", "toStackTraceString", "sendToExtension", "type", "payload", "callback", "getType", "value", "mergeInto", "destination", "source", "circularReferenceChecker", "createCircularReferenceChecker", "flags", "merged", "getType", "key", "deepClone", "value", "combine", "sources", "set", "has", "array", "getConnectivity", "navigator", "_a", "removeDuplicates", "array", "set", "item", "removeItem", "index", "BUFFER_LIMIT", "createBoundedBuffer", "buffer", "callback", "removeItem", "arg", "TelemetryType", "ALLOWED_FRAME_URLS", "TELEMETRY_EXCLUDED_SITES", "INTAKE_SITE_US1_FED", "preStartTelemetryBuffer", "createBoundedBuffer", "onRawTelemetryEventCollected", "event", "startTelemetry", "telemetryService", "configuration", "contextProvider", "observable", "Observable", "alreadySentEvents", "telemetryEnabled", "performDraw", "telemetryEnabledPerType", "TelemetryType", "runtimeEnvInfo", "getRuntimeEnvInfo", "rawEvent", "stringifiedEvent", "jsonStringify", "toTelemetryEvent", "sendToExtension", "startMonitorErrorCollection", "addTelemetryError", "combine", "timeStampNow", "getConnectivity", "getExperimentalFeatures", "provider", "drainPreStartTelemetry", "preStartTelemetryBuffer", "isTelemetryReplicationAllowed", "configuration", "INTAKE_SITE_STAGING", "addTelemetryDebug", "message", "context", "displayIfDebugEnabled", "ConsoleApiName", "onRawTelemetryEventCollected", "TelemetryType", "addTelemetryError", "formatError", "addTelemetryConfiguration", "addTelemetryUsage", "usage", "isError", "stackTrace", "computeStackTrace", "toStackTraceString", "scrubCustomerFrames", "NO_ERROR_STACK_PRESENT_MESSAGE", "jsonStringify", "frame", "ALLOWED_FRAME_URLS", "allowedFrameUrl", "END_OF_TIMES", "CLEAR_OLD_VALUES_INTERVAL", "ONE_MINUTE", "cleanupHistoriesInterval", "cleanupTasks", "cleanupHistories", "task", "createValueHistory", "expireDelay", "maxEntries", "entries", "deletedEntries", "setInterval", "clearExpiredValues", "oldTimeThreshold", "relativeNow", "entry", "add", "value", "startTime", "removeItem", "endTime", "find", "options", "closeActive", "latestEntry", "findAll", "duration", "addDuration", "getAllEntries", "getDeletedEntries", "reset", "stop", "clearInterval", "VISIBILITY_CHECK_DELAY", "ONE_MINUTE", "SESSION_CONTEXT_TIMEOUT_DELAY", "SESSION_TIME_OUT_DELAY", "stopCallbacks", "startSessionManager", "configuration", "productKey", "computeSessionState", "trackingConsentState", "renewObservable", "Observable", "expireObservable", "sessionStore", "startSessionStore", "sessionContextHistory", "createValueHistory", "buildSessionContext", "relativeNow", "clocksOrigin", "trackActivity", "trackVisibility", "trackResume", "startTime", "options", "trackActivity", "configuration", "expandOrRenewSession", "stop", "addEventListeners", "stopCallbacks", "trackVisibility", "expandSession", "expandSessionWhenVisible", "addEventListener", "visibilityCheckInterval", "setInterval", "VISIBILITY_CHECK_DELAY", "clearInterval", "trackResume", "cb", "isServerError", "status", "tryToClone", "response", "MAX_ONGOING_BYTES_COUNT", "MAX_ONGOING_REQUESTS", "MAX_QUEUE_BYTES_COUNT", "MAX_BACKOFF_TIME", "ONE_MINUTE", "INITIAL_BACKOFF_TIME", "ONE_SECOND", "sendWithRetryStrategy", "payload", "state", "sendStrategy", "trackType", "reportError", "send", "retryQueuedPayloads", "scheduleRetry", "setTimeout", "onSuccess", "onFailure", "response", "shouldRetryRequest", "reason", "ErrorSource", "clocksNow", "previousQueue", "newPayloadQueue", "isServerError", "newRetryState", "newBandwidthMonitor", "queue", "createHttpRequest", "endpointBuilder", "bytesLimit", "reportError", "retryState", "newRetryState", "sendStrategyForRetry", "payload", "onResponse", "fetchKeepAliveStrategy", "sendWithRetryStrategy", "sendBeaconStrategy", "beaconUrl", "e", "reportBeaconError", "xhrUrl", "sendXHR", "hasReportedBeaconError", "addTelemetryError", "isKeepAliveSupported", "fetchUrl", "monitor", "response", "url", "data", "request", "addEventListener", "getEventBridge", "eventBridgeGlobal", "getEventBridgeGlobal", "_a", "eventType", "event", "viewId", "view", "canUseEventBridge", "currentHost", "_a", "getGlobalObject", "bridge", "getEventBridge", "allowedHost", "getEventBridgeGlobal", "PageExitReason", "createPageExitObservable", "configuration", "Observable", "observable", "stopListeners", "addEventListeners", "event", "stopBeforeUnloadListener", "addEventListener", "isPageExitReason", "reason", "objectValues", "createBatch", "encoder", "request", "flushController", "messageBytesLimit", "upsertBuffer", "flushSubscription", "event", "flush", "push", "serializedMessage", "estimatedMessageBytesCount", "key", "realMessageBytesCount", "hasMessageFor", "remove", "removedMessage", "messageBytesCount", "addOrUpdate", "message", "jsonStringify", "display", "MORE_DETAILS", "DOCS_TROUBLESHOOTING", "upsertMessages", "objectValues", "isPageExit", "isPageExitReason", "send", "encoderResult", "formatPayloadFromEncoder", "pendingMessages", "computeBytesCount", "data", "createFlushController", "messagesLimit", "bytesLimit", "durationLimit", "pageExitObservable", "sessionExpireObservable", "pageExitSubscription", "event", "flush", "sessionExpireSubscription", "flushObservable", "Observable", "currentBytesCount", "currentMessagesCount", "flushReason", "messagesCount", "bytesCount", "cancelDurationLimitTimeout", "durationLimitTimeoutId", "scheduleDurationLimitTimeout", "setTimeout", "clearTimeout", "estimatedMessageBytesCount", "messageBytesCountDiff", "messageBytesCount", "startBatchWithReplica", "configuration", "primary", "replica", "reportError", "pageExitObservable", "sessionExpireObservable", "batchFactoryImp", "createBatch", "primaryBatch", "createBatchFromConfig", "replicaBatch", "endpoint", "encoder", "createHttpRequest", "createFlushController", "message", "replicated", "key", "createIdentityEncoder", "output", "outputBytesCount", "data", "callback", "additionalEncodedBytesCount", "computeBytesCount", "result", "AbstractLifeCycle", "eventType", "data", "eventCallbacks", "callback", "other", "createEventRateLimiter", "eventType", "limit", "onLimitReached", "eventCount", "allowNextEvent", "setTimeout", "ONE_MINUTE", "ErrorSource", "clocksNow", "xhrObservable", "xhrContexts", "initXhrObservable", "configuration", "createXhrObservable", "Observable", "observable", "stopInstrumentingStart", "instrumentMethod", "openXhr", "stopInstrumentingSend", "call", "sendXhr", "stopInstrumentingAbort", "abortXhr", "xhr", "method", "url", "normalizeUrl", "handlingStack", "context", "startContext", "clocksNow", "hasBeenReported", "stopInstrumentingOnReadyStateChange", "onEnd", "unsubscribeLoadEndListener", "completeContext", "elapsed", "timeStampNow", "shallowClone", "addEventListener", "fetchObservable", "initFetchObservable", "createFetchObservable", "createFetchObservable", "Observable", "observable", "stop", "instrumentMethod", "call", "beforeSend", "parameters", "onPostCall", "handlingStack", "input", "init", "methodFromParams", "method", "url", "normalizeUrl", "startClocks", "clocksNow", "context", "responsePromise", "afterSend", "startContext", "reportFetch", "partialContext", "monitor", "response", "error", "_b", "_a", "consoleObservablesByApi", "initConsoleObservable", "apis", "consoleObservables", "api", "createConsoleObservable", "mergeObservables", "createConsoleObservable", "api", "Observable", "observable", "originalConsoleApi", "globalConsole", "params", "handlingStack", "createHandlingStack", "callMonitored", "buildConsoleLog", "message", "param", "formatConsoleParameters", "error", "ConsoleApiName", "firstErrorParam", "isError", "toStackTraceString", "computeStackTrace", "tryToGetFingerprint", "flattenErrorCauses", "clocksNow", "ErrorSource", "sanitize", "formatErrorMessage", "jsonStringify", "ensureProperties", "context", "propertiesConfig", "name", "newContext", "key", "required", "type", "display", "createContextManager", "customerDataTracker", "changeObservable", "Observable", "contextManager", "deepClone", "getType", "sanitize", "property", "CONTEXT_STORE_KEY_PREFIX", "storageListeners", "storeContextManager", "configuration", "contextManager", "productKey", "customerDataType", "storageKey", "buildStorageKey", "addEventListener", "key", "synchronizeWithStorage", "dumpToStorage", "combine", "getFromStorage", "rawContext", "CUSTOMER_DATA_BYTES_LIMIT", "CUSTOMER_COMPRESSED_DATA_BYTES_LIMIT", "BYTES_COMPUTATION_THROTTLING_DELAY", "createCustomerDataTrackerManager", "compressionStatus", "customerDataTrackers", "alreadyWarned", "checkCustomerDataLimit", "initialBytesCount", "bytesCountLimit", "bytesCount", "tracker", "displayCustomerDataLimitReachedWarning", "createCustomerDataTracker", "type", "newCompressionStatus", "bytesCountCache", "computeBytesCountThrottled", "cancelComputeBytesCount", "throttle", "context", "computeBytesCount", "jsonStringify", "resetBytesCount", "isEmptyObject", "display", "MORE_DETAILS", "DOCS_TROUBLESHOOTING", "readBytesFromStream", "stream", "callback", "options", "reader", "chunks", "readBytesCount", "readMore", "monitor", "result", "onDone", "error", "noop", "bytes", "limitExceeded", "completeBuffer", "offset", "chunk", "SYNTHETICS_TEST_ID_COOKIE_NAME", "SYNTHETICS_RESULT_ID_COOKIE_NAME", "SYNTHETICS_INJECTS_RUM_COOKIE_NAME", "willSyntheticsInjectRum", "getInitCookie", "getSyntheticsTestId", "value", "getSyntheticsResultId", "checkUser", "newUser", "isValid", "getType", "display", "isAuthorized", "status", "handlerType", "logger", "loggerHandler", "sanitizedHandlerType", "STATUS_PRIORITIES", "StatusType", "createErrorFieldFromRawError", "rawError", "includeMessage", "HandlerType", "STATUSES", "StatusType", "Logger", "handleLogStrategy", "customerDataTracker", "name", "handlerType", "level", "loggerContext", "createContextManager", "message", "messageContext", "status", "error", "handlingStack", "sanitizedMessageContext", "sanitize", "context", "rawError", "computeRawError", "isError", "computeStackTrace", "ErrorSource", "clocksNow", "combine", "createErrorFieldFromRawError", "isAuthorized", "createHandlingStack", "key", "value", "handler", "__decorate", "monitored", "createLoggerMethod", "buildCommonContext", "globalContextManager", "userContextManager", "DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT", "validateAndBuildLogsConfiguration", "initConfiguration", "display", "baseConfiguration", "validateAndBuildConfiguration", "forwardConsoleLogs", "validateAndBuildForwardOption", "objectValues", "ConsoleApiName", "forwardReports", "RawReportType", "option", "allowedValues", "label", "api", "removeDuplicates", "serializeLogsConfiguration", "configuration", "baseSerializedInitConfiguration", "serializeConfiguration", "createPreStartStrategy", "getCommonContext", "trackingConsentState", "doStartLogs", "bufferApiCalls", "createBoundedBuffer", "cachedInitConfiguration", "cachedConfiguration", "trackingConsentStateSubscription", "tryStartLogs", "startLogsResult", "initConfiguration", "display", "initFeatureFlags", "canUseEventBridge", "overrideInitConfigurationForBridge", "displayAlreadyInitializedError", "configuration", "validateAndBuildLogsConfiguration", "initFetchObservable", "noop", "message", "statusType", "handlingStack", "context", "date", "timeStampNow", "LOGS_STORAGE_KEY", "makeLogsPublicApi", "startLogsImpl", "customerDataTrackerManager", "createCustomerDataTrackerManager", "globalContextManager", "createContextManager", "userContextManager", "trackingConsentState", "createTrackingConsentState", "getCommonContext", "buildCommonContext", "strategy", "createPreStartStrategy", "initConfiguration", "configuration", "storeContextManager", "startLogsResult", "createPostStartStrategy", "customLoggers", "mainLogger", "Logger", "params", "makePublicApi", "monitor", "trackingConsent", "addTelemetryUsage", "context", "key", "value", "name", "conf", "sanitize", "deepClone", "startTime", "newUser", "checkUser", "property", "displayAlreadyInitializedError", "LOGS_SESSION_KEY", "startLogsSessionManager", "configuration", "trackingConsentState", "sessionManager", "startSessionManager", "rawTrackingType", "computeSessionState", "startTime", "options", "session", "startLogsSessionManagerStub", "computeTrackingType", "Observable", "performDraw", "rawSessionType", "trackingType", "hasValidLoggerSession", "logsSentBeforeRumInjectionTelemetryAdded", "getRUMInternalContext", "startTime", "browserWindow", "willSyntheticsInjectRum", "context", "getInternalContextFromRumGlobal", "addTelemetryDebug", "getSyntheticsTestId", "getSyntheticsResultId", "rumGlobal", "startLogsAssembly", "sessionManager", "configuration", "lifeCycle", "getCommonContext", "reportError", "statusWithCustom", "STATUSES", "logRateLimiters", "status", "createEventRateLimiter", "rawLogsEvent", "messageContext", "savedCommonContext", "domainContext", "startTime", "getRelativeTime", "session", "commonContext", "log", "combine", "isEmptyObject", "getRUMInternalContext", "_a", "ErrorSource", "_b", "LogStatusForApi", "ConsoleApiName", "StatusType", "startConsoleCollection", "configuration", "lifeCycle", "consoleSubscription", "initConsoleObservable", "log", "collectedData", "timeStampNow", "ErrorSource", "createErrorFieldFromRawError", "startReportCollection", "configuration", "lifeCycle", "reportSubscription", "initReportObservable", "rawError", "message", "error", "status", "StatusType", "createErrorFieldFromRawError", "getFileFromStackTraceString", "timeStampNow", "ErrorSource", "startNetworkErrorCollection", "configuration", "lifeCycle", "noop", "xhrSubscription", "initXhrObservable", "context", "handleResponse", "fetchSubscription", "initFetchObservable", "type", "request", "isIntakeUrl", "isRejected", "isServerError", "computeXhrResponseData", "onResponseDataAvailable", "computeFetchResponseText", "computeFetchErrorText", "responseData", "domainContext", "format", "StatusType", "ErrorSource", "xhr", "callback", "truncateResponseText", "error", "toStackTraceString", "computeStackTrace", "response", "clonedResponse", "tryToClone", "truncateResponseStream", "responseText", "monitor", "text", "stream", "bytesLimit", "readBytesFromStream", "bytes", "limitExceeded", "startRuntimeErrorCollection", "configuration", "lifeCycle", "noop", "rawErrorObservable", "Observable", "stopRuntimeErrorTracking", "trackRuntimeError", "rawErrorSubscription", "rawError", "createErrorFieldFromRawError", "ErrorSource", "StatusType", "LifeCycle", "AbstractLifeCycle", "startLoggerCollection", "lifeCycle", "handleLog", "logsMessage", "logger", "handlingStack", "savedCommonContext", "savedDate", "messageContext", "combine", "isAuthorized", "HandlerType", "displayInConsole", "rawLogEventData", "timeStampNow", "ErrorSource", "loggerToConsoleApiName", "StatusType", "ConsoleApiName", "status", "message", "originalConsoleMethods", "globalConsole", "startLogsBatch", "configuration", "lifeCycle", "reportError", "pageExitObservable", "session", "batch", "startBatchWithReplica", "createIdentityEncoder", "serverLogsEvent", "startLogsBridge", "lifeCycle", "bridge", "getEventBridge", "serverLogsEvent", "startInternalContext", "sessionManager", "startTime", "trackedSession", "startReportError", "lifeCycle", "error", "ErrorSource", "StatusType", "addTelemetryDebug", "startLogsTelemetry", "initConfiguration", "configuration", "reportError", "pageExitObservable", "session", "telemetry", "startTelemetry", "_a", "getRUMInternalContext", "_b", "_d", "_c", "_f", "_e", "cleanupTasks", "canUseEventBridge", "bridge", "getEventBridge", "telemetrySubscription", "event", "telemetryBatch", "startBatchWithReplica", "createIdentityEncoder", "isTelemetryReplicationAllowed", "drainPreStartTelemetry", "addTelemetryConfiguration", "serializeLogsConfiguration", "task", "startLogs", "initConfiguration", "configuration", "getCommonContext", "trackingConsentState", "lifeCycle", "LifeCycle", "cleanupTasks", "log", "sendToExtension", "reportError", "startReportError", "pageExitObservable", "createPageExitObservable", "session", "canUseEventBridge", "willSyntheticsInjectRum", "startLogsSessionManager", "startLogsSessionManagerStub", "stopLogsTelemetry", "startLogsTelemetry", "startNetworkErrorCollection", "startRuntimeErrorCollection", "startConsoleCollection", "startReportCollection", "handleLog", "startLoggerCollection", "startLogsAssembly", "startLogsBridge", "stopLogsBatch", "startLogsBatch", "internalContext", "startInternalContext", "task", "datadogLogs", "makeLogsPublicApi", "startLogs", "defineGlobal", "getGlobalObject", "initDatadog", "ddEnv", "appVersion", "datadogLogs", "datadog_default", "datadog_default", "initHeader", "initGreedyNav", "supplier_table_default", "error"] }