import { __async, __objRest, __spreadProps, __spreadValues } from "./chunk-IIEVY7G7.js"; // node_modules/@datadog/browser-core/esm/tools/display.js var ConsoleApiName = { log: "log", debug: "debug", info: "info", warn: "warn", error: "error" }; var globalConsole = console; var originalConsoleMethods = {}; Object.keys(ConsoleApiName).forEach((name) => { originalConsoleMethods[name] = globalConsole[name]; }); var PREFIX = "Datadog Browser SDK:"; var display = { debug: originalConsoleMethods.debug.bind(globalConsole, PREFIX), log: originalConsoleMethods.log.bind(globalConsole, PREFIX), info: originalConsoleMethods.info.bind(globalConsole, PREFIX), warn: originalConsoleMethods.warn.bind(globalConsole, PREFIX), error: originalConsoleMethods.error.bind(globalConsole, PREFIX) }; var DOCS_ORIGIN = "https://docs.datadoghq.com"; var DOCS_TROUBLESHOOTING = `${DOCS_ORIGIN}/real_user_monitoring/browser/troubleshooting`; var MORE_DETAILS = "More details:"; // node_modules/@datadog/browser-core/esm/tools/utils/numberUtils.js function performDraw(threshold) { return threshold !== 0 && Math.random() * 100 <= threshold; } function round(num, decimals) { return +num.toFixed(decimals); } function isPercentage(value) { return isNumber(value) && value >= 0 && value <= 100; } function isNumber(value) { return typeof value === "number"; } // node_modules/@datadog/browser-core/esm/tools/utils/timeUtils.js var ONE_SECOND = 1e3; var ONE_MINUTE = 60 * ONE_SECOND; var ONE_HOUR = 60 * ONE_MINUTE; var ONE_DAY = 24 * ONE_HOUR; var ONE_YEAR = 365 * ONE_DAY; function relativeToClocks(relative) { return { relative, timeStamp: getCorrectedTimeStamp(relative) }; } function timeStampToClocks(timeStamp) { return { relative: getRelativeTime(timeStamp), timeStamp }; } function getCorrectedTimeStamp(relativeTime) { const correctedOrigin = dateNow() - performance.now(); if (correctedOrigin > getNavigationStart()) { return Math.round(addDuration(correctedOrigin, relativeTime)); } return getTimeStamp(relativeTime); } function currentDrift() { return Math.round(dateNow() - addDuration(getNavigationStart(), performance.now())); } function toServerDuration(duration) { if (!isNumber(duration)) { return duration; } return round(duration * 1e6, 0); } function dateNow() { return (/* @__PURE__ */ new Date()).getTime(); } function timeStampNow() { return dateNow(); } function relativeNow() { return performance.now(); } function clocksNow() { return { relative: relativeNow(), timeStamp: timeStampNow() }; } function clocksOrigin() { return { relative: 0, timeStamp: getNavigationStart() }; } function elapsed(start, end) { return end - start; } function addDuration(a, b) { return a + b; } function getRelativeTime(timestamp) { return timestamp - getNavigationStart(); } function getTimeStamp(relativeTime) { return Math.round(addDuration(getNavigationStart(), relativeTime)); } function looksLikeRelativeTime(time) { return time < ONE_YEAR; } var navigationStart; function getNavigationStart() { var _a, _b; if (navigationStart === void 0) { navigationStart = (_b = (_a = performance.timing) === null || _a === void 0 ? void 0 : _a.navigationStart) !== null && _b !== void 0 ? _b : performance.timeOrigin; } return navigationStart; } // node_modules/@datadog/browser-core/esm/tools/globalObject.js function getGlobalObject() { if (typeof globalThis === "object") { return globalThis; } Object.defineProperty(Object.prototype, "_dd_temp_", { get() { return this; }, configurable: true }); let globalObject2 = _dd_temp_; delete Object.prototype._dd_temp_; if (typeof globalObject2 !== "object") { if (typeof self === "object") { globalObject2 = self; } else if (typeof window === "object") { globalObject2 = window; } else { globalObject2 = {}; } } return globalObject2; } var globalObject = getGlobalObject(); var isWorkerEnvironment = "WorkerGlobalScope" in globalObject; // node_modules/@datadog/browser-core/esm/tools/monitor.js var onMonitorErrorCollected; var debugMode = false; function startMonitorErrorCollection(newOnMonitorErrorCollected) { onMonitorErrorCollected = newOnMonitorErrorCollected; } function setDebugMode(newDebugMode) { debugMode = newDebugMode; } function monitor(fn) { return function() { return callMonitored(fn, this, arguments); }; } function callMonitored(fn, context, args) { try { return fn.apply(context, args); } catch (e) { monitorError(e); } } function monitorError(e) { displayIfDebugEnabled(e); if (onMonitorErrorCollected) { try { onMonitorErrorCollected(e); } catch (e2) { displayIfDebugEnabled(e2); } } } function displayIfDebugEnabled(...args) { if (debugMode) { display.error("[MONITOR]", ...args); } } // node_modules/@datadog/browser-core/esm/tools/getZoneJsOriginalValue.js function getZoneJsOriginalValue(target, name) { const browserWindow = getGlobalObject(); let original; if (browserWindow.Zone && typeof browserWindow.Zone.__symbol__ === "function") { original = target[browserWindow.Zone.__symbol__(name)]; } if (!original) { original = target[name]; } return original; } // node_modules/@datadog/browser-core/esm/tools/timer.js function setTimeout(callback, delay) { return getZoneJsOriginalValue(getGlobalObject(), "setTimeout")(monitor(callback), delay); } function clearTimeout(timeoutId) { getZoneJsOriginalValue(getGlobalObject(), "clearTimeout")(timeoutId); } function setInterval(callback, delay) { return getZoneJsOriginalValue(getGlobalObject(), "setInterval")(monitor(callback), delay); } function clearInterval(timeoutId) { getZoneJsOriginalValue(getGlobalObject(), "clearInterval")(timeoutId); } // node_modules/@datadog/browser-core/esm/tools/queueMicrotask.js function queueMicrotask(callback) { var _a; const nativeImplementation = (_a = globalObject.queueMicrotask) === null || _a === void 0 ? void 0 : _a.bind(globalObject); if (typeof nativeImplementation === "function") { nativeImplementation(monitor(callback)); } else { Promise.resolve().then(monitor(callback)); } } // node_modules/@datadog/browser-core/esm/tools/observable.js var Observable = class { constructor(onFirstSubscribe) { this.onFirstSubscribe = onFirstSubscribe; this.observers = []; } subscribe(observer2) { this.addObserver(observer2); return { unsubscribe: () => this.removeObserver(observer2) }; } notify(data) { this.observers.forEach((observer2) => observer2(data)); } addObserver(observer2) { this.observers.push(observer2); if (this.observers.length === 1 && this.onFirstSubscribe) { this.onLastUnsubscribe = this.onFirstSubscribe(this) || void 0; } } removeObserver(observer2) { this.observers = this.observers.filter((other) => observer2 !== other); if (!this.observers.length && this.onLastUnsubscribe) { this.onLastUnsubscribe(); } } }; function mergeObservables(...observables) { return new Observable((globalObservable) => { const subscriptions = observables.map((observable) => observable.subscribe((data) => globalObservable.notify(data))); return () => subscriptions.forEach((subscription) => subscription.unsubscribe()); }); } var BufferedObservable = class extends Observable { constructor(maxBufferSize) { super(); this.maxBufferSize = maxBufferSize; this.buffer = []; } notify(data) { this.buffer.push(data); if (this.buffer.length > this.maxBufferSize) { this.buffer.shift(); } super.notify(data); } subscribe(observer2) { let closed = false; const subscription = { unsubscribe: () => { closed = true; this.removeObserver(observer2); } }; queueMicrotask(() => { for (const data of this.buffer) { if (closed) { return; } observer2(data); } if (!closed) { this.addObserver(observer2); } }); return subscription; } /** * Drop buffered data and don't buffer future data. This is to avoid leaking memory when it's not * needed anymore. This can be seen as a performance optimization, and things will work probably * even if this method isn't called, but still useful to clarify our intent and lowering our * memory impact. */ unbuffer() { queueMicrotask(() => { this.maxBufferSize = this.buffer.length = 0; }); } }; // node_modules/@datadog/browser-core/esm/tools/utils/byteUtils.js var ONE_KIBI_BYTE = 1024; var ONE_MEBI_BYTE = 1024 * ONE_KIBI_BYTE; var HAS_MULTI_BYTES_CHARACTERS = /[^\u0000-\u007F]/; function computeBytesCount(candidate) { if (!HAS_MULTI_BYTES_CHARACTERS.test(candidate)) { return candidate.length; } if (window.TextEncoder !== void 0) { return new TextEncoder().encode(candidate).length; } return new Blob([candidate]).size; } function concatBuffers(buffers) { const length = buffers.reduce((total, buffer) => total + buffer.length, 0); const result = new Uint8Array(length); let offset = 0; for (const buffer of buffers) { result.set(buffer, offset); offset += buffer.length; } return result; } // node_modules/@datadog/browser-core/esm/tools/utils/responseUtils.js function isServerError(status) { return status >= 500; } function tryToClone(response) { try { return response.clone(); } catch (_a) { return; } } // node_modules/@datadog/browser-core/esm/domain/error/error.types.js var ErrorSource = { AGENT: "agent", CONSOLE: "console", CUSTOM: "custom", LOGGER: "logger", NETWORK: "network", SOURCE: "source", REPORT: "report" }; // node_modules/@datadog/browser-core/esm/transport/sendWithRetryStrategy.js var MAX_ONGOING_BYTES_COUNT = 80 * ONE_KIBI_BYTE; var MAX_ONGOING_REQUESTS = 32; var MAX_QUEUE_BYTES_COUNT = 20 * ONE_MEBI_BYTE; var MAX_BACKOFF_TIME = ONE_MINUTE; var INITIAL_BACKOFF_TIME = ONE_SECOND; function sendWithRetryStrategy(payload, state, sendStrategy, trackType, reportError, requestObservable) { if (state.transportStatus === 0 && state.queuedPayloads.size() === 0 && state.bandwidthMonitor.canHandle(payload)) { send(payload, state, sendStrategy, requestObservable, { onSuccess: () => retryQueuedPayloads(0, state, sendStrategy, trackType, reportError, requestObservable), onFailure: () => { if (!state.queuedPayloads.enqueue(payload)) { requestObservable.notify({ type: "queue-full", bandwidth: state.bandwidthMonitor.stats(), payload }); } scheduleRetry(state, sendStrategy, trackType, reportError, requestObservable); } }); } else { if (!state.queuedPayloads.enqueue(payload)) { requestObservable.notify({ type: "queue-full", bandwidth: state.bandwidthMonitor.stats(), payload }); } } } function scheduleRetry(state, sendStrategy, trackType, reportError, requestObservable) { if (state.transportStatus !== 2) { return; } setTimeout(() => { const payload = state.queuedPayloads.first(); send(payload, state, sendStrategy, requestObservable, { onSuccess: () => { state.queuedPayloads.dequeue(); state.currentBackoffTime = INITIAL_BACKOFF_TIME; retryQueuedPayloads(1, state, sendStrategy, trackType, reportError, requestObservable); }, onFailure: () => { state.currentBackoffTime = Math.min(MAX_BACKOFF_TIME, state.currentBackoffTime * 2); scheduleRetry(state, sendStrategy, trackType, reportError, requestObservable); } }); }, state.currentBackoffTime); } function send(payload, state, sendStrategy, requestObservable, { onSuccess, onFailure }) { state.bandwidthMonitor.add(payload); sendStrategy(payload, (response) => { state.bandwidthMonitor.remove(payload); if (!shouldRetryRequest(response)) { state.transportStatus = 0; requestObservable.notify({ type: "success", bandwidth: state.bandwidthMonitor.stats(), payload }); onSuccess(); } else { state.transportStatus = state.bandwidthMonitor.ongoingRequestCount > 0 ? 1 : 2; payload.retry = { count: payload.retry ? payload.retry.count + 1 : 1, lastFailureStatus: response.status }; requestObservable.notify({ type: "failure", bandwidth: state.bandwidthMonitor.stats(), payload }); onFailure(); } }); } function retryQueuedPayloads(reason, state, sendStrategy, trackType, reportError, requestObservable) { if (reason === 0 && state.queuedPayloads.isFull() && !state.queueFullReported) { reportError({ message: `Reached max ${trackType} events size queued for upload: ${MAX_QUEUE_BYTES_COUNT / ONE_MEBI_BYTE}MiB`, source: ErrorSource.AGENT, startClocks: clocksNow() }); state.queueFullReported = true; } const previousQueue = state.queuedPayloads; state.queuedPayloads = newPayloadQueue(); while (previousQueue.size() > 0) { sendWithRetryStrategy(previousQueue.dequeue(), state, sendStrategy, trackType, reportError, requestObservable); } } function shouldRetryRequest(response) { return response.type !== "opaque" && (response.status === 0 && !navigator.onLine || response.status === 408 || response.status === 429 || isServerError(response.status)); } function newRetryState() { return { transportStatus: 0, currentBackoffTime: INITIAL_BACKOFF_TIME, bandwidthMonitor: newBandwidthMonitor(), queuedPayloads: newPayloadQueue(), queueFullReported: false }; } function newPayloadQueue() { const queue = []; return { bytesCount: 0, enqueue(payload) { if (this.isFull()) { return false; } queue.push(payload); this.bytesCount += payload.bytesCount; return true; }, first() { return queue[0]; }, dequeue() { const payload = queue.shift(); if (payload) { this.bytesCount -= payload.bytesCount; } return payload; }, size() { return queue.length; }, isFull() { return this.bytesCount >= MAX_QUEUE_BYTES_COUNT; } }; } function newBandwidthMonitor() { return { ongoingRequestCount: 0, ongoingByteCount: 0, canHandle(payload) { return this.ongoingRequestCount === 0 || this.ongoingByteCount + payload.bytesCount <= MAX_ONGOING_BYTES_COUNT && this.ongoingRequestCount < MAX_ONGOING_REQUESTS; }, add(payload) { this.ongoingRequestCount += 1; this.ongoingByteCount += payload.bytesCount; }, remove(payload) { this.ongoingRequestCount -= 1; this.ongoingByteCount -= payload.bytesCount; }, stats() { return { ongoingByteCount: this.ongoingByteCount, ongoingRequestCount: this.ongoingRequestCount }; } }; } // node_modules/@datadog/browser-core/esm/transport/httpRequest.js function createHttpRequest(endpointBuilders, bytesLimit, reportError) { const observable = new Observable(); const retryState = newRetryState(); return { observable, send: (payload) => { for (const endpointBuilder of endpointBuilders) { sendWithRetryStrategy(payload, retryState, (payload2, onResponse) => fetchKeepAliveStrategy(endpointBuilder, bytesLimit, payload2, onResponse), endpointBuilder.trackType, reportError, observable); } }, /** * Since fetch keepalive behaves like regular fetch on Firefox, * keep using sendBeaconStrategy on exit */ sendOnExit: (payload) => { for (const endpointBuilder of endpointBuilders) { sendBeaconStrategy(endpointBuilder, bytesLimit, payload); } } }; } function sendBeaconStrategy(endpointBuilder, bytesLimit, payload) { const canUseBeacon = !!navigator.sendBeacon && payload.bytesCount < bytesLimit; if (canUseBeacon) { try { const beaconUrl = endpointBuilder.build("beacon", payload); const isQueued = navigator.sendBeacon(beaconUrl, payload.data); if (isQueued) { return; } } catch (e) { reportBeaconError(e); } } fetchStrategy(endpointBuilder, payload); } var hasReportedBeaconError = false; function reportBeaconError(e) { if (!hasReportedBeaconError) { hasReportedBeaconError = true; monitorError(e); } } function fetchKeepAliveStrategy(endpointBuilder, bytesLimit, payload, onResponse) { const canUseKeepAlive = isKeepAliveSupported() && payload.bytesCount < bytesLimit; if (canUseKeepAlive) { const fetchUrl = endpointBuilder.build("fetch-keepalive", payload); fetch(fetchUrl, { method: "POST", body: payload.data, keepalive: true, mode: "cors" }).then(monitor((response) => onResponse === null || onResponse === void 0 ? void 0 : onResponse({ status: response.status, type: response.type }))).catch(monitor(() => fetchStrategy(endpointBuilder, payload, onResponse))); } else { fetchStrategy(endpointBuilder, payload, onResponse); } } function fetchStrategy(endpointBuilder, payload, onResponse) { const fetchUrl = endpointBuilder.build("fetch", payload); fetch(fetchUrl, { method: "POST", body: payload.data, mode: "cors" }).then(monitor((response) => onResponse === null || onResponse === void 0 ? void 0 : onResponse({ status: response.status, type: response.type }))).catch(monitor(() => onResponse === null || onResponse === void 0 ? void 0 : onResponse({ status: 0 }))); } function isKeepAliveSupported() { try { return window.Request && "keepalive" in new Request("http://a"); } catch (_a) { return false; } } // node_modules/@datadog/browser-core/esm/transport/eventBridge.js function getEventBridge() { const eventBridgeGlobal = getEventBridgeGlobal(); if (!eventBridgeGlobal) { return; } return { getCapabilities() { var _a; return JSON.parse(((_a = eventBridgeGlobal.getCapabilities) === null || _a === void 0 ? void 0 : _a.call(eventBridgeGlobal)) || "[]"); }, getPrivacyLevel() { var _a; return (_a = eventBridgeGlobal.getPrivacyLevel) === null || _a === void 0 ? void 0 : _a.call(eventBridgeGlobal); }, getAllowedWebViewHosts() { return JSON.parse(eventBridgeGlobal.getAllowedWebViewHosts()); }, send(eventType, event, viewId) { const view = viewId ? { id: viewId } : void 0; eventBridgeGlobal.send(JSON.stringify({ eventType, event, view })); } }; } function bridgeSupports(capability) { const bridge = getEventBridge(); return !!bridge && bridge.getCapabilities().includes(capability); } function canUseEventBridge(currentHost) { var _a; if (currentHost === void 0) { currentHost = (_a = getGlobalObject().location) === null || _a === void 0 ? void 0 : _a.hostname; } const bridge = getEventBridge(); return !!bridge && bridge.getAllowedWebViewHosts().some((allowedHost) => currentHost === allowedHost || currentHost.endsWith(`.${allowedHost}`)); } function getEventBridgeGlobal() { return getGlobalObject().DatadogEventBridge; } // node_modules/@datadog/browser-core/esm/browser/addEventListener.js function addEventListener(configuration, eventTarget, eventName, listener, options) { return addEventListeners(configuration, eventTarget, [eventName], listener, options); } function addEventListeners(configuration, eventTarget, eventNames, listener, { once, capture, passive } = {}) { const listenerWithMonitor = monitor((event) => { if (!event.isTrusted && !event.__ddIsTrusted && !configuration.allowUntrustedEvents) { return; } if (once) { stop(); } listener(event); }); const options = passive ? { capture, passive } : capture; const listenerTarget = window.EventTarget && eventTarget instanceof EventTarget ? window.EventTarget.prototype : eventTarget; const add = getZoneJsOriginalValue(listenerTarget, "addEventListener"); eventNames.forEach((eventName) => add.call(eventTarget, eventName, listenerWithMonitor, options)); function stop() { const remove = getZoneJsOriginalValue(listenerTarget, "removeEventListener"); eventNames.forEach((eventName) => remove.call(eventTarget, eventName, listenerWithMonitor, options)); } return { stop }; } // node_modules/@datadog/browser-core/esm/tools/utils/polyfills.js function findLast(array, predicate) { for (let i = array.length - 1; i >= 0; i -= 1) { const item = array[i]; if (predicate(item, i, array)) { return item; } } return void 0; } function objectValues(object) { return Object.values(object); } function objectEntries(object) { return Object.entries(object); } // node_modules/@datadog/browser-core/esm/browser/pageMayExitObservable.js var PageExitReason = { HIDDEN: "visibility_hidden", UNLOADING: "before_unload", PAGEHIDE: "page_hide", FROZEN: "page_frozen" }; function createPageMayExitObservable(configuration) { return new Observable((observable) => { const { stop: stopListeners } = addEventListeners(configuration, window, [ "visibilitychange", "freeze" /* DOM_EVENT.FREEZE */ ], (event) => { if (event.type === "visibilitychange" && document.visibilityState === "hidden") { observable.notify({ reason: PageExitReason.HIDDEN }); } else if (event.type === "freeze") { observable.notify({ reason: PageExitReason.FROZEN }); } }, { capture: true }); const stopBeforeUnloadListener = addEventListener(configuration, window, "beforeunload", () => { observable.notify({ reason: PageExitReason.UNLOADING }); }).stop; return () => { stopListeners(); stopBeforeUnloadListener(); }; }); } function isPageExitReason(reason) { return objectValues(PageExitReason).includes(reason); } // node_modules/@datadog/browser-core/esm/tools/utils/functionUtils.js function throttle(fn, wait, options) { const needLeadingExecution = options && options.leading !== void 0 ? options.leading : true; const needTrailingExecution = options && options.trailing !== void 0 ? options.trailing : true; let inWaitPeriod = false; let pendingExecutionWithParameters; let pendingTimeoutId; return { throttled: (...parameters) => { if (inWaitPeriod) { pendingExecutionWithParameters = parameters; return; } if (needLeadingExecution) { fn(...parameters); } else { pendingExecutionWithParameters = parameters; } inWaitPeriod = true; pendingTimeoutId = setTimeout(() => { if (needTrailingExecution && pendingExecutionWithParameters) { fn(...pendingExecutionWithParameters); } inWaitPeriod = false; pendingExecutionWithParameters = void 0; }, wait); }, cancel: () => { clearTimeout(pendingTimeoutId); inWaitPeriod = false; pendingExecutionWithParameters = void 0; } }; } function noop() { } // node_modules/@datadog/browser-core/esm/tools/serialisation/jsonStringify.js function jsonStringify(value, replacer, space) { if (typeof value !== "object" || value === null) { return JSON.stringify(value); } const restoreObjectPrototypeToJson = detachToJsonMethod(Object.prototype); const restoreArrayPrototypeToJson = detachToJsonMethod(Array.prototype); const restoreValuePrototypeToJson = detachToJsonMethod(Object.getPrototypeOf(value)); const restoreValueToJson = detachToJsonMethod(value); try { return JSON.stringify(value, replacer, space); } catch (_a) { return ""; } finally { restoreObjectPrototypeToJson(); restoreArrayPrototypeToJson(); restoreValuePrototypeToJson(); restoreValueToJson(); } } function detachToJsonMethod(value) { const object = value; const objectToJson = object.toJSON; if (objectToJson) { delete object.toJSON; return () => { object.toJSON = objectToJson; }; } return noop; } // node_modules/@datadog/browser-core/esm/transport/batch.js function createBatch({ encoder, request, flushController, messageBytesLimit }) { let upsertBuffer = {}; const flushSubscription = flushController.flushObservable.subscribe((event) => flush(event)); function push(serializedMessage, estimatedMessageBytesCount, key) { flushController.notifyBeforeAddMessage(estimatedMessageBytesCount); if (key !== void 0) { upsertBuffer[key] = serializedMessage; flushController.notifyAfterAddMessage(); } else { encoder.write(encoder.isEmpty ? serializedMessage : ` ${serializedMessage}`, (realMessageBytesCount) => { flushController.notifyAfterAddMessage(realMessageBytesCount - estimatedMessageBytesCount); }); } } function hasMessageFor(key) { return key !== void 0 && upsertBuffer[key] !== void 0; } function remove(key) { const removedMessage = upsertBuffer[key]; delete upsertBuffer[key]; const messageBytesCount = encoder.estimateEncodedBytesCount(removedMessage); flushController.notifyAfterRemoveMessage(messageBytesCount); } function addOrUpdate(message, key) { const serializedMessage = jsonStringify(message); const estimatedMessageBytesCount = encoder.estimateEncodedBytesCount(serializedMessage); if (estimatedMessageBytesCount >= messageBytesLimit) { display.warn(`Discarded a message whose size was bigger than the maximum allowed size ${messageBytesLimit}KB. ${MORE_DETAILS} ${DOCS_TROUBLESHOOTING}/#technical-limitations`); return; } if (hasMessageFor(key)) { remove(key); } push(serializedMessage, estimatedMessageBytesCount, key); } function flush(event) { const upsertMessages = objectValues(upsertBuffer).join("\n"); upsertBuffer = {}; const pageMightExit = isPageExitReason(event.reason); const send2 = pageMightExit ? request.sendOnExit : request.send; if (pageMightExit && // Note: checking that the encoder is async is not strictly needed, but it's an optimization: // if the encoder is async we need to send two requests in some cases (one for encoded data // and the other for non-encoded data). But if it's not async, we don't have to worry about // it and always send a single request. encoder.isAsync) { const encoderResult = encoder.finishSync(); if (encoderResult.outputBytesCount) { send2(formatPayloadFromEncoder(encoderResult)); } const pendingMessages = [encoderResult.pendingData, upsertMessages].filter(Boolean).join("\n"); if (pendingMessages) { send2({ data: pendingMessages, bytesCount: computeBytesCount(pendingMessages) }); } } else { if (upsertMessages) { encoder.write(encoder.isEmpty ? upsertMessages : ` ${upsertMessages}`); } encoder.finish((encoderResult) => { send2(formatPayloadFromEncoder(encoderResult)); }); } } return { flushController, add: addOrUpdate, upsert: addOrUpdate, stop: flushSubscription.unsubscribe }; } function formatPayloadFromEncoder(encoderResult) { let data; if (typeof encoderResult.output === "string") { data = encoderResult.output; } else { data = new Blob([encoderResult.output], { // This will set the 'Content-Type: text/plain' header. Reasoning: // * The intake rejects the request if there is no content type. // * The browser will issue CORS preflight requests if we set it to 'application/json', which // could induce higher intake load (and maybe has other impacts). // * Also it's not quite JSON, since we are concatenating multiple JSON objects separated by // new lines. type: "text/plain" }); } return { data, bytesCount: encoderResult.outputBytesCount, encoding: encoderResult.encoding }; } // node_modules/@datadog/browser-core/esm/transport/flushController.js function createFlushController({ messagesLimit, bytesLimit, durationLimit, pageMayExitObservable, sessionExpireObservable }) { const pageMayExitSubscription = pageMayExitObservable.subscribe((event) => flush(event.reason)); const sessionExpireSubscription = sessionExpireObservable.subscribe(() => flush("session_expire")); const flushObservable = new Observable(() => () => { pageMayExitSubscription.unsubscribe(); sessionExpireSubscription.unsubscribe(); }); let currentBytesCount = 0; let currentMessagesCount = 0; function flush(flushReason) { if (currentMessagesCount === 0) { return; } const messagesCount = currentMessagesCount; const bytesCount = currentBytesCount; currentMessagesCount = 0; currentBytesCount = 0; cancelDurationLimitTimeout(); flushObservable.notify({ reason: flushReason, messagesCount, bytesCount }); } let durationLimitTimeoutId; function scheduleDurationLimitTimeout() { if (durationLimitTimeoutId === void 0) { durationLimitTimeoutId = setTimeout(() => { flush("duration_limit"); }, durationLimit); } } function cancelDurationLimitTimeout() { clearTimeout(durationLimitTimeoutId); durationLimitTimeoutId = void 0; } return { flushObservable, get messagesCount() { return currentMessagesCount; }, /** * Notifies that a message will be added to a pool of pending messages waiting to be flushed. * * This function needs to be called synchronously, right before adding the message, so no flush * event can happen after `notifyBeforeAddMessage` and before adding the message. * * @param estimatedMessageBytesCount - an estimation of the message bytes count once it is * actually added. */ notifyBeforeAddMessage(estimatedMessageBytesCount) { if (currentBytesCount + estimatedMessageBytesCount >= bytesLimit) { flush("bytes_limit"); } currentMessagesCount += 1; currentBytesCount += estimatedMessageBytesCount; scheduleDurationLimitTimeout(); }, /** * Notifies that a message *was* added to a pool of pending messages waiting to be flushed. * * This function can be called asynchronously after the message was added, but in this case it * should not be called if a flush event occurred in between. * * @param messageBytesCountDiff - the difference between the estimated message bytes count and * its actual bytes count once added to the pool. */ notifyAfterAddMessage(messageBytesCountDiff = 0) { currentBytesCount += messageBytesCountDiff; if (currentMessagesCount >= messagesLimit) { flush("messages_limit"); } else if (currentBytesCount >= bytesLimit) { flush("bytes_limit"); } }, /** * Notifies that a message was removed from a pool of pending messages waiting to be flushed. * * This function needs to be called synchronously, right after removing the message, so no flush * event can happen after removing the message and before `notifyAfterRemoveMessage`. * * @param messageBytesCount - the message bytes count that was added to the pool. Should * correspond to the sum of bytes counts passed to `notifyBeforeAddMessage` and * `notifyAfterAddMessage`. */ notifyAfterRemoveMessage(messageBytesCount) { currentBytesCount -= messageBytesCount; currentMessagesCount -= 1; if (currentMessagesCount === 0) { cancelDurationLimitTimeout(); } } }; } // node_modules/@datadog/browser-core/esm/tools/serialisation/sanitize.js var SANITIZE_DEFAULT_MAX_CHARACTER_COUNT = 220 * ONE_KIBI_BYTE; var JSON_PATH_ROOT_ELEMENT = "$"; var KEY_DECORATION_LENGTH = 3; function sanitize(source, maxCharacterCount = SANITIZE_DEFAULT_MAX_CHARACTER_COUNT) { const restoreObjectPrototypeToJson = detachToJsonMethod(Object.prototype); const restoreArrayPrototypeToJson = detachToJsonMethod(Array.prototype); const containerQueue = []; const visitedObjectsWithPath = /* @__PURE__ */ new WeakMap(); const sanitizedData = sanitizeProcessor(source, JSON_PATH_ROOT_ELEMENT, void 0, containerQueue, visitedObjectsWithPath); const serializedSanitizedData = JSON.stringify(sanitizedData); let accumulatedCharacterCount = serializedSanitizedData ? serializedSanitizedData.length : 0; if (accumulatedCharacterCount > maxCharacterCount) { warnOverCharacterLimit(maxCharacterCount, "discarded", source); return void 0; } while (containerQueue.length > 0 && accumulatedCharacterCount < maxCharacterCount) { const containerToProcess = containerQueue.shift(); let separatorLength = 0; if (Array.isArray(containerToProcess.source)) { for (let key = 0; key < containerToProcess.source.length; key++) { const targetData = sanitizeProcessor(containerToProcess.source[key], containerToProcess.path, key, containerQueue, visitedObjectsWithPath); if (targetData !== void 0) { accumulatedCharacterCount += JSON.stringify(targetData).length; } else { accumulatedCharacterCount += 4; } accumulatedCharacterCount += separatorLength; separatorLength = 1; if (accumulatedCharacterCount > maxCharacterCount) { warnOverCharacterLimit(maxCharacterCount, "truncated", source); break; } ; containerToProcess.target[key] = targetData; } } else { for (const key in containerToProcess.source) { if (Object.prototype.hasOwnProperty.call(containerToProcess.source, key)) { const targetData = sanitizeProcessor(containerToProcess.source[key], containerToProcess.path, key, containerQueue, visitedObjectsWithPath); if (targetData !== void 0) { accumulatedCharacterCount += JSON.stringify(targetData).length + separatorLength + key.length + KEY_DECORATION_LENGTH; separatorLength = 1; } if (accumulatedCharacterCount > maxCharacterCount) { warnOverCharacterLimit(maxCharacterCount, "truncated", source); break; } ; containerToProcess.target[key] = targetData; } } } } restoreObjectPrototypeToJson(); restoreArrayPrototypeToJson(); return sanitizedData; } function sanitizeProcessor(source, parentPath, key, queue, visitedObjectsWithPath) { const sourceToSanitize = tryToApplyToJSON(source); if (!sourceToSanitize || typeof sourceToSanitize !== "object") { return sanitizePrimitivesAndFunctions(sourceToSanitize); } const sanitizedSource = sanitizeObjects(sourceToSanitize); if (sanitizedSource !== "[Object]" && sanitizedSource !== "[Array]" && sanitizedSource !== "[Error]") { return sanitizedSource; } const sourceAsObject = source; if (visitedObjectsWithPath.has(sourceAsObject)) { return `[Reference seen at ${visitedObjectsWithPath.get(sourceAsObject)}]`; } const currentPath = key !== void 0 ? `${parentPath}.${key}` : parentPath; const target = Array.isArray(sourceToSanitize) ? [] : {}; visitedObjectsWithPath.set(sourceAsObject, currentPath); queue.push({ source: sourceToSanitize, target, path: currentPath }); return target; } function sanitizePrimitivesAndFunctions(value) { if (typeof value === "bigint") { return `[BigInt] ${value.toString()}`; } if (typeof value === "function") { return `[Function] ${value.name || "unknown"}`; } if (typeof value === "symbol") { return `[Symbol] ${value.description || value.toString()}`; } return value; } function sanitizeObjects(value) { try { if (value instanceof Event) { return sanitizeEvent(value); } if (value instanceof RegExp) { return `[RegExp] ${value.toString()}`; } const result = Object.prototype.toString.call(value); const match = result.match(/\[object (.*)\]/); if (match && match[1]) { return `[${match[1]}]`; } } catch (_a) { } return "[Unserializable]"; } function sanitizeEvent(event) { return { type: event.type, isTrusted: event.isTrusted, currentTarget: event.currentTarget ? sanitizeObjects(event.currentTarget) : null, target: event.target ? sanitizeObjects(event.target) : null }; } function tryToApplyToJSON(value) { const object = value; if (object && typeof object.toJSON === "function") { try { return object.toJSON(); } catch (_a) { } } return value; } function warnOverCharacterLimit(maxCharacterCount, changeType, source) { display.warn(`The data provided has been ${changeType} as it is over the limit of ${maxCharacterCount} characters:`, source); } // node_modules/@datadog/browser-core/esm/tools/stackTrace/computeStackTrace.js var UNKNOWN_FUNCTION = "?"; function computeStackTrace(ex) { var _a, _b; const stack = []; let stackProperty = tryToGetString(ex, "stack"); const exString = String(ex); if (stackProperty && stackProperty.startsWith(exString)) { stackProperty = stackProperty.slice(exString.length); } if (stackProperty) { stackProperty.split("\n").forEach((line) => { const stackFrame = parseChromeLine(line) || parseChromeAnonymousLine(line) || parseWinLine(line) || parseGeckoLine(line); if (stackFrame) { if (!stackFrame.func && stackFrame.line) { stackFrame.func = UNKNOWN_FUNCTION; } stack.push(stackFrame); } }); } if (stack.length > 0 && isWronglyReportingCustomErrors() && ex instanceof Error) { const constructors = []; let currentPrototype = ex; while ((currentPrototype = Object.getPrototypeOf(currentPrototype)) && isNonNativeClassPrototype(currentPrototype)) { const constructorName = ((_a = currentPrototype.constructor) === null || _a === void 0 ? void 0 : _a.name) || UNKNOWN_FUNCTION; constructors.push(constructorName); } for (let i = constructors.length - 1; i >= 0 && ((_b = stack[0]) === null || _b === void 0 ? void 0 : _b.func) === constructors[i]; i--) { stack.shift(); } } return { message: tryToGetString(ex, "message"), name: tryToGetString(ex, "name"), stack }; } var fileUrl = "((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet||\\w+\\.|\\/).*?)"; var filePosition = "(?::(\\d+))"; var CHROME_LINE_RE = new RegExp(`^\\s*at (.*?) ?\\(${fileUrl}${filePosition}?${filePosition}?\\)?\\s*$`, "i"); var CHROME_EVAL_RE = new RegExp(`\\((\\S*)${filePosition}${filePosition}\\)`); function parseChromeLine(line) { const parts = CHROME_LINE_RE.exec(line); if (!parts) { return; } const isNative = parts[2] && parts[2].indexOf("native") === 0; const isEval = parts[2] && parts[2].indexOf("eval") === 0; const submatch = CHROME_EVAL_RE.exec(parts[2]); if (isEval && submatch) { parts[2] = submatch[1]; parts[3] = submatch[2]; parts[4] = submatch[3]; } return { args: isNative ? [parts[2]] : [], column: parts[4] ? +parts[4] : void 0, func: parts[1] || UNKNOWN_FUNCTION, line: parts[3] ? +parts[3] : void 0, url: !isNative ? parts[2] : void 0 }; } var CHROME_ANONYMOUS_FUNCTION_RE = new RegExp(`^\\s*at ?${fileUrl}${filePosition}?${filePosition}??\\s*$`, "i"); function parseChromeAnonymousLine(line) { const parts = CHROME_ANONYMOUS_FUNCTION_RE.exec(line); if (!parts) { return; } return { args: [], column: parts[3] ? +parts[3] : void 0, func: UNKNOWN_FUNCTION, line: parts[2] ? +parts[2] : void 0, url: parts[1] }; } var WINJS_LINE_RE = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i; function parseWinLine(line) { const parts = WINJS_LINE_RE.exec(line); if (!parts) { return; } return { args: [], column: parts[4] ? +parts[4] : void 0, func: parts[1] || UNKNOWN_FUNCTION, line: +parts[3], url: parts[2] }; } var GECKO_LINE_RE = /^\s*(.*?)(?:\((.*?)\))?(?:(?:(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle|\[wasm code\])(?::(\d+))?(?::(\d+))?)|@)\s*$/i; var GECKO_EVAL_RE = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; function parseGeckoLine(line) { const parts = GECKO_LINE_RE.exec(line); if (!parts) { return; } const isEval = parts[3] && parts[3].indexOf(" > eval") > -1; const submatch = GECKO_EVAL_RE.exec(parts[3]); if (isEval && submatch) { parts[3] = submatch[1]; parts[4] = submatch[2]; parts[5] = void 0; } return { args: parts[2] ? parts[2].split(",") : [], column: parts[5] ? +parts[5] : void 0, func: parts[1] || UNKNOWN_FUNCTION, line: parts[4] ? +parts[4] : void 0, url: parts[3] }; } function tryToGetString(candidate, property) { if (typeof candidate !== "object" || !candidate || !(property in candidate)) { return void 0; } const value = candidate[property]; return typeof value === "string" ? value : void 0; } function computeStackTraceFromOnErrorMessage(messageObj, url, line, column) { if (url === void 0) { return; } const { name, message } = tryToParseMessage(messageObj); return { name, message, stack: [{ url, column, line }] }; } var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\s\S]*)$/; function tryToParseMessage(messageObj) { let name; let message; if ({}.toString.call(messageObj) === "[object String]") { ; [, name, message] = ERROR_TYPES_RE.exec(messageObj); } return { name, message }; } function isNonNativeClassPrototype(prototype) { return String(prototype.constructor).startsWith("class "); } var isWronglyReportingCustomErrorsCache; function isWronglyReportingCustomErrors() { if (isWronglyReportingCustomErrorsCache !== void 0) { return isWronglyReportingCustomErrorsCache; } class DatadogTestCustomError extends Error { constructor() { super(); this.name = "Error"; } } const [customError, nativeError] = [DatadogTestCustomError, Error].map((errConstructor) => new errConstructor()); isWronglyReportingCustomErrorsCache = // If customError is not a class, it means that this was built with ES5 as target, converting the class to a normal object. // Thus, error constructors will be reported on all browsers, which is the expected behavior. isNonNativeClassPrototype(Object.getPrototypeOf(customError)) && // If the browser is correctly reporting the stacktrace, the normal error stacktrace should be the same as the custom error stacktrace nativeError.stack !== customError.stack; return isWronglyReportingCustomErrorsCache; } // node_modules/@datadog/browser-core/esm/tools/stackTrace/handlingStack.js function createHandlingStack(type) { const internalFramesToSkip = 2; const error = new Error(type); error.name = "HandlingStack"; let formattedStack; callMonitored(() => { const stackTrace = computeStackTrace(error); stackTrace.stack = stackTrace.stack.slice(internalFramesToSkip); formattedStack = toStackTraceString(stackTrace); }); return formattedStack; } function toStackTraceString(stack) { let result = formatErrorMessage(stack); stack.stack.forEach((frame) => { const func = frame.func === "?" ? "" : frame.func; const args = frame.args && frame.args.length > 0 ? `(${frame.args.join(", ")})` : ""; const line = frame.line ? `:${frame.line}` : ""; const column = frame.line && frame.column ? `:${frame.column}` : ""; result += ` at ${func}${args} @ ${frame.url}${line}${column}`; }); return result; } function formatErrorMessage(stack) { return `${stack.name || "Error"}: ${stack.message}`; } // node_modules/@datadog/browser-core/esm/domain/error/error.js var NO_ERROR_STACK_PRESENT_MESSAGE = "No stack, consider using an instance of Error"; function computeRawError({ stackTrace, originalError, handlingStack, componentStack, startClocks, nonErrorPrefix, useFallbackStack = true, source, handling }) { const isErrorInstance = isError(originalError); if (!stackTrace && isErrorInstance) { stackTrace = computeStackTrace(originalError); } return { startClocks, source, handling, handlingStack, componentStack, originalError, type: stackTrace ? stackTrace.name : void 0, message: computeMessage(stackTrace, isErrorInstance, nonErrorPrefix, originalError), stack: stackTrace ? toStackTraceString(stackTrace) : useFallbackStack ? NO_ERROR_STACK_PRESENT_MESSAGE : void 0, causes: isErrorInstance ? flattenErrorCauses(originalError, source) : void 0, fingerprint: tryToGetFingerprint(originalError), context: tryToGetErrorContext(originalError) }; } function computeMessage(stackTrace, isErrorInstance, nonErrorPrefix, originalError) { return (stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.message) && (stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.name) ? stackTrace.message : !isErrorInstance ? `${nonErrorPrefix} ${jsonStringify(sanitize(originalError))}` : "Empty message"; } function tryToGetFingerprint(originalError) { return isError(originalError) && "dd_fingerprint" in originalError ? String(originalError.dd_fingerprint) : void 0; } function tryToGetErrorContext(originalError) { if (originalError !== null && typeof originalError === "object" && "dd_context" in originalError) { return originalError.dd_context; } } function isError(error) { return error instanceof Error || Object.prototype.toString.call(error) === "[object Error]"; } function flattenErrorCauses(error, parentSource) { let currentError = error; const causes = []; while (isError(currentError === null || currentError === void 0 ? void 0 : currentError.cause) && causes.length < 10) { const stackTrace = computeStackTrace(currentError.cause); causes.push({ message: currentError.cause.message, source: parentSource, type: stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.name, stack: stackTrace && toStackTraceString(stackTrace) }); currentError = currentError.cause; } return causes.length ? causes : void 0; } // node_modules/@datadog/browser-core/esm/tools/utils/objectUtils.js function shallowClone(object) { return __spreadValues({}, object); } function objectHasValue(object, value) { return Object.keys(object).some((key) => object[key] === value); } function isEmptyObject(object) { return Object.keys(object).length === 0; } function mapValues(object, fn) { const newObject = {}; for (const key of Object.keys(object)) { newObject[key] = fn(object[key]); } return newObject; } // node_modules/@datadog/browser-core/esm/tools/experimentalFeatures.js var ExperimentalFeature; (function(ExperimentalFeature2) { ExperimentalFeature2["TRACK_INTAKE_REQUESTS"] = "track_intake_requests"; ExperimentalFeature2["WRITABLE_RESOURCE_GRAPHQL"] = "writable_resource_graphql"; ExperimentalFeature2["USE_TREE_WALKER_FOR_ACTION_NAME"] = "use_tree_walker_for_action_name"; ExperimentalFeature2["GRAPHQL_TRACKING"] = "graphql_tracking"; ExperimentalFeature2["FEATURE_OPERATION_VITAL"] = "feature_operation_vital"; ExperimentalFeature2["SHORT_SESSION_INVESTIGATION"] = "short_session_investigation"; })(ExperimentalFeature || (ExperimentalFeature = {})); var enabledExperimentalFeatures = /* @__PURE__ */ new Set(); function initFeatureFlags(enableExperimentalFeatures) { if (Array.isArray(enableExperimentalFeatures)) { addExperimentalFeatures(enableExperimentalFeatures.filter((flag) => objectHasValue(ExperimentalFeature, flag))); } } function addExperimentalFeatures(enabledFeatures) { enabledFeatures.forEach((flag) => { enabledExperimentalFeatures.add(flag); }); } function isExperimentalFeatureEnabled(featureName) { return enabledExperimentalFeatures.has(featureName); } function getExperimentalFeatures() { return enabledExperimentalFeatures; } // node_modules/@datadog/browser-core/esm/domain/tags.js var TAG_SIZE_LIMIT = 200; function buildTags(configuration) { const { env, service, version, datacenter, sdkVersion, variant } = configuration; const tags = [buildTag("sdk_version", sdkVersion !== null && sdkVersion !== void 0 ? sdkVersion : "6.21.2")]; if (env) { tags.push(buildTag("env", env)); } if (service) { tags.push(buildTag("service", service)); } if (version) { tags.push(buildTag("version", version)); } if (datacenter) { tags.push(buildTag("datacenter", datacenter)); } if (variant) { tags.push(buildTag("variant", variant)); } return tags; } function buildTag(key, rawValue) { const tag = rawValue ? `${key}:${rawValue}` : key; if (tag.length > TAG_SIZE_LIMIT || hasForbiddenCharacters(tag)) { display.warn(`Tag ${tag} doesn't meet tag requirements and will be sanitized. ${MORE_DETAILS} ${DOCS_ORIGIN}/getting_started/tagging/#defining-tags`); } return sanitizeTag(tag); } function sanitizeTag(tag) { return tag.replace(/,/g, "_"); } function hasForbiddenCharacters(rawValue) { if (!supportUnicodePropertyEscapes()) { return false; } return new RegExp("[^\\p{Ll}\\p{Lo}0-9_:./-]", "u").test(rawValue); } function supportUnicodePropertyEscapes() { try { new RegExp("[\\p{Ll}]", "u"); return true; } catch (_a) { return false; } } // node_modules/@datadog/browser-core/esm/domain/intakeSites.js var INTAKE_SITE_STAGING = "datad0g.com"; var INTAKE_SITE_FED_STAGING = "dd0g-gov.com"; var INTAKE_SITE_US1 = "datadoghq.com"; var INTAKE_SITE_EU1 = "datadoghq.eu"; var INTAKE_SITE_US1_FED = "ddog-gov.com"; var PCI_INTAKE_HOST_US1 = "pci.browser-intake-datadoghq.com"; var INTAKE_URL_PARAMETERS = ["ddsource", "dd-api-key", "dd-request-id"]; // node_modules/@datadog/browser-core/esm/tools/sendToExtension.js function sendToExtension(type, payload) { const callback = globalObject.__ddBrowserSdkExtensionCallback; if (callback) { callback({ type, payload }); } } // node_modules/@datadog/browser-core/esm/tools/utils/typeUtils.js function getType(value) { if (value === null) { return "null"; } if (Array.isArray(value)) { return "array"; } return typeof value; } // node_modules/@datadog/browser-core/esm/tools/mergeInto.js function mergeInto(destination, source, circularReferenceChecker = createCircularReferenceChecker()) { if (source === void 0) { return destination; } if (typeof source !== "object" || source === null) { return source; } else if (source instanceof Date) { return new Date(source.getTime()); } else if (source instanceof RegExp) { const flags = source.flags || // old browsers compatibility [source.global ? "g" : "", source.ignoreCase ? "i" : "", source.multiline ? "m" : "", source.sticky ? "y" : "", source.unicode ? "u" : ""].join(""); return new RegExp(source.source, flags); } if (circularReferenceChecker.hasAlreadyBeenSeen(source)) { return void 0; } else if (Array.isArray(source)) { const merged2 = Array.isArray(destination) ? destination : []; for (let i = 0; i < source.length; ++i) { merged2[i] = mergeInto(merged2[i], source[i], circularReferenceChecker); } return merged2; } const merged = getType(destination) === "object" ? destination : {}; for (const key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { merged[key] = mergeInto(merged[key], source[key], circularReferenceChecker); } } return merged; } function deepClone(value) { return mergeInto(void 0, value); } function combine(...sources) { let destination; for (const source of sources) { if (source === void 0 || source === null) { continue; } destination = mergeInto(destination, source); } return destination; } function createCircularReferenceChecker() { if (typeof WeakSet !== "undefined") { const set = /* @__PURE__ */ new WeakSet(); return { hasAlreadyBeenSeen(value) { const has = set.has(value); if (!has) { set.add(value); } return has; } }; } const array = []; return { hasAlreadyBeenSeen(value) { const has = array.indexOf(value) >= 0; if (!has) { array.push(value); } return has; } }; } // node_modules/@datadog/browser-core/esm/domain/connectivity/connectivity.js function getConnectivity() { var _a; const navigator2 = globalObject.navigator; return { status: navigator2.onLine ? "connected" : "not_connected", interfaces: navigator2.connection && navigator2.connection.type ? [navigator2.connection.type] : void 0, effective_type: (_a = navigator2.connection) === null || _a === void 0 ? void 0 : _a.effectiveType }; } // node_modules/@datadog/browser-core/esm/tools/abstractHooks.js var DISCARDED = "DISCARDED"; var SKIPPED = "SKIPPED"; function abstractHooks() { const callbacks = {}; return { register(hookName, callback) { if (!callbacks[hookName]) { callbacks[hookName] = []; } callbacks[hookName].push(callback); return { unregister: () => { callbacks[hookName] = callbacks[hookName].filter((cb) => cb !== callback); } }; }, triggerHook(hookName, param) { const hookCallbacks = callbacks[hookName] || []; const results = []; for (const callback of hookCallbacks) { const result = callback(param); if (result === DISCARDED) { return DISCARDED; } if (result === SKIPPED) { continue; } results.push(result); } return combine(...results); } }; } // node_modules/@datadog/browser-core/esm/domain/telemetry/rawTelemetryEvent.types.js var TelemetryType = { LOG: "log", CONFIGURATION: "configuration", USAGE: "usage" }; // node_modules/@datadog/browser-core/esm/domain/telemetry/telemetry.js var ALLOWED_FRAME_URLS = ["https://www.datadoghq-browser-agent.com", "https://www.datad0g-browser-agent.com", "https://d3uc069fcn7uxw.cloudfront.net", "https://d20xtzwzcl0ceb.cloudfront.net", "http://localhost", ""]; var METRIC_SAMPLE_RATE = 1; var TELEMETRY_EXCLUDED_SITES = [INTAKE_SITE_US1_FED]; var telemetryObservable; function getTelemetryObservable() { if (!telemetryObservable) { telemetryObservable = new BufferedObservable(100); } return telemetryObservable; } function startTelemetry(telemetryService, configuration, hooks, reportError, pageMayExitObservable, createEncoder) { const observable = new Observable(); const { stop } = startTelemetryTransport(configuration, reportError, pageMayExitObservable, createEncoder, observable); const { enabled, metricsEnabled } = startTelemetryCollection(telemetryService, configuration, hooks, observable); return { stop, enabled, metricsEnabled }; } function startTelemetryCollection(telemetryService, configuration, hooks, observable, metricSampleRate = METRIC_SAMPLE_RATE) { const alreadySentEventsByKind = {}; const telemetryEnabled = !TELEMETRY_EXCLUDED_SITES.includes(configuration.site) && performDraw(configuration.telemetrySampleRate); const telemetryEnabledPerType = { [TelemetryType.LOG]: telemetryEnabled, [TelemetryType.CONFIGURATION]: telemetryEnabled && performDraw(configuration.telemetryConfigurationSampleRate), [TelemetryType.USAGE]: telemetryEnabled && performDraw(configuration.telemetryUsageSampleRate), // not an actual "type" but using a single draw for all metrics metric: telemetryEnabled && performDraw(metricSampleRate) }; const runtimeEnvInfo = getRuntimeEnvInfo(); const telemetryObservable2 = getTelemetryObservable(); telemetryObservable2.subscribe(({ rawEvent, metricName }) => { if (metricName && !telemetryEnabledPerType["metric"] || !telemetryEnabledPerType[rawEvent.type]) { return; } const kind = metricName || rawEvent.status || rawEvent.type; let alreadySentEvents = alreadySentEventsByKind[kind]; if (!alreadySentEvents) { alreadySentEvents = alreadySentEventsByKind[kind] = /* @__PURE__ */ new Set(); } if (alreadySentEvents.size >= configuration.maxTelemetryEventsPerPage) { return; } const stringifiedEvent = jsonStringify(rawEvent); if (alreadySentEvents.has(stringifiedEvent)) { return; } const defaultTelemetryEventAttributes = hooks.triggerHook(1, { startTime: clocksNow().relative }); if (defaultTelemetryEventAttributes === DISCARDED) { return; } const event = toTelemetryEvent(defaultTelemetryEventAttributes, telemetryService, rawEvent, runtimeEnvInfo); observable.notify(event); sendToExtension("telemetry", event); alreadySentEvents.add(stringifiedEvent); }); telemetryObservable2.unbuffer(); startMonitorErrorCollection(addTelemetryError); return { enabled: telemetryEnabled, metricsEnabled: telemetryEnabledPerType["metric"] }; function toTelemetryEvent(defaultTelemetryEventAttributes, telemetryService2, rawEvent, runtimeEnvInfo2) { const clockNow = clocksNow(); const event = { type: "telemetry", date: clockNow.timeStamp, service: telemetryService2, version: "6.21.2", source: "browser", _dd: { format_version: 2 }, telemetry: combine(rawEvent, { runtime_env: runtimeEnvInfo2, connectivity: getConnectivity(), sdk_setup: "npm" }), ddtags: buildTags(configuration).join(","), experimental_features: Array.from(getExperimentalFeatures()) }; return combine(event, defaultTelemetryEventAttributes); } } function startTelemetryTransport(configuration, reportError, pageMayExitObservable, createEncoder, telemetryObservable2) { const cleanupTasks2 = []; if (canUseEventBridge()) { const bridge = getEventBridge(); const telemetrySubscription = telemetryObservable2.subscribe((event) => bridge.send("internal_telemetry", event)); cleanupTasks2.push(telemetrySubscription.unsubscribe); } else { const endpoints = [configuration.rumEndpointBuilder]; if (configuration.replica && isTelemetryReplicationAllowed(configuration)) { endpoints.push(configuration.replica.rumEndpointBuilder); } const telemetryBatch = createBatch({ encoder: createEncoder( 4 /* DeflateEncoderStreamId.TELEMETRY */ ), request: createHttpRequest(endpoints, configuration.batchBytesLimit, reportError), flushController: createFlushController({ messagesLimit: configuration.batchMessagesLimit, bytesLimit: configuration.batchBytesLimit, durationLimit: configuration.flushTimeout, pageMayExitObservable, // We don't use an actual session expire observable here, to make telemetry collection // independent of the session. This allows to start and send telemetry events earlier. sessionExpireObservable: new Observable() }), messageBytesLimit: configuration.messageBytesLimit }); cleanupTasks2.push(telemetryBatch.stop); const telemetrySubscription = telemetryObservable2.subscribe(telemetryBatch.add); cleanupTasks2.push(telemetrySubscription.unsubscribe); } return { stop: () => cleanupTasks2.forEach((task) => task()) }; } function getRuntimeEnvInfo() { var _a; return { is_local_file: ((_a = globalObject.location) === null || _a === void 0 ? void 0 : _a.protocol) === "file:", is_worker: isWorkerEnvironment }; } function isTelemetryReplicationAllowed(configuration) { return configuration.site === INTAKE_SITE_STAGING; } function addTelemetryDebug(message, context) { displayIfDebugEnabled(ConsoleApiName.debug, message, context); getTelemetryObservable().notify({ rawEvent: __spreadValues({ type: TelemetryType.LOG, message, status: "debug" }, context) }); } function addTelemetryError(e, context) { getTelemetryObservable().notify({ rawEvent: __spreadValues(__spreadValues({ type: TelemetryType.LOG, status: "error" }, formatError(e)), context) }); } function addTelemetryConfiguration(configuration) { getTelemetryObservable().notify({ rawEvent: { type: TelemetryType.CONFIGURATION, configuration } }); } function addTelemetryMetrics(metricName, context) { getTelemetryObservable().notify({ rawEvent: __spreadValues({ type: TelemetryType.LOG, message: metricName, status: "debug" }, context), metricName }); } function addTelemetryUsage(usage) { getTelemetryObservable().notify({ rawEvent: { type: TelemetryType.USAGE, usage } }); } function formatError(e) { if (isError(e)) { const stackTrace = computeStackTrace(e); return { error: { kind: stackTrace.name, stack: toStackTraceString(scrubCustomerFrames(stackTrace)) }, message: stackTrace.message }; } return { error: { stack: NO_ERROR_STACK_PRESENT_MESSAGE }, message: `${"Uncaught"} ${jsonStringify(e)}` }; } function scrubCustomerFrames(stackTrace) { stackTrace.stack = stackTrace.stack.filter((frame) => !frame.url || ALLOWED_FRAME_URLS.some((allowedFrameUrl) => frame.url.startsWith(allowedFrameUrl))); return stackTrace; } // node_modules/@datadog/browser-core/esm/tools/catchUserErrors.js function catchUserErrors(fn, errorMsg) { return (...args) => { try { return fn(...args); } catch (err) { display.error(errorMsg, err); } }; } // node_modules/@datadog/browser-core/esm/tools/utils/stringUtils.js function generateUUID(placeholder) { return placeholder ? ( // eslint-disable-next-line no-bitwise (parseInt(placeholder, 10) ^ Math.random() * 16 >> parseInt(placeholder, 10) / 4).toString(16) ) : `${1e7}-${1e3}-${4e3}-${8e3}-${1e11}`.replace(/[018]/g, generateUUID); } var COMMA_SEPARATED_KEY_VALUE = /([\w-]+)\s*=\s*([^;]+)/g; function findCommaSeparatedValue(rawString, name) { COMMA_SEPARATED_KEY_VALUE.lastIndex = 0; while (true) { const match = COMMA_SEPARATED_KEY_VALUE.exec(rawString); if (match) { if (match[1] === name) { return match[2]; } } else { break; } } } function findCommaSeparatedValues(rawString) { const result = /* @__PURE__ */ new Map(); COMMA_SEPARATED_KEY_VALUE.lastIndex = 0; while (true) { const match = COMMA_SEPARATED_KEY_VALUE.exec(rawString); if (match) { result.set(match[1], match[2]); } else { break; } } return result; } function safeTruncate(candidate, length, suffix = "") { const lastChar = candidate.charCodeAt(length - 1); const isLastCharSurrogatePair = lastChar >= 55296 && lastChar <= 56319; const correctedLength = isLastCharSurrogatePair ? length + 1 : length; if (candidate.length <= correctedLength) { return candidate; } return `${candidate.slice(0, correctedLength)}${suffix}`; } // node_modules/@datadog/browser-core/esm/tools/utils/browserDetection.js function isChromium() { return detectBrowserCached() === 0; } function isSafari() { return detectBrowserCached() === 1; } var browserCache; function detectBrowserCached() { return browserCache !== null && browserCache !== void 0 ? browserCache : browserCache = detectBrowser(); } function detectBrowser(browserWindow = window) { var _a; const userAgent = browserWindow.navigator.userAgent; if (browserWindow.chrome || /HeadlessChrome/.test(userAgent)) { return 0; } if ( // navigator.vendor is deprecated, but it is the most resilient way we found to detect // "Apple maintained browsers" (AKA Safari). If one day it gets removed, we still have the // useragent test as a semi-working fallback. ((_a = browserWindow.navigator.vendor) === null || _a === void 0 ? void 0 : _a.indexOf("Apple")) === 0 || /safari/i.test(userAgent) && !/chrome|android/i.test(userAgent) ) { return 1; } return 2; } // node_modules/@datadog/browser-core/esm/tools/utils/urlPolyfill.js function normalizeUrl(url) { return buildUrl(url, location.href).href; } function isValidUrl(url) { try { return !!buildUrl(url); } catch (_a) { return false; } } function getPathName(url) { const pathname = buildUrl(url).pathname; return pathname[0] === "/" ? pathname : `/${pathname}`; } function buildUrl(url, base) { const { URL } = getPristineWindow(); try { return base !== void 0 ? new URL(url, base) : new URL(url); } catch (error) { throw new Error(`Failed to construct URL: ${String(error)}`); } } var getPristineGlobalObjectCache; function getPristineWindow() { if (!getPristineGlobalObjectCache) { let iframe; let pristineWindow; try { iframe = document.createElement("iframe"); iframe.style.display = "none"; document.body.appendChild(iframe); pristineWindow = iframe.contentWindow; } catch (_a) { pristineWindow = globalObject; } getPristineGlobalObjectCache = { URL: pristineWindow.URL }; iframe === null || iframe === void 0 ? void 0 : iframe.remove(); } return getPristineGlobalObjectCache; } // node_modules/@datadog/browser-core/esm/browser/cookie.js function setCookie(name, value, expireDelay = 0, options) { const date = /* @__PURE__ */ new Date(); date.setTime(date.getTime() + expireDelay); const expires = `expires=${date.toUTCString()}`; const sameSite = options && options.crossSite ? "none" : "strict"; const domain = options && options.domain ? `;domain=${options.domain}` : ""; const secure = options && options.secure ? ";secure" : ""; const partitioned = options && options.partitioned ? ";partitioned" : ""; document.cookie = `${name}=${value};${expires};path=/;samesite=${sameSite}${domain}${secure}${partitioned}`; } function getCookie(name) { return findCommaSeparatedValue(document.cookie, name); } var initCookieParsed; function getInitCookie(name) { if (!initCookieParsed) { initCookieParsed = findCommaSeparatedValues(document.cookie); } return initCookieParsed.get(name); } function deleteCookie(name, options) { setCookie(name, "", 0, options); } function areCookiesAuthorized(options) { if (document.cookie === void 0 || document.cookie === null) { return false; } try { const testCookieName = `dd_cookie_test_${generateUUID()}`; const testCookieValue = "test"; setCookie(testCookieName, testCookieValue, ONE_MINUTE, options); const isCookieCorrectlySet = getCookie(testCookieName) === testCookieValue; deleteCookie(testCookieName, options); return isCookieCorrectlySet; } catch (error) { display.error(error); return false; } } var getCurrentSiteCache; function getCurrentSite(hostname = location.hostname, referrer = document.referrer) { if (getCurrentSiteCache === void 0) { const defaultHostName = getCookieDefaultHostName(hostname, referrer); if (defaultHostName) { const testCookieName = `dd_site_test_${generateUUID()}`; const testCookieValue = "test"; const domainLevels = defaultHostName.split("."); let candidateDomain = domainLevels.pop(); while (domainLevels.length && !getCookie(testCookieName)) { candidateDomain = `${domainLevels.pop()}.${candidateDomain}`; setCookie(testCookieName, testCookieValue, ONE_SECOND, { domain: candidateDomain }); } deleteCookie(testCookieName, { domain: candidateDomain }); getCurrentSiteCache = candidateDomain; } } return getCurrentSiteCache; } function getCookieDefaultHostName(hostname, referrer) { try { return hostname || buildUrl(referrer).hostname; } catch (_a) { } } // node_modules/@datadog/browser-core/esm/domain/session/storeStrategies/sessionStoreStrategy.js var SESSION_STORE_KEY = "_dd_s"; // node_modules/@datadog/browser-core/esm/domain/session/sessionConstants.js var SESSION_TIME_OUT_DELAY = 4 * ONE_HOUR; var SESSION_EXPIRATION_DELAY = 15 * ONE_MINUTE; var SESSION_COOKIE_EXPIRATION_DELAY = ONE_YEAR; var SESSION_NOT_TRACKED = "0"; var SessionPersistence = { COOKIE: "cookie", LOCAL_STORAGE: "local-storage" }; // node_modules/@datadog/browser-core/esm/domain/session/sessionStateValidation.js var SESSION_ENTRY_REGEXP = /^([a-zA-Z]+)=([a-z0-9-]+)$/; var SESSION_ENTRY_SEPARATOR = "&"; function isValidSessionString(sessionString) { return !!sessionString && (sessionString.indexOf(SESSION_ENTRY_SEPARATOR) !== -1 || SESSION_ENTRY_REGEXP.test(sessionString)); } // node_modules/@datadog/browser-core/esm/domain/session/sessionState.js var EXPIRED = "1"; function getExpiredSessionState(previousSessionState, configuration) { const expiredSessionState = { isExpired: EXPIRED }; if (configuration.trackAnonymousUser) { if (previousSessionState === null || previousSessionState === void 0 ? void 0 : previousSessionState.anonymousId) { expiredSessionState.anonymousId = previousSessionState === null || previousSessionState === void 0 ? void 0 : previousSessionState.anonymousId; } else { expiredSessionState.anonymousId = generateUUID(); } } return expiredSessionState; } function isSessionInNotStartedState(session) { return isEmptyObject(session); } function isSessionStarted(session) { return !isSessionInNotStartedState(session); } function isSessionInExpiredState(session) { return session.isExpired !== void 0 || !isActiveSession(session); } function isActiveSession(sessionState) { return (sessionState.created === void 0 || dateNow() - Number(sessionState.created) < SESSION_TIME_OUT_DELAY) && (sessionState.expire === void 0 || dateNow() < Number(sessionState.expire)); } function expandSessionState(session) { session.expire = String(dateNow() + SESSION_EXPIRATION_DELAY); } function toSessionString(session) { return objectEntries(session).map(([key, value]) => key === "anonymousId" ? `aid=${value}` : `${key}=${value}`).join(SESSION_ENTRY_SEPARATOR); } function toSessionState(sessionString) { const session = {}; if (isValidSessionString(sessionString)) { sessionString.split(SESSION_ENTRY_SEPARATOR).forEach((entry) => { const matches = SESSION_ENTRY_REGEXP.exec(entry); if (matches !== null) { const [, key, value] = matches; if (key === "aid") { session.anonymousId = value; } else { session[key] = value; } } }); } return session; } // node_modules/@datadog/browser-core/esm/domain/session/oldCookiesMigration.js var OLD_SESSION_COOKIE_NAME = "_dd"; var OLD_RUM_COOKIE_NAME = "_dd_r"; var OLD_LOGS_COOKIE_NAME = "_dd_l"; var RUM_SESSION_KEY = "rum"; var LOGS_SESSION_KEY = "logs"; function tryOldCookiesMigration(cookieStoreStrategy) { const sessionString = getInitCookie(SESSION_STORE_KEY); if (!sessionString) { const oldSessionId = getInitCookie(OLD_SESSION_COOKIE_NAME); const oldRumType = getInitCookie(OLD_RUM_COOKIE_NAME); const oldLogsType = getInitCookie(OLD_LOGS_COOKIE_NAME); const session = {}; if (oldSessionId) { session.id = oldSessionId; } if (oldLogsType && /^[01]$/.test(oldLogsType)) { session[LOGS_SESSION_KEY] = oldLogsType; } if (oldRumType && /^[012]$/.test(oldRumType)) { session[RUM_SESSION_KEY] = oldRumType; } if (isSessionStarted(session)) { expandSessionState(session); cookieStoreStrategy.persistSession(session); } } } // node_modules/@datadog/browser-core/esm/domain/session/storeStrategies/sessionInCookie.js function selectCookieStrategy(initConfiguration) { const cookieOptions = buildCookieOptions(initConfiguration); return cookieOptions && areCookiesAuthorized(cookieOptions) ? { type: SessionPersistence.COOKIE, cookieOptions } : void 0; } function initCookieStrategy(configuration, cookieOptions) { const cookieStore2 = { /** * Lock strategy allows mitigating issues due to concurrent access to cookie. * This issue concerns only chromium browsers and enabling this on firefox increases cookie write failures. */ isLockEnabled: isChromium(), persistSession: (sessionState) => storeSessionCookie(cookieOptions, configuration, sessionState, SESSION_EXPIRATION_DELAY), retrieveSession: retrieveSessionCookie, expireSession: (sessionState) => storeSessionCookie(cookieOptions, configuration, getExpiredSessionState(sessionState, configuration), SESSION_TIME_OUT_DELAY) }; tryOldCookiesMigration(cookieStore2); return cookieStore2; } function storeSessionCookie(options, configuration, sessionState, defaultTimeout) { setCookie(SESSION_STORE_KEY, toSessionString(sessionState), configuration.trackAnonymousUser ? SESSION_COOKIE_EXPIRATION_DELAY : defaultTimeout, options); } function retrieveSessionCookie() { const sessionString = getCookie(SESSION_STORE_KEY); const sessionState = toSessionState(sessionString); return sessionState; } function buildCookieOptions(initConfiguration) { const cookieOptions = {}; cookieOptions.secure = !!initConfiguration.useSecureSessionCookie || !!initConfiguration.usePartitionedCrossSiteSessionCookie; cookieOptions.crossSite = !!initConfiguration.usePartitionedCrossSiteSessionCookie; cookieOptions.partitioned = !!initConfiguration.usePartitionedCrossSiteSessionCookie; if (initConfiguration.trackSessionAcrossSubdomains) { const currentSite = getCurrentSite(); if (!currentSite) { return; } cookieOptions.domain = currentSite; } return cookieOptions; } // node_modules/@datadog/browser-core/esm/domain/session/storeStrategies/sessionInLocalStorage.js var LOCAL_STORAGE_TEST_KEY = "_dd_test_"; function selectLocalStorageStrategy() { try { const id = generateUUID(); const testKey = `${LOCAL_STORAGE_TEST_KEY}${id}`; localStorage.setItem(testKey, id); const retrievedId = localStorage.getItem(testKey); localStorage.removeItem(testKey); return id === retrievedId ? { type: SessionPersistence.LOCAL_STORAGE } : void 0; } catch (_a) { return void 0; } } function initLocalStorageStrategy(configuration) { return { isLockEnabled: false, persistSession: persistInLocalStorage, retrieveSession: retrieveSessionFromLocalStorage, expireSession: (sessionState) => expireSessionFromLocalStorage(sessionState, configuration) }; } function persistInLocalStorage(sessionState) { localStorage.setItem(SESSION_STORE_KEY, toSessionString(sessionState)); } function retrieveSessionFromLocalStorage() { const sessionString = localStorage.getItem(SESSION_STORE_KEY); return toSessionState(sessionString); } function expireSessionFromLocalStorage(previousSessionState, configuration) { persistInLocalStorage(getExpiredSessionState(previousSessionState, configuration)); } // node_modules/@datadog/browser-core/esm/domain/session/sessionStoreOperations.js var LOCK_RETRY_DELAY = 10; var LOCK_MAX_TRIES = 100; var LOCK_EXPIRATION_DELAY = ONE_SECOND; var LOCK_SEPARATOR = "--"; var bufferedOperations = []; var ongoingOperations; function processSessionStoreOperations(operations, sessionStoreStrategy, numberOfRetries = 0) { var _a; const { isLockEnabled, persistSession, expireSession } = sessionStoreStrategy; const persistWithLock = (session) => persistSession(__spreadProps(__spreadValues({}, session), { lock: currentLock })); const retrieveStore = () => { const _a2 = sessionStoreStrategy.retrieveSession(), { lock } = _a2, session = __objRest(_a2, [ "lock" ]); return { session, lock: lock && !isLockExpired(lock) ? lock : void 0 }; }; if (!ongoingOperations) { ongoingOperations = operations; } if (operations !== ongoingOperations) { bufferedOperations.push(operations); return; } if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) { next(sessionStoreStrategy); return; } let currentLock; let currentStore = retrieveStore(); if (isLockEnabled) { if (currentStore.lock) { retryLater(operations, sessionStoreStrategy, numberOfRetries); return; } currentLock = createLock(); persistWithLock(currentStore.session); currentStore = retrieveStore(); if (currentStore.lock !== currentLock) { retryLater(operations, sessionStoreStrategy, numberOfRetries); return; } } let processedSession = operations.process(currentStore.session); if (isLockEnabled) { currentStore = retrieveStore(); if (currentStore.lock !== currentLock) { retryLater(operations, sessionStoreStrategy, numberOfRetries); return; } } if (processedSession) { if (isSessionInExpiredState(processedSession)) { expireSession(processedSession); } else { expandSessionState(processedSession); if (isLockEnabled) { persistWithLock(processedSession); } else { persistSession(processedSession); } } } if (isLockEnabled) { if (!(processedSession && isSessionInExpiredState(processedSession))) { currentStore = retrieveStore(); if (currentStore.lock !== currentLock) { retryLater(operations, sessionStoreStrategy, numberOfRetries); return; } persistSession(currentStore.session); processedSession = currentStore.session; } } (_a = operations.after) === null || _a === void 0 ? void 0 : _a.call(operations, processedSession || currentStore.session); next(sessionStoreStrategy); } function retryLater(operations, sessionStore, currentNumberOfRetries) { setTimeout(() => { processSessionStoreOperations(operations, sessionStore, currentNumberOfRetries + 1); }, LOCK_RETRY_DELAY); } function next(sessionStore) { ongoingOperations = void 0; const nextOperations = bufferedOperations.shift(); if (nextOperations) { processSessionStoreOperations(nextOperations, sessionStore); } } function createLock() { return generateUUID() + LOCK_SEPARATOR + timeStampNow(); } function isLockExpired(lock) { const [, timeStamp] = lock.split(LOCK_SEPARATOR); return !timeStamp || elapsed(Number(timeStamp), timeStampNow()) > LOCK_EXPIRATION_DELAY; } // node_modules/@datadog/browser-core/esm/domain/session/sessionStore.js var STORAGE_POLL_DELAY = ONE_SECOND; function selectSessionStoreStrategyType(initConfiguration) { switch (initConfiguration.sessionPersistence) { case SessionPersistence.COOKIE: return selectCookieStrategy(initConfiguration); case SessionPersistence.LOCAL_STORAGE: return selectLocalStorageStrategy(); case void 0: { let sessionStoreStrategyType = selectCookieStrategy(initConfiguration); if (!sessionStoreStrategyType && initConfiguration.allowFallbackToLocalStorage) { sessionStoreStrategyType = selectLocalStorageStrategy(); } return sessionStoreStrategyType; } default: display.error(`Invalid session persistence '${String(initConfiguration.sessionPersistence)}'`); } } function getSessionStoreStrategy(sessionStoreStrategyType, configuration) { return sessionStoreStrategyType.type === SessionPersistence.COOKIE ? initCookieStrategy(configuration, sessionStoreStrategyType.cookieOptions) : initLocalStorageStrategy(configuration); } function startSessionStore(sessionStoreStrategyType, configuration, productKey, computeTrackingType2, sessionStoreStrategy = getSessionStoreStrategy(sessionStoreStrategyType, configuration)) { const renewObservable = new Observable(); const expireObservable = new Observable(); const sessionStateUpdateObservable = new Observable(); const watchSessionTimeoutId = setInterval(watchSession, STORAGE_POLL_DELAY); let sessionCache; startSession(); const { throttled: throttledExpandOrRenewSession, cancel: cancelExpandOrRenewSession } = throttle(() => { processSessionStoreOperations({ process: (sessionState) => { if (isSessionInNotStartedState(sessionState)) { return; } const synchronizedSession = synchronizeSession(sessionState); expandOrRenewSessionState(synchronizedSession); return synchronizedSession; }, after: (sessionState) => { if (isSessionStarted(sessionState) && !hasSessionInCache()) { renewSessionInCache(sessionState); } sessionCache = sessionState; } }, sessionStoreStrategy); }, STORAGE_POLL_DELAY); function expandSession() { processSessionStoreOperations({ process: (sessionState) => hasSessionInCache() ? synchronizeSession(sessionState) : void 0 }, sessionStoreStrategy); } function watchSession() { const sessionState = sessionStoreStrategy.retrieveSession(); if (isSessionInExpiredState(sessionState)) { processSessionStoreOperations({ process: (sessionState2) => isSessionInExpiredState(sessionState2) ? getExpiredSessionState(sessionState2, configuration) : void 0, after: synchronizeSession }, sessionStoreStrategy); } else { synchronizeSession(sessionState); } } function synchronizeSession(sessionState) { if (isSessionInExpiredState(sessionState)) { sessionState = getExpiredSessionState(sessionState, configuration); } if (hasSessionInCache()) { if (isSessionInCacheOutdated(sessionState)) { expireSessionInCache(); } else { sessionStateUpdateObservable.notify({ previousState: sessionCache, newState: sessionState }); sessionCache = sessionState; } } return sessionState; } function startSession() { processSessionStoreOperations({ process: (sessionState) => { if (isSessionInNotStartedState(sessionState)) { return getExpiredSessionState(sessionState, configuration); } }, after: (sessionState) => { sessionCache = sessionState; } }, sessionStoreStrategy); } function expandOrRenewSessionState(sessionState) { if (isSessionInNotStartedState(sessionState)) { return false; } const trackingType = computeTrackingType2(sessionState[productKey]); sessionState[productKey] = trackingType; delete sessionState.isExpired; if (trackingType !== SESSION_NOT_TRACKED && !sessionState.id) { sessionState.id = generateUUID(); sessionState.created = String(dateNow()); } } function hasSessionInCache() { return (sessionCache === null || sessionCache === void 0 ? void 0 : sessionCache[productKey]) !== void 0; } function isSessionInCacheOutdated(sessionState) { return sessionCache.id !== sessionState.id || sessionCache[productKey] !== sessionState[productKey]; } function expireSessionInCache() { sessionCache = getExpiredSessionState(sessionCache, configuration); expireObservable.notify(); } function renewSessionInCache(sessionState) { sessionCache = sessionState; renewObservable.notify(); } function updateSessionState(partialSessionState) { processSessionStoreOperations({ process: (sessionState) => __spreadValues(__spreadValues({}, sessionState), partialSessionState), after: synchronizeSession }, sessionStoreStrategy); } return { expandOrRenewSession: throttledExpandOrRenewSession, expandSession, getSession: () => sessionCache, renewObservable, expireObservable, sessionStateUpdateObservable, restartSession: startSession, expire: () => { cancelExpandOrRenewSession(); sessionStoreStrategy.expireSession(sessionCache); synchronizeSession(getExpiredSessionState(sessionCache, configuration)); }, stop: () => { clearInterval(watchSessionTimeoutId); }, updateSessionState }; } // node_modules/@datadog/browser-core/esm/domain/trackingConsent.js var TrackingConsent = { GRANTED: "granted", NOT_GRANTED: "not-granted" }; function createTrackingConsentState(currentConsent) { const observable = new Observable(); return { tryToInit(trackingConsent) { if (!currentConsent) { currentConsent = trackingConsent; } }, update(trackingConsent) { currentConsent = trackingConsent; observable.notify(); }, isGranted() { return currentConsent === TrackingConsent.GRANTED; }, observable }; } // node_modules/@datadog/browser-core/esm/tools/matchOption.js function isMatchOption(item) { const itemType = getType(item); return itemType === "string" || itemType === "function" || item instanceof RegExp; } function matchList(list, value, useStartsWith = false) { return list.some((item) => { try { if (typeof item === "function") { return item(value); } else if (item instanceof RegExp) { return item.test(value); } else if (typeof item === "string") { return useStartsWith ? value.startsWith(item) : item === value; } } catch (e) { display.error(e); } return false; }); } // node_modules/@datadog/browser-core/esm/domain/extension/extensionUtils.js var EXTENSION_PREFIXES = ["chrome-extension://", "moz-extension://"]; function containsExtensionUrl(str) { return EXTENSION_PREFIXES.some((prefix) => str.includes(prefix)); } function isUnsupportedExtensionEnvironment(windowLocation, stack = "") { if (containsExtensionUrl(windowLocation)) { return false; } const frameLines = stack.split("\n").filter((line) => { const trimmedLine = line.trim(); return trimmedLine.length && /^at\s+|@/.test(trimmedLine); }); const target = frameLines[1] || ""; return containsExtensionUrl(target); } function extractExtensionUrlFromStack(stack = "") { for (const prefix of EXTENSION_PREFIXES) { const match = stack.match(new RegExp(`${prefix}[^/]+`)); if (match) { return match[0]; } } } // node_modules/@datadog/browser-core/esm/domain/allowedTrackingOrigins.js var WARN_DOES_NOT_HAVE_ALLOWED_TRACKING_ORIGIN = "Running the Browser SDK in a Web extension content script is discouraged and will be forbidden in a future major release unless the `allowedTrackingOrigins` option is provided."; var ERROR_NOT_ALLOWED_TRACKING_ORIGIN = "SDK initialized on a non-allowed domain."; function isAllowedTrackingOrigins(configuration, errorStack, windowOrigin = typeof location !== "undefined" ? location.origin : "") { const allowedTrackingOrigins = configuration.allowedTrackingOrigins; if (!allowedTrackingOrigins) { if (isUnsupportedExtensionEnvironment(windowOrigin, errorStack)) { display.warn(WARN_DOES_NOT_HAVE_ALLOWED_TRACKING_ORIGIN); const extensionUrl = extractExtensionUrlFromStack(errorStack); addTelemetryDebug(WARN_DOES_NOT_HAVE_ALLOWED_TRACKING_ORIGIN, { extensionUrl: extensionUrl || "unknown" }); } return true; } const isAllowed = matchList(allowedTrackingOrigins, windowOrigin); if (!isAllowed) { display.error(ERROR_NOT_ALLOWED_TRACKING_ORIGIN); } return isAllowed; } // node_modules/@datadog/browser-core/esm/domain/configuration/endpointBuilder.js function createEndpointBuilder(initConfiguration, trackType, extraParameters) { const buildUrlWithParameters = createEndpointUrlWithParametersBuilder(initConfiguration, trackType); return { build(api, payload) { const parameters = buildEndpointParameters(initConfiguration, trackType, api, payload, extraParameters); return buildUrlWithParameters(parameters); }, trackType }; } function createEndpointUrlWithParametersBuilder(initConfiguration, trackType) { const path = `/api/v2/${trackType}`; const proxy = initConfiguration.proxy; if (typeof proxy === "string") { const normalizedProxyUrl = normalizeUrl(proxy); return (parameters) => `${normalizedProxyUrl}?ddforward=${encodeURIComponent(`${path}?${parameters}`)}`; } if (typeof proxy === "function") { return (parameters) => proxy({ path, parameters }); } const host = buildEndpointHost(trackType, initConfiguration); return (parameters) => `https://${host}${path}?${parameters}`; } function buildEndpointHost(trackType, initConfiguration) { const { site = INTAKE_SITE_US1, internalAnalyticsSubdomain } = initConfiguration; if (trackType === "logs" && initConfiguration.usePciIntake && site === INTAKE_SITE_US1) { return PCI_INTAKE_HOST_US1; } if (internalAnalyticsSubdomain && site === INTAKE_SITE_US1) { return `${internalAnalyticsSubdomain}.${INTAKE_SITE_US1}`; } if (site === INTAKE_SITE_FED_STAGING) { return `http-intake.logs.${site}`; } const domainParts = site.split("."); const extension = domainParts.pop(); return `browser-intake-${domainParts.join("-")}.${extension}`; } function buildEndpointParameters({ clientToken, internalAnalyticsSubdomain, source = "browser" }, trackType, api, { retry, encoding }, extraParameters = []) { const parameters = [`ddsource=${source}`, `dd-api-key=${clientToken}`, `dd-evp-origin-version=${encodeURIComponent("6.21.2")}`, "dd-evp-origin=browser", `dd-request-id=${generateUUID()}`].concat(extraParameters); if (encoding) { parameters.push(`dd-evp-encoding=${encoding}`); } if (trackType === "rum") { parameters.push(`batch_time=${timeStampNow()}`, `_dd.api=${api}`); if (retry) { parameters.push(`_dd.retry_count=${retry.count}`, `_dd.retry_after=${retry.lastFailureStatus}`); } } if (internalAnalyticsSubdomain) { parameters.reverse(); } return parameters.join("&"); } // node_modules/@datadog/browser-core/esm/domain/configuration/transportConfiguration.js function computeTransportConfiguration(initConfiguration) { const site = initConfiguration.site || INTAKE_SITE_US1; const source = validateSource(initConfiguration.source); const endpointBuilders = computeEndpointBuilders(__spreadProps(__spreadValues({}, initConfiguration), { site, source })); const replicaConfiguration = computeReplicaConfiguration(__spreadProps(__spreadValues({}, initConfiguration), { site, source })); return __spreadValues({ replica: replicaConfiguration, site, source }, endpointBuilders); } function validateSource(source) { if (source === "flutter" || source === "unity") { return source; } return "browser"; } function computeEndpointBuilders(initConfiguration) { return { logsEndpointBuilder: createEndpointBuilder(initConfiguration, "logs"), rumEndpointBuilder: createEndpointBuilder(initConfiguration, "rum"), profilingEndpointBuilder: createEndpointBuilder(initConfiguration, "profile"), sessionReplayEndpointBuilder: createEndpointBuilder(initConfiguration, "replay"), exposuresEndpointBuilder: createEndpointBuilder(initConfiguration, "exposures") }; } function computeReplicaConfiguration(initConfiguration) { if (!initConfiguration.replica) { return; } const replicaConfiguration = __spreadProps(__spreadValues({}, initConfiguration), { site: INTAKE_SITE_US1, clientToken: initConfiguration.replica.clientToken }); return { logsEndpointBuilder: createEndpointBuilder(replicaConfiguration, "logs"), rumEndpointBuilder: createEndpointBuilder(replicaConfiguration, "rum", [`application.id=${initConfiguration.replica.applicationId}`]) }; } function isIntakeUrl(url) { return INTAKE_URL_PARAMETERS.every((param) => url.includes(param)); } // node_modules/@datadog/browser-core/esm/domain/configuration/configuration.js var DefaultPrivacyLevel = { ALLOW: "allow", MASK: "mask", MASK_USER_INPUT: "mask-user-input", MASK_UNLESS_ALLOWLISTED: "mask-unless-allowlisted" }; var TraceContextInjection = { ALL: "all", SAMPLED: "sampled" }; function isString(tag, tagName) { if (tag !== void 0 && tag !== null && typeof tag !== "string") { display.error(`${tagName} must be defined as a string`); return false; } return true; } function isDatadogSite(site) { if (site && typeof site === "string" && !/(datadog|ddog|datad0g|dd0g)/.test(site)) { display.error(`Site should be a valid Datadog site. ${MORE_DETAILS} ${DOCS_ORIGIN}/getting_started/site/.`); return false; } return true; } function isSampleRate(sampleRate, name) { if (sampleRate !== void 0 && !isPercentage(sampleRate)) { display.error(`${name} Sample Rate should be a number between 0 and 100`); return false; } return true; } function validateAndBuildConfiguration(initConfiguration, errorStack) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; if (!initConfiguration || !initConfiguration.clientToken) { display.error("Client Token is not configured, we will not send any data."); return; } if (initConfiguration.allowedTrackingOrigins !== void 0 && !Array.isArray(initConfiguration.allowedTrackingOrigins)) { display.error("Allowed Tracking Origins must be an array"); return; } if (!isDatadogSite(initConfiguration.site) || !isSampleRate(initConfiguration.sessionSampleRate, "Session") || !isSampleRate(initConfiguration.telemetrySampleRate, "Telemetry") || !isSampleRate(initConfiguration.telemetryConfigurationSampleRate, "Telemetry Configuration") || !isSampleRate(initConfiguration.telemetryUsageSampleRate, "Telemetry Usage") || !isString(initConfiguration.version, "Version") || !isString(initConfiguration.env, "Env") || !isString(initConfiguration.service, "Service") || !isAllowedTrackingOrigins(initConfiguration, errorStack !== null && errorStack !== void 0 ? errorStack : "")) { return; } if (initConfiguration.trackingConsent !== void 0 && !objectHasValue(TrackingConsent, initConfiguration.trackingConsent)) { display.error('Tracking Consent should be either "granted" or "not-granted"'); return; } return __spreadValues({ beforeSend: initConfiguration.beforeSend && catchUserErrors(initConfiguration.beforeSend, "beforeSend threw an error:"), sessionStoreStrategyType: isWorkerEnvironment ? void 0 : selectSessionStoreStrategyType(initConfiguration), sessionSampleRate: (_a = initConfiguration.sessionSampleRate) !== null && _a !== void 0 ? _a : 100, telemetrySampleRate: (_b = initConfiguration.telemetrySampleRate) !== null && _b !== void 0 ? _b : 20, telemetryConfigurationSampleRate: (_c = initConfiguration.telemetryConfigurationSampleRate) !== null && _c !== void 0 ? _c : 5, telemetryUsageSampleRate: (_d = initConfiguration.telemetryUsageSampleRate) !== null && _d !== void 0 ? _d : 5, service: (_e = initConfiguration.service) !== null && _e !== void 0 ? _e : void 0, env: (_f = initConfiguration.env) !== null && _f !== void 0 ? _f : void 0, version: (_g = initConfiguration.version) !== null && _g !== void 0 ? _g : void 0, datacenter: (_h = initConfiguration.datacenter) !== null && _h !== void 0 ? _h : void 0, silentMultipleInit: !!initConfiguration.silentMultipleInit, allowUntrustedEvents: !!initConfiguration.allowUntrustedEvents, trackingConsent: (_j = initConfiguration.trackingConsent) !== null && _j !== void 0 ? _j : TrackingConsent.GRANTED, trackAnonymousUser: (_k = initConfiguration.trackAnonymousUser) !== null && _k !== void 0 ? _k : true, storeContextsAcrossPages: !!initConfiguration.storeContextsAcrossPages, /** * beacon payload max queue size implementation is 64kb * ensure that we leave room for logs, rum and potential other users */ batchBytesLimit: 16 * ONE_KIBI_BYTE, eventRateLimiterThreshold: 3e3, maxTelemetryEventsPerPage: 15, /** * flush automatically, aim to be lower than ALB connection timeout * to maximize connection reuse. */ flushTimeout: 30 * ONE_SECOND, /** * Logs intake limit. When using the SDK in a Worker Environment, we * limit the batch size to 1 to ensure it can be sent in a single event. */ batchMessagesLimit: isWorkerEnvironment ? 1 : 50, messageBytesLimit: 256 * ONE_KIBI_BYTE, /** * The source of the SDK, used for support plugins purposes. */ variant: initConfiguration.variant, sdkVersion: initConfiguration.sdkVersion }, computeTransportConfiguration(initConfiguration)); } function serializeConfiguration(initConfiguration) { return { session_sample_rate: initConfiguration.sessionSampleRate, telemetry_sample_rate: initConfiguration.telemetrySampleRate, telemetry_configuration_sample_rate: initConfiguration.telemetryConfigurationSampleRate, telemetry_usage_sample_rate: initConfiguration.telemetryUsageSampleRate, use_before_send: !!initConfiguration.beforeSend, use_partitioned_cross_site_session_cookie: initConfiguration.usePartitionedCrossSiteSessionCookie, use_secure_session_cookie: initConfiguration.useSecureSessionCookie, use_proxy: !!initConfiguration.proxy, silent_multiple_init: initConfiguration.silentMultipleInit, track_session_across_subdomains: initConfiguration.trackSessionAcrossSubdomains, track_anonymous_user: initConfiguration.trackAnonymousUser, session_persistence: initConfiguration.sessionPersistence, allow_fallback_to_local_storage: !!initConfiguration.allowFallbackToLocalStorage, store_contexts_across_pages: !!initConfiguration.storeContextsAcrossPages, allow_untrusted_events: !!initConfiguration.allowUntrustedEvents, tracking_consent: initConfiguration.trackingConsent, use_allowed_tracking_origins: Array.isArray(initConfiguration.allowedTrackingOrigins), source: initConfiguration.source, sdk_version: initConfiguration.sdkVersion, variant: initConfiguration.variant }; } // node_modules/@datadog/browser-core/esm/tools/instrumentMethod.js function instrumentMethod(targetPrototype, method, onPreCall, { computeHandlingStack } = {}) { let original = targetPrototype[method]; if (typeof original !== "function") { if (method in targetPrototype && method.startsWith("on")) { original = noop; } else { return { stop: noop }; } } let stopped = false; const instrumentation = function() { if (stopped) { return original.apply(this, arguments); } const parameters = Array.from(arguments); let postCallCallback; callMonitored(onPreCall, null, [{ target: this, parameters, onPostCall: (callback) => { postCallCallback = callback; }, handlingStack: computeHandlingStack ? createHandlingStack("instrumented method") : void 0 }]); const result = original.apply(this, parameters); if (postCallCallback) { callMonitored(postCallCallback, null, [result]); } return result; }; targetPrototype[method] = instrumentation; return { stop: () => { stopped = true; if (targetPrototype[method] === instrumentation) { targetPrototype[method] = original; } } }; } function instrumentSetter(targetPrototype, property, after) { const originalDescriptor = Object.getOwnPropertyDescriptor(targetPrototype, property); if (!originalDescriptor || !originalDescriptor.set || !originalDescriptor.configurable) { return { stop: noop }; } const stoppedInstrumentation = noop; let instrumentation = (target, value) => { setTimeout(() => { if (instrumentation !== stoppedInstrumentation) { after(target, value); } }, 0); }; const instrumentationWrapper = function(value) { originalDescriptor.set.call(this, value); instrumentation(this, value); }; Object.defineProperty(targetPrototype, property, { set: instrumentationWrapper }); return { stop: () => { var _a; if (((_a = Object.getOwnPropertyDescriptor(targetPrototype, property)) === null || _a === void 0 ? void 0 : _a.set) === instrumentationWrapper) { Object.defineProperty(targetPrototype, property, originalDescriptor); } instrumentation = stoppedInstrumentation; } }; } // node_modules/@datadog/browser-core/esm/domain/error/trackRuntimeError.js function trackRuntimeError() { return new Observable((observer2) => { const handleRuntimeError = (originalError, stackTrace) => { const rawError = computeRawError({ stackTrace, originalError, startClocks: clocksNow(), nonErrorPrefix: "Uncaught", source: ErrorSource.SOURCE, handling: "unhandled" /* ErrorHandling.UNHANDLED */ }); observer2.notify(rawError); }; const { stop: stopInstrumentingOnError } = instrumentOnError(handleRuntimeError); const { stop: stopInstrumentingOnUnhandledRejection } = instrumentUnhandledRejection(handleRuntimeError); return () => { stopInstrumentingOnError(); stopInstrumentingOnUnhandledRejection(); }; }); } function instrumentOnError(callback) { return instrumentMethod(getGlobalObject(), "onerror", ({ parameters: [messageObj, url, line, column, errorObj] }) => { let stackTrace; if (!isError(errorObj)) { stackTrace = computeStackTraceFromOnErrorMessage(messageObj, url, line, column); } callback(errorObj !== null && errorObj !== void 0 ? errorObj : messageObj, stackTrace); }); } function instrumentUnhandledRejection(callback) { return instrumentMethod(getGlobalObject(), "onunhandledrejection", ({ parameters: [e] }) => { callback(e.reason || "Empty reason"); }); } // node_modules/@datadog/browser-core/esm/boot/init.js function makePublicApi(stub) { const publicApi = __spreadValues({ version: "6.21.2", // This API method is intentionally not monitored, since the only thing executed is the // user-provided 'callback'. All SDK usages executed in the callback should be monitored, and // we don't want to interfere with the user uncaught exceptions. onReady(callback) { callback(); } }, stub); Object.defineProperty(publicApi, "_setDebug", { get() { return setDebugMode; }, enumerable: false }); return publicApi; } function defineGlobal(global, name, api) { const existingGlobalVariable = global[name]; if (existingGlobalVariable && !existingGlobalVariable.q && existingGlobalVariable.version) { display.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."); } global[name] = api; if (existingGlobalVariable && existingGlobalVariable.q) { existingGlobalVariable.q.forEach((fn) => catchUserErrors(fn, "onReady callback threw an error:")()); } } // node_modules/@datadog/browser-core/esm/boot/displayAlreadyInitializedError.js function displayAlreadyInitializedError(sdkName, initConfiguration) { if (!initConfiguration.silentMultipleInit) { display.error(`${sdkName} is already initialized.`); } } // node_modules/@datadog/browser-core/esm/domain/report/reportObservable.js var RawReportType = { intervention: "intervention", deprecation: "deprecation", cspViolation: "csp_violation" }; function initReportObservable(configuration, apis) { const observables = []; if (apis.includes(RawReportType.cspViolation)) { observables.push(createCspViolationReportObservable(configuration)); } const reportTypes = apis.filter((api) => api !== RawReportType.cspViolation); if (reportTypes.length) { observables.push(createReportObservable(reportTypes)); } return mergeObservables(...observables); } function createReportObservable(reportTypes) { return new Observable((observable) => { if (!window.ReportingObserver) { return; } const handleReports = monitor((reports, _) => reports.forEach((report) => observable.notify(buildRawReportErrorFromReport(report)))); const observer2 = new window.ReportingObserver(handleReports, { types: reportTypes, buffered: true }); observer2.observe(); return () => { observer2.disconnect(); }; }); } function createCspViolationReportObservable(configuration) { return new Observable((observable) => { const { stop } = addEventListener(configuration, document, "securitypolicyviolation", (event) => { observable.notify(buildRawReportErrorFromCspViolation(event)); }); return stop; }); } function buildRawReportErrorFromReport(report) { const { type, body } = report; return buildRawReportError({ type: body.id, message: `${type}: ${body.message}`, originalError: report, stack: buildStack(body.id, body.message, body.sourceFile, body.lineNumber, body.columnNumber) }); } function buildRawReportErrorFromCspViolation(event) { const message = `'${event.blockedURI}' blocked by '${event.effectiveDirective}' directive`; return buildRawReportError({ type: event.effectiveDirective, message: `${RawReportType.cspViolation}: ${message}`, originalError: event, csp: { disposition: event.disposition }, stack: buildStack(event.effectiveDirective, event.originalPolicy ? `${message} of the policy "${safeTruncate(event.originalPolicy, 100, "...")}"` : "no policy", event.sourceFile, event.lineNumber, event.columnNumber) }); } function buildRawReportError(partial) { return __spreadValues({ startClocks: clocksNow(), source: ErrorSource.REPORT, handling: "unhandled" }, partial); } function buildStack(name, message, sourceFile, lineNumber, columnNumber) { return sourceFile ? toStackTraceString({ name, message, stack: [{ func: "?", url: sourceFile, line: lineNumber !== null && lineNumber !== void 0 ? lineNumber : void 0, column: columnNumber !== null && columnNumber !== void 0 ? columnNumber : void 0 }] }) : void 0; } // node_modules/@datadog/browser-core/esm/tools/utils/arrayUtils.js function removeItem(array, item) { const index = array.indexOf(item); if (index >= 0) { array.splice(index, 1); } } function isNonEmptyArray(value) { return Array.isArray(value) && value.length > 0; } // node_modules/@datadog/browser-core/esm/tools/valueHistory.js var END_OF_TIMES = Infinity; var CLEAR_OLD_VALUES_INTERVAL = ONE_MINUTE; var cleanupHistoriesInterval = null; var cleanupTasks = /* @__PURE__ */ new Set(); function cleanupHistories() { cleanupTasks.forEach((task) => task()); } function createValueHistory({ expireDelay, maxEntries }) { let entries = []; if (!cleanupHistoriesInterval) { cleanupHistoriesInterval = setInterval(() => cleanupHistories(), CLEAR_OLD_VALUES_INTERVAL); } const clearExpiredValues = () => { const oldTimeThreshold = relativeNow() - expireDelay; while (entries.length > 0 && entries[entries.length - 1].endTime < oldTimeThreshold) { entries.pop(); } }; cleanupTasks.add(clearExpiredValues); function add(value, startTime) { const entry = { value, startTime, endTime: END_OF_TIMES, remove: () => { removeItem(entries, entry); }, close: (endTime2) => { entry.endTime = endTime2; } }; if (maxEntries && entries.length >= maxEntries) { entries.pop(); } entries.unshift(entry); return entry; } function find(startTime = END_OF_TIMES, options = { returnInactive: false }) { for (const entry of entries) { if (entry.startTime <= startTime) { if (options.returnInactive || startTime <= entry.endTime) { return entry.value; } break; } } } function closeActive(endTime2) { const latestEntry = entries[0]; if (latestEntry && latestEntry.endTime === END_OF_TIMES) { latestEntry.close(endTime2); } } function findAll(startTime = END_OF_TIMES, duration = 0) { const endTime2 = addDuration(startTime, duration); return entries.filter((entry) => entry.startTime <= endTime2 && startTime <= entry.endTime).map((entry) => entry.value); } function reset() { entries = []; } function stop() { cleanupTasks.delete(clearExpiredValues); if (cleanupTasks.size === 0 && cleanupHistoriesInterval) { clearInterval(cleanupHistoriesInterval); cleanupHistoriesInterval = null; } } return { add, find, closeActive, findAll, reset, stop }; } // node_modules/@datadog/browser-core/esm/domain/synthetics/syntheticsWorkerValues.js var SYNTHETICS_TEST_ID_COOKIE_NAME = "datadog-synthetics-public-id"; var SYNTHETICS_RESULT_ID_COOKIE_NAME = "datadog-synthetics-result-id"; var SYNTHETICS_INJECTS_RUM_COOKIE_NAME = "datadog-synthetics-injects-rum"; function willSyntheticsInjectRum() { if (isWorkerEnvironment) { return false; } return Boolean(globalObject._DATADOG_SYNTHETICS_INJECTS_RUM || getInitCookie(SYNTHETICS_INJECTS_RUM_COOKIE_NAME)); } function getSyntheticsTestId() { const value = window._DATADOG_SYNTHETICS_PUBLIC_ID || getInitCookie(SYNTHETICS_TEST_ID_COOKIE_NAME); return typeof value === "string" ? value : void 0; } function getSyntheticsResultId() { const value = window._DATADOG_SYNTHETICS_RESULT_ID || getInitCookie(SYNTHETICS_RESULT_ID_COOKIE_NAME); return typeof value === "string" ? value : void 0; } function isSyntheticsTest() { return Boolean(getSyntheticsTestId() && getSyntheticsResultId()); } // node_modules/@datadog/browser-core/esm/domain/session/sessionManager.js var VISIBILITY_CHECK_DELAY = ONE_MINUTE; var SESSION_CONTEXT_TIMEOUT_DELAY = SESSION_TIME_OUT_DELAY; var stopCallbacks = []; function startSessionManager(configuration, productKey, computeTrackingType2, trackingConsentState) { const renewObservable = new Observable(); const expireObservable = new Observable(); const sessionStore = startSessionStore(configuration.sessionStoreStrategyType, configuration, productKey, computeTrackingType2); stopCallbacks.push(() => sessionStore.stop()); const sessionContextHistory = createValueHistory({ expireDelay: SESSION_CONTEXT_TIMEOUT_DELAY }); stopCallbacks.push(() => sessionContextHistory.stop()); sessionStore.renewObservable.subscribe(() => { sessionContextHistory.add(buildSessionContext(), relativeNow()); renewObservable.notify(); }); sessionStore.expireObservable.subscribe(() => { expireObservable.notify(); sessionContextHistory.closeActive(relativeNow()); }); sessionStore.expandOrRenewSession(); sessionContextHistory.add(buildSessionContext(), clocksOrigin().relative); if (isExperimentalFeatureEnabled(ExperimentalFeature.SHORT_SESSION_INVESTIGATION)) { const session = sessionStore.getSession(); if (session) { detectSessionIdChange(configuration, session); } } trackingConsentState.observable.subscribe(() => { if (trackingConsentState.isGranted()) { sessionStore.expandOrRenewSession(); } else { sessionStore.expire(); } }); trackActivity(configuration, () => { if (trackingConsentState.isGranted()) { sessionStore.expandOrRenewSession(); } }); trackVisibility(configuration, () => sessionStore.expandSession()); trackResume(configuration, () => sessionStore.restartSession()); function buildSessionContext() { const session = sessionStore.getSession(); if (!session) { reportUnexpectedSessionState().catch(() => void 0); return { id: "invalid", trackingType: SESSION_NOT_TRACKED, isReplayForced: false, anonymousId: void 0 }; } return { id: session.id, trackingType: session[productKey], isReplayForced: !!session.forcedReplay, anonymousId: session.anonymousId }; } return { findSession: (startTime, options) => sessionContextHistory.find(startTime, options), renewObservable, expireObservable, sessionStateUpdateObservable: sessionStore.sessionStateUpdateObservable, expire: sessionStore.expire, updateSessionState: sessionStore.updateSessionState }; } function trackActivity(configuration, expandOrRenewSession) { const { stop } = addEventListeners(configuration, window, [ "click", "touchstart", "keydown", "scroll" /* DOM_EVENT.SCROLL */ ], expandOrRenewSession, { capture: true, passive: true }); stopCallbacks.push(stop); } function trackVisibility(configuration, expandSession) { const expandSessionWhenVisible = () => { if (document.visibilityState === "visible") { expandSession(); } }; const { stop } = addEventListener(configuration, document, "visibilitychange", expandSessionWhenVisible); stopCallbacks.push(stop); const visibilityCheckInterval = setInterval(expandSessionWhenVisible, VISIBILITY_CHECK_DELAY); stopCallbacks.push(() => { clearInterval(visibilityCheckInterval); }); } function trackResume(configuration, cb) { const { stop } = addEventListener(configuration, window, "resume", cb, { capture: true }); stopCallbacks.push(stop); } function reportUnexpectedSessionState() { return __async(this, null, function* () { const rawSession = retrieveSessionCookie(); addTelemetryDebug("Unexpected session state", { session: rawSession, isSyntheticsTest: isSyntheticsTest(), createdTimestamp: rawSession === null || rawSession === void 0 ? void 0 : rawSession.created, expireTimestamp: rawSession === null || rawSession === void 0 ? void 0 : rawSession.expire, cookie: yield getSessionCookies(), currentDomain: `${window.location.protocol}//${window.location.hostname}` }); }); } function detectSessionIdChange(configuration, initialSessionState) { if (!window.cookieStore || !initialSessionState.created) { return; } const sessionCreatedTime = Number(initialSessionState.created); const sdkInitTime = dateNow(); const { stop } = addEventListener(configuration, cookieStore, "change", listener); stopCallbacks.push(stop); function listener(event) { const changed = findLast(event.changed, (change) => change.name === SESSION_STORE_KEY); if (!changed) { return; } const sessionAge = dateNow() - sessionCreatedTime; if (sessionAge > 14 * ONE_MINUTE) { stop(); } else { const newSessionState = toSessionState(changed.value); if (newSessionState.id && newSessionState.id !== initialSessionState.id) { stop(); const time = dateNow() - sdkInitTime; getSessionCookies().then((cookie) => { addTelemetryDebug("Session cookie changed", { time, session_age: sessionAge, old: initialSessionState, new: newSessionState, cookie }); }).catch(monitorError); } } } } function getSessionCookies() { return __async(this, null, function* () { let sessionCookies; if ("cookieStore" in window) { sessionCookies = yield window.cookieStore.getAll(SESSION_STORE_KEY); } else { sessionCookies = document.cookie.split(/\s*;\s*/).filter((cookie) => cookie.startsWith(SESSION_STORE_KEY)); } return __spreadValues({ count: sessionCookies.length, domain: getCurrentSite() || "undefined" }, sessionCookies); }); } // node_modules/@datadog/browser-core/esm/tools/encoder.js function createIdentityEncoder() { let output = ""; let outputBytesCount = 0; return { isAsync: false, get isEmpty() { return !output; }, write(data, callback) { const additionalEncodedBytesCount = computeBytesCount(data); outputBytesCount += additionalEncodedBytesCount; output += data; if (callback) { callback(additionalEncodedBytesCount); } }, finish(callback) { callback(this.finishSync()); }, finishSync() { const result = { output, outputBytesCount, rawBytesCount: outputBytesCount, pendingData: "" }; output = ""; outputBytesCount = 0; return result; }, estimateEncodedBytesCount(data) { return data.length; } }; } // node_modules/@datadog/browser-core/esm/tools/abstractLifeCycle.js var AbstractLifeCycle = class { constructor() { this.callbacks = {}; } notify(eventType, data) { const eventCallbacks = this.callbacks[eventType]; if (eventCallbacks) { eventCallbacks.forEach((callback) => callback(data)); } } subscribe(eventType, callback) { if (!this.callbacks[eventType]) { this.callbacks[eventType] = []; } this.callbacks[eventType].push(callback); return { unsubscribe: () => { this.callbacks[eventType] = this.callbacks[eventType].filter((other) => callback !== other); } }; } }; // node_modules/@datadog/browser-core/esm/domain/eventRateLimiter/createEventRateLimiter.js function createEventRateLimiter(eventType, limit, onLimitReached) { let eventCount = 0; let allowNextEvent = false; return { isLimitReached() { if (eventCount === 0) { setTimeout(() => { eventCount = 0; }, ONE_MINUTE); } eventCount += 1; if (eventCount <= limit || allowNextEvent) { allowNextEvent = false; return false; } if (eventCount === limit + 1) { allowNextEvent = true; try { onLimitReached({ message: `Reached max number of ${eventType}s by minute: ${limit}`, source: ErrorSource.AGENT, startClocks: clocksNow() }); } finally { allowNextEvent = false; } } return true; } }; } // node_modules/@datadog/browser-core/esm/browser/runOnReadyState.js function runOnReadyState(configuration, expectedReadyState, callback) { if (document.readyState === expectedReadyState || document.readyState === "complete") { callback(); return { stop: noop }; } const eventName = expectedReadyState === "complete" ? "load" : "DOMContentLoaded"; return addEventListener(configuration, window, eventName, callback, { once: true }); } function asyncRunOnReadyState(configuration, expectedReadyState) { return new Promise((resolve) => { runOnReadyState(configuration, expectedReadyState, resolve); }); } // node_modules/@datadog/browser-core/esm/browser/xhrObservable.js var xhrObservable; var xhrContexts = /* @__PURE__ */ new WeakMap(); function initXhrObservable(configuration) { if (!xhrObservable) { xhrObservable = createXhrObservable(configuration); } return xhrObservable; } function createXhrObservable(configuration) { return new Observable((observable) => { const { stop: stopInstrumentingStart } = instrumentMethod(XMLHttpRequest.prototype, "open", openXhr); const { stop: stopInstrumentingSend } = instrumentMethod(XMLHttpRequest.prototype, "send", (call) => { sendXhr(call, configuration, observable); }, { computeHandlingStack: true }); const { stop: stopInstrumentingAbort } = instrumentMethod(XMLHttpRequest.prototype, "abort", abortXhr); return () => { stopInstrumentingStart(); stopInstrumentingSend(); stopInstrumentingAbort(); }; }); } function openXhr({ target: xhr, parameters: [method, url] }) { xhrContexts.set(xhr, { state: "open", method: String(method).toUpperCase(), url: normalizeUrl(String(url)) }); } function sendXhr({ target: xhr, parameters: [body], handlingStack }, configuration, observable) { const context = xhrContexts.get(xhr); if (!context) { return; } const startContext = context; startContext.state = "start"; startContext.startClocks = clocksNow(); startContext.isAborted = false; startContext.xhr = xhr; startContext.handlingStack = handlingStack; startContext.body = body; let hasBeenReported = false; const { stop: stopInstrumentingOnReadyStateChange } = instrumentMethod(xhr, "onreadystatechange", () => { if (xhr.readyState === XMLHttpRequest.DONE) { onEnd(); } }); const onEnd = () => { unsubscribeLoadEndListener(); stopInstrumentingOnReadyStateChange(); if (hasBeenReported) { return; } hasBeenReported = true; const completeContext = context; completeContext.state = "complete"; completeContext.duration = elapsed(startContext.startClocks.timeStamp, timeStampNow()); completeContext.status = xhr.status; observable.notify(shallowClone(completeContext)); }; const { stop: unsubscribeLoadEndListener } = addEventListener(configuration, xhr, "loadend", onEnd); observable.notify(startContext); } function abortXhr({ target: xhr }) { const context = xhrContexts.get(xhr); if (context) { context.isAborted = true; } } // node_modules/@datadog/browser-core/esm/browser/fetchObservable.js var fetchObservable; function initFetchObservable() { if (!fetchObservable) { fetchObservable = createFetchObservable(); } return fetchObservable; } function createFetchObservable() { return new Observable((observable) => { if (!globalObject.fetch) { return; } const { stop } = instrumentMethod(globalObject, "fetch", (call) => beforeSend(call, observable), { computeHandlingStack: true }); return stop; }); } function beforeSend({ parameters, onPostCall, handlingStack }, observable) { const [input, init] = parameters; let methodFromParams = init && init.method; if (methodFromParams === void 0 && input instanceof Request) { methodFromParams = input.method; } const method = methodFromParams !== void 0 ? String(methodFromParams).toUpperCase() : "GET"; const url = input instanceof Request ? input.url : normalizeUrl(String(input)); const startClocks = clocksNow(); const context = { state: "start", init, input, method, startClocks, url, handlingStack }; observable.notify(context); parameters[0] = context.input; parameters[1] = context.init; onPostCall((responsePromise) => afterSend(observable, responsePromise, context)); } function afterSend(observable, responsePromise, startContext) { const context = startContext; function reportFetch(partialContext) { context.state = "resolve"; Object.assign(context, partialContext); observable.notify(context); } responsePromise.then(monitor((response) => { reportFetch({ response, responseType: response.type, status: response.status, isAborted: false }); }), monitor((error) => { var _a, _b; reportFetch({ status: 0, isAborted: ((_b = (_a = context.init) === null || _a === void 0 ? void 0 : _a.signal) === null || _b === void 0 ? void 0 : _b.aborted) || error instanceof DOMException && error.code === DOMException.ABORT_ERR, error }); })); } // node_modules/@datadog/browser-core/esm/tools/requestIdleCallback.js function requestIdleCallback(callback, opts) { if (window.requestIdleCallback && window.cancelIdleCallback) { const id = window.requestIdleCallback(monitor(callback), opts); return () => window.cancelIdleCallback(id); } return requestIdleCallbackShim(callback); } var MAX_TASK_TIME = 50; function requestIdleCallbackShim(callback) { const start = dateNow(); const timeoutId = setTimeout(() => { callback({ didTimeout: false, timeRemaining: () => Math.max(0, MAX_TASK_TIME - (dateNow() - start)) }); }, 0); return () => clearTimeout(timeoutId); } // node_modules/@datadog/browser-core/esm/tools/taskQueue.js var IDLE_CALLBACK_TIMEOUT = ONE_SECOND; var MAX_EXECUTION_TIME_ON_TIMEOUT = 30; function createTaskQueue() { const pendingTasks = []; function run(deadline) { let executionTimeRemaining; if (deadline.didTimeout) { const start = performance.now(); executionTimeRemaining = () => MAX_EXECUTION_TIME_ON_TIMEOUT - (performance.now() - start); } else { executionTimeRemaining = deadline.timeRemaining.bind(deadline); } while (executionTimeRemaining() > 0 && pendingTasks.length) { pendingTasks.shift()(); } if (pendingTasks.length) { scheduleNextRun(); } } function scheduleNextRun() { requestIdleCallback(run, { timeout: IDLE_CALLBACK_TIMEOUT }); } return { push(task) { if (pendingTasks.push(task) === 1) { scheduleNextRun(); } }, stop() { pendingTasks.length = 0; } }; } // node_modules/@datadog/browser-core/esm/domain/console/consoleObservable.js var consoleObservablesByApi = {}; function initConsoleObservable(apis) { const consoleObservables = apis.map((api) => { if (!consoleObservablesByApi[api]) { consoleObservablesByApi[api] = createConsoleObservable(api); } return consoleObservablesByApi[api]; }); return mergeObservables(...consoleObservables); } function createConsoleObservable(api) { return new Observable((observable) => { const originalConsoleApi = globalConsole[api]; globalConsole[api] = (...params) => { originalConsoleApi.apply(console, params); const handlingStack = createHandlingStack("console error"); callMonitored(() => { observable.notify(buildConsoleLog(params, api, handlingStack)); }); }; return () => { globalConsole[api] = originalConsoleApi; }; }); } function buildConsoleLog(params, api, handlingStack) { const message = params.map((param) => formatConsoleParameters(param)).join(" "); if (api === ConsoleApiName.error) { const firstErrorParam = params.find(isError); const rawError = computeRawError({ originalError: firstErrorParam, handlingStack, startClocks: clocksNow(), source: ErrorSource.CONSOLE, handling: "handled", nonErrorPrefix: "Provided", // if no good stack is computed from the error, let's not use the fallback stack message // advising the user to use an instance of Error, as console.error is commonly used without an // Error instance. useFallbackStack: false }); rawError.message = message; return { api, message, handlingStack, error: rawError }; } return { api, message, error: void 0, handlingStack }; } function formatConsoleParameters(param) { if (typeof param === "string") { return sanitize(param); } if (isError(param)) { return formatErrorMessage(computeStackTrace(param)); } return jsonStringify(sanitize(param), void 0, 2); } // node_modules/@datadog/browser-core/esm/tools/boundedBuffer.js var BUFFER_LIMIT = 500; function createBoundedBuffer() { const buffer = []; const add = (callback) => { const length = buffer.push(callback); if (length > BUFFER_LIMIT) { buffer.splice(0, 1); } }; const remove = (callback) => { removeItem(buffer, callback); }; const drain = (arg) => { buffer.forEach((callback) => callback(arg)); buffer.length = 0; }; return { add, remove, drain }; } // node_modules/@datadog/browser-core/esm/domain/context/contextUtils.js function checkContext(maybeContext) { const isValid = getType(maybeContext) === "object"; if (!isValid) { display.error("Unsupported context:", maybeContext); } return isValid; } // node_modules/@datadog/browser-core/esm/domain/context/contextManager.js function ensureProperties(context, propertiesConfig, name) { const newContext = __spreadValues({}, context); for (const [key, { required, type }] of Object.entries(propertiesConfig)) { if (type === "string" && !isDefined(newContext[key])) { newContext[key] = String(newContext[key]); } if (required && isDefined(newContext[key])) { display.warn(`The property ${key} of ${name} is required; context will not be sent to the intake.`); } } return newContext; } function isDefined(value) { return value === void 0 || value === null || value === ""; } function createContextManager(name = "", { propertiesConfig = {} } = {}) { let context = {}; const changeObservable = new Observable(); const contextManager = { getContext: () => deepClone(context), setContext: (newContext) => { if (checkContext(newContext)) { context = sanitize(ensureProperties(newContext, propertiesConfig, name)); } else { contextManager.clearContext(); } changeObservable.notify(); }, setContextProperty: (key, property) => { context = sanitize(ensureProperties(__spreadProps(__spreadValues({}, context), { [key]: property }), propertiesConfig, name)); changeObservable.notify(); }, removeContextProperty: (key) => { delete context[key]; ensureProperties(context, propertiesConfig, name); changeObservable.notify(); }, clearContext: () => { context = {}; changeObservable.notify(); }, changeObservable }; return contextManager; } // node_modules/@datadog/browser-core/esm/domain/context/defineContextMethod.js function defineContextMethod(getStrategy, contextName, methodName, usage) { return monitor((...args) => { if (usage) { addTelemetryUsage({ feature: usage }); } return getStrategy()[contextName][methodName](...args); }); } // node_modules/@datadog/browser-core/esm/domain/context/storeContextManager.js var CONTEXT_STORE_KEY_PREFIX = "_dd_c"; var storageListeners = []; function storeContextManager(configuration, contextManager, productKey, customerDataType) { const storageKey = buildStorageKey(productKey, customerDataType); storageListeners.push(addEventListener(configuration, window, "storage", ({ key }) => { if (storageKey === key) { synchronizeWithStorage(); } })); contextManager.changeObservable.subscribe(dumpToStorage); const contextFromStorage = combine(getFromStorage(), contextManager.getContext()); if (!isEmptyObject(contextFromStorage)) { contextManager.setContext(contextFromStorage); } function synchronizeWithStorage() { contextManager.setContext(getFromStorage()); } function dumpToStorage() { localStorage.setItem(storageKey, JSON.stringify(contextManager.getContext())); } function getFromStorage() { const rawContext = localStorage.getItem(storageKey); return rawContext ? JSON.parse(rawContext) : {}; } } function buildStorageKey(productKey, customerDataType) { return `${CONTEXT_STORE_KEY_PREFIX}_${productKey}_${customerDataType}`; } // node_modules/@datadog/browser-core/esm/domain/contexts/accountContext.js function startAccountContext(hooks, configuration, productKey) { const accountContextManager = buildAccountContextManager(); if (configuration.storeContextsAcrossPages) { storeContextManager( configuration, accountContextManager, productKey, 4 /* CustomerDataType.Account */ ); } hooks.register(0, () => { const account = accountContextManager.getContext(); if (isEmptyObject(account) || !account.id) { return SKIPPED; } return { account }; }); return accountContextManager; } function buildAccountContextManager() { return createContextManager("account", { propertiesConfig: { id: { type: "string", required: true }, name: { type: "string" } } }); } // node_modules/@datadog/browser-core/esm/domain/contexts/globalContext.js function startGlobalContext(hooks, configuration, productKey, useContextNamespace) { const globalContextManager = buildGlobalContextManager(); if (configuration.storeContextsAcrossPages) { storeContextManager( configuration, globalContextManager, productKey, 2 /* CustomerDataType.GlobalContext */ ); } hooks.register(0, () => { const context = globalContextManager.getContext(); return useContextNamespace ? { context } : context; }); return globalContextManager; } function buildGlobalContextManager() { return createContextManager("global context"); } // node_modules/@datadog/browser-core/esm/domain/contexts/userContext.js function startUserContext(hooks, configuration, sessionManager, productKey) { const userContextManager = buildUserContextManager(); if (configuration.storeContextsAcrossPages) { storeContextManager( configuration, userContextManager, productKey, 1 /* CustomerDataType.User */ ); } hooks.register(0, ({ eventType, startTime }) => { const user = userContextManager.getContext(); const session = sessionManager.findTrackedSession(startTime); if (session && session.anonymousId && !user.anonymous_id && !!configuration.trackAnonymousUser) { user.anonymous_id = session.anonymousId; } if (isEmptyObject(user)) { return SKIPPED; } return { type: eventType, usr: user }; }); hooks.register(1, ({ startTime }) => { var _a; return { anonymous_id: (_a = sessionManager.findTrackedSession(startTime)) === null || _a === void 0 ? void 0 : _a.anonymousId }; }); return userContextManager; } function buildUserContextManager() { return createContextManager("user", { propertiesConfig: { id: { type: "string" }, name: { type: "string" }, email: { type: "string" } } }); } // node_modules/@datadog/browser-core/esm/domain/context/contextConstants.js var CustomerContextKey = { userContext: "userContext", globalContext: "globalContext", accountContext: "accountContext" }; var ContextManagerMethod = { getContext: "getContext", setContext: "setContext", setContextProperty: "setContextProperty", removeContextProperty: "removeContextProperty", clearContext: "clearContext" }; // node_modules/@datadog/browser-core/esm/tools/readBytesFromStream.js function readBytesFromStream(stream, callback, options) { const reader = stream.getReader(); const chunks = []; let readBytesCount = 0; readMore(); function readMore() { reader.read().then(monitor((result) => { if (result.done) { onDone(); return; } if (options.collectStreamBody) { chunks.push(result.value); } readBytesCount += result.value.length; if (readBytesCount > options.bytesLimit) { onDone(); } else { readMore(); } }), monitor((error) => callback(error))); } function onDone() { reader.cancel().catch( // we don't care if cancel fails, but we still need to catch the error to avoid reporting it // as an unhandled rejection noop ); let bytes; let limitExceeded; if (options.collectStreamBody) { let completeBuffer; if (chunks.length === 1) { completeBuffer = chunks[0]; } else { completeBuffer = new Uint8Array(readBytesCount); let offset = 0; chunks.forEach((chunk) => { completeBuffer.set(chunk, offset); offset += chunk.length; }); } bytes = completeBuffer.slice(0, options.bytesLimit); limitExceeded = completeBuffer.length > options.bytesLimit; } callback(void 0, bytes, limitExceeded); } } // node_modules/@datadog/browser-core/esm/domain/resourceUtils.js var ResourceType = { DOCUMENT: "document", XHR: "xhr", BEACON: "beacon", FETCH: "fetch", CSS: "css", JS: "js", IMAGE: "image", FONT: "font", MEDIA: "media", OTHER: "other" }; var RequestType = { FETCH: ResourceType.FETCH, XHR: ResourceType.XHR }; // node_modules/@datadog/browser-core/esm/domain/bufferedData.js var BUFFER_LIMIT2 = 500; function startBufferingData(trackRuntimeErrorImpl = trackRuntimeError) { const observable = new BufferedObservable(BUFFER_LIMIT2); const runtimeErrorSubscription = trackRuntimeErrorImpl().subscribe((error) => { observable.notify({ type: 0, error }); }); return { observable, stop: () => { runtimeErrorSubscription.unsubscribe(); } }; } // node_modules/@datadog/browser-core/esm/tools/utils/timezone.js function getTimeZone() { try { const intl = new Intl.DateTimeFormat(); return intl.resolvedOptions().timeZone; } catch (_a) { return void 0; } } // node_modules/@datadog/browser-rum-core/esm/domain/resource/resourceUtils.js var FAKE_INITIAL_DOCUMENT = "initial_document"; var RESOURCE_TYPES = [[ResourceType.DOCUMENT, (initiatorType) => FAKE_INITIAL_DOCUMENT === initiatorType], [ResourceType.XHR, (initiatorType) => "xmlhttprequest" === initiatorType], [ResourceType.FETCH, (initiatorType) => "fetch" === initiatorType], [ResourceType.BEACON, (initiatorType) => "beacon" === initiatorType], [ResourceType.CSS, (_, path) => /\.css$/i.test(path)], [ResourceType.JS, (_, path) => /\.js$/i.test(path)], [ResourceType.IMAGE, (initiatorType, path) => ["image", "img", "icon"].includes(initiatorType) || /\.(gif|jpg|jpeg|tiff|png|svg|ico)$/i.exec(path) !== null], [ResourceType.FONT, (_, path) => /\.(woff|eot|woff2|ttf)$/i.exec(path) !== null], [ResourceType.MEDIA, (initiatorType, path) => ["audio", "video"].includes(initiatorType) || /\.(mp3|mp4)$/i.exec(path) !== null]]; function computeResourceEntryType(entry) { const url = entry.name; if (!isValidUrl(url)) { return ResourceType.OTHER; } const path = getPathName(url); for (const [type, isType] of RESOURCE_TYPES) { if (isType(entry.initiatorType, path)) { return type; } } return ResourceType.OTHER; } function areInOrder(...numbers) { for (let i = 1; i < numbers.length; i += 1) { if (numbers[i - 1] > numbers[i]) { return false; } } return true; } function isResourceEntryRequestType(entry) { return entry.initiatorType === "xmlhttprequest" || entry.initiatorType === "fetch"; } function computeResourceEntryDuration(entry) { const { duration, startTime, responseEnd } = entry; if (duration === 0 && startTime < responseEnd) { return elapsed(startTime, responseEnd); } return duration; } function computeResourceEntryDetails(entry) { if (!hasValidResourceEntryTimings(entry)) { return void 0; } const { startTime, fetchStart, workerStart, redirectStart, redirectEnd, domainLookupStart, domainLookupEnd, connectStart, secureConnectionStart, connectEnd, requestStart, responseStart, responseEnd } = entry; const details = { download: formatTiming(startTime, responseStart, responseEnd), first_byte: formatTiming(startTime, requestStart, responseStart) }; if (0 < workerStart && workerStart < fetchStart) { details.worker = formatTiming(startTime, workerStart, fetchStart); } if (fetchStart < connectEnd) { details.connect = formatTiming(startTime, connectStart, connectEnd); if (connectStart <= secureConnectionStart && secureConnectionStart <= connectEnd) { details.ssl = formatTiming(startTime, secureConnectionStart, connectEnd); } } if (fetchStart < domainLookupEnd) { details.dns = formatTiming(startTime, domainLookupStart, domainLookupEnd); } if (startTime < redirectEnd) { details.redirect = formatTiming(startTime, redirectStart, redirectEnd); } return details; } function hasValidResourceEntryDuration(entry) { return entry.duration >= 0; } function hasValidResourceEntryTimings(entry) { const areCommonTimingsInOrder = areInOrder(entry.startTime, entry.fetchStart, entry.domainLookupStart, entry.domainLookupEnd, entry.connectStart, entry.connectEnd, entry.requestStart, entry.responseStart, entry.responseEnd); const areRedirectionTimingsInOrder = hasRedirection(entry) ? areInOrder(entry.startTime, entry.redirectStart, entry.redirectEnd, entry.fetchStart) : true; return areCommonTimingsInOrder && areRedirectionTimingsInOrder; } function hasRedirection(entry) { return entry.redirectEnd > entry.startTime; } function formatTiming(origin, start, end) { if (origin <= start && start <= end) { return { duration: toServerDuration(elapsed(start, end)), start: toServerDuration(elapsed(origin, start)) }; } } function computeResourceEntryProtocol(entry) { return entry.nextHopProtocol === "" ? void 0 : entry.nextHopProtocol; } function computeResourceEntryDeliveryType(entry) { return entry.deliveryType === "" ? "other" : entry.deliveryType; } function computeResourceEntrySize(entry) { if (entry.startTime < entry.responseStart) { const { encodedBodySize, decodedBodySize, transferSize } = entry; return { size: decodedBodySize, encoded_body_size: encodedBodySize, decoded_body_size: decodedBodySize, transfer_size: transferSize }; } return { size: void 0, encoded_body_size: void 0, decoded_body_size: void 0, transfer_size: void 0 }; } function isAllowedRequestUrl(url) { return url && (!isIntakeUrl(url) || isExperimentalFeatureEnabled(ExperimentalFeature.TRACK_INTAKE_REQUESTS)); } var DATA_URL_REGEX = /data:(.+)?(;base64)?,/g; var MAX_RESOURCE_VALUE_CHAR_LENGTH = 24e3; function sanitizeIfLongDataUrl(url, lengthLimit = MAX_RESOURCE_VALUE_CHAR_LENGTH) { if (url.length <= lengthLimit || !url.startsWith("data:")) { return url; } const dataUrlMatchArray = url.substring(0, 100).match(DATA_URL_REGEX); if (!dataUrlMatchArray) { return url; } return `${dataUrlMatchArray[0]}[...]`; } // node_modules/@datadog/browser-rum-core/esm/browser/firstInputPolyfill.js function retrieveFirstInputTiming(configuration, callback) { const startTimeStamp = dateNow(); let timingSent = false; const { stop: removeEventListeners } = addEventListeners(configuration, window, [ "click", "mousedown", "keydown", "touchstart", "pointerdown" /* DOM_EVENT.POINTER_DOWN */ ], (evt) => { if (!evt.cancelable) { return; } const timing = { entryType: "first-input", processingStart: relativeNow(), processingEnd: relativeNow(), startTime: evt.timeStamp, duration: 0, // arbitrary value to avoid nullable duration and simplify INP logic name: "", cancelable: false, target: null, toJSON: () => ({}) }; if (evt.type === "pointerdown") { sendTimingIfPointerIsNotCancelled(configuration, timing); } else { sendTiming(timing); } }, { passive: true, capture: true }); return { stop: removeEventListeners }; function sendTimingIfPointerIsNotCancelled(configuration2, timing) { addEventListeners(configuration2, window, [ "pointerup", "pointercancel" /* DOM_EVENT.POINTER_CANCEL */ ], (event) => { if (event.type === "pointerup") { sendTiming(timing); } }, { once: true }); } function sendTiming(timing) { if (!timingSent) { timingSent = true; removeEventListeners(); const delay = timing.processingStart - timing.startTime; if (delay >= 0 && delay < dateNow() - startTimeStamp) { callback(timing); } } } } // node_modules/@datadog/browser-rum-core/esm/browser/performanceObservable.js var RumPerformanceEntryType; (function(RumPerformanceEntryType2) { RumPerformanceEntryType2["EVENT"] = "event"; RumPerformanceEntryType2["FIRST_INPUT"] = "first-input"; RumPerformanceEntryType2["LARGEST_CONTENTFUL_PAINT"] = "largest-contentful-paint"; RumPerformanceEntryType2["LAYOUT_SHIFT"] = "layout-shift"; RumPerformanceEntryType2["LONG_TASK"] = "longtask"; RumPerformanceEntryType2["LONG_ANIMATION_FRAME"] = "long-animation-frame"; RumPerformanceEntryType2["NAVIGATION"] = "navigation"; RumPerformanceEntryType2["PAINT"] = "paint"; RumPerformanceEntryType2["RESOURCE"] = "resource"; RumPerformanceEntryType2["VISIBILITY_STATE"] = "visibility-state"; })(RumPerformanceEntryType || (RumPerformanceEntryType = {})); function createPerformanceObservable(configuration, options) { return new Observable((observable) => { if (!window.PerformanceObserver) { return; } const handlePerformanceEntries = (entries) => { const rumPerformanceEntries = filterRumPerformanceEntries(entries); if (rumPerformanceEntries.length > 0) { observable.notify(rumPerformanceEntries); } }; let timeoutId; let isObserverInitializing = true; const observer2 = new PerformanceObserver(monitor((entries) => { if (isObserverInitializing) { timeoutId = setTimeout(() => handlePerformanceEntries(entries.getEntries())); } else { handlePerformanceEntries(entries.getEntries()); } })); try { observer2.observe(options); } catch (_a) { const fallbackSupportedEntryTypes = [RumPerformanceEntryType.RESOURCE, RumPerformanceEntryType.NAVIGATION, RumPerformanceEntryType.LONG_TASK, RumPerformanceEntryType.PAINT]; if (fallbackSupportedEntryTypes.includes(options.type)) { if (options.buffered) { timeoutId = setTimeout(() => handlePerformanceEntries(performance.getEntriesByType(options.type))); } try { observer2.observe({ entryTypes: [options.type] }); } catch (_b) { return; } } } isObserverInitializing = false; manageResourceTimingBufferFull(configuration); let stopFirstInputTiming; if (!supportPerformanceTimingEvent(RumPerformanceEntryType.FIRST_INPUT) && options.type === RumPerformanceEntryType.FIRST_INPUT) { ; ({ stop: stopFirstInputTiming } = retrieveFirstInputTiming(configuration, (timing) => { handlePerformanceEntries([timing]); })); } return () => { observer2.disconnect(); if (stopFirstInputTiming) { stopFirstInputTiming(); } clearTimeout(timeoutId); }; }); } var resourceTimingBufferFullListener; function manageResourceTimingBufferFull(configuration) { if (!resourceTimingBufferFullListener && supportPerformanceObject() && "addEventListener" in performance) { resourceTimingBufferFullListener = addEventListener(configuration, performance, "resourcetimingbufferfull", () => { performance.clearResourceTimings(); }); } return () => { resourceTimingBufferFullListener === null || resourceTimingBufferFullListener === void 0 ? void 0 : resourceTimingBufferFullListener.stop(); }; } function supportPerformanceObject() { return window.performance !== void 0 && "getEntries" in performance; } function supportPerformanceTimingEvent(entryType) { return window.PerformanceObserver && PerformanceObserver.supportedEntryTypes !== void 0 && PerformanceObserver.supportedEntryTypes.includes(entryType); } function filterRumPerformanceEntries(entries) { return entries.filter((entry) => !isForbiddenResource(entry)); } function isForbiddenResource(entry) { return entry.entryType === RumPerformanceEntryType.RESOURCE && (!isAllowedRequestUrl(entry.name) || !hasValidResourceEntryDuration(entry)); } // node_modules/@datadog/browser-rum-core/esm/rawRumEvent.types.js var RumEventType = { ACTION: "action", ERROR: "error", LONG_TASK: "long_task", VIEW: "view", RESOURCE: "resource", VITAL: "vital" }; var RumLongTaskEntryType = { LONG_TASK: "long-task", LONG_ANIMATION_FRAME: "long-animation-frame" }; var ViewLoadingType = { INITIAL_LOAD: "initial_load", ROUTE_CHANGE: "route_change", BF_CACHE: "bf_cache" }; var ActionType = { CLICK: "click", CUSTOM: "custom" }; var FrustrationType = { RAGE_CLICK: "rage_click", ERROR_CLICK: "error_click", DEAD_CLICK: "dead_click" }; var VitalType = { DURATION: "duration", OPERATION_STEP: "operation_step" }; // node_modules/@datadog/browser-rum-core/esm/domain/vital/vitalCollection.js function createCustomVitalsState() { const vitalsByName = /* @__PURE__ */ new Map(); const vitalsByReference = /* @__PURE__ */ new WeakMap(); return { vitalsByName, vitalsByReference }; } function startVitalCollection(lifeCycle, pageStateHistory, customVitalsState) { function isValid(vital) { return !pageStateHistory.wasInPageStateDuringPeriod("frozen", vital.startClocks.relative, vital.duration); } function addDurationVital(vital) { if (isValid(vital)) { lifeCycle.notify(12, processVital(vital)); } } function addOperationStepVital(name, stepType, options, failureReason) { if (!isExperimentalFeatureEnabled(ExperimentalFeature.FEATURE_OPERATION_VITAL)) { return; } const { operationKey, context, description } = options || {}; const vital = { name, type: VitalType.OPERATION_STEP, operationKey, failureReason, stepType, startClocks: clocksNow(), context: sanitize(context), description }; lifeCycle.notify(12, processVital(vital)); } return { addOperationStepVital, addDurationVital, startDurationVital: (name, options = {}) => startDurationVital(customVitalsState, name, options), stopDurationVital: (nameOrRef, options = {}) => { stopDurationVital(addDurationVital, customVitalsState, nameOrRef, options); } }; } function startDurationVital({ vitalsByName, vitalsByReference }, name, options = {}) { const vital = __spreadValues({ name, startClocks: clocksNow() }, options); const reference = { __dd_vital_reference: true }; vitalsByName.set(name, vital); vitalsByReference.set(reference, vital); return reference; } function stopDurationVital(stopCallback, { vitalsByName, vitalsByReference }, nameOrRef, options = {}) { const vitalStart = typeof nameOrRef === "string" ? vitalsByName.get(nameOrRef) : vitalsByReference.get(nameOrRef); if (!vitalStart) { return; } stopCallback(buildDurationVital(vitalStart, vitalStart.startClocks, options, clocksNow())); if (typeof nameOrRef === "string") { vitalsByName.delete(nameOrRef); } else { vitalsByReference.delete(nameOrRef); } } function buildDurationVital(vitalStart, startClocks, stopOptions, stopClocks) { var _a; return { name: vitalStart.name, type: VitalType.DURATION, startClocks, duration: elapsed(startClocks.timeStamp, stopClocks.timeStamp), context: combine(vitalStart.context, stopOptions.context), description: (_a = stopOptions.description) !== null && _a !== void 0 ? _a : vitalStart.description }; } function processVital(vital) { const { startClocks, type, name, description, context } = vital; const vitalData = __spreadValues({ id: generateUUID(), type, name, description }, type === VitalType.DURATION ? { duration: toServerDuration(vital.duration) } : { step_type: vital.stepType, operation_key: vital.operationKey, failure_reason: vital.failureReason }); return { rawRumEvent: { date: startClocks.timeStamp, vital: vitalData, type: RumEventType.VITAL, context }, startTime: startClocks.relative, duration: type === VitalType.DURATION ? vital.duration : void 0, domainContext: {} }; } // node_modules/@datadog/browser-rum-core/esm/domain/plugins.js function callPluginsMethod(plugins, methodName, parameter) { if (!plugins) { return; } for (const plugin of plugins) { const method = plugin[methodName]; if (method) { method(parameter); } } } // node_modules/@datadog/browser-rum-core/esm/domain/sampler/sampler.js var sampleDecisionCache = /* @__PURE__ */ new Map(); function isSampled(sessionId, sampleRate) { if (sampleRate === 100) { return true; } if (sampleRate === 0) { return false; } const cachedDecision = sampleDecisionCache.get(sampleRate); if (cachedDecision && sessionId === cachedDecision.sessionId) { return cachedDecision.decision; } let decision; if (window.BigInt) { decision = sampleUsingKnuthFactor(BigInt(`0x${sessionId.split("-")[4]}`), sampleRate); } else { decision = performDraw(sampleRate); } sampleDecisionCache.set(sampleRate, { sessionId, decision }); return decision; } function sampleUsingKnuthFactor(identifier, sampleRate) { const knuthFactor = BigInt("1111111111111111111"); const twoPow64 = BigInt("0x10000000000000000"); const hash = identifier * knuthFactor % twoPow64; return Number(hash) <= sampleRate / 100 * Number(twoPow64); } // node_modules/@datadog/browser-rum-core/esm/domain/tracing/identifier.js function createTraceIdentifier() { return createIdentifier(64); } function createSpanIdentifier() { return createIdentifier(63); } function createIdentifier(bits) { const buffer = crypto.getRandomValues(new Uint32Array(2)); if (bits === 63) { buffer[buffer.length - 1] >>>= 1; } return { toString(radix = 10) { let high = buffer[1]; let low = buffer[0]; let str = ""; do { const mod = high % radix * 4294967296 + low; high = Math.floor(high / radix); low = Math.floor(mod / radix); str = (mod % radix).toString(radix) + str; } while (high || low); return str; } }; } function toPaddedHexadecimalString(id) { return id.toString(16).padStart(16, "0"); } // node_modules/@datadog/browser-rum-core/esm/domain/tracing/tracer.js function isTracingOption(item) { const expectedItem = item; return getType(expectedItem) === "object" && isMatchOption(expectedItem.match) && Array.isArray(expectedItem.propagatorTypes); } function clearTracingIfNeeded(context) { if (context.status === 0 && !context.isAborted) { context.traceId = void 0; context.spanId = void 0; context.traceSampled = void 0; } } function startTracer(configuration, sessionManager, userContext, accountContext) { return { clearTracingIfNeeded, traceFetch: (context) => injectHeadersIfTracingAllowed(configuration, context, sessionManager, userContext, accountContext, (tracingHeaders) => { var _a; if (context.input instanceof Request && !((_a = context.init) === null || _a === void 0 ? void 0 : _a.headers)) { context.input = new Request(context.input); Object.keys(tracingHeaders).forEach((key) => { ; context.input.headers.append(key, tracingHeaders[key]); }); } else { context.init = shallowClone(context.init); const headers = []; if (context.init.headers instanceof Headers) { context.init.headers.forEach((value, key) => { headers.push([key, value]); }); } else if (Array.isArray(context.init.headers)) { context.init.headers.forEach((header) => { headers.push(header); }); } else if (context.init.headers) { Object.keys(context.init.headers).forEach((key) => { headers.push([key, context.init.headers[key]]); }); } context.init.headers = headers.concat(objectEntries(tracingHeaders)); } }), traceXhr: (context, xhr) => injectHeadersIfTracingAllowed(configuration, context, sessionManager, userContext, accountContext, (tracingHeaders) => { Object.keys(tracingHeaders).forEach((name) => { xhr.setRequestHeader(name, tracingHeaders[name]); }); }) }; } function injectHeadersIfTracingAllowed(configuration, context, sessionManager, userContext, accountContext, inject) { const session = sessionManager.findTrackedSession(); if (!session) { return; } const tracingOption = configuration.allowedTracingUrls.find((tracingOption2) => matchList([tracingOption2.match], context.url, true)); if (!tracingOption) { return; } const traceSampled = isSampled(session.id, configuration.traceSampleRate); const shouldInjectHeaders = traceSampled || configuration.traceContextInjection === TraceContextInjection.ALL; if (!shouldInjectHeaders) { return; } context.traceSampled = traceSampled; context.traceId = createTraceIdentifier(); context.spanId = createSpanIdentifier(); inject(makeTracingHeaders(context.traceId, context.spanId, context.traceSampled, session.id, tracingOption.propagatorTypes, userContext, accountContext, configuration)); } function makeTracingHeaders(traceId, spanId, traceSampled, sessionId, propagatorTypes, userContext, accountContext, configuration) { const tracingHeaders = {}; propagatorTypes.forEach((propagatorType) => { switch (propagatorType) { case "datadog": { Object.assign(tracingHeaders, { "x-datadog-origin": "rum", "x-datadog-parent-id": spanId.toString(), "x-datadog-sampling-priority": traceSampled ? "1" : "0", "x-datadog-trace-id": traceId.toString() }); break; } // https://www.w3.org/TR/trace-context/ case "tracecontext": { Object.assign(tracingHeaders, { traceparent: `00-0000000000000000${toPaddedHexadecimalString(traceId)}-${toPaddedHexadecimalString(spanId)}-0${traceSampled ? "1" : "0"}`, tracestate: `dd=s:${traceSampled ? "1" : "0"};o:rum` }); break; } // https://github.com/openzipkin/b3-propagation case "b3": { Object.assign(tracingHeaders, { b3: `${toPaddedHexadecimalString(traceId)}-${toPaddedHexadecimalString(spanId)}-${traceSampled ? "1" : "0"}` }); break; } case "b3multi": { Object.assign(tracingHeaders, { "X-B3-TraceId": toPaddedHexadecimalString(traceId), "X-B3-SpanId": toPaddedHexadecimalString(spanId), "X-B3-Sampled": traceSampled ? "1" : "0" }); break; } } }); if (configuration.propagateTraceBaggage) { const baggageItems = { "session.id": sessionId }; const userId = userContext.getContext().id; if (typeof userId === "string") { baggageItems["user.id"] = userId; } const accountId = accountContext.getContext().id; if (typeof accountId === "string") { baggageItems["account.id"] = accountId; } const baggageHeader = Object.entries(baggageItems).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join(","); if (baggageHeader) { tracingHeaders["baggage"] = baggageHeader; } } return tracingHeaders; } // node_modules/@datadog/browser-rum-core/esm/domain/configuration/configuration.js var DEFAULT_PROPAGATOR_TYPES = ["tracecontext", "datadog"]; function validateAndBuildRumConfiguration(initConfiguration, errorStack) { var _a, _b, _c, _d, _e, _f, _g; if (initConfiguration.trackFeatureFlagsForEvents !== void 0 && !Array.isArray(initConfiguration.trackFeatureFlagsForEvents)) { display.warn("trackFeatureFlagsForEvents should be an array"); } if (!initConfiguration.applicationId) { display.error("Application ID is not configured, no RUM data will be collected."); return; } if (!isSampleRate(initConfiguration.sessionReplaySampleRate, "Session Replay") || !isSampleRate(initConfiguration.traceSampleRate, "Trace")) { return; } if (initConfiguration.excludedActivityUrls !== void 0 && !Array.isArray(initConfiguration.excludedActivityUrls)) { display.error("Excluded Activity Urls should be an array"); return; } const allowedTracingUrls = validateAndBuildTracingOptions(initConfiguration); if (!allowedTracingUrls) { return; } const baseConfiguration = validateAndBuildConfiguration(initConfiguration, errorStack); const allowedGraphQlUrls = validateAndBuildGraphQlOptions(initConfiguration); if (!baseConfiguration) { return; } const sessionReplaySampleRate = (_a = initConfiguration.sessionReplaySampleRate) !== null && _a !== void 0 ? _a : 0; return __spreadValues({ applicationId: initConfiguration.applicationId, actionNameAttribute: initConfiguration.actionNameAttribute, sessionReplaySampleRate, startSessionReplayRecordingManually: initConfiguration.startSessionReplayRecordingManually !== void 0 ? !!initConfiguration.startSessionReplayRecordingManually : sessionReplaySampleRate === 0, traceSampleRate: (_b = initConfiguration.traceSampleRate) !== null && _b !== void 0 ? _b : 100, rulePsr: isNumber(initConfiguration.traceSampleRate) ? initConfiguration.traceSampleRate / 100 : void 0, allowedTracingUrls, excludedActivityUrls: (_c = initConfiguration.excludedActivityUrls) !== null && _c !== void 0 ? _c : [], workerUrl: initConfiguration.workerUrl, compressIntakeRequests: !!initConfiguration.compressIntakeRequests, trackUserInteractions: !!((_d = initConfiguration.trackUserInteractions) !== null && _d !== void 0 ? _d : true), trackViewsManually: !!initConfiguration.trackViewsManually, trackResources: !!((_e = initConfiguration.trackResources) !== null && _e !== void 0 ? _e : true), trackLongTasks: !!((_f = initConfiguration.trackLongTasks) !== null && _f !== void 0 ? _f : true), trackBfcacheViews: !!initConfiguration.trackBfcacheViews, trackEarlyRequests: !!initConfiguration.trackEarlyRequests, subdomain: initConfiguration.subdomain, defaultPrivacyLevel: objectHasValue(DefaultPrivacyLevel, initConfiguration.defaultPrivacyLevel) ? initConfiguration.defaultPrivacyLevel : DefaultPrivacyLevel.MASK, enablePrivacyForActionName: !!initConfiguration.enablePrivacyForActionName, traceContextInjection: objectHasValue(TraceContextInjection, initConfiguration.traceContextInjection) ? initConfiguration.traceContextInjection : TraceContextInjection.SAMPLED, plugins: initConfiguration.plugins || [], trackFeatureFlagsForEvents: initConfiguration.trackFeatureFlagsForEvents || [], profilingSampleRate: (_g = initConfiguration.profilingSampleRate) !== null && _g !== void 0 ? _g : 0, propagateTraceBaggage: !!initConfiguration.propagateTraceBaggage, allowedGraphQlUrls }, baseConfiguration); } function validateAndBuildTracingOptions(initConfiguration) { if (initConfiguration.allowedTracingUrls === void 0) { return []; } if (!Array.isArray(initConfiguration.allowedTracingUrls)) { display.error("Allowed Tracing URLs should be an array"); return; } if (initConfiguration.allowedTracingUrls.length !== 0 && initConfiguration.service === void 0) { display.error("Service needs to be configured when tracing is enabled"); return; } const tracingOptions = []; initConfiguration.allowedTracingUrls.forEach((option) => { if (isMatchOption(option)) { tracingOptions.push({ match: option, propagatorTypes: DEFAULT_PROPAGATOR_TYPES }); } else if (isTracingOption(option)) { tracingOptions.push(option); } else { display.warn("Allowed Tracing Urls parameters should be a string, RegExp, function, or an object. Ignoring parameter", option); } }); return tracingOptions; } function getSelectedTracingPropagators(configuration) { const usedTracingPropagators = /* @__PURE__ */ new Set(); if (isNonEmptyArray(configuration.allowedTracingUrls)) { configuration.allowedTracingUrls.forEach((option) => { if (isMatchOption(option)) { DEFAULT_PROPAGATOR_TYPES.forEach((propagatorType) => usedTracingPropagators.add(propagatorType)); } else if (getType(option) === "object" && Array.isArray(option.propagatorTypes)) { option.propagatorTypes.forEach((propagatorType) => usedTracingPropagators.add(propagatorType)); } }); } return Array.from(usedTracingPropagators); } function validateAndBuildGraphQlOptions(initConfiguration) { if (!initConfiguration.allowedGraphQlUrls) { return []; } if (!Array.isArray(initConfiguration.allowedGraphQlUrls)) { display.warn("allowedGraphQlUrls should be an array"); return []; } const graphQlOptions = []; initConfiguration.allowedGraphQlUrls.forEach((option) => { if (isMatchOption(option)) { graphQlOptions.push({ match: option, trackPayload: false }); } else if (option && typeof option === "object" && "match" in option && isMatchOption(option.match)) { graphQlOptions.push({ match: option.match, trackPayload: !!option.trackPayload }); } }); return graphQlOptions; } function hasGraphQlPayloadTracking(allowedGraphQlUrls) { return isNonEmptyArray(allowedGraphQlUrls) && allowedGraphQlUrls.some((option) => { if (typeof option === "object" && "trackPayload" in option) { return !!option.trackPayload; } return false; }); } function serializeRumConfiguration(configuration) { var _a; const baseSerializedConfiguration = serializeConfiguration(configuration); return __spreadValues({ session_replay_sample_rate: configuration.sessionReplaySampleRate, start_session_replay_recording_manually: configuration.startSessionReplayRecordingManually, trace_sample_rate: configuration.traceSampleRate, trace_context_injection: configuration.traceContextInjection, propagate_trace_baggage: configuration.propagateTraceBaggage, action_name_attribute: configuration.actionNameAttribute, use_allowed_tracing_urls: isNonEmptyArray(configuration.allowedTracingUrls), use_allowed_graph_ql_urls: isNonEmptyArray(configuration.allowedGraphQlUrls), use_track_graph_ql_payload: hasGraphQlPayloadTracking(configuration.allowedGraphQlUrls), selected_tracing_propagators: getSelectedTracingPropagators(configuration), default_privacy_level: configuration.defaultPrivacyLevel, enable_privacy_for_action_name: configuration.enablePrivacyForActionName, use_excluded_activity_urls: isNonEmptyArray(configuration.excludedActivityUrls), use_worker_url: !!configuration.workerUrl, compress_intake_requests: configuration.compressIntakeRequests, track_views_manually: configuration.trackViewsManually, track_user_interactions: configuration.trackUserInteractions, track_resources: configuration.trackResources, track_long_task: configuration.trackLongTasks, track_bfcache_views: configuration.trackBfcacheViews, track_early_requests: configuration.trackEarlyRequests, plugins: (_a = configuration.plugins) === null || _a === void 0 ? void 0 : _a.map((plugin) => { var _a2; return __spreadValues({ name: plugin.name }, (_a2 = plugin.getConfigurationTelemetry) === null || _a2 === void 0 ? void 0 : _a2.call(plugin)); }), track_feature_flags_for_events: configuration.trackFeatureFlagsForEvents, remote_configuration_id: configuration.remoteConfigurationId, profiling_sample_rate: configuration.profilingSampleRate, use_remote_configuration_proxy: !!configuration.remoteConfigurationProxy }, baseSerializedConfiguration); } // node_modules/@datadog/browser-rum-core/esm/domain/configuration/jsonPathParser.js function parseJsonPath(path) { const selectors = []; let previousToken = 0; let currentToken; const parsingContext = { quote: void 0, escapeSequence: void 0 }; let currentSelector = ""; for (const char of path) { currentToken = ALLOWED_NEXT_TOKENS[previousToken].find((token) => TOKEN_PREDICATE[token](char, parsingContext)); if (!currentToken) { return []; } if (parsingContext.escapeSequence !== void 0 && currentToken !== 12) { if (!isValidEscapeSequence(parsingContext.escapeSequence)) { return []; } currentSelector += resolveEscapeSequence(parsingContext.escapeSequence); parsingContext.escapeSequence = void 0; } if (ALLOWED_SELECTOR_TOKENS.includes(currentToken)) { currentSelector += char; } else if (ALLOWED_SELECTOR_DELIMITER_TOKENS.includes(currentToken) && currentSelector !== "") { selectors.push(currentSelector); currentSelector = ""; } else if (currentToken === 12) { parsingContext.escapeSequence = parsingContext.escapeSequence ? `${parsingContext.escapeSequence}${char}` : char; } else if (currentToken === 8) { parsingContext.quote = char; } else if (currentToken === 9) { parsingContext.quote = void 0; } previousToken = currentToken; } if (!ALLOWED_NEXT_TOKENS[previousToken].includes( 1 /* Token.END */ )) { return []; } if (currentSelector !== "") { selectors.push(currentSelector); } return selectors; } var NAME_SHORTHAND_FIRST_CHAR_REGEX = /[a-zA-Z_$]/; var NAME_SHORTHAND_CHAR_REGEX = /[a-zA-Z0-9_$]/; var DIGIT_REGEX = /[0-9]/; var UNICODE_CHAR_REGEX = /[a-fA-F0-9]/; var QUOTE_CHARS = `'"`; var TOKEN_PREDICATE = { // no char should match to START or END [ 0 /* Token.START */ ]: () => false, [ 1 /* Token.END */ ]: () => false, [ 2 /* Token.NAME_SHORTHAND_FIRST_CHAR */ ]: (char) => NAME_SHORTHAND_FIRST_CHAR_REGEX.test(char), [ 3 /* Token.NAME_SHORTHAND_CHAR */ ]: (char) => NAME_SHORTHAND_CHAR_REGEX.test(char), [ 4 /* Token.DOT */ ]: (char) => char === ".", [ 5 /* Token.BRACKET_START */ ]: (char) => char === "[", [ 6 /* Token.BRACKET_END */ ]: (char) => char === "]", [ 7 /* Token.DIGIT */ ]: (char) => DIGIT_REGEX.test(char), [ 8 /* Token.QUOTE_START */ ]: (char) => QUOTE_CHARS.includes(char), [ 9 /* Token.QUOTE_END */ ]: (char, parsingContext) => char === parsingContext.quote, [ 10 /* Token.NAME_SELECTOR_CHAR */ ]: () => true, // any char can be used in name selector [ 11 /* Token.ESCAPE */ ]: (char) => char === "\\", [ 12 /* Token.ESCAPE_SEQUENCE_CHAR */ ]: (char, parsingContext) => { if (parsingContext.escapeSequence === void 0) { return `${parsingContext.quote}/\\bfnrtu`.includes(char); } else if (parsingContext.escapeSequence.startsWith("u") && parsingContext.escapeSequence.length < 5) { return UNICODE_CHAR_REGEX.test(char); } return false; } }; var ALLOWED_NEXT_TOKENS = { [ 0 /* Token.START */ ]: [ 2, 5 /* Token.BRACKET_START */ ], [ 1 /* Token.END */ ]: [], [ 2 /* Token.NAME_SHORTHAND_FIRST_CHAR */ ]: [ 3, 4, 5, 1 /* Token.END */ ], [ 3 /* Token.NAME_SHORTHAND_CHAR */ ]: [ 3, 4, 5, 1 /* Token.END */ ], [ 4 /* Token.DOT */ ]: [ 2 /* Token.NAME_SHORTHAND_FIRST_CHAR */ ], [ 5 /* Token.BRACKET_START */ ]: [ 8, 7 /* Token.DIGIT */ ], [ 6 /* Token.BRACKET_END */ ]: [ 4, 5, 1 /* Token.END */ ], [ 7 /* Token.DIGIT */ ]: [ 7, 6 /* Token.BRACKET_END */ ], [ 8 /* Token.QUOTE_START */ ]: [ 11, 9, 10 /* Token.NAME_SELECTOR_CHAR */ ], [ 9 /* Token.QUOTE_END */ ]: [ 6 /* Token.BRACKET_END */ ], [ 10 /* Token.NAME_SELECTOR_CHAR */ ]: [ 11, 9, 10 /* Token.NAME_SELECTOR_CHAR */ ], [ 11 /* Token.ESCAPE */ ]: [ 12 /* Token.ESCAPE_SEQUENCE_CHAR */ ], [ 12 /* Token.ESCAPE_SEQUENCE_CHAR */ ]: [ 12, 11, 9, 10 /* Token.NAME_SELECTOR_CHAR */ ] }; var ALLOWED_SELECTOR_TOKENS = [ 2, 3, 7, 10 /* Token.NAME_SELECTOR_CHAR */ ]; var ALLOWED_SELECTOR_DELIMITER_TOKENS = [ 4, 5, 6 /* Token.BRACKET_END */ ]; function isValidEscapeSequence(escapeSequence) { return `"'/\\bfnrt`.includes(escapeSequence) || escapeSequence.startsWith("u") && escapeSequence.length === 5; } var ESCAPED_CHARS = { '"': '"', "'": "'", "/": "/", "\\": "\\", b: "\b", f: "\f", n: "\n", r: "\r", t: " " }; function resolveEscapeSequence(escapeSequence) { if (escapeSequence.startsWith("u")) { return String.fromCharCode(parseInt(escapeSequence.slice(1), 16)); } return ESCAPED_CHARS[escapeSequence]; } // node_modules/@datadog/browser-rum-core/esm/domain/configuration/remoteConfiguration.js var REMOTE_CONFIGURATION_VERSION = "v1"; var SUPPORTED_FIELDS = ["applicationId", "service", "env", "version", "sessionSampleRate", "sessionReplaySampleRate", "defaultPrivacyLevel", "enablePrivacyForActionName", "traceSampleRate", "trackSessionAcrossSubdomains", "allowedTracingUrls", "allowedTrackingOrigins"]; function fetchAndApplyRemoteConfiguration(initConfiguration, supportedContextManagers) { return __async(this, null, function* () { let rumInitConfiguration; const metrics = initMetrics(); const fetchResult = yield fetchRemoteConfiguration(initConfiguration); if (!fetchResult.ok) { metrics.increment("fetch", "failure"); display.error(fetchResult.error); } else { metrics.increment("fetch", "success"); rumInitConfiguration = applyRemoteConfiguration(initConfiguration, fetchResult.value, supportedContextManagers, metrics); } addTelemetryMetrics("remote configuration metrics", { metrics: metrics.get() }); return rumInitConfiguration; }); } function applyRemoteConfiguration(initConfiguration, rumRemoteConfiguration, supportedContextManagers, metrics) { const appliedConfiguration = __spreadValues({}, initConfiguration); SUPPORTED_FIELDS.forEach((option) => { if (option in rumRemoteConfiguration) { appliedConfiguration[option] = resolveConfigurationProperty(rumRemoteConfiguration[option]); } }); Object.keys(supportedContextManagers).forEach((context) => { if (rumRemoteConfiguration[context] !== void 0) { resolveContextProperty(supportedContextManagers[context], rumRemoteConfiguration[context]); } }); return appliedConfiguration; function resolveConfigurationProperty(property) { if (Array.isArray(property)) { return property.map(resolveConfigurationProperty); } if (isObject(property)) { if (isSerializedOption(property)) { const type = property.rcSerializedType; switch (type) { case "string": return property.value; case "regex": return resolveRegex(property.value); case "dynamic": return resolveDynamicOption(property); default: display.error(`Unsupported remote configuration: "rcSerializedType": "${type}"`); return; } } return mapValues(property, resolveConfigurationProperty); } return property; } function resolveContextProperty(contextManager, contextItems) { contextItems.forEach(({ key, value }) => { contextManager.setContextProperty(key, resolveConfigurationProperty(value)); }); } function resolveDynamicOption(property) { const strategy = property.strategy; let resolvedValue; switch (strategy) { case "cookie": resolvedValue = resolveCookieValue(property); break; case "dom": resolvedValue = resolveDomValue(property); break; case "js": resolvedValue = resolveJsValue(property); break; default: display.error(`Unsupported remote configuration: "strategy": "${strategy}"`); return; } const extractor = property.extractor; if (extractor !== void 0 && typeof resolvedValue === "string") { return extractValue(extractor, resolvedValue); } return resolvedValue; } function resolveCookieValue({ name }) { const value = getCookie(name); metrics.increment("cookie", value !== void 0 ? "success" : "missing"); return value; } function resolveDomValue({ selector, attribute }) { let element; try { element = document.querySelector(selector); } catch (_a) { display.error(`Invalid selector in the remote configuration: '${selector}'`); metrics.increment("dom", "failure"); return; } if (!element) { metrics.increment("dom", "missing"); return; } if (isForbidden(element, attribute)) { display.error(`Forbidden element selected by the remote configuration: '${selector}'`); metrics.increment("dom", "failure"); return; } const domValue = attribute !== void 0 ? element.getAttribute(attribute) : element.textContent; if (domValue === null) { metrics.increment("dom", "missing"); return; } metrics.increment("dom", "success"); return domValue; } function isForbidden(element, attribute) { return element.getAttribute("type") === "password" && attribute === "value"; } function resolveJsValue({ path }) { let current = window; const pathParts = parseJsonPath(path); if (pathParts.length === 0) { display.error(`Invalid JSON path in the remote configuration: '${path}'`); metrics.increment("js", "failure"); return; } for (const pathPart of pathParts) { if (!(pathPart in current)) { metrics.increment("js", "missing"); return; } try { current = current[pathPart]; } catch (e) { display.error(`Error accessing: '${path}'`, e); metrics.increment("js", "failure"); return; } } metrics.increment("js", "success"); return current; } } function initMetrics() { const metrics = { fetch: {} }; return { get: () => metrics, increment: (metricName, type) => { if (!metrics[metricName]) { metrics[metricName] = {}; } if (!metrics[metricName][type]) { metrics[metricName][type] = 0; } metrics[metricName][type] = metrics[metricName][type] + 1; } }; } function isObject(property) { return typeof property === "object" && property !== null; } function isSerializedOption(value) { return "rcSerializedType" in value; } function resolveRegex(pattern) { try { return new RegExp(pattern); } catch (_a) { display.error(`Invalid regex in the remote configuration: '${pattern}'`); } } function extractValue(extractor, candidate) { const resolvedExtractor = resolveRegex(extractor.value); if (resolvedExtractor === void 0) { return; } const regexResult = resolvedExtractor.exec(candidate); if (regexResult === null) { return; } const [match, capture] = regexResult; return capture ? capture : match; } function fetchRemoteConfiguration(configuration) { return __async(this, null, function* () { let response; try { response = yield fetch(buildEndpoint(configuration)); } catch (_a) { response = void 0; } if (!response || !response.ok) { return { ok: false, error: new Error("Error fetching the remote configuration.") }; } const remoteConfiguration = yield response.json(); if (remoteConfiguration.rum) { return { ok: true, value: remoteConfiguration.rum }; } return { ok: false, error: new Error("No remote configuration for RUM.") }; }); } function buildEndpoint(configuration) { if (configuration.remoteConfigurationProxy) { return configuration.remoteConfigurationProxy; } return `https://sdk-configuration.${buildEndpointHost("rum", configuration)}/${REMOTE_CONFIGURATION_VERSION}/${encodeURIComponent(configuration.remoteConfigurationId)}.json`; } // node_modules/@datadog/browser-rum-core/esm/boot/preStartRum.js function createPreStartStrategy({ ignoreInitIfSyntheticsWillInjectRum = true, startDeflateWorker }, trackingConsentState, customVitalsState, doStartRum) { const bufferApiCalls = createBoundedBuffer(); const globalContext = buildGlobalContextManager(); bufferContextCalls2(globalContext, CustomerContextKey.globalContext, bufferApiCalls); const userContext = buildUserContextManager(); bufferContextCalls2(userContext, CustomerContextKey.userContext, bufferApiCalls); const accountContext = buildAccountContextManager(); bufferContextCalls2(accountContext, CustomerContextKey.accountContext, bufferApiCalls); let firstStartViewCall; let deflateWorker; let cachedInitConfiguration; let cachedConfiguration; const trackingConsentStateSubscription = trackingConsentState.observable.subscribe(tryStartRum); const emptyContext = {}; function tryStartRum() { if (!cachedInitConfiguration || !cachedConfiguration || !trackingConsentState.isGranted()) { return; } trackingConsentStateSubscription.unsubscribe(); let initialViewOptions; if (cachedConfiguration.trackViewsManually) { if (!firstStartViewCall) { return; } bufferApiCalls.remove(firstStartViewCall.callback); initialViewOptions = firstStartViewCall.options; } const startRumResult = doStartRum(cachedConfiguration, deflateWorker, initialViewOptions); bufferApiCalls.drain(startRumResult); } function doInit(initConfiguration, errorStack) { const eventBridgeAvailable = canUseEventBridge(); if (eventBridgeAvailable) { initConfiguration = overrideInitConfigurationForBridge(initConfiguration); } cachedInitConfiguration = initConfiguration; addTelemetryConfiguration(serializeRumConfiguration(initConfiguration)); if (cachedConfiguration) { displayAlreadyInitializedError("DD_RUM", initConfiguration); return; } const configuration = validateAndBuildRumConfiguration(initConfiguration, errorStack); if (!configuration) { return; } if (!eventBridgeAvailable && !configuration.sessionStoreStrategyType) { display.warn("No storage available for session. We will not send any data."); return; } if (configuration.compressIntakeRequests && !eventBridgeAvailable && startDeflateWorker) { deflateWorker = startDeflateWorker( configuration, "Datadog RUM", // Worker initialization can fail asynchronously, especially in Firefox where even CSP // issues are reported asynchronously. For now, the SDK will continue its execution even if // data won't be sent to Datadog. We could improve this behavior in the future. noop ); if (!deflateWorker) { return; } } cachedConfiguration = configuration; initFetchObservable().subscribe(noop); trackingConsentState.tryToInit(configuration.trackingConsent); tryStartRum(); } const addDurationVital = (vital) => { bufferApiCalls.add((startRumResult) => startRumResult.addDurationVital(vital)); }; const addOperationStepVital = (name, stepType, options, failureReason) => { bufferApiCalls.add((startRumResult) => startRumResult.addOperationStepVital(sanitize(name), stepType, sanitize(options), sanitize(failureReason))); }; const strategy = { init(initConfiguration, publicApi, errorStack) { if (!initConfiguration) { display.error("Missing configuration"); return; } initFeatureFlags(initConfiguration.enableExperimentalFeatures); cachedInitConfiguration = initConfiguration; if (ignoreInitIfSyntheticsWillInjectRum && willSyntheticsInjectRum()) { return; } callPluginsMethod(initConfiguration.plugins, "onInit", { initConfiguration, publicApi }); if (initConfiguration.remoteConfigurationId) { fetchAndApplyRemoteConfiguration(initConfiguration, { user: userContext, context: globalContext }).then((initConfiguration2) => { if (initConfiguration2) { doInit(initConfiguration2, errorStack); } }).catch(monitorError); } else { doInit(initConfiguration, errorStack); } }, get initConfiguration() { return cachedInitConfiguration; }, getInternalContext: noop, stopSession: noop, addTiming(name, time = timeStampNow()) { bufferApiCalls.add((startRumResult) => startRumResult.addTiming(name, time)); }, startView(options, startClocks = clocksNow()) { const callback = (startRumResult) => { startRumResult.startView(options, startClocks); }; bufferApiCalls.add(callback); if (!firstStartViewCall) { firstStartViewCall = { options, callback }; tryStartRum(); } }, setViewName(name) { bufferApiCalls.add((startRumResult) => startRumResult.setViewName(name)); }, // View context APIs setViewContext(context) { bufferApiCalls.add((startRumResult) => startRumResult.setViewContext(context)); }, setViewContextProperty(key, value) { bufferApiCalls.add((startRumResult) => startRumResult.setViewContextProperty(key, value)); }, getViewContext: () => emptyContext, globalContext, userContext, accountContext, addAction(action) { bufferApiCalls.add((startRumResult) => startRumResult.addAction(action)); }, addError(providedError) { bufferApiCalls.add((startRumResult) => startRumResult.addError(providedError)); }, addFeatureFlagEvaluation(key, value) { bufferApiCalls.add((startRumResult) => startRumResult.addFeatureFlagEvaluation(key, value)); }, startDurationVital(name, options) { return startDurationVital(customVitalsState, name, options); }, stopDurationVital(name, options) { stopDurationVital(addDurationVital, customVitalsState, name, options); }, addDurationVital, addOperationStepVital }; return strategy; } function overrideInitConfigurationForBridge(initConfiguration) { var _a, _b; return __spreadProps(__spreadValues({}, initConfiguration), { applicationId: "00000000-aaaa-0000-aaaa-000000000000", clientToken: "empty", sessionSampleRate: 100, defaultPrivacyLevel: (_a = initConfiguration.defaultPrivacyLevel) !== null && _a !== void 0 ? _a : (_b = getEventBridge()) === null || _b === void 0 ? void 0 : _b.getPrivacyLevel() }); } function bufferContextCalls2(preStartContextManager, name, bufferApiCalls) { preStartContextManager.changeObservable.subscribe(() => { const context = preStartContextManager.getContext(); bufferApiCalls.add((startRumResult) => startRumResult[name].setContext(context)); }); } // node_modules/@datadog/browser-rum-core/esm/boot/rumPublicApi.js function makeRumPublicApi(startRumImpl, recorderApi, profilerApi, options = {}) { const trackingConsentState = createTrackingConsentState(); const customVitalsState = createCustomVitalsState(); const bufferedDataObservable = startBufferingData().observable; let strategy = createPreStartStrategy(options, trackingConsentState, customVitalsState, (configuration, deflateWorker, initialViewOptions) => { const startRumResult = startRumImpl(configuration, recorderApi, profilerApi, initialViewOptions, deflateWorker && options.createDeflateEncoder ? (streamId) => options.createDeflateEncoder(configuration, deflateWorker, streamId) : createIdentityEncoder, trackingConsentState, customVitalsState, bufferedDataObservable, options.sdkName); recorderApi.onRumStart(startRumResult.lifeCycle, configuration, startRumResult.session, startRumResult.viewHistory, deflateWorker, startRumResult.telemetry); profilerApi.onRumStart(startRumResult.lifeCycle, startRumResult.hooks, configuration, startRumResult.session, startRumResult.viewHistory); strategy = createPostStartStrategy(strategy, startRumResult); callPluginsMethod(configuration.plugins, "onRumStart", { strategy, // TODO: remove this in the next major release addEvent: startRumResult.addEvent }); return startRumResult; }); const getStrategy = () => strategy; const startView = monitor((options2) => { const sanitizedOptions = typeof options2 === "object" ? options2 : { name: options2 }; strategy.startView(sanitizedOptions); addTelemetryUsage({ feature: "start-view" }); }); const rumPublicApi = makePublicApi({ init: (initConfiguration) => { const errorStack = new Error().stack; callMonitored(() => strategy.init(initConfiguration, rumPublicApi, errorStack)); }, setTrackingConsent: monitor((trackingConsent) => { trackingConsentState.update(trackingConsent); addTelemetryUsage({ feature: "set-tracking-consent", tracking_consent: trackingConsent }); }), setViewName: monitor((name) => { strategy.setViewName(name); addTelemetryUsage({ feature: "set-view-name" }); }), setViewContext: monitor((context) => { strategy.setViewContext(context); addTelemetryUsage({ feature: "set-view-context" }); }), setViewContextProperty: monitor((key, value) => { strategy.setViewContextProperty(key, value); addTelemetryUsage({ feature: "set-view-context-property" }); }), getViewContext: monitor(() => { addTelemetryUsage({ feature: "set-view-context-property" }); return strategy.getViewContext(); }), getInternalContext: monitor((startTime) => strategy.getInternalContext(startTime)), getInitConfiguration: monitor(() => deepClone(strategy.initConfiguration)), addAction: (name, context) => { const handlingStack = createHandlingStack("action"); callMonitored(() => { strategy.addAction({ name: sanitize(name), context: sanitize(context), startClocks: clocksNow(), type: ActionType.CUSTOM, handlingStack }); addTelemetryUsage({ feature: "add-action" }); }); }, addError: (error, context) => { const handlingStack = createHandlingStack("error"); callMonitored(() => { strategy.addError({ error, // Do not sanitize error here, it is needed unserialized by computeRawError() handlingStack, context: sanitize(context), startClocks: clocksNow() }); addTelemetryUsage({ feature: "add-error" }); }); }, addTiming: monitor((name, time) => { strategy.addTiming(sanitize(name), time); }), setGlobalContext: defineContextMethod(getStrategy, CustomerContextKey.globalContext, ContextManagerMethod.setContext, "set-global-context"), getGlobalContext: defineContextMethod(getStrategy, CustomerContextKey.globalContext, ContextManagerMethod.getContext, "get-global-context"), setGlobalContextProperty: defineContextMethod(getStrategy, CustomerContextKey.globalContext, ContextManagerMethod.setContextProperty, "set-global-context-property"), removeGlobalContextProperty: defineContextMethod(getStrategy, CustomerContextKey.globalContext, ContextManagerMethod.removeContextProperty, "remove-global-context-property"), clearGlobalContext: defineContextMethod(getStrategy, CustomerContextKey.globalContext, ContextManagerMethod.clearContext, "clear-global-context"), setUser: defineContextMethod(getStrategy, CustomerContextKey.userContext, ContextManagerMethod.setContext, "set-user"), getUser: defineContextMethod(getStrategy, CustomerContextKey.userContext, ContextManagerMethod.getContext, "get-user"), setUserProperty: defineContextMethod(getStrategy, CustomerContextKey.userContext, ContextManagerMethod.setContextProperty, "set-user-property"), removeUserProperty: defineContextMethod(getStrategy, CustomerContextKey.userContext, ContextManagerMethod.removeContextProperty, "remove-user-property"), clearUser: defineContextMethod(getStrategy, CustomerContextKey.userContext, ContextManagerMethod.clearContext, "clear-user"), setAccount: defineContextMethod(getStrategy, CustomerContextKey.accountContext, ContextManagerMethod.setContext, "set-account"), getAccount: defineContextMethod(getStrategy, CustomerContextKey.accountContext, ContextManagerMethod.getContext, "get-account"), setAccountProperty: defineContextMethod(getStrategy, CustomerContextKey.accountContext, ContextManagerMethod.setContextProperty, "set-account-property"), removeAccountProperty: defineContextMethod(getStrategy, CustomerContextKey.accountContext, ContextManagerMethod.removeContextProperty, "remove-account-property"), clearAccount: defineContextMethod(getStrategy, CustomerContextKey.accountContext, ContextManagerMethod.clearContext, "clear-account"), startView, stopSession: monitor(() => { strategy.stopSession(); addTelemetryUsage({ feature: "stop-session" }); }), addFeatureFlagEvaluation: monitor((key, value) => { strategy.addFeatureFlagEvaluation(sanitize(key), sanitize(value)); addTelemetryUsage({ feature: "add-feature-flag-evaluation" }); }), getSessionReplayLink: monitor(() => recorderApi.getSessionReplayLink()), startSessionReplayRecording: monitor((options2) => { recorderApi.start(options2); addTelemetryUsage({ feature: "start-session-replay-recording", force: options2 && options2.force }); }), stopSessionReplayRecording: monitor(() => recorderApi.stop()), addDurationVital: monitor((name, options2) => { addTelemetryUsage({ feature: "add-duration-vital" }); strategy.addDurationVital({ name: sanitize(name), type: VitalType.DURATION, startClocks: timeStampToClocks(options2.startTime), duration: options2.duration, context: sanitize(options2 && options2.context), description: sanitize(options2 && options2.description) }); }), startDurationVital: monitor((name, options2) => { addTelemetryUsage({ feature: "start-duration-vital" }); return strategy.startDurationVital(sanitize(name), { context: sanitize(options2 && options2.context), description: sanitize(options2 && options2.description) }); }), stopDurationVital: monitor((nameOrRef, options2) => { addTelemetryUsage({ feature: "stop-duration-vital" }); strategy.stopDurationVital(typeof nameOrRef === "string" ? sanitize(nameOrRef) : nameOrRef, { context: sanitize(options2 && options2.context), description: sanitize(options2 && options2.description) }); }), startFeatureOperation: monitor((name, options2) => { addTelemetryUsage({ feature: "add-operation-step-vital", action_type: "start" }); strategy.addOperationStepVital(name, "start", options2); }), succeedFeatureOperation: monitor((name, options2) => { addTelemetryUsage({ feature: "add-operation-step-vital", action_type: "succeed" }); strategy.addOperationStepVital(name, "end", options2); }), failFeatureOperation: monitor((name, failureReason, options2) => { addTelemetryUsage({ feature: "add-operation-step-vital", action_type: "fail" }); strategy.addOperationStepVital(name, "end", options2, failureReason); }) }); return rumPublicApi; } function createPostStartStrategy(preStartStrategy, startRumResult) { return __spreadValues({ init: (initConfiguration) => { displayAlreadyInitializedError("DD_RUM", initConfiguration); }, initConfiguration: preStartStrategy.initConfiguration }, startRumResult); } // node_modules/@datadog/browser-rum-core/esm/browser/domMutationObservable.js function createDOMMutationObservable() { const MutationObserver = getMutationObserverConstructor(); return new Observable((observable) => { if (!MutationObserver) { return; } const observer2 = new MutationObserver(monitor((records) => observable.notify(records))); observer2.observe(document, { attributes: true, characterData: true, childList: true, subtree: true }); return () => observer2.disconnect(); }); } function getMutationObserverConstructor() { let constructor; const browserWindow = window; if (browserWindow.Zone) { constructor = getZoneJsOriginalValue(browserWindow, "MutationObserver"); if (browserWindow.MutationObserver && constructor === browserWindow.MutationObserver) { const patchedInstance = new browserWindow.MutationObserver(noop); const originalInstance = getZoneJsOriginalValue(patchedInstance, "originalInstance"); constructor = originalInstance && originalInstance.constructor; } } if (!constructor) { constructor = browserWindow.MutationObserver; } return constructor; } // node_modules/@datadog/browser-rum-core/esm/browser/windowOpenObservable.js function createWindowOpenObservable() { const observable = new Observable(); const { stop } = instrumentMethod(window, "open", () => observable.notify()); return { observable, stop }; } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/internalContext.js function startInternalContext(applicationId, sessionManager, viewHistory, actionContexts, urlContexts) { return { get: (startTime) => { const viewContext = viewHistory.findView(startTime); const urlContext = urlContexts.findUrl(startTime); const session = sessionManager.findTrackedSession(startTime); if (session && viewContext && urlContext) { const actionId = actionContexts.findActionId(startTime); return { application_id: applicationId, session_id: session.id, user_action: actionId ? { id: actionId } : void 0, view: { id: viewContext.id, name: viewContext.name, referrer: urlContext.referrer, url: urlContext.url } }; } } }; } // node_modules/@datadog/browser-rum-core/esm/domain/lifeCycle.js var LifeCycle = AbstractLifeCycle; // node_modules/@datadog/browser-rum-core/esm/domain/contexts/viewHistory.js var VIEW_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY; function startViewHistory(lifeCycle) { const viewValueHistory = createValueHistory({ expireDelay: VIEW_CONTEXT_TIME_OUT_DELAY }); lifeCycle.subscribe(1, (view) => { viewValueHistory.add(buildViewHistoryEntry(view), view.startClocks.relative); }); lifeCycle.subscribe(6, ({ endClocks }) => { viewValueHistory.closeActive(endClocks.relative); }); lifeCycle.subscribe(3, (viewUpdate) => { const currentView = viewValueHistory.find(viewUpdate.startClocks.relative); if (!currentView) { return; } if (viewUpdate.name) { currentView.name = viewUpdate.name; } if (viewUpdate.context) { currentView.context = viewUpdate.context; } currentView.sessionIsActive = viewUpdate.sessionIsActive; }); lifeCycle.subscribe(10, () => { viewValueHistory.reset(); }); function buildViewHistoryEntry(view) { return { service: view.service, version: view.version, context: view.context, id: view.id, name: view.name, startClocks: view.startClocks }; } return { findView: (startTime) => viewValueHistory.find(startTime), stop: () => { viewValueHistory.stop(); } }; } // node_modules/@datadog/browser-rum-core/esm/domain/requestCollection.js var nextRequestIndex = 1; function startRequestCollection(lifeCycle, configuration, sessionManager, userContext, accountContext) { const tracer = startTracer(configuration, sessionManager, userContext, accountContext); trackXhr(lifeCycle, configuration, tracer); trackFetch(lifeCycle, tracer); } function trackXhr(lifeCycle, configuration, tracer) { const subscription = initXhrObservable(configuration).subscribe((rawContext) => { const context = rawContext; if (!isAllowedRequestUrl(context.url)) { return; } switch (context.state) { case "start": tracer.traceXhr(context, context.xhr); context.requestIndex = getNextRequestIndex(); lifeCycle.notify(7, { requestIndex: context.requestIndex, url: context.url }); break; case "complete": tracer.clearTracingIfNeeded(context); lifeCycle.notify(8, { duration: context.duration, method: context.method, requestIndex: context.requestIndex, spanId: context.spanId, startClocks: context.startClocks, status: context.status, traceId: context.traceId, traceSampled: context.traceSampled, type: RequestType.XHR, url: context.url, xhr: context.xhr, isAborted: context.isAborted, handlingStack: context.handlingStack, body: context.body }); break; } }); return { stop: () => subscription.unsubscribe() }; } function trackFetch(lifeCycle, tracer) { const subscription = initFetchObservable().subscribe((rawContext) => { const context = rawContext; if (!isAllowedRequestUrl(context.url)) { return; } switch (context.state) { case "start": tracer.traceFetch(context); context.requestIndex = getNextRequestIndex(); lifeCycle.notify(7, { requestIndex: context.requestIndex, url: context.url }); break; case "resolve": waitForResponseToComplete(context, (duration) => { var _a; tracer.clearTracingIfNeeded(context); lifeCycle.notify(8, { duration, method: context.method, requestIndex: context.requestIndex, responseType: context.responseType, spanId: context.spanId, startClocks: context.startClocks, status: context.status, traceId: context.traceId, traceSampled: context.traceSampled, type: RequestType.FETCH, url: context.url, response: context.response, init: context.init, input: context.input, isAborted: context.isAborted, handlingStack: context.handlingStack, body: (_a = context.init) === null || _a === void 0 ? void 0 : _a.body }); }); break; } }); return { stop: () => subscription.unsubscribe() }; } function getNextRequestIndex() { const result = nextRequestIndex; nextRequestIndex += 1; return result; } function waitForResponseToComplete(context, callback) { const clonedResponse = context.response && tryToClone(context.response); if (!clonedResponse || !clonedResponse.body) { callback(elapsed(context.startClocks.timeStamp, timeStampNow())); } else { readBytesFromStream(clonedResponse.body, () => { callback(elapsed(context.startClocks.timeStamp, timeStampNow())); }, { bytesLimit: Number.POSITIVE_INFINITY, collectStreamBody: false }); } } // node_modules/@datadog/browser-rum-core/esm/domain/discardNegativeDuration.js function discardNegativeDuration(duration) { return isNumber(duration) && duration < 0 ? void 0 : duration; } // node_modules/@datadog/browser-rum-core/esm/domain/trackEventCounts.js function trackEventCounts({ lifeCycle, isChildEvent, onChange: callback = noop }) { const eventCounts = { errorCount: 0, longTaskCount: 0, resourceCount: 0, actionCount: 0, frustrationCount: 0 }; const subscription = lifeCycle.subscribe(13, (event) => { var _a; if (event.type === "view" || event.type === "vital" || !isChildEvent(event)) { return; } switch (event.type) { case RumEventType.ERROR: eventCounts.errorCount += 1; callback(); break; case RumEventType.ACTION: eventCounts.actionCount += 1; if (event.action.frustration) { eventCounts.frustrationCount += event.action.frustration.type.length; } callback(); break; case RumEventType.LONG_TASK: eventCounts.longTaskCount += 1; callback(); break; case RumEventType.RESOURCE: if (!((_a = event._dd) === null || _a === void 0 ? void 0 : _a.discarded)) { eventCounts.resourceCount += 1; callback(); } break; } }); return { stop: () => { subscription.unsubscribe(); }, eventCounts }; } // node_modules/@datadog/browser-rum-core/esm/browser/htmlDomUtils.js function isTextNode(node) { return node.nodeType === Node.TEXT_NODE; } function isCommentNode(node) { return node.nodeType === Node.COMMENT_NODE; } function isElementNode(node) { return node.nodeType === Node.ELEMENT_NODE; } function isNodeShadowHost(node) { return isElementNode(node) && Boolean(node.shadowRoot); } function isNodeShadowRoot(node) { const shadowRoot = node; return !!shadowRoot.host && shadowRoot.nodeType === Node.DOCUMENT_FRAGMENT_NODE && isElementNode(shadowRoot.host); } function hasChildNodes(node) { return node.childNodes.length > 0 || isNodeShadowHost(node); } function forEachChildNodes(node, callback) { let child = node.firstChild; while (child) { callback(child); child = child.nextSibling; } if (isNodeShadowHost(node)) { callback(node.shadowRoot); } } function getParentNode(node) { return isNodeShadowRoot(node) ? node.host : node.parentNode; } // node_modules/@datadog/browser-rum-core/esm/domain/waitPageActivityEnd.js var PAGE_ACTIVITY_VALIDATION_DELAY = 100; var PAGE_ACTIVITY_END_DELAY = 100; var EXCLUDED_MUTATIONS_ATTRIBUTE = "data-dd-excluded-activity-mutations"; function waitPageActivityEnd(lifeCycle, domMutationObservable, windowOpenObservable, configuration, pageActivityEndCallback, maxDuration) { const pageActivityObservable = createPageActivityObservable(lifeCycle, domMutationObservable, windowOpenObservable, configuration); return doWaitPageActivityEnd(pageActivityObservable, pageActivityEndCallback, maxDuration); } function doWaitPageActivityEnd(pageActivityObservable, pageActivityEndCallback, maxDuration) { let pageActivityEndTimeoutId; let hasCompleted = false; const validationTimeoutId = setTimeout(monitor(() => complete({ hadActivity: false })), PAGE_ACTIVITY_VALIDATION_DELAY); const maxDurationTimeoutId = maxDuration !== void 0 ? setTimeout(monitor(() => complete({ hadActivity: true, end: timeStampNow() })), maxDuration) : void 0; const pageActivitySubscription = pageActivityObservable.subscribe(({ isBusy }) => { clearTimeout(validationTimeoutId); clearTimeout(pageActivityEndTimeoutId); const lastChangeTime = timeStampNow(); if (!isBusy) { pageActivityEndTimeoutId = setTimeout(monitor(() => complete({ hadActivity: true, end: lastChangeTime })), PAGE_ACTIVITY_END_DELAY); } }); const stop = () => { hasCompleted = true; clearTimeout(validationTimeoutId); clearTimeout(pageActivityEndTimeoutId); clearTimeout(maxDurationTimeoutId); pageActivitySubscription.unsubscribe(); }; function complete(event) { if (hasCompleted) { return; } stop(); pageActivityEndCallback(event); } return { stop }; } function createPageActivityObservable(lifeCycle, domMutationObservable, windowOpenObservable, configuration) { return new Observable((observable) => { const subscriptions = []; let firstRequestIndex; let pendingRequestsCount = 0; subscriptions.push(domMutationObservable.subscribe((mutations) => { if (!mutations.every(isExcludedMutation)) { notifyPageActivity(); } }), windowOpenObservable.subscribe(notifyPageActivity), createPerformanceObservable(configuration, { type: RumPerformanceEntryType.RESOURCE }).subscribe((entries) => { if (entries.some((entry) => !isExcludedUrl(configuration, entry.name))) { notifyPageActivity(); } }), lifeCycle.subscribe(7, (startEvent) => { if (isExcludedUrl(configuration, startEvent.url)) { return; } if (firstRequestIndex === void 0) { firstRequestIndex = startEvent.requestIndex; } pendingRequestsCount += 1; notifyPageActivity(); }), lifeCycle.subscribe(8, (request) => { if (isExcludedUrl(configuration, request.url) || firstRequestIndex === void 0 || // If the request started before the tracking start, ignore it request.requestIndex < firstRequestIndex) { return; } pendingRequestsCount -= 1; notifyPageActivity(); })); return () => { subscriptions.forEach((s) => s.unsubscribe()); }; function notifyPageActivity() { observable.notify({ isBusy: pendingRequestsCount > 0 }); } }); } function isExcludedUrl(configuration, requestUrl) { return matchList(configuration.excludedActivityUrls, requestUrl); } function isExcludedMutation(mutation) { const targetElement = mutation.type === "characterData" ? mutation.target.parentElement : mutation.target; return Boolean(targetElement && isElementNode(targetElement) && targetElement.matches(`[${EXCLUDED_MUTATIONS_ATTRIBUTE}], [${EXCLUDED_MUTATIONS_ATTRIBUTE}] *`)); } // node_modules/@datadog/browser-rum-core/esm/domain/action/actionNameConstants.js var DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE = "data-dd-action-name"; var ACTION_NAME_PLACEHOLDER = "Masked Element"; // node_modules/@datadog/browser-rum-core/esm/domain/getSelectorFromElement.js var STABLE_ATTRIBUTES = [ DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE, // Common test attributes (list provided by google recorder) "data-testid", "data-test", "data-qa", "data-cy", "data-test-id", "data-qa-id", "data-testing", // FullStory decorator attributes: "data-component", "data-element", "data-source-file" ]; var GLOBALLY_UNIQUE_SELECTOR_GETTERS = [getStableAttributeSelector, getIDSelector]; var UNIQUE_AMONG_CHILDREN_SELECTOR_GETTERS = [getStableAttributeSelector, getClassSelector, getTagNameSelector]; function getSelectorFromElement(targetElement, actionNameAttribute) { if (!targetElement.isConnected) { return; } let targetElementSelector; let currentElement = targetElement; while (currentElement && currentElement.nodeName !== "HTML") { const globallyUniqueSelector = findSelector(currentElement, GLOBALLY_UNIQUE_SELECTOR_GETTERS, isSelectorUniqueGlobally, actionNameAttribute, targetElementSelector); if (globallyUniqueSelector) { return globallyUniqueSelector; } const uniqueSelectorAmongChildren = findSelector(currentElement, UNIQUE_AMONG_CHILDREN_SELECTOR_GETTERS, isSelectorUniqueAmongSiblings, actionNameAttribute, targetElementSelector); targetElementSelector = uniqueSelectorAmongChildren || combineSelector(getPositionSelector(currentElement), targetElementSelector); currentElement = currentElement.parentElement; } return targetElementSelector; } function isGeneratedValue(value) { return /[0-9]/.test(value); } function getIDSelector(element) { if (element.id && !isGeneratedValue(element.id)) { return `#${CSS.escape(element.id)}`; } } function getClassSelector(element) { if (element.tagName === "BODY") { return; } const classList = element.classList; for (let i = 0; i < classList.length; i += 1) { const className = classList[i]; if (isGeneratedValue(className)) { continue; } return `${CSS.escape(element.tagName)}.${CSS.escape(className)}`; } } function getTagNameSelector(element) { return CSS.escape(element.tagName); } function getStableAttributeSelector(element, actionNameAttribute) { if (actionNameAttribute) { const selector = getAttributeSelector(actionNameAttribute); if (selector) { return selector; } } for (const attributeName of STABLE_ATTRIBUTES) { const selector = getAttributeSelector(attributeName); if (selector) { return selector; } } function getAttributeSelector(attributeName) { if (element.hasAttribute(attributeName)) { return `${CSS.escape(element.tagName)}[${attributeName}="${CSS.escape(element.getAttribute(attributeName))}"]`; } } } function getPositionSelector(element) { let sibling = element.parentElement.firstElementChild; let elementIndex = 1; while (sibling && sibling !== element) { if (sibling.tagName === element.tagName) { elementIndex += 1; } sibling = sibling.nextElementSibling; } return `${CSS.escape(element.tagName)}:nth-of-type(${elementIndex})`; } function findSelector(element, selectorGetters, predicate, actionNameAttribute, childSelector) { for (const selectorGetter of selectorGetters) { const elementSelector = selectorGetter(element, actionNameAttribute); if (!elementSelector) { continue; } if (predicate(element, elementSelector, childSelector)) { return combineSelector(elementSelector, childSelector); } } } function isSelectorUniqueGlobally(element, elementSelector, childSelector) { return element.ownerDocument.querySelectorAll(combineSelector(elementSelector, childSelector)).length === 1; } function isSelectorUniqueAmongSiblings(currentElement, currentElementSelector, childSelector) { let isSiblingMatching; if (childSelector === void 0) { isSiblingMatching = (sibling2) => sibling2.matches(currentElementSelector); } else { const scopedSelector = combineSelector(`${currentElementSelector}:scope`, childSelector); isSiblingMatching = (sibling2) => sibling2.querySelector(scopedSelector) !== null; } const parent = currentElement.parentElement; let sibling = parent.firstElementChild; while (sibling) { if (sibling !== currentElement && isSiblingMatching(sibling)) { return false; } sibling = sibling.nextElementSibling; } return true; } function combineSelector(parent, child) { return child ? `${parent}>${child}` : parent; } // node_modules/@datadog/browser-rum-core/esm/domain/privacyConstants.js var NodePrivacyLevel = { IGNORE: "ignore", HIDDEN: "hidden", ALLOW: DefaultPrivacyLevel.ALLOW, MASK: DefaultPrivacyLevel.MASK, MASK_USER_INPUT: DefaultPrivacyLevel.MASK_USER_INPUT, MASK_UNLESS_ALLOWLISTED: DefaultPrivacyLevel.MASK_UNLESS_ALLOWLISTED }; var PRIVACY_ATTR_NAME = "data-dd-privacy"; var PRIVACY_ATTR_VALUE_HIDDEN = "hidden"; var PRIVACY_CLASS_PREFIX = "dd-privacy-"; var CENSORED_STRING_MARK = "***"; var CENSORED_IMG_MARK = "data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="; var FORM_PRIVATE_TAG_NAMES = { INPUT: true, OUTPUT: true, TEXTAREA: true, SELECT: true, OPTION: true, DATALIST: true, OPTGROUP: true }; var TEXT_MASKING_CHAR = "x"; function getPrivacySelector(privacyLevel) { return `[${PRIVACY_ATTR_NAME}="${privacyLevel}"], .${PRIVACY_CLASS_PREFIX}${privacyLevel}`; } // node_modules/@datadog/browser-rum-core/esm/domain/privacy.js function getNodePrivacyLevel(node, defaultPrivacyLevel, cache) { if (cache && cache.has(node)) { return cache.get(node); } const parentNode = getParentNode(node); const parentNodePrivacyLevel = parentNode ? getNodePrivacyLevel(parentNode, defaultPrivacyLevel, cache) : defaultPrivacyLevel; const selfNodePrivacyLevel = getNodeSelfPrivacyLevel(node); const nodePrivacyLevel = reducePrivacyLevel(selfNodePrivacyLevel, parentNodePrivacyLevel); if (cache) { cache.set(node, nodePrivacyLevel); } return nodePrivacyLevel; } function reducePrivacyLevel(childPrivacyLevel, parentNodePrivacyLevel) { switch (parentNodePrivacyLevel) { // These values cannot be overridden case NodePrivacyLevel.HIDDEN: case NodePrivacyLevel.IGNORE: return parentNodePrivacyLevel; } switch (childPrivacyLevel) { case NodePrivacyLevel.ALLOW: case NodePrivacyLevel.MASK: case NodePrivacyLevel.MASK_USER_INPUT: case NodePrivacyLevel.MASK_UNLESS_ALLOWLISTED: case NodePrivacyLevel.HIDDEN: case NodePrivacyLevel.IGNORE: return childPrivacyLevel; default: return parentNodePrivacyLevel; } } function getNodeSelfPrivacyLevel(node) { if (!isElementNode(node)) { return; } if (node.tagName === "BASE") { return NodePrivacyLevel.ALLOW; } if (node.tagName === "INPUT") { const inputElement = node; if (inputElement.type === "password" || inputElement.type === "email" || inputElement.type === "tel") { return NodePrivacyLevel.MASK; } if (inputElement.type === "hidden") { return NodePrivacyLevel.MASK; } const autocomplete = inputElement.getAttribute("autocomplete"); if (autocomplete && (autocomplete.startsWith("cc-") || autocomplete.endsWith("-password"))) { return NodePrivacyLevel.MASK; } } if (node.matches(getPrivacySelector(NodePrivacyLevel.HIDDEN))) { return NodePrivacyLevel.HIDDEN; } if (node.matches(getPrivacySelector(NodePrivacyLevel.MASK))) { return NodePrivacyLevel.MASK; } if (node.matches(getPrivacySelector(NodePrivacyLevel.MASK_UNLESS_ALLOWLISTED))) { return NodePrivacyLevel.MASK_UNLESS_ALLOWLISTED; } if (node.matches(getPrivacySelector(NodePrivacyLevel.MASK_USER_INPUT))) { return NodePrivacyLevel.MASK_USER_INPUT; } if (node.matches(getPrivacySelector(NodePrivacyLevel.ALLOW))) { return NodePrivacyLevel.ALLOW; } if (shouldIgnoreElement(node)) { return NodePrivacyLevel.IGNORE; } } function shouldMaskNode(node, privacyLevel) { switch (privacyLevel) { case NodePrivacyLevel.MASK: case NodePrivacyLevel.HIDDEN: case NodePrivacyLevel.IGNORE: return true; case NodePrivacyLevel.MASK_UNLESS_ALLOWLISTED: if (isTextNode(node)) { return isFormElement(node.parentNode) ? true : !isAllowlisted(node.textContent || ""); } return isFormElement(node); case NodePrivacyLevel.MASK_USER_INPUT: return isTextNode(node) ? isFormElement(node.parentNode) : isFormElement(node); default: return false; } } function isFormElement(node) { if (!node || node.nodeType !== node.ELEMENT_NODE) { return false; } const element = node; if (element.tagName === "INPUT") { switch (element.type) { case "button": case "color": case "reset": case "submit": return false; } } return !!FORM_PRIVATE_TAG_NAMES[element.tagName]; } var censorText = (text) => text.replace(/\S/g, TEXT_MASKING_CHAR); function getTextContent(textNode, ignoreWhiteSpace, parentNodePrivacyLevel) { var _a; const parentTagName = (_a = textNode.parentElement) === null || _a === void 0 ? void 0 : _a.tagName; let textContent = textNode.textContent || ""; if (ignoreWhiteSpace && !textContent.trim()) { return; } const nodePrivacyLevel = parentNodePrivacyLevel; const isScript = parentTagName === "SCRIPT"; if (isScript) { textContent = CENSORED_STRING_MARK; } else if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) { textContent = CENSORED_STRING_MARK; } else if (shouldMaskNode(textNode, nodePrivacyLevel)) { if ( // Scrambling the child list breaks text nodes for DATALIST/SELECT/OPTGROUP parentTagName === "DATALIST" || parentTagName === "SELECT" || parentTagName === "OPTGROUP" ) { if (!textContent.trim()) { return; } } else if (parentTagName === "OPTION") { textContent = CENSORED_STRING_MARK; } else if (nodePrivacyLevel === NodePrivacyLevel.MASK_UNLESS_ALLOWLISTED) { textContent = maskDisallowedTextContent(textContent); } else { textContent = censorText(textContent); } } return textContent; } function shouldIgnoreElement(element) { if (element.nodeName === "SCRIPT") { return true; } if (element.nodeName === "LINK") { const relAttribute = getLowerCaseAttribute("rel"); return ( // Link as script - Ignore only when rel=preload, modulepreload or prefetch /preload|prefetch/i.test(relAttribute) && getLowerCaseAttribute("as") === "script" || // Favicons relAttribute === "shortcut icon" || relAttribute === "icon" ); } if (element.nodeName === "META") { const nameAttribute = getLowerCaseAttribute("name"); const relAttribute = getLowerCaseAttribute("rel"); const propertyAttribute = getLowerCaseAttribute("property"); return ( // Favicons /^msapplication-tile(image|color)$/.test(nameAttribute) || nameAttribute === "application-name" || relAttribute === "icon" || relAttribute === "apple-touch-icon" || relAttribute === "shortcut icon" || // Description nameAttribute === "keywords" || nameAttribute === "description" || // Social /^(og|twitter|fb):/.test(propertyAttribute) || /^(og|twitter):/.test(nameAttribute) || nameAttribute === "pinterest" || // Robots nameAttribute === "robots" || nameAttribute === "googlebot" || nameAttribute === "bingbot" || // Http headers. Ex: X-UA-Compatible, Content-Type, Content-Language, cache-control, // X-Translated-By element.hasAttribute("http-equiv") || // Authorship nameAttribute === "author" || nameAttribute === "generator" || nameAttribute === "framework" || nameAttribute === "publisher" || nameAttribute === "progid" || /^article:/.test(propertyAttribute) || /^product:/.test(propertyAttribute) || // Verification nameAttribute === "google-site-verification" || nameAttribute === "yandex-verification" || nameAttribute === "csrf-token" || nameAttribute === "p:domain_verify" || nameAttribute === "verify-v1" || nameAttribute === "verification" || nameAttribute === "shopify-checkout-api-token" ); } function getLowerCaseAttribute(name) { return (element.getAttribute(name) || "").toLowerCase(); } return false; } function isAllowlisted(text) { var _a; if (!text || !text.trim()) { return true; } return ((_a = window.$DD_ALLOW) === null || _a === void 0 ? void 0 : _a.has(text.toLocaleLowerCase())) || false; } function maskDisallowedTextContent(text, fixedMask) { if (isAllowlisted(text)) { return text; } return fixedMask || censorText(text); } // node_modules/@datadog/browser-rum-core/esm/domain/action/clickChain.js var MAX_DURATION_BETWEEN_CLICKS = ONE_SECOND; var MAX_DISTANCE_BETWEEN_CLICKS = 100; function createClickChain(firstClick, onFinalize) { const bufferedClicks = []; let status = 0; let maxDurationBetweenClicksTimeoutId; appendClick(firstClick); function appendClick(click) { click.stopObservable.subscribe(tryFinalize); bufferedClicks.push(click); clearTimeout(maxDurationBetweenClicksTimeoutId); maxDurationBetweenClicksTimeoutId = setTimeout(dontAcceptMoreClick, MAX_DURATION_BETWEEN_CLICKS); } function tryFinalize() { if (status === 1 && bufferedClicks.every((click) => click.isStopped())) { status = 2; onFinalize(bufferedClicks); } } function dontAcceptMoreClick() { clearTimeout(maxDurationBetweenClicksTimeoutId); if (status === 0) { status = 1; tryFinalize(); } } return { tryAppend: (click) => { if (status !== 0) { return false; } if (bufferedClicks.length > 0 && !areEventsSimilar(bufferedClicks[bufferedClicks.length - 1].event, click.event)) { dontAcceptMoreClick(); return false; } appendClick(click); return true; }, stop: () => { dontAcceptMoreClick(); } }; } function areEventsSimilar(first, second) { return first.target === second.target && mouseEventDistance(first, second) <= MAX_DISTANCE_BETWEEN_CLICKS && first.timeStamp - second.timeStamp <= MAX_DURATION_BETWEEN_CLICKS; } function mouseEventDistance(origin, other) { return Math.sqrt(Math.pow(origin.clientX - other.clientX, 2) + Math.pow(origin.clientY - other.clientY, 2)); } // node_modules/@datadog/browser-rum-core/esm/domain/action/getActionNameFromElement.js function getActionNameFromElement(element, rumConfiguration, nodePrivacyLevel = NodePrivacyLevel.ALLOW) { const { actionNameAttribute: userProgrammaticAttribute } = rumConfiguration; const defaultActionName = getActionNameFromElementProgrammatically(element, DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE) || userProgrammaticAttribute && getActionNameFromElementProgrammatically(element, userProgrammaticAttribute); if (defaultActionName) { return { name: defaultActionName, nameSource: "custom_attribute" /* ActionNameSource.CUSTOM_ATTRIBUTE */ }; } else if (nodePrivacyLevel === NodePrivacyLevel.MASK) { return { name: ACTION_NAME_PLACEHOLDER, nameSource: "mask_placeholder" /* ActionNameSource.MASK_PLACEHOLDER */ }; } return getActionNameFromElementForStrategies(element, priorityStrategies, rumConfiguration) || getActionNameFromElementForStrategies(element, fallbackStrategies, rumConfiguration) || { name: "", nameSource: "blank" /* ActionNameSource.BLANK */ }; } function getActionNameFromElementProgrammatically(targetElement, programmaticAttribute) { const elementWithAttribute = targetElement.closest(`[${programmaticAttribute}]`); if (!elementWithAttribute) { return; } const name = elementWithAttribute.getAttribute(programmaticAttribute); return truncate(normalizeWhitespace(name.trim())); } var priorityStrategies = [ // associated LABEL text (element, rumConfiguration) => { if ("labels" in element && element.labels && element.labels.length > 0) { return getActionNameFromTextualContent(element.labels[0], rumConfiguration); } }, // INPUT button (and associated) value (element) => { if (element.nodeName === "INPUT") { const input = element; const type = input.getAttribute("type"); if (type === "button" || type === "submit" || type === "reset") { return { name: input.value, nameSource: "text_content" /* ActionNameSource.TEXT_CONTENT */ }; } } }, // BUTTON, LABEL or button-like element text (element, rumConfiguration) => { if (element.nodeName === "BUTTON" || element.nodeName === "LABEL" || element.getAttribute("role") === "button") { return getActionNameFromTextualContent(element, rumConfiguration); } }, (element) => getActionNameFromStandardAttribute(element, "aria-label"), // associated element text designated by the aria-labelledby attribute (element, rumConfiguration) => { const labelledByAttribute = element.getAttribute("aria-labelledby"); if (labelledByAttribute) { return { name: labelledByAttribute.split(/\s+/).map((id) => getElementById(element, id)).filter((label) => Boolean(label)).map((element2) => getTextualContent(element2, rumConfiguration)).join(" "), nameSource: "text_content" /* ActionNameSource.TEXT_CONTENT */ }; } }, (element) => getActionNameFromStandardAttribute(element, "alt"), (element) => getActionNameFromStandardAttribute(element, "name"), (element) => getActionNameFromStandardAttribute(element, "title"), (element) => getActionNameFromStandardAttribute(element, "placeholder"), // SELECT first OPTION text (element, rumConfiguration) => { if ("options" in element && element.options.length > 0) { return getActionNameFromTextualContent(element.options[0], rumConfiguration); } } ]; var fallbackStrategies = [(element, rumConfiguration) => getActionNameFromTextualContent(element, rumConfiguration)]; var MAX_PARENTS_TO_CONSIDER = 10; function getActionNameFromElementForStrategies(targetElement, strategies, rumConfiguration) { let element = targetElement; let recursionCounter = 0; while (recursionCounter <= MAX_PARENTS_TO_CONSIDER && element && element.nodeName !== "BODY" && element.nodeName !== "HTML" && element.nodeName !== "HEAD") { for (const strategy of strategies) { const actionName = strategy(element, rumConfiguration); if (actionName) { const { name, nameSource } = actionName; const trimmedName = name && name.trim(); if (trimmedName) { return { name: truncate(normalizeWhitespace(trimmedName)), nameSource }; } } } if (element.nodeName === "FORM") { break; } element = element.parentElement; recursionCounter += 1; } } function normalizeWhitespace(s) { return s.replace(/\s+/g, " "); } function truncate(s) { return s.length > 100 ? `${safeTruncate(s, 100)} [...]` : s; } function getElementById(refElement, id) { return refElement.ownerDocument ? refElement.ownerDocument.getElementById(id) : null; } function getActionNameFromStandardAttribute(element, attribute) { return { name: element.getAttribute(attribute) || "", nameSource: "standard_attribute" /* ActionNameSource.STANDARD_ATTRIBUTE */ }; } function getActionNameFromTextualContent(element, rumConfiguration) { return { name: getTextualContent(element, rumConfiguration) || "", nameSource: "text_content" /* ActionNameSource.TEXT_CONTENT */ }; } function getTextualContent(element, rumConfiguration) { if (element.isContentEditable) { return; } const { enablePrivacyForActionName, actionNameAttribute: userProgrammaticAttribute, defaultPrivacyLevel } = rumConfiguration; if (isExperimentalFeatureEnabled(ExperimentalFeature.USE_TREE_WALKER_FOR_ACTION_NAME)) { return getTextualContentWithTreeWalker(element, userProgrammaticAttribute, enablePrivacyForActionName, defaultPrivacyLevel); } if ("innerText" in element) { let text = element.innerText; const removeTextFromElements = (query) => { const list = element.querySelectorAll(query); for (let index = 0; index < list.length; index += 1) { const element2 = list[index]; if ("innerText" in element2) { const textToReplace = element2.innerText; if (textToReplace && textToReplace.trim().length > 0) { text = text.replace(textToReplace, ""); } } } }; removeTextFromElements(`[${DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE}]`); if (userProgrammaticAttribute) { removeTextFromElements(`[${userProgrammaticAttribute}]`); } if (enablePrivacyForActionName) { removeTextFromElements(`${getPrivacySelector(NodePrivacyLevel.HIDDEN)}, ${getPrivacySelector(NodePrivacyLevel.MASK)}`); } return text; } return element.textContent; } function getTextualContentWithTreeWalker(element, userProgrammaticAttribute, privacyEnabledActionName, defaultPrivacyLevel) { const nodePrivacyLevelCache = /* @__PURE__ */ new Map(); const walker = document.createTreeWalker( element, // eslint-disable-next-line no-bitwise NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, rejectInvisibleOrMaskedElementsFilter ); let text = ""; while (walker.nextNode()) { const node = walker.currentNode; if (isElementNode(node)) { if ( // Following InnerText rendering spec https://html.spec.whatwg.org/multipage/dom.html#rendered-text-collection-steps node.nodeName === "BR" || node.nodeName === "P" || ["block", "flex", "grid", "list-item", "table", "table-caption"].includes(getComputedStyle(node).display) ) { text += " "; } continue; } text += node.textContent || ""; } return text.replace(/\s+/g, " ").trim(); function rejectInvisibleOrMaskedElementsFilter(node) { const nodeSelfPrivacyLevel = getNodePrivacyLevel(node, defaultPrivacyLevel, nodePrivacyLevelCache); if (privacyEnabledActionName && nodeSelfPrivacyLevel && shouldMaskNode(node, nodeSelfPrivacyLevel)) { return NodeFilter.FILTER_REJECT; } if (isElementNode(node)) { if (node.hasAttribute(DEFAULT_PROGRAMMATIC_ACTION_NAME_ATTRIBUTE) || userProgrammaticAttribute && node.hasAttribute(userProgrammaticAttribute)) { return NodeFilter.FILTER_REJECT; } const style = getComputedStyle(node); if (style.visibility !== "visible" || style.display === "none" || style.contentVisibility && style.contentVisibility !== "visible") { return NodeFilter.FILTER_REJECT; } } return NodeFilter.FILTER_ACCEPT; } } // node_modules/@datadog/browser-rum-core/esm/domain/action/listenActionEvents.js function listenActionEvents(configuration, { onPointerDown, onPointerUp }) { let selectionEmptyAtPointerDown; let userActivity = { selection: false, input: false, scroll: false }; let clickContext; const listeners = [addEventListener(configuration, window, "pointerdown", (event) => { if (isValidPointerEvent(event)) { selectionEmptyAtPointerDown = isSelectionEmpty(); userActivity = { selection: false, input: false, scroll: false }; clickContext = onPointerDown(event); } }, { capture: true }), addEventListener(configuration, window, "selectionchange", () => { if (!selectionEmptyAtPointerDown || !isSelectionEmpty()) { userActivity.selection = true; } }, { capture: true }), addEventListener(configuration, window, "scroll", () => { userActivity.scroll = true; }, { capture: true, passive: true }), addEventListener(configuration, window, "pointerup", (event) => { if (isValidPointerEvent(event) && clickContext) { const localUserActivity = userActivity; onPointerUp(clickContext, event, () => localUserActivity); clickContext = void 0; } }, { capture: true }), addEventListener(configuration, window, "input", () => { userActivity.input = true; }, { capture: true })]; return { stop: () => { listeners.forEach((listener) => listener.stop()); } }; } function isSelectionEmpty() { const selection = window.getSelection(); return !selection || selection.isCollapsed; } function isValidPointerEvent(event) { return event.target instanceof Element && // Only consider 'primary' pointer events for now. Multi-touch support could be implemented in // the future. event.isPrimary !== false; } // node_modules/@datadog/browser-rum-core/esm/domain/action/computeFrustration.js var MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE = 3; function computeFrustration(clicks, rageClick) { if (isRage(clicks)) { rageClick.addFrustration(FrustrationType.RAGE_CLICK); if (clicks.some(isDead)) { rageClick.addFrustration(FrustrationType.DEAD_CLICK); } if (rageClick.hasError) { rageClick.addFrustration(FrustrationType.ERROR_CLICK); } return { isRage: true }; } const hasSelectionChanged = clicks.some((click) => click.getUserActivity().selection); clicks.forEach((click) => { if (click.hasError) { click.addFrustration(FrustrationType.ERROR_CLICK); } if (isDead(click) && // Avoid considering clicks part of a double-click or triple-click selections as dead clicks !hasSelectionChanged) { click.addFrustration(FrustrationType.DEAD_CLICK); } }); return { isRage: false }; } function isRage(clicks) { if (clicks.some((click) => click.getUserActivity().selection || click.getUserActivity().scroll)) { return false; } for (let i = 0; i < clicks.length - (MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE - 1); i += 1) { if (clicks[i + MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE - 1].event.timeStamp - clicks[i].event.timeStamp <= ONE_SECOND) { return true; } } return false; } var DEAD_CLICK_EXCLUDE_SELECTOR = ( // inputs that don't trigger a meaningful event like "input" when clicked, including textual // inputs (using a negative selector is shorter here) 'input:not([type="checkbox"]):not([type="radio"]):not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="range"]),textarea,select,[contenteditable],[contenteditable] *,canvas,a[href],a[href] *' ); function isDead(click) { if (click.hasPageActivity || click.getUserActivity().input || click.getUserActivity().scroll) { return false; } let target = click.event.target; if (target.tagName === "LABEL" && target.hasAttribute("for")) { target = document.getElementById(target.getAttribute("for")); } return !target || !target.matches(DEAD_CLICK_EXCLUDE_SELECTOR); } // node_modules/@datadog/browser-rum-core/esm/domain/action/interactionSelectorCache.js var CLICK_ACTION_MAX_DURATION = 10 * ONE_SECOND; var interactionSelectorCache = /* @__PURE__ */ new Map(); function getInteractionSelector(relativeTimestamp) { const selector = interactionSelectorCache.get(relativeTimestamp); interactionSelectorCache.delete(relativeTimestamp); return selector; } function updateInteractionSelector(relativeTimestamp, selector) { interactionSelectorCache.set(relativeTimestamp, selector); interactionSelectorCache.forEach((_, relativeTimestamp2) => { if (elapsed(relativeTimestamp2, relativeNow()) > CLICK_ACTION_MAX_DURATION) { interactionSelectorCache.delete(relativeTimestamp2); } }); } // node_modules/@datadog/browser-rum-core/esm/domain/action/trackClickActions.js var ACTION_CONTEXT_TIME_OUT_DELAY = 5 * ONE_MINUTE; function trackClickActions(lifeCycle, domMutationObservable, windowOpenObservable, configuration) { const history2 = createValueHistory({ expireDelay: ACTION_CONTEXT_TIME_OUT_DELAY }); const stopObservable = new Observable(); let currentClickChain; lifeCycle.subscribe(10, () => { history2.reset(); }); lifeCycle.subscribe(5, stopClickChain); lifeCycle.subscribe(11, (event) => { if (event.reason === PageExitReason.UNLOADING) { stopClickChain(); } }); const { stop: stopActionEventsListener } = listenActionEvents(configuration, { onPointerDown: (pointerDownEvent) => processPointerDown(configuration, lifeCycle, domMutationObservable, pointerDownEvent, windowOpenObservable), onPointerUp: ({ clickActionBase, hadActivityOnPointerDown }, startEvent, getUserActivity) => { startClickAction(configuration, lifeCycle, domMutationObservable, windowOpenObservable, history2, stopObservable, appendClickToClickChain, clickActionBase, startEvent, getUserActivity, hadActivityOnPointerDown); } }); const actionContexts = { findActionId: (startTime) => history2.findAll(startTime) }; return { stop: () => { stopClickChain(); stopObservable.notify(); stopActionEventsListener(); }, actionContexts }; function appendClickToClickChain(click) { if (!currentClickChain || !currentClickChain.tryAppend(click)) { const rageClick = click.clone(); currentClickChain = createClickChain(click, (clicks) => { finalizeClicks(clicks, rageClick); }); } } function stopClickChain() { if (currentClickChain) { currentClickChain.stop(); } } } function processPointerDown(configuration, lifeCycle, domMutationObservable, pointerDownEvent, windowOpenObservable) { let nodePrivacyLevel; if (configuration.enablePrivacyForActionName) { nodePrivacyLevel = getNodePrivacyLevel(pointerDownEvent.target, configuration.defaultPrivacyLevel); } else { nodePrivacyLevel = NodePrivacyLevel.ALLOW; } if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) { return void 0; } const clickActionBase = computeClickActionBase(pointerDownEvent, nodePrivacyLevel, configuration); let hadActivityOnPointerDown = false; waitPageActivityEnd( lifeCycle, domMutationObservable, windowOpenObservable, configuration, (pageActivityEndEvent) => { hadActivityOnPointerDown = pageActivityEndEvent.hadActivity; }, // We don't care about the activity duration, we just want to know whether an activity did happen // within the "validation delay" or not. Limit the duration so the callback is called sooner. PAGE_ACTIVITY_VALIDATION_DELAY ); return { clickActionBase, hadActivityOnPointerDown: () => hadActivityOnPointerDown }; } function startClickAction(configuration, lifeCycle, domMutationObservable, windowOpenObservable, history2, stopObservable, appendClickToClickChain, clickActionBase, startEvent, getUserActivity, hadActivityOnPointerDown) { var _a; const click = newClick(lifeCycle, history2, getUserActivity, clickActionBase, startEvent); appendClickToClickChain(click); const selector = (_a = clickActionBase === null || clickActionBase === void 0 ? void 0 : clickActionBase.target) === null || _a === void 0 ? void 0 : _a.selector; if (selector) { updateInteractionSelector(startEvent.timeStamp, selector); } const { stop: stopWaitPageActivityEnd } = waitPageActivityEnd(lifeCycle, domMutationObservable, windowOpenObservable, configuration, (pageActivityEndEvent) => { if (pageActivityEndEvent.hadActivity && pageActivityEndEvent.end < click.startClocks.timeStamp) { click.discard(); } else { if (pageActivityEndEvent.hadActivity) { click.stop(pageActivityEndEvent.end); } else if (hadActivityOnPointerDown()) { click.stop( // using the click start as activity end, so the click will have some activity but its // duration will be 0 (as the activity started before the click start) click.startClocks.timeStamp ); } else { click.stop(); } } }, CLICK_ACTION_MAX_DURATION); const viewEndedSubscription = lifeCycle.subscribe(5, ({ endClocks }) => { click.stop(endClocks.timeStamp); }); const stopSubscription = stopObservable.subscribe(() => { click.stop(); }); click.stopObservable.subscribe(() => { viewEndedSubscription.unsubscribe(); stopWaitPageActivityEnd(); stopSubscription.unsubscribe(); }); } function computeClickActionBase(event, nodePrivacyLevel, configuration) { const rect = event.target.getBoundingClientRect(); const selector = getSelectorFromElement(event.target, configuration.actionNameAttribute); if (selector) { updateInteractionSelector(event.timeStamp, selector); } const { name, nameSource } = getActionNameFromElement(event.target, configuration, nodePrivacyLevel); return { type: ActionType.CLICK, target: { width: Math.round(rect.width), height: Math.round(rect.height), selector }, position: { // Use clientX and Y because for SVG element offsetX and Y are relatives to the element x: Math.round(event.clientX - rect.left), y: Math.round(event.clientY - rect.top) }, name, nameSource }; } function newClick(lifeCycle, history2, getUserActivity, clickActionBase, startEvent) { const id = generateUUID(); const startClocks = clocksNow(); const historyEntry = history2.add(id, startClocks.relative); const eventCountsSubscription = trackEventCounts({ lifeCycle, isChildEvent: (event) => event.action !== void 0 && (Array.isArray(event.action.id) ? event.action.id.includes(id) : event.action.id === id) }); let status = 0; let activityEndTime; const frustrationTypes = []; const stopObservable = new Observable(); function stop(newActivityEndTime) { if (status !== 0) { return; } activityEndTime = newActivityEndTime; status = 1; if (activityEndTime) { historyEntry.close(getRelativeTime(activityEndTime)); } else { historyEntry.remove(); } eventCountsSubscription.stop(); stopObservable.notify(); } return { event: startEvent, stop, stopObservable, get hasError() { return eventCountsSubscription.eventCounts.errorCount > 0; }, get hasPageActivity() { return activityEndTime !== void 0; }, getUserActivity, addFrustration: (frustrationType) => { frustrationTypes.push(frustrationType); }, startClocks, isStopped: () => status === 1 || status === 2, clone: () => newClick(lifeCycle, history2, getUserActivity, clickActionBase, startEvent), validate: (domEvents) => { stop(); if (status !== 1) { return; } const { resourceCount, errorCount, longTaskCount } = eventCountsSubscription.eventCounts; const clickAction = __spreadValues({ duration: activityEndTime && elapsed(startClocks.timeStamp, activityEndTime), startClocks, id, frustrationTypes, counts: { resourceCount, errorCount, longTaskCount }, events: domEvents !== null && domEvents !== void 0 ? domEvents : [startEvent], event: startEvent }, clickActionBase); lifeCycle.notify(0, clickAction); status = 2; }, discard: () => { stop(); status = 2; } }; } function finalizeClicks(clicks, rageClick) { const { isRage: isRage2 } = computeFrustration(clicks, rageClick); if (isRage2) { clicks.forEach((click) => click.discard()); rageClick.stop(timeStampNow()); rageClick.validate(clicks.map((click) => click.event)); } else { rageClick.discard(); clicks.forEach((click) => click.validate()); } } // node_modules/@datadog/browser-rum-core/esm/domain/action/actionCollection.js function startActionCollection(lifeCycle, hooks, domMutationObservable, windowOpenObservable, configuration) { const { unsubscribe: unsubscribeAutoAction } = lifeCycle.subscribe(0, (action) => { lifeCycle.notify(12, processAction(action)); }); hooks.register(0, ({ startTime, eventType }) => { if (eventType !== RumEventType.ERROR && eventType !== RumEventType.RESOURCE && eventType !== RumEventType.LONG_TASK) { return SKIPPED; } const actionId = actionContexts.findActionId(startTime); if (!actionId) { return SKIPPED; } return { type: eventType, action: { id: actionId } }; }); hooks.register(1, ({ startTime }) => ({ action: { id: actionContexts.findActionId(startTime) } })); let actionContexts = { findActionId: noop }; let stop = noop; if (configuration.trackUserInteractions) { ; ({ actionContexts, stop } = trackClickActions(lifeCycle, domMutationObservable, windowOpenObservable, configuration)); } return { addAction: (action) => { lifeCycle.notify(12, processAction(action)); }, actionContexts, stop: () => { unsubscribeAutoAction(); stop(); } }; } function processAction(action) { const autoActionProperties = isAutoAction(action) ? { action: { id: action.id, loading_time: discardNegativeDuration(toServerDuration(action.duration)), frustration: { type: action.frustrationTypes }, error: { count: action.counts.errorCount }, long_task: { count: action.counts.longTaskCount }, resource: { count: action.counts.resourceCount } }, _dd: { action: { target: action.target, position: action.position, name_source: action.nameSource } } } : { context: action.context }; const actionEvent = combine({ action: { id: generateUUID(), target: { name: action.name }, type: action.type }, date: action.startClocks.timeStamp, type: RumEventType.ACTION }, autoActionProperties); const duration = isAutoAction(action) ? action.duration : void 0; const domainContext = isAutoAction(action) ? { events: action.events } : { handlingStack: action.handlingStack }; return { rawRumEvent: actionEvent, duration, startTime: action.startClocks.relative, domainContext }; } function isAutoAction(action) { return action.type !== ActionType.CUSTOM; } // node_modules/@datadog/browser-rum-core/esm/domain/error/trackConsoleError.js function trackConsoleError(errorObservable) { const subscription = initConsoleObservable([ConsoleApiName.error]).subscribe((consoleLog) => errorObservable.notify(consoleLog.error)); return { stop: () => { subscription.unsubscribe(); } }; } // node_modules/@datadog/browser-rum-core/esm/domain/error/trackReportError.js function trackReportError(configuration, errorObservable) { const subscription = initReportObservable(configuration, [RawReportType.cspViolation, RawReportType.intervention]).subscribe((rawError) => errorObservable.notify(rawError)); return { stop: () => { subscription.unsubscribe(); } }; } // node_modules/@datadog/browser-rum-core/esm/domain/error/errorCollection.js function startErrorCollection(lifeCycle, configuration, bufferedDataObservable) { const errorObservable = new Observable(); bufferedDataObservable.subscribe((bufferedData) => { if (bufferedData.type === 0) { errorObservable.notify(bufferedData.error); } }); trackConsoleError(errorObservable); trackReportError(configuration, errorObservable); errorObservable.subscribe((error) => lifeCycle.notify(14, { error })); return doStartErrorCollection(lifeCycle); } function doStartErrorCollection(lifeCycle) { lifeCycle.subscribe(14, ({ error }) => { lifeCycle.notify(12, processError(error)); }); return { addError: ({ error, handlingStack, componentStack, startClocks, context }) => { const rawError = computeRawError({ originalError: error, handlingStack, componentStack, startClocks, nonErrorPrefix: "Provided", source: ErrorSource.CUSTOM, handling: "handled" /* ErrorHandling.HANDLED */ }); rawError.context = combine(rawError.context, context); lifeCycle.notify(14, { error: rawError }); } }; } function processError(error) { const rawRumEvent = { date: error.startClocks.timeStamp, error: { id: generateUUID(), message: error.message, source: error.source, stack: error.stack, handling_stack: error.handlingStack, component_stack: error.componentStack, type: error.type, handling: error.handling, causes: error.causes, source_type: "browser", fingerprint: error.fingerprint, csp: error.csp }, type: RumEventType.ERROR, context: error.context }; const domainContext = { error: error.originalError, handlingStack: error.handlingStack }; return { rawRumEvent, startTime: error.startClocks.relative, domainContext }; } // node_modules/@datadog/browser-rum-core/esm/domain/resource/matchRequestResourceEntry.js var alreadyMatchedEntries = /* @__PURE__ */ new WeakSet(); function matchRequestResourceEntry(request) { if (!performance || !("getEntriesByName" in performance)) { return; } const sameNameEntries = performance.getEntriesByName(request.url, "resource"); if (!sameNameEntries.length || !("toJSON" in sameNameEntries[0])) { return; } const candidates = sameNameEntries.filter((entry) => !alreadyMatchedEntries.has(entry)).filter((entry) => hasValidResourceEntryDuration(entry) && hasValidResourceEntryTimings(entry)).filter((entry) => isBetween(entry, request.startClocks.relative, endTime({ startTime: request.startClocks.relative, duration: request.duration }))); if (candidates.length === 1) { alreadyMatchedEntries.add(candidates[0]); return candidates[0].toJSON(); } return; } function endTime(timing) { return addDuration(timing.startTime, timing.duration); } function isBetween(timing, start, end) { const errorMargin = 1; return timing.startTime >= start - errorMargin && endTime(timing) <= addDuration(end, errorMargin); } // node_modules/@datadog/browser-rum-core/esm/domain/tracing/getDocumentTraceId.js var INITIAL_DOCUMENT_OUTDATED_TRACE_ID_THRESHOLD = 2 * ONE_MINUTE; function getDocumentTraceId(document2) { const data = getDocumentTraceDataFromMeta(document2) || getDocumentTraceDataFromComment(document2); if (!data || data.traceTime <= dateNow() - INITIAL_DOCUMENT_OUTDATED_TRACE_ID_THRESHOLD) { return void 0; } return data.traceId; } function getDocumentTraceDataFromMeta(document2) { const traceIdMeta = document2.querySelector("meta[name=dd-trace-id]"); const traceTimeMeta = document2.querySelector("meta[name=dd-trace-time]"); return createDocumentTraceData(traceIdMeta && traceIdMeta.content, traceTimeMeta && traceTimeMeta.content); } function getDocumentTraceDataFromComment(document2) { const comment = findTraceComment(document2); if (!comment) { return void 0; } return createDocumentTraceData(findCommaSeparatedValue(comment, "trace-id"), findCommaSeparatedValue(comment, "trace-time")); } function createDocumentTraceData(traceId, rawTraceTime) { const traceTime = rawTraceTime && Number(rawTraceTime); if (!traceId || !traceTime) { return void 0; } return { traceId, traceTime }; } function findTraceComment(document2) { for (let i = 0; i < document2.childNodes.length; i += 1) { const comment = getTraceCommentFromNode(document2.childNodes[i]); if (comment) { return comment; } } if (document2.body) { for (let i = document2.body.childNodes.length - 1; i >= 0; i -= 1) { const node = document2.body.childNodes[i]; const comment = getTraceCommentFromNode(node); if (comment) { return comment; } if (!isTextNode(node)) { break; } } } } function getTraceCommentFromNode(node) { if (node && isCommentNode(node)) { const match = /^\s*DATADOG;(.*?)\s*$/.exec(node.data); if (match) { return match[1]; } } } // node_modules/@datadog/browser-rum-core/esm/browser/performanceUtils.js function getNavigationEntry() { if (supportPerformanceTimingEvent(RumPerformanceEntryType.NAVIGATION)) { const navigationEntry = performance.getEntriesByType(RumPerformanceEntryType.NAVIGATION)[0]; if (navigationEntry) { return navigationEntry; } } const timings = computeTimingsFromDeprecatedPerformanceTiming(); const entry = __spreadValues({ entryType: RumPerformanceEntryType.NAVIGATION, initiatorType: "navigation", name: window.location.href, startTime: 0, duration: timings.loadEventEnd, decodedBodySize: 0, encodedBodySize: 0, transferSize: 0, workerStart: 0, toJSON: () => __spreadProps(__spreadValues({}, entry), { toJSON: void 0 }) }, timings); return entry; } function computeTimingsFromDeprecatedPerformanceTiming() { const result = {}; const timing = performance.timing; for (const key in timing) { if (isNumber(timing[key])) { const numberKey = key; const timingElement = timing[numberKey]; result[numberKey] = timingElement === 0 ? 0 : getRelativeTime(timingElement); } } return result; } // node_modules/@datadog/browser-rum-core/esm/domain/resource/retrieveInitialDocumentResourceTiming.js function retrieveInitialDocumentResourceTiming(configuration, callback, getNavigationEntryImpl = getNavigationEntry) { runOnReadyState(configuration, "interactive", () => { const navigationEntry = getNavigationEntryImpl(); const entry = Object.assign(navigationEntry.toJSON(), { entryType: RumPerformanceEntryType.RESOURCE, initiatorType: FAKE_INITIAL_DOCUMENT, // The ResourceTiming duration entry should be `responseEnd - startTime`. With // NavigationTiming entries, `startTime` is always 0, so set it to `responseEnd`. duration: navigationEntry.responseEnd, traceId: getDocumentTraceId(document), toJSON: () => __spreadProps(__spreadValues({}, entry), { toJSON: void 0 }) }); callback(entry); }); } // node_modules/@datadog/browser-rum-core/esm/domain/resource/requestRegistry.js var MAX_REQUESTS = 1e3; function createRequestRegistry(lifeCycle) { const requests = /* @__PURE__ */ new Set(); const subscription = lifeCycle.subscribe(8, (request) => { requests.add(request); if (requests.size > MAX_REQUESTS) { addTelemetryDebug("Too many requests"); requests.delete(requests.values().next().value); } }); return { getMatchingRequest(entry) { let minTimeDifference = Infinity; let closestRequest; for (const request of requests) { const timeDifference = entry.startTime - request.startClocks.relative; if (0 <= timeDifference && timeDifference < minTimeDifference && request.url === entry.name) { minTimeDifference = Math.abs(timeDifference); closestRequest = request; } } if (closestRequest) { requests.delete(closestRequest); } return closestRequest; }, stop() { subscription.unsubscribe(); } }; } // node_modules/@datadog/browser-rum-core/esm/domain/resource/graphql.js var GRAPHQL_PAYLOAD_LIMIT = 32 * ONE_KIBI_BYTE; function findGraphQlConfiguration(url, configuration) { return configuration.allowedGraphQlUrls.find((graphQlOption) => matchList([graphQlOption.match], url)); } function extractGraphQlMetadata(requestBody, trackPayload = false) { if (!requestBody || typeof requestBody !== "string") { return; } let graphqlBody; try { graphqlBody = JSON.parse(requestBody); } catch (_a) { return; } if (!graphqlBody || !graphqlBody.query) { return; } const query = graphqlBody.query.trim(); const operationType = getOperationType(query); const operationName = graphqlBody.operationName; if (!operationType) { return; } let variables; if (graphqlBody.variables) { variables = JSON.stringify(graphqlBody.variables); } return { operationType, operationName, variables, payload: trackPayload ? safeTruncate(query, GRAPHQL_PAYLOAD_LIMIT, "...") : void 0 }; } function getOperationType(query) { var _a; return (_a = query.match(/^\s*(query|mutation|subscription)\b/i)) === null || _a === void 0 ? void 0 : _a[1]; } // node_modules/@datadog/browser-rum-core/esm/domain/resource/resourceCollection.js function startResourceCollection(lifeCycle, configuration, pageStateHistory, taskQueue = createTaskQueue(), retrieveInitialDocumentResourceTimingImpl = retrieveInitialDocumentResourceTiming) { let requestRegistry; const isEarlyRequestCollectionEnabled = configuration.trackEarlyRequests; if (isEarlyRequestCollectionEnabled) { requestRegistry = createRequestRegistry(lifeCycle); } else { lifeCycle.subscribe(8, (request) => { handleResource(() => processRequest(request, configuration, pageStateHistory)); }); } const performanceResourceSubscription = createPerformanceObservable(configuration, { type: RumPerformanceEntryType.RESOURCE, buffered: true }).subscribe((entries) => { for (const entry of entries) { if (isEarlyRequestCollectionEnabled || !isResourceEntryRequestType(entry)) { handleResource(() => processResourceEntry(entry, configuration, pageStateHistory, requestRegistry)); } } }); retrieveInitialDocumentResourceTimingImpl(configuration, (timing) => { handleResource(() => processResourceEntry(timing, configuration, pageStateHistory, requestRegistry)); }); function handleResource(computeRawEvent) { taskQueue.push(() => { const rawEvent = computeRawEvent(); if (rawEvent) { lifeCycle.notify(12, rawEvent); } }); } return { stop: () => { taskQueue.stop(); performanceResourceSubscription.unsubscribe(); } }; } function processRequest(request, configuration, pageStateHistory) { const matchingTiming = matchRequestResourceEntry(request); return assembleResource(matchingTiming, request, pageStateHistory, configuration); } function processResourceEntry(entry, configuration, pageStateHistory, requestRegistry) { const matchingRequest = isResourceEntryRequestType(entry) && requestRegistry ? requestRegistry.getMatchingRequest(entry) : void 0; return assembleResource(entry, matchingRequest, pageStateHistory, configuration); } function assembleResource(entry, request, pageStateHistory, configuration) { if (!entry && !request) { return; } const tracingInfo = request ? computeRequestTracingInfo(request, configuration) : computeResourceEntryTracingInfo(entry, configuration); if (!configuration.trackResources && !tracingInfo) { return; } const startClocks = entry ? relativeToClocks(entry.startTime) : request.startClocks; const duration = entry ? computeResourceEntryDuration(entry) : computeRequestDuration(pageStateHistory, startClocks, request.duration); const graphql = request && computeGraphQlMetaData(request, configuration); const resourceEvent = combine({ date: startClocks.timeStamp, resource: { id: generateUUID(), duration: toServerDuration(duration), // TODO: in the future when `entry` is required, we can probably only rely on `computeResourceEntryType` type: request ? request.type === RequestType.XHR ? ResourceType.XHR : ResourceType.FETCH : computeResourceEntryType(entry), method: request ? request.method : void 0, status_code: request ? request.status : discardZeroStatus(entry.responseStatus), url: request ? sanitizeIfLongDataUrl(request.url) : entry.name, protocol: entry && computeResourceEntryProtocol(entry), delivery_type: entry && computeResourceEntryDeliveryType(entry), graphql }, type: RumEventType.RESOURCE, _dd: { discarded: !configuration.trackResources } }, tracingInfo, entry && computeResourceEntryMetrics(entry)); return { startTime: startClocks.relative, duration, rawRumEvent: resourceEvent, domainContext: getResourceDomainContext(entry, request) }; } function computeGraphQlMetaData(request, configuration) { if (!isExperimentalFeatureEnabled(ExperimentalFeature.GRAPHQL_TRACKING)) { return; } const graphQlConfig = findGraphQlConfiguration(request.url, configuration); if (!graphQlConfig) { return; } return extractGraphQlMetadata(request.body, graphQlConfig.trackPayload); } function getResourceDomainContext(entry, request) { if (request) { const baseDomainContext = { performanceEntry: entry, isAborted: request.isAborted, handlingStack: request.handlingStack }; if (request.type === RequestType.XHR) { return __spreadValues({ xhr: request.xhr }, baseDomainContext); } return __spreadValues({ requestInput: request.input, requestInit: request.init, response: request.response, error: request.error }, baseDomainContext); } return { // Currently, at least one of `entry` or `request` must be defined when calling this function. // So `entry` is guaranteed to be defined here. In the future, when `entry` is required, we can // remove the `!` assertion. performanceEntry: entry }; } function computeResourceEntryMetrics(entry) { const { renderBlockingStatus } = entry; return { resource: __spreadValues(__spreadValues({ render_blocking_status: renderBlockingStatus }, computeResourceEntrySize(entry)), computeResourceEntryDetails(entry)) }; } function computeRequestTracingInfo(request, configuration) { const hasBeenTraced = request.traceSampled && request.traceId && request.spanId; if (!hasBeenTraced) { return void 0; } return { _dd: { span_id: request.spanId.toString(), trace_id: request.traceId.toString(), rule_psr: configuration.rulePsr } }; } function computeResourceEntryTracingInfo(entry, configuration) { const hasBeenTraced = entry.traceId; if (!hasBeenTraced) { return void 0; } return { _dd: { trace_id: entry.traceId, span_id: createSpanIdentifier().toString(), rule_psr: configuration.rulePsr } }; } function computeRequestDuration(pageStateHistory, startClocks, duration) { return !pageStateHistory.wasInPageStateDuringPeriod("frozen", startClocks.relative, duration) ? duration : void 0; } function discardZeroStatus(statusCode) { return statusCode === 0 ? void 0 : statusCode; } // node_modules/@datadog/browser-rum-core/esm/domain/view/trackViewEventCounts.js function trackViewEventCounts(lifeCycle, viewId, onChange) { const { stop, eventCounts } = trackEventCounts({ lifeCycle, isChildEvent: (event) => event.view.id === viewId, onChange }); return { stop, eventCounts }; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackFirstContentfulPaint.js var FCP_MAXIMUM_DELAY = 10 * ONE_MINUTE; function trackFirstContentfulPaint(configuration, firstHidden, callback) { const performanceSubscription = createPerformanceObservable(configuration, { type: RumPerformanceEntryType.PAINT, buffered: true }).subscribe((entries) => { const fcpEntry = entries.find((entry) => entry.name === "first-contentful-paint" && entry.startTime < firstHidden.timeStamp && entry.startTime < FCP_MAXIMUM_DELAY); if (fcpEntry) { callback(fcpEntry.startTime); } }); return { stop: performanceSubscription.unsubscribe }; } function trackRestoredFirstContentfulPaint(viewStartRelative, callback) { requestAnimationFrame(() => { requestAnimationFrame(() => { callback(elapsed(viewStartRelative, relativeNow())); }); }); } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackFirstInput.js function trackFirstInput(configuration, firstHidden, callback) { const performanceFirstInputSubscription = createPerformanceObservable(configuration, { type: RumPerformanceEntryType.FIRST_INPUT, buffered: true }).subscribe((entries) => { const firstInputEntry = entries.find((entry) => entry.startTime < firstHidden.timeStamp); if (firstInputEntry) { const firstInputDelay = elapsed(firstInputEntry.startTime, firstInputEntry.processingStart); let firstInputTargetSelector; if (firstInputEntry.target && isElementNode(firstInputEntry.target)) { firstInputTargetSelector = getSelectorFromElement(firstInputEntry.target, configuration.actionNameAttribute); } callback({ // Ensure firstInputDelay to be positive, see // https://bugs.chromium.org/p/chromium/issues/detail?id=1185815 delay: firstInputDelay >= 0 ? firstInputDelay : 0, time: firstInputEntry.startTime, targetSelector: firstInputTargetSelector }); } }); return { stop: () => { performanceFirstInputSubscription.unsubscribe(); } }; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackNavigationTimings.js function trackNavigationTimings(configuration, callback, getNavigationEntryImpl = getNavigationEntry) { return waitAfterLoadEvent(configuration, () => { const entry = getNavigationEntryImpl(); if (!isIncompleteNavigation(entry)) { callback(processNavigationEntry(entry)); } }); } function processNavigationEntry(entry) { return { domComplete: entry.domComplete, domContentLoaded: entry.domContentLoadedEventEnd, domInteractive: entry.domInteractive, loadEvent: entry.loadEventEnd, // In some cases the value reported is negative or is larger // than the current page time. Ignore these cases: // https://github.com/GoogleChrome/web-vitals/issues/137 // https://github.com/GoogleChrome/web-vitals/issues/162 firstByte: entry.responseStart >= 0 && entry.responseStart <= relativeNow() ? entry.responseStart : void 0 }; } function isIncompleteNavigation(entry) { return entry.loadEventEnd <= 0; } function waitAfterLoadEvent(configuration, callback) { let timeoutId; const { stop: stopOnReadyState } = runOnReadyState(configuration, "complete", () => { timeoutId = setTimeout(() => callback()); }); return { stop: () => { stopOnReadyState(); clearTimeout(timeoutId); } }; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackLargestContentfulPaint.js var LCP_MAXIMUM_DELAY = 10 * ONE_MINUTE; function trackLargestContentfulPaint(configuration, firstHidden, eventTarget, callback) { let firstInteractionTimestamp = Infinity; const { stop: stopEventListener } = addEventListeners(configuration, eventTarget, [ "pointerdown", "keydown" /* DOM_EVENT.KEY_DOWN */ ], (event) => { firstInteractionTimestamp = event.timeStamp; }, { capture: true, once: true }); let biggestLcpSize = 0; const performanceLcpSubscription = createPerformanceObservable(configuration, { type: RumPerformanceEntryType.LARGEST_CONTENTFUL_PAINT, buffered: true }).subscribe((entries) => { const lcpEntry = findLast(entries, (entry) => entry.entryType === RumPerformanceEntryType.LARGEST_CONTENTFUL_PAINT && entry.startTime < firstInteractionTimestamp && entry.startTime < firstHidden.timeStamp && entry.startTime < LCP_MAXIMUM_DELAY && // Ensure to get the LCP entry with the biggest size, see // https://bugs.chromium.org/p/chromium/issues/detail?id=1516655 entry.size > biggestLcpSize); if (lcpEntry) { let lcpTargetSelector; if (lcpEntry.element) { lcpTargetSelector = getSelectorFromElement(lcpEntry.element, configuration.actionNameAttribute); } callback({ value: lcpEntry.startTime, targetSelector: lcpTargetSelector, resourceUrl: computeLcpEntryUrl(lcpEntry) }); biggestLcpSize = lcpEntry.size; } }); return { stop: () => { stopEventListener(); performanceLcpSubscription.unsubscribe(); } }; } function computeLcpEntryUrl(entry) { return entry.url === "" ? void 0 : entry.url; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackFirstHidden.js function trackFirstHidden(configuration, viewStart, eventTarget = window) { if (document.visibilityState === "hidden") { return { timeStamp: 0, stop: noop }; } if (supportPerformanceTimingEvent(RumPerformanceEntryType.VISIBILITY_STATE)) { const firstHiddenEntry = performance.getEntriesByType(RumPerformanceEntryType.VISIBILITY_STATE).filter((entry) => entry.name === "hidden").find((entry) => entry.startTime >= viewStart.relative); if (firstHiddenEntry) { return { timeStamp: firstHiddenEntry.startTime, stop: noop }; } } let timeStamp = Infinity; const { stop } = addEventListeners(configuration, eventTarget, [ "pagehide", "visibilitychange" /* DOM_EVENT.VISIBILITY_CHANGE */ ], (event) => { if (event.type === "pagehide" || document.visibilityState === "hidden") { timeStamp = event.timeStamp; stop(); } }, { capture: true }); return { get timeStamp() { return timeStamp; }, stop }; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackInitialViewMetrics.js function trackInitialViewMetrics(configuration, viewStart, setLoadEvent, scheduleViewUpdate) { const initialViewMetrics = {}; const { stop: stopNavigationTracking } = trackNavigationTimings(configuration, (navigationTimings) => { setLoadEvent(navigationTimings.loadEvent); initialViewMetrics.navigationTimings = navigationTimings; scheduleViewUpdate(); }); const firstHidden = trackFirstHidden(configuration, viewStart); const { stop: stopFCPTracking } = trackFirstContentfulPaint(configuration, firstHidden, (firstContentfulPaint) => { initialViewMetrics.firstContentfulPaint = firstContentfulPaint; scheduleViewUpdate(); }); const { stop: stopLCPTracking } = trackLargestContentfulPaint(configuration, firstHidden, window, (largestContentfulPaint) => { initialViewMetrics.largestContentfulPaint = largestContentfulPaint; scheduleViewUpdate(); }); const { stop: stopFIDTracking } = trackFirstInput(configuration, firstHidden, (firstInput) => { initialViewMetrics.firstInput = firstInput; scheduleViewUpdate(); }); function stop() { stopNavigationTracking(); stopFCPTracking(); stopLCPTracking(); stopFIDTracking(); firstHidden.stop(); } return { stop, initialViewMetrics }; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/getClsAttributionImpactedArea.js var calculateArea = (width, height) => width * height; var calculateIntersectionArea = (rect1, rect2) => { const left = Math.max(rect1.left, rect2.left); const top = Math.max(rect1.top, rect2.top); const right = Math.min(rect1.right, rect2.right); const bottom = Math.min(rect1.bottom, rect2.bottom); if (left >= right || top >= bottom) { return 0; } return calculateArea(right - left, bottom - top); }; var getClsAttributionImpactedArea = (source) => { const previousArea = calculateArea(source.previousRect.width, source.previousRect.height); const currentArea = calculateArea(source.currentRect.width, source.currentRect.height); const intersectionArea = calculateIntersectionArea(source.previousRect, source.currentRect); return previousArea + currentArea - intersectionArea; }; // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackCumulativeLayoutShift.js function trackCumulativeLayoutShift(configuration, viewStart, callback) { if (!isLayoutShiftSupported()) { return { stop: noop }; } let maxClsValue = 0; let biggestShift; callback({ value: 0 }); const slidingWindow = slidingSessionWindow(); const performanceSubscription = createPerformanceObservable(configuration, { type: RumPerformanceEntryType.LAYOUT_SHIFT, buffered: true }).subscribe((entries) => { var _a; for (const entry of entries) { if (entry.hadRecentInput || entry.startTime < viewStart) { continue; } const { cumulatedValue, isMaxValue } = slidingWindow.update(entry); if (isMaxValue) { const attribution = getTopImpactedElement(entry.sources); biggestShift = { target: (attribution === null || attribution === void 0 ? void 0 : attribution.node) ? new WeakRef(attribution.node) : void 0, time: elapsed(viewStart, entry.startTime), previousRect: attribution === null || attribution === void 0 ? void 0 : attribution.previousRect, currentRect: attribution === null || attribution === void 0 ? void 0 : attribution.currentRect, devicePixelRatio: window.devicePixelRatio }; } if (cumulatedValue > maxClsValue) { maxClsValue = cumulatedValue; const target = (_a = biggestShift === null || biggestShift === void 0 ? void 0 : biggestShift.target) === null || _a === void 0 ? void 0 : _a.deref(); callback({ value: round(maxClsValue, 4), targetSelector: target && getSelectorFromElement(target, configuration.actionNameAttribute), time: biggestShift === null || biggestShift === void 0 ? void 0 : biggestShift.time, previousRect: (biggestShift === null || biggestShift === void 0 ? void 0 : biggestShift.previousRect) ? asRumRect(biggestShift.previousRect) : void 0, currentRect: (biggestShift === null || biggestShift === void 0 ? void 0 : biggestShift.currentRect) ? asRumRect(biggestShift.currentRect) : void 0, devicePixelRatio: biggestShift === null || biggestShift === void 0 ? void 0 : biggestShift.devicePixelRatio }); } } }); return { stop: () => { performanceSubscription.unsubscribe(); } }; } function getTopImpactedElement(sources) { let topImpactedSource; for (const source of sources) { if (source.node && isElementNode(source.node)) { const currentImpactedArea = getClsAttributionImpactedArea(source); if (!topImpactedSource || getClsAttributionImpactedArea(topImpactedSource) < currentImpactedArea) { topImpactedSource = source; } } } return topImpactedSource; } function asRumRect({ x, y, width, height }) { return { x, y, width, height }; } var MAX_WINDOW_DURATION = 5 * ONE_SECOND; var MAX_UPDATE_GAP = ONE_SECOND; function slidingSessionWindow() { let cumulatedValue = 0; let startTime; let endTime2; let maxValue = 0; return { update: (entry) => { const shouldCreateNewWindow = startTime === void 0 || entry.startTime - endTime2 >= MAX_UPDATE_GAP || entry.startTime - startTime >= MAX_WINDOW_DURATION; let isMaxValue; if (shouldCreateNewWindow) { startTime = endTime2 = entry.startTime; maxValue = cumulatedValue = entry.value; isMaxValue = true; } else { cumulatedValue += entry.value; endTime2 = entry.startTime; isMaxValue = entry.value > maxValue; if (isMaxValue) { maxValue = entry.value; } } return { cumulatedValue, isMaxValue }; } }; } function isLayoutShiftSupported() { return supportPerformanceTimingEvent(RumPerformanceEntryType.LAYOUT_SHIFT) && "WeakRef" in window; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/interactionCountPolyfill.js var observer; var interactionCountEstimate = 0; var minKnownInteractionId = Infinity; var maxKnownInteractionId = 0; function initInteractionCountPolyfill() { if ("interactionCount" in performance || observer) { return; } observer = new window.PerformanceObserver(monitor((entries) => { entries.getEntries().forEach((e) => { const entry = e; if (entry.interactionId) { minKnownInteractionId = Math.min(minKnownInteractionId, entry.interactionId); maxKnownInteractionId = Math.max(maxKnownInteractionId, entry.interactionId); interactionCountEstimate = (maxKnownInteractionId - minKnownInteractionId) / 7 + 1; } }); })); observer.observe({ type: "event", buffered: true, durationThreshold: 0 }); } var getInteractionCount = () => observer ? interactionCountEstimate : window.performance.interactionCount || 0; // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackInteractionToNextPaint.js var MAX_INTERACTION_ENTRIES = 10; var MAX_INP_VALUE = 1 * ONE_MINUTE; function trackInteractionToNextPaint(configuration, viewStart, viewLoadingType) { if (!isInteractionToNextPaintSupported()) { return { getInteractionToNextPaint: () => void 0, setViewEnd: noop, stop: noop }; } const { getViewInteractionCount, stopViewInteractionCount } = trackViewInteractionCount(viewLoadingType); let viewEnd = Infinity; const longestInteractions = trackLongestInteractions(getViewInteractionCount); let interactionToNextPaint = -1; let interactionToNextPaintTargetSelector; let interactionToNextPaintStartTime; function handleEntries(entries) { for (const entry of entries) { if (entry.interactionId && // Check the entry start time is inside the view bounds because some view interactions can be reported after the view end (if long duration). entry.startTime >= viewStart && entry.startTime <= viewEnd) { longestInteractions.process(entry); } } const newInteraction = longestInteractions.estimateP98Interaction(); if (newInteraction && newInteraction.duration !== interactionToNextPaint) { interactionToNextPaint = newInteraction.duration; interactionToNextPaintStartTime = elapsed(viewStart, newInteraction.startTime); interactionToNextPaintTargetSelector = getInteractionSelector(newInteraction.startTime); if (!interactionToNextPaintTargetSelector && newInteraction.target && isElementNode(newInteraction.target)) { interactionToNextPaintTargetSelector = getSelectorFromElement(newInteraction.target, configuration.actionNameAttribute); } } } const firstInputSubscription = createPerformanceObservable(configuration, { type: RumPerformanceEntryType.FIRST_INPUT, buffered: true }).subscribe(handleEntries); const eventSubscription = createPerformanceObservable(configuration, { type: RumPerformanceEntryType.EVENT, // durationThreshold only impact PerformanceEventTiming entries used for INP computation which requires a threshold at 40 (default is 104ms) // cf: https://github.com/GoogleChrome/web-vitals/blob/3806160ffbc93c3c4abf210a167b81228172b31c/src/onINP.ts#L202-L210 durationThreshold: 40, buffered: true }).subscribe(handleEntries); return { getInteractionToNextPaint: () => { if (interactionToNextPaint >= 0) { return { value: Math.min(interactionToNextPaint, MAX_INP_VALUE), targetSelector: interactionToNextPaintTargetSelector, time: interactionToNextPaintStartTime }; } else if (getViewInteractionCount()) { return { value: 0 }; } }, setViewEnd: (viewEndTime) => { viewEnd = viewEndTime; stopViewInteractionCount(); }, stop: () => { eventSubscription.unsubscribe(); firstInputSubscription.unsubscribe(); } }; } function trackLongestInteractions(getViewInteractionCount) { const longestInteractions = []; function sortAndTrimLongestInteractions() { longestInteractions.sort((a, b) => b.duration - a.duration).splice(MAX_INTERACTION_ENTRIES); } return { /** * Process the performance entry: * - if its duration is long enough, add the performance entry to the list of worst interactions * - if an entry with the same interaction id exists and its duration is lower than the new one, then replace it in the list of worst interactions */ process(entry) { const interactionIndex = longestInteractions.findIndex((interaction) => entry.interactionId === interaction.interactionId); const minLongestInteraction = longestInteractions[longestInteractions.length - 1]; if (interactionIndex !== -1) { if (entry.duration > longestInteractions[interactionIndex].duration) { longestInteractions[interactionIndex] = entry; sortAndTrimLongestInteractions(); } } else if (longestInteractions.length < MAX_INTERACTION_ENTRIES || entry.duration > minLongestInteraction.duration) { longestInteractions.push(entry); sortAndTrimLongestInteractions(); } }, /** * Compute the p98 longest interaction. * For better performance the computation is based on 10 longest interactions and the interaction count of the current view. */ estimateP98Interaction() { const interactionIndex = Math.min(longestInteractions.length - 1, Math.floor(getViewInteractionCount() / 50)); return longestInteractions[interactionIndex]; } }; } function trackViewInteractionCount(viewLoadingType) { initInteractionCountPolyfill(); const previousInteractionCount = viewLoadingType === ViewLoadingType.INITIAL_LOAD ? 0 : getInteractionCount(); let state = { stopped: false }; function computeViewInteractionCount() { return getInteractionCount() - previousInteractionCount; } return { getViewInteractionCount: () => { if (state.stopped) { return state.interactionCount; } return computeViewInteractionCount(); }, stopViewInteractionCount: () => { state = { stopped: true, interactionCount: computeViewInteractionCount() }; } }; } function isInteractionToNextPaintSupported() { return supportPerformanceTimingEvent(RumPerformanceEntryType.EVENT) && window.PerformanceEventTiming && "interactionId" in PerformanceEventTiming.prototype; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackLoadingTime.js function trackLoadingTime(lifeCycle, domMutationObservable, windowOpenObservable, configuration, loadType, viewStart, callback) { let isWaitingForLoadEvent = loadType === ViewLoadingType.INITIAL_LOAD; let isWaitingForActivityLoadingTime = true; const loadingTimeCandidates = []; const firstHidden = trackFirstHidden(configuration, viewStart); function invokeCallbackIfAllCandidatesAreReceived() { if (!isWaitingForActivityLoadingTime && !isWaitingForLoadEvent && loadingTimeCandidates.length > 0) { const loadingTime = Math.max(...loadingTimeCandidates); if (loadingTime < firstHidden.timeStamp - viewStart.relative) { callback(loadingTime); } } } const { stop } = waitPageActivityEnd(lifeCycle, domMutationObservable, windowOpenObservable, configuration, (event) => { if (isWaitingForActivityLoadingTime) { isWaitingForActivityLoadingTime = false; if (event.hadActivity) { loadingTimeCandidates.push(elapsed(viewStart.timeStamp, event.end)); } invokeCallbackIfAllCandidatesAreReceived(); } }); return { stop: () => { stop(); firstHidden.stop(); }, setLoadEvent: (loadEvent) => { if (isWaitingForLoadEvent) { isWaitingForLoadEvent = false; loadingTimeCandidates.push(loadEvent); invokeCallbackIfAllCandidatesAreReceived(); } } }; } // node_modules/@datadog/browser-rum-core/esm/browser/scroll.js function getScrollX() { let scrollX; const visual = window.visualViewport; if (visual) { scrollX = visual.pageLeft - visual.offsetLeft; } else if (window.scrollX !== void 0) { scrollX = window.scrollX; } else { scrollX = window.pageXOffset || 0; } return Math.round(scrollX); } function getScrollY() { let scrollY; const visual = window.visualViewport; if (visual) { scrollY = visual.pageTop - visual.offsetTop; } else if (window.scrollY !== void 0) { scrollY = window.scrollY; } else { scrollY = window.pageYOffset || 0; } return Math.round(scrollY); } // node_modules/@datadog/browser-rum-core/esm/browser/viewportObservable.js var viewportObservable; function initViewportObservable(configuration) { if (!viewportObservable) { viewportObservable = createViewportObservable(configuration); } return viewportObservable; } function createViewportObservable(configuration) { return new Observable((observable) => { const { throttled: updateDimension } = throttle(() => { observable.notify(getViewportDimension()); }, 200); return addEventListener(configuration, window, "resize", updateDimension, { capture: true, passive: true }).stop; }); } function getViewportDimension() { const visual = window.visualViewport; if (visual) { return { width: Number(visual.width * visual.scale), height: Number(visual.height * visual.scale) }; } return { width: Number(window.innerWidth || 0), height: Number(window.innerHeight || 0) }; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackScrollMetrics.js var THROTTLE_SCROLL_DURATION = ONE_SECOND; function trackScrollMetrics(configuration, viewStart, callback, scrollValues = createScrollValuesObservable(configuration)) { let maxScrollDepth = 0; let maxScrollHeight = 0; let maxScrollHeightTime = 0; const subscription = scrollValues.subscribe(({ scrollDepth, scrollTop, scrollHeight }) => { let shouldUpdate = false; if (scrollDepth > maxScrollDepth) { maxScrollDepth = scrollDepth; shouldUpdate = true; } if (scrollHeight > maxScrollHeight) { maxScrollHeight = scrollHeight; const now = relativeNow(); maxScrollHeightTime = elapsed(viewStart.relative, now); shouldUpdate = true; } if (shouldUpdate) { callback({ maxDepth: Math.min(maxScrollDepth, maxScrollHeight), maxDepthScrollTop: scrollTop, maxScrollHeight, maxScrollHeightTime }); } }); return { stop: () => subscription.unsubscribe() }; } function computeScrollValues() { const scrollTop = getScrollY(); const { height } = getViewportDimension(); const scrollHeight = Math.round((document.scrollingElement || document.documentElement).scrollHeight); const scrollDepth = Math.round(height + scrollTop); return { scrollHeight, scrollDepth, scrollTop }; } function createScrollValuesObservable(configuration, throttleDuration = THROTTLE_SCROLL_DURATION) { return new Observable((observable) => { function notify() { observable.notify(computeScrollValues()); } if (window.ResizeObserver) { const throttledNotify = throttle(notify, throttleDuration, { leading: false, trailing: true }); const observerTarget = document.scrollingElement || document.documentElement; const resizeObserver = new ResizeObserver(monitor(throttledNotify.throttled)); if (observerTarget) { resizeObserver.observe(observerTarget); } const eventListener = addEventListener(configuration, window, "scroll", throttledNotify.throttled, { passive: true }); return () => { throttledNotify.cancel(); resizeObserver.disconnect(); eventListener.stop(); }; } }); } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackCommonViewMetrics.js function trackCommonViewMetrics(lifeCycle, domMutationObservable, windowOpenObservable, configuration, scheduleViewUpdate, loadingType, viewStart) { const commonViewMetrics = {}; const { stop: stopLoadingTimeTracking, setLoadEvent } = trackLoadingTime(lifeCycle, domMutationObservable, windowOpenObservable, configuration, loadingType, viewStart, (newLoadingTime) => { commonViewMetrics.loadingTime = newLoadingTime; scheduleViewUpdate(); }); const { stop: stopScrollMetricsTracking } = trackScrollMetrics(configuration, viewStart, (newScrollMetrics) => { commonViewMetrics.scroll = newScrollMetrics; }); const { stop: stopCLSTracking } = trackCumulativeLayoutShift(configuration, viewStart.relative, (cumulativeLayoutShift) => { commonViewMetrics.cumulativeLayoutShift = cumulativeLayoutShift; scheduleViewUpdate(); }); const { stop: stopINPTracking, getInteractionToNextPaint, setViewEnd } = trackInteractionToNextPaint(configuration, viewStart.relative, loadingType); return { stop: () => { stopLoadingTimeTracking(); stopCLSTracking(); stopScrollMetricsTracking(); }, stopINPTracking, setLoadEvent, setViewEnd, getCommonViewMetrics: () => { commonViewMetrics.interactionToNextPaint = getInteractionToNextPaint(); return commonViewMetrics; } }; } // node_modules/@datadog/browser-rum-core/esm/domain/view/bfCacheSupport.js function onBFCacheRestore(configuration, callback) { const { stop } = addEventListener(configuration, window, "pageshow", (event) => { if (event.persisted) { callback(event); } }, { capture: true }); return stop; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackBfcacheMetrics.js function trackBfcacheMetrics(viewStart, metrics, scheduleViewUpdate) { trackRestoredFirstContentfulPaint(viewStart.relative, (paintTime) => { metrics.firstContentfulPaint = paintTime; metrics.largestContentfulPaint = { value: paintTime }; scheduleViewUpdate(); }); } // node_modules/@datadog/browser-rum-core/esm/domain/view/trackViews.js var THROTTLE_VIEW_UPDATE_PERIOD = 3e3; var SESSION_KEEP_ALIVE_INTERVAL = 5 * ONE_MINUTE; var KEEP_TRACKING_AFTER_VIEW_DELAY = 5 * ONE_MINUTE; function trackViews(location2, lifeCycle, domMutationObservable, windowOpenObservable, configuration, locationChangeObservable, areViewsTrackedAutomatically, initialViewOptions) { const activeViews = /* @__PURE__ */ new Set(); let currentView = startNewView(ViewLoadingType.INITIAL_LOAD, clocksOrigin(), initialViewOptions); let stopOnBFCacheRestore; startViewLifeCycle(); let locationChangeSubscription; if (areViewsTrackedAutomatically) { locationChangeSubscription = renewViewOnLocationChange(locationChangeObservable); if (configuration.trackBfcacheViews) { stopOnBFCacheRestore = onBFCacheRestore(configuration, (pageshowEvent) => { currentView.end(); const startClocks = relativeToClocks(pageshowEvent.timeStamp); currentView = startNewView(ViewLoadingType.BF_CACHE, startClocks, void 0); }); } } function startNewView(loadingType, startClocks, viewOptions) { const newlyCreatedView = newView(lifeCycle, domMutationObservable, windowOpenObservable, configuration, location2, loadingType, startClocks, viewOptions); activeViews.add(newlyCreatedView); newlyCreatedView.stopObservable.subscribe(() => { activeViews.delete(newlyCreatedView); }); return newlyCreatedView; } function startViewLifeCycle() { lifeCycle.subscribe(10, () => { currentView = startNewView(ViewLoadingType.ROUTE_CHANGE, void 0, { name: currentView.name, service: currentView.service, version: currentView.version, context: currentView.contextManager.getContext() }); }); lifeCycle.subscribe(9, () => { currentView.end({ sessionIsActive: false }); }); } function renewViewOnLocationChange(locationChangeObservable2) { return locationChangeObservable2.subscribe(({ oldLocation, newLocation }) => { if (areDifferentLocation(oldLocation, newLocation)) { currentView.end(); currentView = startNewView(ViewLoadingType.ROUTE_CHANGE); } }); } return { addTiming: (name, time = timeStampNow()) => { currentView.addTiming(name, time); }, startView: (options, startClocks) => { currentView.end({ endClocks: startClocks }); currentView = startNewView(ViewLoadingType.ROUTE_CHANGE, startClocks, options); }, setViewContext: (context) => { currentView.contextManager.setContext(context); }, setViewContextProperty: (key, value) => { currentView.contextManager.setContextProperty(key, value); }, setViewName: (name) => { currentView.setViewName(name); }, getViewContext: () => currentView.contextManager.getContext(), stop: () => { if (locationChangeSubscription) { locationChangeSubscription.unsubscribe(); } if (stopOnBFCacheRestore) { stopOnBFCacheRestore(); } currentView.end(); activeViews.forEach((view) => view.stop()); } }; } function newView(lifeCycle, domMutationObservable, windowOpenObservable, configuration, initialLocation, loadingType, startClocks = clocksNow(), viewOptions) { const id = generateUUID(); const stopObservable = new Observable(); const customTimings = {}; let documentVersion = 0; let endClocks; const location2 = shallowClone(initialLocation); const contextManager = createContextManager(); let sessionIsActive = true; let name = viewOptions === null || viewOptions === void 0 ? void 0 : viewOptions.name; const service = (viewOptions === null || viewOptions === void 0 ? void 0 : viewOptions.service) || configuration.service; const version = (viewOptions === null || viewOptions === void 0 ? void 0 : viewOptions.version) || configuration.version; const context = viewOptions === null || viewOptions === void 0 ? void 0 : viewOptions.context; if (context) { contextManager.setContext(context); } const viewCreatedEvent = { id, name, startClocks, service, version, context }; lifeCycle.notify(1, viewCreatedEvent); lifeCycle.notify(2, viewCreatedEvent); const { throttled, cancel: cancelScheduleViewUpdate } = throttle(triggerViewUpdate, THROTTLE_VIEW_UPDATE_PERIOD, { leading: false }); const { setLoadEvent, setViewEnd, stop: stopCommonViewMetricsTracking, stopINPTracking, getCommonViewMetrics } = trackCommonViewMetrics(lifeCycle, domMutationObservable, windowOpenObservable, configuration, scheduleViewUpdate, loadingType, startClocks); const { stop: stopInitialViewMetricsTracking, initialViewMetrics } = loadingType === ViewLoadingType.INITIAL_LOAD ? trackInitialViewMetrics(configuration, startClocks, setLoadEvent, scheduleViewUpdate) : { stop: noop, initialViewMetrics: {} }; if (loadingType === ViewLoadingType.BF_CACHE) { trackBfcacheMetrics(startClocks, initialViewMetrics, scheduleViewUpdate); } const { stop: stopEventCountsTracking, eventCounts } = trackViewEventCounts(lifeCycle, id, scheduleViewUpdate); const keepAliveIntervalId = setInterval(triggerViewUpdate, SESSION_KEEP_ALIVE_INTERVAL); const pageMayExitSubscription = lifeCycle.subscribe(11, (pageMayExitEvent) => { if (pageMayExitEvent.reason === PageExitReason.UNLOADING) { triggerViewUpdate(); } }); triggerViewUpdate(); contextManager.changeObservable.subscribe(scheduleViewUpdate); function triggerBeforeViewUpdate() { lifeCycle.notify(3, { id, name, context: contextManager.getContext(), startClocks, sessionIsActive }); } function scheduleViewUpdate() { triggerBeforeViewUpdate(); throttled(); } function triggerViewUpdate() { cancelScheduleViewUpdate(); triggerBeforeViewUpdate(); documentVersion += 1; const currentEnd = endClocks === void 0 ? timeStampNow() : endClocks.timeStamp; lifeCycle.notify(4, { customTimings, documentVersion, id, name, service, version, context: contextManager.getContext(), loadingType, location: location2, startClocks, commonViewMetrics: getCommonViewMetrics(), initialViewMetrics, duration: elapsed(startClocks.timeStamp, currentEnd), isActive: endClocks === void 0, sessionIsActive, eventCounts }); } return { get name() { return name; }, service, version, contextManager, stopObservable, end(options = {}) { var _a, _b; if (endClocks) { return; } endClocks = (_a = options.endClocks) !== null && _a !== void 0 ? _a : clocksNow(); sessionIsActive = (_b = options.sessionIsActive) !== null && _b !== void 0 ? _b : true; lifeCycle.notify(5, { endClocks }); lifeCycle.notify(6, { endClocks }); clearInterval(keepAliveIntervalId); setViewEnd(endClocks.relative); stopCommonViewMetricsTracking(); pageMayExitSubscription.unsubscribe(); triggerViewUpdate(); setTimeout(() => { this.stop(); }, KEEP_TRACKING_AFTER_VIEW_DELAY); }, stop() { stopInitialViewMetricsTracking(); stopEventCountsTracking(); stopINPTracking(); stopObservable.notify(); }, addTiming(name2, time) { if (endClocks) { return; } const relativeTime = looksLikeRelativeTime(time) ? time : elapsed(startClocks.timeStamp, time); customTimings[sanitizeTiming(name2)] = relativeTime; scheduleViewUpdate(); }, setViewName(updatedName) { name = updatedName; triggerViewUpdate(); } }; } function sanitizeTiming(name) { const sanitized = name.replace(/[^a-zA-Z0-9-_.@$]/g, "_"); if (sanitized !== name) { display.warn(`Invalid timing name: ${name}, sanitized to: ${sanitized}`); } return sanitized; } function areDifferentLocation(currentLocation, otherLocation) { return currentLocation.pathname !== otherLocation.pathname || !isHashAnAnchor(otherLocation.hash) && getPathFromHash(otherLocation.hash) !== getPathFromHash(currentLocation.hash); } function isHashAnAnchor(hash) { const correspondingId = hash.substring(1); return correspondingId !== "" && !!document.getElementById(correspondingId); } function getPathFromHash(hash) { const index = hash.indexOf("?"); return index < 0 ? hash : hash.slice(0, index); } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewCollection.js function startViewCollection(lifeCycle, hooks, configuration, location2, domMutationObservable, pageOpenObservable, locationChangeObservable, recorderApi, viewHistory, initialViewOptions) { lifeCycle.subscribe(4, (view) => lifeCycle.notify(12, processViewUpdate(view, configuration, recorderApi))); hooks.register(0, ({ startTime, eventType }) => { const view = viewHistory.findView(startTime); if (!view) { return DISCARDED; } return { type: eventType, service: view.service, version: view.version, context: view.context, view: { id: view.id, name: view.name } }; }); hooks.register(1, ({ startTime }) => { var _a; return { view: { id: (_a = viewHistory.findView(startTime)) === null || _a === void 0 ? void 0 : _a.id } }; }); return trackViews(location2, lifeCycle, domMutationObservable, pageOpenObservable, configuration, locationChangeObservable, !configuration.trackViewsManually, initialViewOptions); } function processViewUpdate(view, configuration, recorderApi) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t; const replayStats = recorderApi.getReplayStats(view.id); const clsDevicePixelRatio = (_b = (_a = view.commonViewMetrics) === null || _a === void 0 ? void 0 : _a.cumulativeLayoutShift) === null || _b === void 0 ? void 0 : _b.devicePixelRatio; const viewEvent = { _dd: { document_version: view.documentVersion, replay_stats: replayStats, cls: clsDevicePixelRatio ? { device_pixel_ratio: clsDevicePixelRatio } : void 0, configuration: { start_session_replay_recording_manually: configuration.startSessionReplayRecordingManually } }, date: view.startClocks.timeStamp, type: RumEventType.VIEW, view: { action: { count: view.eventCounts.actionCount }, frustration: { count: view.eventCounts.frustrationCount }, cumulative_layout_shift: (_c = view.commonViewMetrics.cumulativeLayoutShift) === null || _c === void 0 ? void 0 : _c.value, cumulative_layout_shift_time: toServerDuration((_d = view.commonViewMetrics.cumulativeLayoutShift) === null || _d === void 0 ? void 0 : _d.time), cumulative_layout_shift_target_selector: (_e = view.commonViewMetrics.cumulativeLayoutShift) === null || _e === void 0 ? void 0 : _e.targetSelector, first_byte: toServerDuration((_f = view.initialViewMetrics.navigationTimings) === null || _f === void 0 ? void 0 : _f.firstByte), dom_complete: toServerDuration((_g = view.initialViewMetrics.navigationTimings) === null || _g === void 0 ? void 0 : _g.domComplete), dom_content_loaded: toServerDuration((_h = view.initialViewMetrics.navigationTimings) === null || _h === void 0 ? void 0 : _h.domContentLoaded), dom_interactive: toServerDuration((_j = view.initialViewMetrics.navigationTimings) === null || _j === void 0 ? void 0 : _j.domInteractive), error: { count: view.eventCounts.errorCount }, first_contentful_paint: toServerDuration(view.initialViewMetrics.firstContentfulPaint), first_input_delay: toServerDuration((_k = view.initialViewMetrics.firstInput) === null || _k === void 0 ? void 0 : _k.delay), first_input_time: toServerDuration((_l = view.initialViewMetrics.firstInput) === null || _l === void 0 ? void 0 : _l.time), first_input_target_selector: (_m = view.initialViewMetrics.firstInput) === null || _m === void 0 ? void 0 : _m.targetSelector, interaction_to_next_paint: toServerDuration((_o = view.commonViewMetrics.interactionToNextPaint) === null || _o === void 0 ? void 0 : _o.value), interaction_to_next_paint_time: toServerDuration((_p = view.commonViewMetrics.interactionToNextPaint) === null || _p === void 0 ? void 0 : _p.time), interaction_to_next_paint_target_selector: (_q = view.commonViewMetrics.interactionToNextPaint) === null || _q === void 0 ? void 0 : _q.targetSelector, is_active: view.isActive, name: view.name, largest_contentful_paint: toServerDuration((_r = view.initialViewMetrics.largestContentfulPaint) === null || _r === void 0 ? void 0 : _r.value), largest_contentful_paint_target_selector: (_s = view.initialViewMetrics.largestContentfulPaint) === null || _s === void 0 ? void 0 : _s.targetSelector, load_event: toServerDuration((_t = view.initialViewMetrics.navigationTimings) === null || _t === void 0 ? void 0 : _t.loadEvent), loading_time: discardNegativeDuration(toServerDuration(view.commonViewMetrics.loadingTime)), loading_type: view.loadingType, long_task: { count: view.eventCounts.longTaskCount }, performance: computeViewPerformanceData(view.commonViewMetrics, view.initialViewMetrics), resource: { count: view.eventCounts.resourceCount }, time_spent: toServerDuration(view.duration) }, display: view.commonViewMetrics.scroll ? { scroll: { max_depth: view.commonViewMetrics.scroll.maxDepth, max_depth_scroll_top: view.commonViewMetrics.scroll.maxDepthScrollTop, max_scroll_height: view.commonViewMetrics.scroll.maxScrollHeight, max_scroll_height_time: toServerDuration(view.commonViewMetrics.scroll.maxScrollHeightTime) } } : void 0, privacy: { replay_level: configuration.defaultPrivacyLevel }, device: { locale: navigator.language, locales: navigator.languages, time_zone: getTimeZone() } }; if (!isEmptyObject(view.customTimings)) { viewEvent.view.custom_timings = mapValues(view.customTimings, toServerDuration); } return { rawRumEvent: viewEvent, startTime: view.startClocks.relative, duration: view.duration, domainContext: { location: view.location } }; } function computeViewPerformanceData({ cumulativeLayoutShift, interactionToNextPaint }, { firstContentfulPaint, firstInput, largestContentfulPaint }) { return { cls: cumulativeLayoutShift && { score: cumulativeLayoutShift.value, timestamp: toServerDuration(cumulativeLayoutShift.time), target_selector: cumulativeLayoutShift.targetSelector, previous_rect: cumulativeLayoutShift.previousRect, current_rect: cumulativeLayoutShift.currentRect }, fcp: firstContentfulPaint && { timestamp: toServerDuration(firstContentfulPaint) }, fid: firstInput && { duration: toServerDuration(firstInput.delay), timestamp: toServerDuration(firstInput.time), target_selector: firstInput.targetSelector }, inp: interactionToNextPaint && { duration: toServerDuration(interactionToNextPaint.value), timestamp: toServerDuration(interactionToNextPaint.time), target_selector: interactionToNextPaint.targetSelector }, lcp: largestContentfulPaint && { timestamp: toServerDuration(largestContentfulPaint.value), target_selector: largestContentfulPaint.targetSelector, resource_url: largestContentfulPaint.resourceUrl } }; } // node_modules/@datadog/browser-rum-core/esm/domain/rumSessionManager.js var RUM_SESSION_KEY2 = "rum"; function startRumSessionManager(configuration, lifeCycle, trackingConsentState) { const sessionManager = startSessionManager(configuration, RUM_SESSION_KEY2, (rawTrackingType) => computeTrackingType(configuration, rawTrackingType), trackingConsentState); sessionManager.expireObservable.subscribe(() => { lifeCycle.notify( 9 /* LifeCycleEventType.SESSION_EXPIRED */ ); }); sessionManager.renewObservable.subscribe(() => { lifeCycle.notify( 10 /* LifeCycleEventType.SESSION_RENEWED */ ); }); sessionManager.sessionStateUpdateObservable.subscribe(({ previousState, newState }) => { if (!previousState.forcedReplay && newState.forcedReplay) { const sessionEntity = sessionManager.findSession(); if (sessionEntity) { sessionEntity.isReplayForced = true; } } }); return { findTrackedSession: (startTime) => { const session = sessionManager.findSession(startTime); if (!session || session.trackingType === "0") { return; } return { id: session.id, sessionReplay: session.trackingType === "1" ? 1 : session.isReplayForced ? 2 : 0, anonymousId: session.anonymousId }; }, expire: sessionManager.expire, expireObservable: sessionManager.expireObservable, setForcedReplay: () => sessionManager.updateSessionState({ forcedReplay: "1" }) }; } function startRumSessionManagerStub() { const session = { id: "00000000-aaaa-0000-aaaa-000000000000", sessionReplay: bridgeSupports( "records" /* BridgeCapability.RECORDS */ ) ? 1 : 0 /* SessionReplayState.OFF */ }; return { findTrackedSession: () => session, expire: noop, expireObservable: new Observable(), setForcedReplay: noop }; } function computeTrackingType(configuration, rawTrackingType) { if (hasValidRumSession(rawTrackingType)) { return rawTrackingType; } if (!performDraw(configuration.sessionSampleRate)) { return "0"; } if (!performDraw(configuration.sessionReplaySampleRate)) { return "2"; } return "1"; } function hasValidRumSession(trackingType) { return trackingType === "0" || trackingType === "1" || trackingType === "2"; } // node_modules/@datadog/browser-rum-core/esm/transport/startRumBatch.js function startRumBatch(configuration, lifeCycle, reportError, pageMayExitObservable, sessionExpireObservable, createEncoder) { const endpoints = [configuration.rumEndpointBuilder]; if (configuration.replica) { endpoints.push(configuration.replica.rumEndpointBuilder); } const batch = createBatch({ encoder: createEncoder( 2 /* DeflateEncoderStreamId.RUM */ ), request: createHttpRequest(endpoints, configuration.batchBytesLimit, reportError), flushController: createFlushController({ messagesLimit: configuration.batchMessagesLimit, bytesLimit: configuration.batchBytesLimit, durationLimit: configuration.flushTimeout, pageMayExitObservable, sessionExpireObservable }), messageBytesLimit: configuration.messageBytesLimit }); lifeCycle.subscribe(13, (serverRumEvent) => { if (serverRumEvent.type === RumEventType.VIEW) { batch.upsert(serverRumEvent, serverRumEvent.view.id); } else { batch.add(serverRumEvent); } }); return batch; } // node_modules/@datadog/browser-rum-core/esm/transport/startRumEventBridge.js function startRumEventBridge(lifeCycle) { const bridge = getEventBridge(); lifeCycle.subscribe(13, (serverRumEvent) => { bridge.send("rum", serverRumEvent); }); } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/urlContexts.js var URL_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY; function startUrlContexts(lifeCycle, hooks, locationChangeObservable, location2) { const urlContextHistory = createValueHistory({ expireDelay: URL_CONTEXT_TIME_OUT_DELAY }); let previousViewUrl; lifeCycle.subscribe(1, ({ startClocks }) => { const viewUrl = location2.href; urlContextHistory.add(buildUrlContext({ url: viewUrl, referrer: !previousViewUrl ? document.referrer : previousViewUrl }), startClocks.relative); previousViewUrl = viewUrl; }); lifeCycle.subscribe(6, ({ endClocks }) => { urlContextHistory.closeActive(endClocks.relative); }); const locationChangeSubscription = locationChangeObservable.subscribe(({ newLocation }) => { const current = urlContextHistory.find(); if (current) { const changeTime = relativeNow(); urlContextHistory.closeActive(changeTime); urlContextHistory.add(buildUrlContext({ url: newLocation.href, referrer: current.referrer }), changeTime); } }); function buildUrlContext({ url, referrer }) { return { url, referrer }; } hooks.register(0, ({ startTime, eventType }) => { const urlContext = urlContextHistory.find(startTime); if (!urlContext) { return DISCARDED; } return { type: eventType, view: { url: urlContext.url, referrer: urlContext.referrer } }; }); return { findUrl: (startTime) => urlContextHistory.find(startTime), stop: () => { locationChangeSubscription.unsubscribe(); urlContextHistory.stop(); } }; } // node_modules/@datadog/browser-rum-core/esm/browser/locationChangeObservable.js function createLocationChangeObservable(configuration, location2) { let currentLocation = shallowClone(location2); return new Observable((observable) => { const { stop: stopHistoryTracking } = trackHistory(configuration, onLocationChange); const { stop: stopHashTracking } = trackHash(configuration, onLocationChange); function onLocationChange() { if (currentLocation.href === location2.href) { return; } const newLocation = shallowClone(location2); observable.notify({ newLocation, oldLocation: currentLocation }); currentLocation = newLocation; } return () => { stopHistoryTracking(); stopHashTracking(); }; }); } function trackHistory(configuration, onHistoryChange) { const { stop: stopInstrumentingPushState } = instrumentMethod(getHistoryInstrumentationTarget("pushState"), "pushState", ({ onPostCall }) => { onPostCall(onHistoryChange); }); const { stop: stopInstrumentingReplaceState } = instrumentMethod(getHistoryInstrumentationTarget("replaceState"), "replaceState", ({ onPostCall }) => { onPostCall(onHistoryChange); }); const { stop: removeListener } = addEventListener(configuration, window, "popstate", onHistoryChange); return { stop: () => { stopInstrumentingPushState(); stopInstrumentingReplaceState(); removeListener(); } }; } function trackHash(configuration, onHashChange) { return addEventListener(configuration, window, "hashchange", onHashChange); } function getHistoryInstrumentationTarget(methodName) { return Object.prototype.hasOwnProperty.call(history, methodName) ? history : History.prototype; } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/featureFlagContext.js var FEATURE_FLAG_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY; function startFeatureFlagContexts(lifeCycle, hooks, configuration) { const featureFlagContexts = createValueHistory({ expireDelay: FEATURE_FLAG_CONTEXT_TIME_OUT_DELAY }); lifeCycle.subscribe(1, ({ startClocks }) => { featureFlagContexts.add({}, startClocks.relative); }); lifeCycle.subscribe(6, ({ endClocks }) => { featureFlagContexts.closeActive(endClocks.relative); }); hooks.register(0, ({ startTime, eventType }) => { const trackFeatureFlagsForEvents = configuration.trackFeatureFlagsForEvents.concat([RumEventType.VIEW, RumEventType.ERROR]); if (!trackFeatureFlagsForEvents.includes(eventType)) { return SKIPPED; } const featureFlagContext = featureFlagContexts.find(startTime); if (!featureFlagContext || isEmptyObject(featureFlagContext)) { return SKIPPED; } return { type: eventType, feature_flags: featureFlagContext }; }); return { addFeatureFlagEvaluation: (key, value) => { const currentContext = featureFlagContexts.find(); if (currentContext) { currentContext[key] = value; } } }; } // node_modules/@datadog/browser-rum-core/esm/domain/startCustomerDataTelemetry.js var MEASURES_PERIOD_DURATION = 10 * ONE_SECOND; var currentPeriodMeasures; var batchHasRumEvent; function startCustomerDataTelemetry(telemetry, lifeCycle, batchFlushObservable) { if (!telemetry.metricsEnabled) { return; } initCurrentPeriodMeasures(); batchHasRumEvent = false; lifeCycle.subscribe(13, () => { batchHasRumEvent = true; }); batchFlushObservable.subscribe(({ bytesCount, messagesCount }) => { if (!batchHasRumEvent) { return; } batchHasRumEvent = false; currentPeriodMeasures.batchCount += 1; updateMeasure(currentPeriodMeasures.batchBytesCount, bytesCount); updateMeasure(currentPeriodMeasures.batchMessagesCount, messagesCount); }); setInterval(sendCurrentPeriodMeasures, MEASURES_PERIOD_DURATION); } function sendCurrentPeriodMeasures() { if (currentPeriodMeasures.batchCount === 0) { return; } addTelemetryMetrics("Customer data measures", currentPeriodMeasures); initCurrentPeriodMeasures(); } function createMeasure() { return { min: Infinity, max: 0, sum: 0 }; } function updateMeasure(measure, value) { measure.sum += value; measure.min = Math.min(measure.min, value); measure.max = Math.max(measure.max, value); } function initCurrentPeriodMeasures() { currentPeriodMeasures = { batchCount: 0, batchBytesCount: createMeasure(), batchMessagesCount: createMeasure() }; } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/pageStateHistory.js var MAX_PAGE_STATE_ENTRIES = 4e3; var MAX_PAGE_STATE_ENTRIES_SELECTABLE = 500; var PAGE_STATE_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY; function startPageStateHistory(hooks, configuration, maxPageStateEntriesSelectable = MAX_PAGE_STATE_ENTRIES_SELECTABLE) { const pageStateEntryHistory = createValueHistory({ expireDelay: PAGE_STATE_CONTEXT_TIME_OUT_DELAY, maxEntries: MAX_PAGE_STATE_ENTRIES }); let currentPageState; if (supportPerformanceTimingEvent(RumPerformanceEntryType.VISIBILITY_STATE)) { const visibilityEntries = performance.getEntriesByType(RumPerformanceEntryType.VISIBILITY_STATE); visibilityEntries.forEach((entry) => { const state = entry.name === "hidden" ? "hidden" : "active"; addPageState(state, entry.startTime); }); } addPageState(getPageState(), relativeNow()); const { stop: stopEventListeners } = addEventListeners(configuration, window, [ "pageshow", "focus", "blur", "visibilitychange", "resume", "freeze", "pagehide" /* DOM_EVENT.PAGE_HIDE */ ], (event) => { addPageState(computePageState(event), event.timeStamp); }, { capture: true }); function addPageState(nextPageState, startTime = relativeNow()) { if (nextPageState === currentPageState) { return; } currentPageState = nextPageState; pageStateEntryHistory.closeActive(startTime); pageStateEntryHistory.add({ state: currentPageState, startTime }, startTime); } function wasInPageStateDuringPeriod(state, startTime, duration) { return pageStateEntryHistory.findAll(startTime, duration).some((pageState) => pageState.state === state); } hooks.register(0, ({ startTime, duration = 0, eventType }) => { if (eventType === RumEventType.VIEW) { const pageStates = pageStateEntryHistory.findAll(startTime, duration); return { type: eventType, _dd: { page_states: processPageStates(pageStates, startTime, maxPageStateEntriesSelectable) } }; } if (eventType === RumEventType.ACTION || eventType === RumEventType.ERROR) { return { type: eventType, view: { in_foreground: wasInPageStateDuringPeriod("active", startTime, 0) } }; } return SKIPPED; }); return { wasInPageStateDuringPeriod, addPageState, stop: () => { stopEventListeners(); pageStateEntryHistory.stop(); } }; } function processPageStates(pageStateEntries, eventStartTime, maxPageStateEntriesSelectable) { if (pageStateEntries.length === 0) { return; } return pageStateEntries.slice(-maxPageStateEntriesSelectable).reverse().map(({ state, startTime }) => ({ state, start: toServerDuration(elapsed(eventStartTime, startTime)) })); } function computePageState(event) { if (event.type === "freeze") { return "frozen"; } else if (event.type === "pagehide") { return event.persisted ? "frozen" : "terminated"; } return getPageState(); } function getPageState() { if (document.visibilityState === "hidden") { return "hidden"; } if (document.hasFocus()) { return "active"; } return "passive"; } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/displayContext.js function startDisplayContext(hooks, configuration) { let viewport; const animationFrameId = requestAnimationFrame(monitor(() => { viewport = getViewportDimension(); })); const unsubscribeViewport = initViewportObservable(configuration).subscribe((viewportDimension) => { viewport = viewportDimension; }).unsubscribe; hooks.register(0, ({ eventType }) => ({ type: eventType, display: viewport ? { viewport } : void 0 })); return { stop: () => { unsubscribeViewport(); if (animationFrameId) { cancelAnimationFrame(animationFrameId); } } }; } // node_modules/@datadog/browser-rum-core/esm/browser/cookieObservable.js function createCookieObservable(configuration, cookieName) { const detectCookieChangeStrategy = window.cookieStore ? listenToCookieStoreChange(configuration) : watchCookieFallback; return new Observable((observable) => detectCookieChangeStrategy(cookieName, (event) => observable.notify(event))); } function listenToCookieStoreChange(configuration) { return (cookieName, callback) => { const listener = addEventListener(configuration, window.cookieStore, "change", (event) => { const changeEvent = event.changed.find((event2) => event2.name === cookieName) || event.deleted.find((event2) => event2.name === cookieName); if (changeEvent) { callback(changeEvent.value); } }); return listener.stop; }; } var WATCH_COOKIE_INTERVAL_DELAY = ONE_SECOND; function watchCookieFallback(cookieName, callback) { const previousCookieValue = findCommaSeparatedValue(document.cookie, cookieName); const watchCookieIntervalId = setInterval(() => { const cookieValue = findCommaSeparatedValue(document.cookie, cookieName); if (cookieValue !== previousCookieValue) { callback(cookieValue); } }, WATCH_COOKIE_INTERVAL_DELAY); return () => { clearInterval(watchCookieIntervalId); }; } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/ciVisibilityContext.js var CI_VISIBILITY_TEST_ID_COOKIE_NAME = "datadog-ci-visibility-test-execution-id"; function startCiVisibilityContext(configuration, hooks, cookieObservable = createCookieObservable(configuration, CI_VISIBILITY_TEST_ID_COOKIE_NAME)) { var _a; let testExecutionId = getInitCookie(CI_VISIBILITY_TEST_ID_COOKIE_NAME) || ((_a = window.Cypress) === null || _a === void 0 ? void 0 : _a.env("traceId")); const cookieObservableSubscription = cookieObservable.subscribe((value) => { testExecutionId = value; }); hooks.register(0, ({ eventType }) => { if (typeof testExecutionId !== "string") { return SKIPPED; } return { type: eventType, session: { type: "ci_test" /* SessionType.CI_TEST */ }, ci_test: { test_execution_id: testExecutionId } }; }); return { stop: () => { cookieObservableSubscription.unsubscribe(); } }; } // node_modules/@datadog/browser-rum-core/esm/domain/longAnimationFrame/longAnimationFrameCollection.js function startLongAnimationFrameCollection(lifeCycle, configuration) { const performanceResourceSubscription = createPerformanceObservable(configuration, { type: RumPerformanceEntryType.LONG_ANIMATION_FRAME, buffered: true }).subscribe((entries) => { for (const entry of entries) { const startClocks = relativeToClocks(entry.startTime); const rawRumEvent = { date: startClocks.timeStamp, long_task: { id: generateUUID(), entry_type: RumLongTaskEntryType.LONG_ANIMATION_FRAME, duration: toServerDuration(entry.duration), blocking_duration: toServerDuration(entry.blockingDuration), first_ui_event_timestamp: toServerDuration(entry.firstUIEventTimestamp), render_start: toServerDuration(entry.renderStart), style_and_layout_start: toServerDuration(entry.styleAndLayoutStart), start_time: toServerDuration(entry.startTime), scripts: entry.scripts.map((script) => ({ duration: toServerDuration(script.duration), pause_duration: toServerDuration(script.pauseDuration), forced_style_and_layout_duration: toServerDuration(script.forcedStyleAndLayoutDuration), start_time: toServerDuration(script.startTime), execution_start: toServerDuration(script.executionStart), source_url: script.sourceURL, source_function_name: script.sourceFunctionName, source_char_position: script.sourceCharPosition, invoker: script.invoker, invoker_type: script.invokerType, window_attribution: script.windowAttribution })) }, type: RumEventType.LONG_TASK, _dd: { discarded: false } }; lifeCycle.notify(12, { rawRumEvent, startTime: startClocks.relative, duration: entry.duration, domainContext: { performanceEntry: entry } }); } }); return { stop: () => performanceResourceSubscription.unsubscribe() }; } // node_modules/@datadog/browser-rum-core/esm/domain/longTask/longTaskCollection.js function startLongTaskCollection(lifeCycle, configuration) { const performanceLongTaskSubscription = createPerformanceObservable(configuration, { type: RumPerformanceEntryType.LONG_TASK, buffered: true }).subscribe((entries) => { for (const entry of entries) { if (entry.entryType !== RumPerformanceEntryType.LONG_TASK) { break; } if (!configuration.trackLongTasks) { break; } const startClocks = relativeToClocks(entry.startTime); const rawRumEvent = { date: startClocks.timeStamp, long_task: { id: generateUUID(), entry_type: RumLongTaskEntryType.LONG_TASK, duration: toServerDuration(entry.duration) }, type: RumEventType.LONG_TASK, _dd: { discarded: false } }; lifeCycle.notify(12, { rawRumEvent, startTime: startClocks.relative, duration: entry.duration, domainContext: { performanceEntry: entry } }); } }); return { stop() { performanceLongTaskSubscription.unsubscribe(); } }; } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/syntheticsContext.js function startSyntheticsContext(hooks) { hooks.register(0, ({ eventType }) => { if (!isSyntheticsTest()) { return SKIPPED; } const testId = getSyntheticsTestId(); const resultId = getSyntheticsResultId(); return { type: eventType, session: { type: "synthetics" /* SessionType.SYNTHETICS */ }, synthetics: { test_id: testId, result_id: resultId, injected: willSyntheticsInjectRum() } }; }); } // node_modules/@datadog/browser-rum-core/esm/domain/limitModification.js function limitModification(object, modifiableFieldPaths, modifier) { const clone = deepClone(object); const result = modifier(clone); objectEntries(modifiableFieldPaths).forEach(([fieldPath, fieldType]) => ( // Traverse both object and clone simultaneously up to the path and apply the modification from the clone to the original object when the type is valid setValueAtPath(object, clone, fieldPath.split(/\.|(?=\[\])/), fieldType) )); return result; } function setValueAtPath(object, clone, pathSegments, fieldType) { const [field, ...restPathSegments] = pathSegments; if (field === "[]") { if (Array.isArray(object) && Array.isArray(clone)) { object.forEach((item, i) => setValueAtPath(item, clone[i], restPathSegments, fieldType)); } return; } if (!isValidObject(object) || !isValidObject(clone)) { return; } if (restPathSegments.length > 0) { return setValueAtPath(object[field], clone[field], restPathSegments, fieldType); } setNestedValue(object, field, clone[field], fieldType); } function setNestedValue(object, field, value, fieldType) { const newType = getType(value); if (newType === fieldType) { object[field] = sanitize(value); } else if (fieldType === "object" && (newType === "undefined" || newType === "null")) { object[field] = {}; } } function isValidObject(object) { return getType(object) === "object"; } // node_modules/@datadog/browser-rum-core/esm/domain/assembly.js var VIEW_MODIFIABLE_FIELD_PATHS = { "view.name": "string", "view.url": "string", "view.referrer": "string" }; var USER_CUSTOMIZABLE_FIELD_PATHS = { context: "object" }; var ROOT_MODIFIABLE_FIELD_PATHS = { service: "string", version: "string" }; var modifiableFieldPathsByEvent; function startRumAssembly(configuration, lifeCycle, hooks, reportError) { modifiableFieldPathsByEvent = { [RumEventType.VIEW]: __spreadValues(__spreadValues(__spreadValues({ "view.performance.lcp.resource_url": "string" }, USER_CUSTOMIZABLE_FIELD_PATHS), VIEW_MODIFIABLE_FIELD_PATHS), ROOT_MODIFIABLE_FIELD_PATHS), [RumEventType.ERROR]: __spreadValues(__spreadValues(__spreadValues({ "error.message": "string", "error.stack": "string", "error.resource.url": "string", "error.fingerprint": "string" }, USER_CUSTOMIZABLE_FIELD_PATHS), VIEW_MODIFIABLE_FIELD_PATHS), ROOT_MODIFIABLE_FIELD_PATHS), [RumEventType.RESOURCE]: __spreadValues(__spreadValues(__spreadValues(__spreadValues({ "resource.url": "string" }, isExperimentalFeatureEnabled(ExperimentalFeature.WRITABLE_RESOURCE_GRAPHQL) ? { "resource.graphql": "object" } : {}), USER_CUSTOMIZABLE_FIELD_PATHS), VIEW_MODIFIABLE_FIELD_PATHS), ROOT_MODIFIABLE_FIELD_PATHS), [RumEventType.ACTION]: __spreadValues(__spreadValues(__spreadValues({ "action.target.name": "string" }, USER_CUSTOMIZABLE_FIELD_PATHS), VIEW_MODIFIABLE_FIELD_PATHS), ROOT_MODIFIABLE_FIELD_PATHS), [RumEventType.LONG_TASK]: __spreadValues(__spreadValues(__spreadValues({ "long_task.scripts[].source_url": "string", "long_task.scripts[].invoker": "string" }, USER_CUSTOMIZABLE_FIELD_PATHS), VIEW_MODIFIABLE_FIELD_PATHS), ROOT_MODIFIABLE_FIELD_PATHS), [RumEventType.VITAL]: __spreadValues(__spreadValues(__spreadValues({}, USER_CUSTOMIZABLE_FIELD_PATHS), VIEW_MODIFIABLE_FIELD_PATHS), ROOT_MODIFIABLE_FIELD_PATHS) }; const eventRateLimiters = { [RumEventType.ERROR]: createEventRateLimiter(RumEventType.ERROR, configuration.eventRateLimiterThreshold, reportError), [RumEventType.ACTION]: createEventRateLimiter(RumEventType.ACTION, configuration.eventRateLimiterThreshold, reportError), [RumEventType.VITAL]: createEventRateLimiter(RumEventType.VITAL, configuration.eventRateLimiterThreshold, reportError) }; lifeCycle.subscribe(12, ({ startTime, duration, rawRumEvent, domainContext }) => { const defaultRumEventAttributes = hooks.triggerHook(0, { eventType: rawRumEvent.type, startTime, duration }); if (defaultRumEventAttributes === DISCARDED) { return; } const serverRumEvent = combine(defaultRumEventAttributes, rawRumEvent, { ddtags: buildTags(configuration).join(",") }); if (shouldSend(serverRumEvent, configuration.beforeSend, domainContext, eventRateLimiters)) { if (isEmptyObject(serverRumEvent.context)) { delete serverRumEvent.context; } lifeCycle.notify(13, serverRumEvent); } }); } function shouldSend(event, beforeSend2, domainContext, eventRateLimiters) { var _a; if (beforeSend2) { const result = limitModification(event, modifiableFieldPathsByEvent[event.type], (event2) => beforeSend2(event2, domainContext)); if (result === false && event.type !== RumEventType.VIEW) { return false; } if (result === false) { display.warn("Can't dismiss view events using beforeSend!"); } } const rateLimitReached = (_a = eventRateLimiters[event.type]) === null || _a === void 0 ? void 0 : _a.isLimitReached(); return !rateLimitReached; } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/sessionContext.js function startSessionContext(hooks, sessionManager, recorderApi, viewHistory) { hooks.register(0, ({ eventType, startTime }) => { const session = sessionManager.findTrackedSession(startTime); const view = viewHistory.findView(startTime); if (!session || !view) { return DISCARDED; } let hasReplay; let sampledForReplay; let isActive; if (eventType === RumEventType.VIEW) { hasReplay = recorderApi.getReplayStats(view.id) ? true : void 0; sampledForReplay = session.sessionReplay === 1; isActive = view.sessionIsActive ? void 0 : false; } else { hasReplay = recorderApi.isRecording() ? true : void 0; } return { type: eventType, session: { id: session.id, type: "user", has_replay: hasReplay, sampled_for_replay: sampledForReplay, is_active: isActive } }; }); hooks.register(1, ({ startTime }) => { const session = sessionManager.findTrackedSession(startTime); if (!session) { return SKIPPED; } return { session: { id: session.id } }; }); } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/connectivityContext.js function startConnectivityContext(hooks) { hooks.register(0, ({ eventType }) => ({ type: eventType, connectivity: getConnectivity() })); } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/defaultContext.js function startDefaultContext(hooks, configuration, sdkName) { hooks.register(0, ({ eventType }) => { const source = configuration.source; return { type: eventType, _dd: { format_version: 2, drift: currentDrift(), configuration: { session_sample_rate: round(configuration.sessionSampleRate, 3), session_replay_sample_rate: round(configuration.sessionReplaySampleRate, 3), profiling_sample_rate: round(configuration.profilingSampleRate, 3) }, browser_sdk_version: canUseEventBridge() ? "6.21.2" : void 0, sdk_name: sdkName }, application: { id: configuration.applicationId }, date: timeStampNow(), source }; }); hooks.register(1, () => ({ application: { id: configuration.applicationId } })); } // node_modules/@datadog/browser-rum-core/esm/domain/contexts/trackingConsentContext.js function startTrackingConsentContext(hooks, trackingConsentState) { hooks.register(1, () => { const wasConsented = trackingConsentState.isGranted(); if (!wasConsented) { return DISCARDED; } return SKIPPED; }); } // node_modules/@datadog/browser-rum-core/esm/domain/hooks.js var createHooks = abstractHooks; // node_modules/@datadog/browser-rum-core/esm/domain/event/eventCollection.js var allowedEventTypes = [RumEventType.ACTION, RumEventType.ERROR, RumEventType.LONG_TASK, RumEventType.RESOURCE, RumEventType.VITAL]; function startEventCollection(lifeCycle) { return { addEvent: (startTime, event, domainContext, duration) => { if (!allowedEventTypes.includes(event.type)) { return; } lifeCycle.notify(12, { startTime, rawRumEvent: event, domainContext, duration }); } }; } // node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/startInitialViewMetricsTelemetry.js function startInitialViewMetricsTelemetry(lifeCycle, telemetry) { if (!telemetry.metricsEnabled) { return { stop: noop }; } const { unsubscribe } = lifeCycle.subscribe(4, ({ initialViewMetrics }) => { if (!initialViewMetrics.largestContentfulPaint || !initialViewMetrics.navigationTimings) { return; } addTelemetryMetrics("Initial view metrics", { metrics: createCoreInitialViewMetrics(initialViewMetrics.largestContentfulPaint, initialViewMetrics.navigationTimings) }); unsubscribe(); }); return { stop: unsubscribe }; } function createCoreInitialViewMetrics(lcp, navigation) { return { lcp: { value: lcp.value }, navigation: { domComplete: navigation.domComplete, domContentLoaded: navigation.domContentLoaded, domInteractive: navigation.domInteractive, firstByte: navigation.firstByte, loadEvent: navigation.loadEvent } }; } // node_modules/@datadog/browser-rum-core/esm/boot/startRum.js function startRum(configuration, recorderApi, profilerApi, initialViewOptions, createEncoder, trackingConsentState, customVitalsState, bufferedDataObservable, sdkName) { const cleanupTasks2 = []; const lifeCycle = new LifeCycle(); const hooks = createHooks(); lifeCycle.subscribe(13, (event) => sendToExtension("rum", event)); const reportError = (error) => { lifeCycle.notify(14, { error }); addTelemetryDebug("Error reported to customer", { "error.message": error.message }); }; const pageMayExitObservable = createPageMayExitObservable(configuration); const pageMayExitSubscription = pageMayExitObservable.subscribe((event) => { lifeCycle.notify(11, event); }); cleanupTasks2.push(() => pageMayExitSubscription.unsubscribe()); const telemetry = startTelemetry("browser-rum-sdk", configuration, hooks, reportError, pageMayExitObservable, createEncoder); cleanupTasks2.push(telemetry.stop); const session = !canUseEventBridge() ? startRumSessionManager(configuration, lifeCycle, trackingConsentState) : startRumSessionManagerStub(); if (!canUseEventBridge()) { const batch = startRumBatch(configuration, lifeCycle, reportError, pageMayExitObservable, session.expireObservable, createEncoder); cleanupTasks2.push(() => batch.stop()); startCustomerDataTelemetry(telemetry, lifeCycle, batch.flushController.flushObservable); } else { startRumEventBridge(lifeCycle); } const domMutationObservable = createDOMMutationObservable(); const locationChangeObservable = createLocationChangeObservable(configuration, location); const { observable: windowOpenObservable, stop: stopWindowOpen } = createWindowOpenObservable(); cleanupTasks2.push(stopWindowOpen); startDefaultContext(hooks, configuration, sdkName); const pageStateHistory = startPageStateHistory(hooks, configuration); const viewHistory = startViewHistory(lifeCycle); cleanupTasks2.push(() => viewHistory.stop()); const urlContexts = startUrlContexts(lifeCycle, hooks, locationChangeObservable, location); cleanupTasks2.push(() => urlContexts.stop()); const featureFlagContexts = startFeatureFlagContexts(lifeCycle, hooks, configuration); startSessionContext(hooks, session, recorderApi, viewHistory); startConnectivityContext(hooks); startTrackingConsentContext(hooks, trackingConsentState); const globalContext = startGlobalContext(hooks, configuration, "rum", true); const userContext = startUserContext(hooks, configuration, session, "rum"); const accountContext = startAccountContext(hooks, configuration, "rum"); const { actionContexts, addAction, addEvent, stop: stopRumEventCollection } = startRumEventCollection(lifeCycle, hooks, configuration, pageStateHistory, domMutationObservable, windowOpenObservable, reportError); cleanupTasks2.push(stopRumEventCollection); const { addTiming, startView, setViewName, setViewContext, setViewContextProperty, getViewContext, stop: stopViewCollection } = startViewCollection(lifeCycle, hooks, configuration, location, domMutationObservable, windowOpenObservable, locationChangeObservable, recorderApi, viewHistory, initialViewOptions); cleanupTasks2.push(stopViewCollection); const { stop: stopInitialViewMetricsTelemetry } = startInitialViewMetricsTelemetry(lifeCycle, telemetry); cleanupTasks2.push(stopInitialViewMetricsTelemetry); const { stop: stopResourceCollection } = startResourceCollection(lifeCycle, configuration, pageStateHistory); cleanupTasks2.push(stopResourceCollection); if (configuration.trackLongTasks) { if (supportPerformanceTimingEvent(RumPerformanceEntryType.LONG_ANIMATION_FRAME)) { const { stop: stopLongAnimationFrameCollection } = startLongAnimationFrameCollection(lifeCycle, configuration); cleanupTasks2.push(stopLongAnimationFrameCollection); } else { startLongTaskCollection(lifeCycle, configuration); } } const { addError } = startErrorCollection(lifeCycle, configuration, bufferedDataObservable); bufferedDataObservable.unbuffer(); startRequestCollection(lifeCycle, configuration, session, userContext, accountContext); const vitalCollection = startVitalCollection(lifeCycle, pageStateHistory, customVitalsState); const internalContext = startInternalContext(configuration.applicationId, session, viewHistory, actionContexts, urlContexts); cleanupTasks2.push(() => profilerApi.stop()); return { addAction, addEvent, addError, addTiming, addFeatureFlagEvaluation: featureFlagContexts.addFeatureFlagEvaluation, startView, setViewContext, setViewContextProperty, getViewContext, setViewName, lifeCycle, viewHistory, session, stopSession: () => session.expire(), getInternalContext: internalContext.get, startDurationVital: vitalCollection.startDurationVital, stopDurationVital: vitalCollection.stopDurationVital, addDurationVital: vitalCollection.addDurationVital, addOperationStepVital: vitalCollection.addOperationStepVital, globalContext, userContext, accountContext, telemetry, stop: () => { cleanupTasks2.forEach((task) => task()); }, hooks }; } function startRumEventCollection(lifeCycle, hooks, configuration, pageStateHistory, domMutationObservable, windowOpenObservable, reportError) { const actionCollection = startActionCollection(lifeCycle, hooks, domMutationObservable, windowOpenObservable, configuration); const eventCollection = startEventCollection(lifeCycle); const displayContext = startDisplayContext(hooks, configuration); const ciVisibilityContext = startCiVisibilityContext(configuration, hooks); startSyntheticsContext(hooks); startRumAssembly(configuration, lifeCycle, hooks, reportError); return { pageStateHistory, addAction: actionCollection.addAction, addEvent: eventCollection.addEvent, actionContexts: actionCollection.actionContexts, stop: () => { actionCollection.stop(); ciVisibilityContext.stop(); displayContext.stop(); pageStateHistory.stop(); } }; } // node_modules/@datadog/browser-rum-core/esm/domain/getSessionReplayUrl.js function getSessionReplayUrl(configuration, { session, viewContext, errorType }) { const sessionId = session ? session.id : "no-session-id"; const parameters = []; if (errorType !== void 0) { parameters.push(`error-type=${errorType}`); } if (viewContext) { parameters.push(`seed=${viewContext.id}`); parameters.push(`from=${viewContext.startClocks.timeStamp}`); } const origin = getDatadogSiteUrl(configuration); const path = `/rum/replay/sessions/${sessionId}`; return `${origin}${path}?${parameters.join("&")}`; } function getDatadogSiteUrl(rumConfiguration) { const site = rumConfiguration.site; const subdomain = rumConfiguration.subdomain || getSiteDefaultSubdomain(rumConfiguration); return `https://${subdomain ? `${subdomain}.` : ""}${site}`; } function getSiteDefaultSubdomain(configuration) { switch (configuration.site) { case INTAKE_SITE_US1: case INTAKE_SITE_EU1: return "app"; case INTAKE_SITE_STAGING: return "dd"; default: return void 0; } } export { display, DOCS_ORIGIN, ONE_SECOND, relativeToClocks, currentDrift, timeStampNow, clocksNow, clocksOrigin, elapsed, concatBuffers, getGlobalObject, monitor, monitorError, setTimeout, clearTimeout, Observable, throttle, noop, isSafari, buildUrl, buildTags, sendToExtension, createHttpRequest, getEventBridge, bridgeSupports, canUseEventBridge, addEventListener, addEventListeners, isPageExitReason, SKIPPED, addTelemetryDebug, addTelemetryError, addTelemetryMetrics, DefaultPrivacyLevel, instrumentMethod, instrumentSetter, defineGlobal, asyncRunOnReadyState, requestIdleCallback, RumEventType, ActionType, isSampled, makeRumPublicApi, getMutationObserverConstructor, sanitizeIfLongDataUrl, RumPerformanceEntryType, supportPerformanceTimingEvent, isNodeShadowHost, isNodeShadowRoot, hasChildNodes, forEachChildNodes, getParentNode, STABLE_ATTRIBUTES, NodePrivacyLevel, PRIVACY_ATTR_NAME, PRIVACY_ATTR_VALUE_HIDDEN, CENSORED_STRING_MARK, CENSORED_IMG_MARK, getNodePrivacyLevel, reducePrivacyLevel, getNodeSelfPrivacyLevel, shouldMaskNode, getTextContent, getScrollX, getScrollY, initViewportObservable, getViewportDimension, startRum, getSessionReplayUrl }; //# sourceMappingURL=chunk-72EJWOW6.js.map